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
use std::io::{self, Write};
use packet::PacketWriter;
use writers;
use Column;
use std::borrow::Borrow;
use byteorder::WriteBytesExt;
use value::ToMysqlValue;
use myc::io::WriteMysqlExt;
use myc::constants::{ColumnFlags, StatusFlags};

/// Convenience type for responding to a client `PREPARE` command.
///
/// This type should not be dropped without calling `reply`.
#[must_use]
pub struct StatementMetaWriter<'a, W: Write + 'a> {
    pub(crate) writer: &'a mut PacketWriter<W>,
}

impl<'a, W: Write + 'a> StatementMetaWriter<'a, W> {
    /// Reply to the client with the given meta-information.
    ///
    /// `id` is a statement identifier that the client should supply when it later wants to execute
    /// this statement. `params` is a set of `Column` descriptors for the parameters the client
    /// must provide when executing the prepared statement. `columns` is a set of `Column`
    /// descriptors for the values that will be returned in each row then the statement is later
    /// executed.
    pub fn reply<PI, CI>(self, id: u32, params: PI, columns: CI) -> io::Result<()>
    where
        PI: IntoIterator<Item = &'a Column>,
        CI: IntoIterator<Item = &'a Column>,
        <PI as IntoIterator>::IntoIter: ExactSizeIterator,
        <CI as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        writers::write_prepare_ok(id, params, columns, self.writer)
    }
}

/// Convenience type for providing query results to clients.
///
/// This type should not be dropped without calling either `start` or `completed`.
#[must_use]
pub struct QueryResultWriter<'a, W: Write + 'a> {
    // XXX: specialization instead?
    pub(crate) is_bin: bool,
    pub(crate) writer: &'a mut PacketWriter<W>,
}

impl<'a, W: Write> QueryResultWriter<'a, W> {
    /// Start a resultset response to the client that conforms to the given `columns`.
    ///
    /// See `RowWriter`.
    pub fn start(self, columns: &'a [Column]) -> io::Result<RowWriter<'a, W>> {
        RowWriter::new(self.writer, columns, self.is_bin)
    }

    /// Send an empty resultset response to the client indicating that `rows` rows were affected by
    /// the query. `last_insert_id` may be given to communiate an identifier for a client's most
    /// recent insertion.
    pub fn completed(self, rows: u64, last_insert_id: u64) -> io::Result<()> {
        self.writer.write_u8(0x00)?; // OK packet type
        self.writer.write_lenenc_int(rows)?;
        self.writer.write_lenenc_int(last_insert_id)?;
        self.writer.write_all(&[0x00, 0x00])?; // no server status
        self.writer.write_all(&[0x00, 0x00])?; // no warnings
        Ok(())
    }
}

/// Convenience type for sending rows of a resultset to a client.
///
/// This type *may* be dropped without calling `write_row` or `finish`. However, in this case, the
/// program may panic if an I/O error occurs when sending the end-of-records marker to the client.
/// To avoid this, call `finish` explicitly.
#[must_use]
pub struct RowWriter<'a, W: Write + 'a> {
    // XXX: specialization instead?
    is_bin: bool,
    writer: &'a mut PacketWriter<W>,
    bitmap_len: usize,
    data: Vec<u8>,
    columns: &'a [Column],

    finished: bool,
}

impl<'a, W> RowWriter<'a, W>
where
    W: Write + 'a,
{
    fn new(
        writer: &'a mut PacketWriter<W>,
        columns: &'a [Column],
        is_bin: bool,
    ) -> io::Result<RowWriter<'a, W>> {
        writers::column_definitions(columns, writer)?;

        let bitmap_len = (columns.len() + 7 + 2) / 8;
        Ok(RowWriter {
            is_bin: is_bin,
            writer: writer,
            columns: columns,
            bitmap_len,
            data: Vec::new(),
            finished: false,
        })
    }

    /// Write a single row as a part of this resultset.
    ///
    /// Note that the row *must* conform to the column specification provided to
    /// `QueryResultWriter::start`. If it does not, this method will return an error indicating
    /// that an invalid value type or specification was provided.
    pub fn write_row<I, E>(&mut self, row: I) -> io::Result<()>
    where
        I: IntoIterator<Item = E>,
        E: ToMysqlValue,
    {
        if self.is_bin {
            self.writer.write_u8(0x00)?;

            // leave space for nullmap
            self.data.resize(self.bitmap_len, 0);

            let mut cols = 0;
            for (i, v) in row.into_iter().enumerate() {
                let c = self.columns
                    .get(i)
                    .ok_or_else(|| {
                        io::Error::new(
                            io::ErrorKind::InvalidData,
                            "row has more columns than specification",
                        )
                    })?
                    .borrow();
                if v.is_null() {
                    if c.colflags.contains(ColumnFlags::NOT_NULL_FLAG) {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            "given NULL value for NOT NULL column",
                        ));
                    } else {
                        // https://web.archive.org/web/20170404144156/https://dev.mysql.com/doc/internals/en/null-bitmap.html
                        // NULL-bitmap-byte = ((field-pos + offset) / 8)
                        // NULL-bitmap-bit  = ((field-pos + offset) % 8)
                        self.data[(i + 2) / 8] |= 1u8 << ((i + 2) % 8);
                    }
                } else {
                    v.to_mysql_bin(&mut self.data, c)?;
                }
                cols += 1;
            }

            if cols != self.columns.len() {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "row has fewer columns than specification",
                ));
            }

            self.writer.write_all(&self.data[..])?;
            self.data.clear();
        } else {
            for v in row {
                v.to_mysql_text(self.writer)?;
            }
        }

        Ok(())
    }
}

impl<'a, W: Write + 'a> RowWriter<'a, W> {
    fn finish_inner(&mut self) -> io::Result<()> {
        self.finished = true;
        self.writer.end_packet()?;
        writers::write_eof_packet(self.writer, StatusFlags::empty())
    }

    /// End this resultset response, and indicate to the client that no more rows are coming.
    pub fn finish(mut self) -> io::Result<()> {
        self.finish_inner()
    }
}

impl<'a, W: Write + 'a> Drop for RowWriter<'a, W> {
    fn drop(&mut self) {
        if !self.finished {
            self.finish_inner().unwrap();
        }
    }
}