1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#![doc(html_root_url="https://sfackler.github.io/rust-postgres-binary-copy/doc/v0.1.0")]
#![warn(missing_docs)]
extern crate byteorder;
extern crate postgres;
use byteorder::{BigEndian, WriteBytesExt};
use postgres::error::Error;
use postgres::types::{Type, ToSql, SessionInfo, IsNull, ReadWithInfo};
use std::error;
use std::io::prelude::*;
use std::io::{self, Cursor};
pub trait StreamingIterator {
type Item: ?Sized;
fn next(&mut self) -> Option<&Self::Item>;
}
impl<'a, T: 'a + ?Sized, I: Iterator<Item = &'a T>> StreamingIterator for I {
type Item = T;
fn next(&mut self) -> Option<&T> {
unsafe { std::mem::transmute(Iterator::next(self)) }
}
}
#[derive(Debug, Copy, Clone)]
enum ReadState {
Header,
Body(usize),
Footer,
}
#[derive(Debug)]
pub struct BinaryCopyReader<'a, I> {
types: &'a [Type],
state: ReadState,
it: I,
buf: Cursor<Vec<u8>>,
}
impl<'a, I> BinaryCopyReader<'a, I> where I: StreamingIterator<Item = ToSql> {
pub fn new(types: &'a [Type], it: I) -> BinaryCopyReader<'a, I> {
let mut buf = vec![];
let _ = buf.write(b"PGCOPY\n\xff\r\n\0");
let _ = buf.write_i32::<BigEndian>(0);
let _ = buf.write_i32::<BigEndian>(0);
BinaryCopyReader {
types: types,
state: ReadState::Header,
it: it,
buf: Cursor::new(buf),
}
}
fn fill_buf(&mut self, info: &SessionInfo) -> io::Result<()> {
enum Op<'a> {
Value(usize, &'a ToSql),
Footer,
Nothing,
}
let op = match (self.state, self.it.next()) {
(ReadState::Header, Some(value)) => {
self.state = ReadState::Body(0);
Op::Value(0, value)
}
(ReadState::Body(old_idx), Some(value)) => {
let idx = (old_idx + 1) % self.types.len();
self.state = ReadState::Body(idx);
Op::Value(idx, value)
}
(ReadState::Header, None) | (ReadState::Body(_), None) => {
self.state = ReadState::Footer;
Op::Footer
}
(ReadState::Footer, _) => Op::Nothing,
};
self.buf.set_position(0);
self.buf.get_mut().clear();
match op {
Op::Value(idx, value) => {
if idx == 0 {
let len = self.types.len();
let len = if len > i16::max_value() as usize {
let err: Box<error::Error+Sync+Send> =
"value too large to transmit".into();
return Err(io::Error::new(io::ErrorKind::InvalidInput,
Error::Conversion(err)));
} else {
len as i16
};
let _ = self.buf.write_i16::<BigEndian>(len);
}
let len_pos = self.buf.position();
let _ = self.buf.write_i32::<BigEndian>(0);
let len = match value.to_sql_checked(&self.types[idx], &mut self.buf, info) {
Ok(IsNull::Yes) => -1,
Ok(IsNull::No) => {
let len = self.buf.position() - 4 - len_pos;
if len > i32::max_value() as u64 {
let err: Box<error::Error+Sync+Send> =
"value too large to transmit".into();
return Err(io::Error::new(io::ErrorKind::InvalidInput,
Error::Conversion(err)));
} else {
len as i32
}
}
Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, e)),
};
self.buf.set_position(len_pos);
let _ = self.buf.write_i32::<BigEndian>(len);
}
Op::Footer => {
let _ = self.buf.write_i16::<BigEndian>(-1);
}
Op::Nothing => {}
}
self.buf.set_position(0);
Ok(())
}
}
impl<'a, I> ReadWithInfo for BinaryCopyReader<'a, I> where I: StreamingIterator<Item = ToSql> {
fn read_with_info(&mut self, buf: &mut [u8], info: &SessionInfo) -> io::Result<usize> {
if self.buf.position() == self.buf.get_ref().len() as u64 {
try!(self.fill_buf(info));
}
self.buf.read(buf)
}
}
#[cfg(test)]
mod test {
use super::BinaryCopyReader;
use postgres::{Connection, SslMode};
use postgres::types::{Type, ToSql};
#[test]
fn basic() {
let conn = Connection::connect("postgres://postgres@localhost", &SslMode::None).unwrap();
conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY, bar VARCHAR)", &[]).unwrap();
let stmt = conn.prepare("COPY foo (id, bar) FROM STDIN BINARY").unwrap();
let types = &[Type::Int4, Type::Varchar];
let values: Vec<Box<ToSql>> = vec![Box::new(1i32), Box::new("foobar"),
Box::new(2i32), Box::new(None::<String>)];
let values = values.iter().map(|e| &**e);
let mut reader = BinaryCopyReader::new(types, values);
stmt.copy_in(&[], &mut reader).unwrap();
let stmt = conn.prepare("SELECT id, bar FROM foo ORDER BY id").unwrap();
assert_eq!(vec![(1i32, Some("foobar".to_string())), (2i32, None)],
stmt.query(&[])
.unwrap()
.into_iter()
.map(|r| (r.get(0), r.get(1)))
.collect::<Vec<(i32, Option<String>)>>());
}
#[test]
fn many_rows() {
let conn = Connection::connect("postgres://postgres@localhost", &SslMode::None).unwrap();
conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY, bar VARCHAR)", &[]).unwrap();
let stmt = conn.prepare("COPY foo (id, bar) FROM STDIN BINARY").unwrap();
let types = &[Type::Int4, Type::Varchar];
let mut values: Vec<Box<ToSql>> = vec![];
for i in 0..10000i32 {
values.push(Box::new(i));
values.push(Box::new(format!("the value for {}", i)));
}
let values = values.iter().map(|e| &**e);
let mut reader = BinaryCopyReader::new(types, values);
stmt.copy_in(&[], &mut reader).unwrap();
let stmt = conn.prepare("SELECT id, bar FROM foo ORDER BY id").unwrap();
let result = stmt.query(&[]).unwrap();
assert_eq!(10000, result.len());
for (i, row) in result.into_iter().enumerate() {
assert_eq!(i as i32, row.get(0));
assert_eq!(format!("the value for {}", i), row.get::<_, String>(1));
}
}
#[test]
fn big_rows() {
let conn = Connection::connect("postgres://postgres@localhost", &SslMode::None).unwrap();
conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY, bar BYTEA)", &[]).unwrap();
let stmt = conn.prepare("COPY foo (id, bar) FROM STDIN BINARY").unwrap();
let types = &[Type::Int4, Type::Bytea];
let mut values: Vec<Box<ToSql>> = vec![];
for i in 0..2i32 {
values.push(Box::new(i));
values.push(Box::new(vec![i as u8; 128 * 1024]));
}
let values = values.iter().map(|e| &**e);
let mut reader = BinaryCopyReader::new(types, values);
stmt.copy_in(&[], &mut reader).unwrap();
let stmt = conn.prepare("SELECT id, bar FROM foo ORDER BY id").unwrap();
let result = stmt.query(&[]).unwrap();
assert_eq!(2, result.len());
for (i, row) in result.into_iter().enumerate() {
assert_eq!(i as i32, row.get(0));
assert_eq!(vec![i as u8; 128 * 1024], row.get::<_, Vec<u8>>(1));
}
}
}