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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use byteorder::WriteBytesExt;
use statement::*;
use msg::*;
use std::io::Write;
use byteorder::{BigEndian, ByteOrder};
use {Connection, WriteState, Parameters};
use std::borrow::Cow;
use std::collections::HashMap;
// use tokio::io::{AsyncRead, AsyncWrite};
use tokio_io::{AsyncRead, AsyncWrite};

impl<W: AsyncRead + AsyncWrite, P: AsRef<Parameters>> Connection<W, P> {
    /// Return a pointer to this connection's internal buffer, when
    /// the connection is reading. The connection's `write` method
    /// must be called after the buffer is finished.
    pub fn buffer(&mut self) -> Buffer {
        if let Some(WriteState::Idle { ref mut buf, .. }) = self.write {
            buf.clear();
            Buffer {
                buf,
                parse_buffer: None,
                parsed: &mut self.parsed_queries
            }
        } else {
            unreachable!()
        }
    }
}


/// A single connection uses just two buffers, allocated at the
/// beginning of the connection. This type is a view into one of these
/// buffer, which can be used to send orders via the provided methods.
pub struct Buffer<'a> {
    // Since names are assigned to new queries when they are parsed,
    // and re-issued queries (on reconnection after an error) reuse
    // the same names, we need to reparse queries with the same names
    // at the beginning of each reconnection.  This means that
    // re-issued queries MUST NOT contain parse commands, which is why
    // there are two buffers here. `parse_buffer` will be None when
    // this buffer is for a reconnection, and will be Some when
    // parsing new queries.
    buf: &'a mut Vec<u8>,
    parse_buffer: Option<&'a mut Vec<u8>>,
    parsed: &'a mut HashMap<Cow<'static, str>, usize>
}

/// A portal (the result of a bind). Portals can be executed, or… executed.
pub struct Portal<'b, 'a: 'b, 'c> {
    name: &'c str,
    buf: &'b mut Buffer<'a>
}

impl<'a, 'b: 'a, 'c> Portal<'a, 'b, 'c> {
    /// Execute a given portal, returning at most the supplied number
    /// of rows, or an unlimited number if `max_rows == 0`.
    pub fn execute(self, max_rows: i32) {
        self.buf.execute(self.name, max_rows);
    }
}

impl<'a, 'b:'a, 'c> Drop for Portal<'a, 'b, 'c> {
    fn drop(&mut self) {
        self.buf.close_portal(self.name)
    }
}
use std::str::from_utf8;

#[doc(hidden)]
pub fn name(len: usize) -> [u8; 20] {
    let mut name: [u8; 20] = [b'_'; 20];
    write!(&mut name[..], "__{}", len).unwrap();
    name
}

fn parse_into(buf: &mut Vec<u8>, statement_name: &[u8], statement: &str, parameter_types: &[SqlType]) {
    { debug!("parse {:?} {:?}", from_utf8(statement_name), statement); }
    // Prepare statement
    let l0 = buf.len();
    buf.push(MSG_PARSE);
    buf.extend(&[0, 0, 0, 0]);
    buf.extend(statement_name);
    buf.push(0);
    buf.extend(statement.as_bytes());
    buf.push(0);
    buf.write_i16::<BigEndian>(parameter_types.len() as i16).unwrap();
    for p in parameter_types {
        buf.write_i32::<BigEndian>(*p as i32).unwrap()
    }
    let len = buf.len() - l0 - 1;
    BigEndian::write_u32(&mut buf[l0 + 1..], len as u32);
}


impl<'a> Buffer<'a> {

    #[doc(hidden)]
    pub fn buf(buf: &'a mut Vec<u8>, parse_buffer: &'a mut Vec<u8>, parsed: &'a mut HashMap<Cow<'static, str>, usize>) -> Self {
        Buffer {
            buf: buf,
            parse_buffer: Some(parse_buffer),
            parsed: parsed
        }
    }

    #[doc(hidden)]
    pub fn clone_from_buf(&mut self, v: &[u8]) {
        self.buf.clear();
        self.buf.extend(v)
    }

    #[doc(hidden)]
    pub fn extend(&mut self, v: &[u8]) {
        self.buf.extend(v)
    }

    #[doc(hidden)]
    pub fn clear(&mut self) {
        self.buf.clear();
    }

    /// Parse a statement.
    pub fn parse<Name:AsRef<[u8]>>(&mut self, statement_name: Name, statement: &str, parameter_types: &[SqlType]) {
        if let Some(ref mut buf) = self.parse_buffer {
            parse_into(buf, statement_name.as_ref(), statement, parameter_types)
        } else {
            parse_into(&mut self.buf, statement_name.as_ref(), statement, parameter_types)
        }
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn named_bind<'b, 'c>(&'b mut self, portal_name: &'c str, statement: &'static str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'c> {
        debug!("named_bind {:?} {:?}", portal_name, statement);
        let len = self.parsed.len();
        let sta = Cow::Borrowed(statement);

        let mut name_ = len;
        if let Some(&n) = self.parsed.get(&sta) {
            name_ = n
        } else {
            let name = name(len);
            self.parse(&name[..], statement, &[]);
            self.parsed.insert(sta, len);
        };
        self.bind_(portal_name, Some(name_), parameters);
        Portal { name: portal_name, buf: self }
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn bind<'b>(&'b mut self, statement: &'static str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'static> {
        self.named_bind("", statement, parameters)
    }

    /// Bind a statement to parameters and a "portal", which is a
    /// result identifier. If only one statement is executed at a
    /// time, the unnamed portal (i.e. `""`) works.
    pub fn bind_unnamed<'b>(&'b mut self, statement: &str, parameters: &[&ToSql]) -> Portal<'b, 'a, 'static> {
        self.parse("", statement, &[]);
        self.bind_("", None, parameters);
        Portal { name: "", buf: self }
    }


    fn bind_(&mut self, portal_name: &str, statement: Option<usize>, parameters: &[&ToSql]) {

        // Bind
        let l0 = self.buf.len();
        self.buf.push(MSG_BIND);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.extend(portal_name.as_bytes());
        self.buf.push(0);
        if let Some(statement) = statement {
            let name = name(statement);
            self.buf.extend(&name);
        }
        self.buf.push(0);

        // Parameter format codes
        {
            let mut diff = false;
            let mut first = None;
            let l1 = self.buf.len();
            self.buf.write_i16::<BigEndian>(parameters.len() as i16).unwrap();
            for p in parameters {
                let code = p.format_code() as i16;
                if let Some(first) = first {
                    if first != code {
                        diff = true
                    }
                } else {
                    first = Some(code)
                }
                self.buf.write_i16::<BigEndian>(code).unwrap()
            }
            match first {
                Some(p) if !diff => {
                    self.buf.resize(l1, 0);
                    self.buf.write_i16::<BigEndian>(1).unwrap();
                    self.buf.write_i16::<BigEndian>(p).unwrap();
                }
                _ => {}
            }
        }

        // Parameters
        {
            self.buf.write_i16::<BigEndian>(parameters.len() as i16).unwrap();
            for p in parameters {
                let l0 = self.buf.len();
                self.buf.extend(&[0, 0, 0, 0]);
                let is_not_null = p.write_sql(self.buf);
                let len = self.buf.len() - 4 - l0;

                if is_not_null || len > 0 {
                    BigEndian::write_i32(&mut self.buf[l0..], len as i32);
                } else {
                    BigEndian::write_i32(&mut self.buf[l0..], -1);
                }
            }
        }

        // Return values.
        self.buf.write_i16::<BigEndian>(0).unwrap(); // All return values are text

        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    /// Ask the server to flush.
    pub fn flush(&mut self) {
        debug!("flush");
        let l0 = self.buf.len();
        self.buf.push(MSG_FLUSH);
        self.buf.extend(&[0, 0, 0, 0]);
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }


    fn execute(&mut self, destination_portal: &str, max_rows: i32) {
        let l0 = self.buf.len();
        self.buf.push(MSG_EXECUTE);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.extend(destination_portal.as_bytes());
        self.buf.push(0);
        self.buf.write_i32::<BigEndian>(max_rows).unwrap();
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    fn close(&mut self, close: Close, s: &str) {
        let l0 = self.buf.len();
        self.buf.push(MSG_CLOSE);
        self.buf.extend(&[0, 0, 0, 0]);
        self.buf.push(close as u8);
        self.buf.extend(s.as_bytes());
        self.buf.push(0);
        let len = self.buf.len() - l0 - 1;
        BigEndian::write_u32(&mut self.buf[l0 + 1..], len as u32);
    }

    /// Close a named portal. The unnamed portal is automatically
    /// closed when a new `bind` on the unnamed portal is issued.
    fn close_portal(&mut self, s: &str) {
        self.close(Close::Portal, s)
    }
}


#[doc(hidden)]
pub fn sync(buf: &mut Vec<u8>) {
    let l0 = buf.len();
    buf.push(MSG_SYNC);
    buf.extend(&[0, 0, 0, 0]);
    let len = buf.len() - l0 - 1;
    BigEndian::write_u32(&mut buf[l0 + 1..], len as u32);
}


#[derive(Debug, Clone, Copy)]
#[repr(u8)]
enum Close {
    // Statement = b'S',
    Portal = b'P',
}