turnloop-mysql 0.1.0-beta.2

Pull-driven sans-I/O MySQL client protocol
Documentation
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use crate::{Error, Result};
pub use mysql_common::value::Value;
use mysql_common::{
    constants::{ColumnFlags, ColumnType},
    io::ParseBuf,
    proto::MyDeserialize,
    value::{BinValue, ValueDeserializer},
};

#[derive(Clone, Copy, Debug)]
pub(crate) struct Cursor<'a>(pub &'a [u8]);
impl<'a> Cursor<'a> {
    pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        if n > self.0.len() {
            return Err(Error::Protocol("truncated packet"));
        }
        let (v, r) = self.0.split_at(n);
        self.0 = r;
        Ok(v)
    }
    pub fn u8(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }
    pub fn u16(&mut self) -> Result<u16> {
        Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
    }
    pub fn u32(&mut self) -> Result<u32> {
        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
    }
    pub fn lenenc(&mut self) -> Result<u64> {
        match self.u8()? {
            0xfc => Ok(self.u16()? as u64),
            0xfd => {
                let b = self.take(3)?;
                Ok(u32::from_le_bytes([b[0], b[1], b[2], 0]) as u64)
            }
            0xfe => Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())),
            0xfb | 0xff => Err(Error::Protocol("invalid length encoded integer")),
            n => Ok(n as u64),
        }
    }
    pub fn bytes(&mut self) -> Result<&'a [u8]> {
        let n = usize::try_from(self.lenenc()?).map_err(|_| Error::Limit)?;
        self.take(n)
    }
    pub fn end(self) -> Result<()> {
        if self.0.is_empty() {
            Ok(())
        } else {
            Err(Error::Protocol("trailing packet bytes"))
        }
    }
}
/// Per-column wire metadata that decides how a value is decoded. Rows carry it
/// for every column (`Row::columns`, `Row::typed`), so a host can apply its own
/// policy by MySQL column type without tracking `Column` events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ColumnTypeInfo {
    pub column_type: ColumnType,
    pub flags: ColumnFlags,
    pub character_set: u16,
    /// Declared fractional-second digits for temporal columns (0..=6); 0x1f
    /// (31) for columns without a fixed scale.
    pub decimals: u8,
}
#[derive(Debug, Clone, Copy)]
pub struct Column<'a> {
    pub schema: &'a [u8],
    pub table: &'a [u8],
    pub original_table: &'a [u8],
    pub name: &'a [u8],
    pub original_name: &'a [u8],
    pub column_length: u32,
    pub decimals: u8,
    pub type_info: ColumnTypeInfo,
}
impl<'a> Column<'a> {
    pub(crate) fn parse(b: &'a [u8]) -> Result<Self> {
        let mut c = Cursor(b);
        if c.bytes()? != b"def" {
            return Err(Error::Protocol("invalid column catalog"));
        }
        let schema = c.bytes()?;
        let table = c.bytes()?;
        let original_table = c.bytes()?;
        let name = c.bytes()?;
        let original_name = c.bytes()?;
        if c.lenenc()? != 12 {
            return Err(Error::Protocol("invalid column fixed length"));
        }
        let character_set = c.u16()?;
        let column_length = c.u32()?;
        let column_type = ColumnType::try_from(c.u8()?)
            .map_err(|_| Error::Protocol("unsupported column type"))?;
        let flags = ColumnFlags::from_bits_truncate(c.u16()?);
        let decimals = c.u8()?;
        c.take(2)?;
        c.end()?;
        Ok(Self {
            schema,
            table,
            original_table,
            name,
            original_name,
            column_length,
            decimals,
            type_info: ColumnTypeInfo {
                column_type,
                flags,
                character_set,
                decimals,
            },
        })
    }
}
#[derive(Debug, Clone, PartialEq)]
pub enum RawValue<'a> {
    Null,
    Bytes(&'a [u8]),
    Scalar(Value),
}
/// One row packet, decoded lazily and validated as it is iterated.
///
/// `Row::parse` checks the header (binary marker and NULL bitmap) eagerly; each
/// value is bounds-checked and decoded exactly once as the iterator reaches it,
/// and the final value also rejects trailing packet bytes. The first `Err` ends
/// the iteration (every later `next` is `None`), so nothing past a malformed
/// value is ever yielded. A row error means the server sent a malformed packet:
/// treat it like any other parsing error and `abort` the connection.
#[derive(Debug, Clone)]
pub struct Row<'a> {
    cursor: Cursor<'a>,
    columns: &'a [ColumnTypeInfo],
    bitmap: &'a [u8],
    binary: bool,
    at: usize,
}
impl<'a> Row<'a> {
    pub(crate) fn parse(
        bytes: &'a [u8],
        columns: &'a [ColumnTypeInfo],
        binary: bool,
    ) -> Result<Self> {
        let mut cursor = Cursor(bytes);
        let bitmap = if binary {
            if cursor.u8()? != 0 {
                return Err(Error::Protocol("invalid binary row marker"));
            }
            cursor.take((columns.len() + 2).div_ceil(8))?
        } else {
            &[]
        };
        Ok(Self {
            cursor,
            columns,
            bitmap,
            binary,
            at: 0,
        })
    }
    /// Wire metadata of every column in this row, in value order.
    pub fn columns(&self) -> &'a [ColumnTypeInfo] {
        self.columns
    }
    /// Pair each remaining value with its column's wire metadata, ready for
    /// `types::decode` or a host's own per-type policy. Validation is the same
    /// as iterating the row itself.
    pub fn typed(
        self,
    ) -> impl ExactSizeIterator<Item = Result<(ColumnTypeInfo, RawValue<'a>)>> + 'a {
        let columns = &self.columns[self.at..];
        self.zip(columns)
            .map(|(value, info)| value.map(|value| (*info, value)))
    }
    fn value(&mut self, index: usize) -> Result<RawValue<'a>> {
        if !self.binary {
            if self.cursor.0.first() == Some(&0xfb) {
                self.cursor.take(1)?;
                return Ok(RawValue::Null);
            }
            return Ok(RawValue::Bytes(self.cursor.bytes()?));
        }
        if self.bitmap[(index + 2) / 8] & (1 << ((index + 2) % 8)) != 0 {
            return Ok(RawValue::Null);
        }
        let info = self.columns[index];
        let t = info.column_type as u8;
        if matches!(t, 0 | 15 | 16 | 245..=255 | 242) {
            return Ok(RawValue::Bytes(self.cursor.bytes()?));
        }
        if !matches!(t, 1..=14) {
            return Err(Error::Protocol("unsupported binary column type"));
        }
        // Numeric/calendar scalars from mysql_common contain no heap buffers.
        let mut b = ParseBuf(self.cursor.0);
        let value =
            ValueDeserializer::<BinValue>::deserialize((info.column_type, info.flags), &mut b)
                .map_err(|_| Error::Protocol("invalid binary scalar"))?
                .0;
        self.cursor.0 = b.0;
        Ok(if value == Value::NULL {
            RawValue::Null
        } else {
            RawValue::Scalar(value)
        })
    }
}
impl<'a> Iterator for Row<'a> {
    type Item = Result<RawValue<'a>>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.at == self.columns.len() {
            return None;
        }
        let i = self.at;
        self.at += 1;
        let value = self.value(i).and_then(|value| {
            if self.at == self.columns.len() {
                self.cursor.end()?;
            }
            Ok(value)
        });
        if value.is_err() {
            // Fuse: never decode past a malformed value.
            self.at = self.columns.len();
        }
        Some(value)
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        let n = self.columns.len() - self.at;
        (n, Some(n))
    }
}
impl ExactSizeIterator for Row<'_> {}

#[derive(Debug, Clone, Copy)]
pub struct ServerError<'a> {
    pub errno: u16,
    pub sql_state: &'a str,
    pub sql_message: &'a str,
}
impl<'a> ServerError<'a> {
    pub(crate) fn parse(b: &'a [u8]) -> Result<Self> {
        let mut c = Cursor(b);
        if c.u8()? != 0xff {
            return Err(Error::Protocol("invalid ERR marker"));
        }
        let errno = c.u16()?;
        let sql_state = if c.0.first() == Some(&b'#') {
            c.u8()?;
            std::str::from_utf8(c.take(5)?).map_err(|_| Error::Protocol("invalid SQLSTATE"))?
        } else {
            "HY000"
        };
        let sql_message =
            std::str::from_utf8(c.0).map_err(|_| Error::Protocol("invalid error encoding"))?;
        Ok(Self {
            errno,
            sql_state,
            sql_message,
        })
    }
    pub fn code(&self) -> Option<&'static str> {
        error_code(self.errno)
    }
}
pub fn error_code(errno: u16) -> Option<&'static str> {
    Some(match errno {
        1022 => "ER_DUP_KEY",
        1040 => "ER_CON_COUNT_ERROR",
        1044 => "ER_DBACCESS_DENIED_ERROR",
        1045 => "ER_ACCESS_DENIED_ERROR",
        1048 => "ER_BAD_NULL_ERROR",
        1049 => "ER_BAD_DB_ERROR",
        1050 => "ER_TABLE_EXISTS_ERROR",
        1051 => "ER_BAD_TABLE_ERROR",
        1052 => "ER_NON_UNIQ_ERROR",
        1054 => "ER_BAD_FIELD_ERROR",
        1062 => "ER_DUP_ENTRY",
        1064 => "ER_PARSE_ERROR",
        1146 => "ER_NO_SUCH_TABLE",
        1169 => "ER_DUP_UNIQUE",
        1205 => "ER_LOCK_WAIT_TIMEOUT",
        1213 => "ER_LOCK_DEADLOCK",
        1216 => "ER_NO_REFERENCED_ROW",
        1217 => "ER_ROW_IS_REFERENCED",
        1264 => "ER_WARN_DATA_OUT_OF_RANGE",
        1292 => "ER_TRUNCATED_WRONG_VALUE",
        1364 => "ER_NO_DEFAULT_FOR_FIELD",
        1406 => "ER_DATA_TOO_LONG",
        1451 => "ER_ROW_IS_REFERENCED_2",
        1452 => "ER_NO_REFERENCED_ROW_2",
        1524 => "ER_PLUGIN_IS_NOT_LOADED",
        1586 => "ER_DUP_ENTRY_WITH_KEY_NAME",
        1830 => "ER_FK_COLUMN_NOT_NULL",
        1834 => "ER_FK_CANNOT_DELETE_PARENT",
        1859 => "ER_DUP_UNKNOWN_IN_INDEX",
        _ => return None,
    })
}
#[cfg(test)]
mod tests {
    use super::*;
    fn info(column_type: ColumnType) -> ColumnTypeInfo {
        ColumnTypeInfo {
            column_type,
            flags: ColumnFlags::empty(),
            character_set: 45,
            decimals: 0,
        }
    }
    fn text() -> [ColumnTypeInfo; 2] {
        [info(ColumnType::MYSQL_TYPE_VAR_STRING); 2]
    }
    #[test]
    fn a_valid_row_is_decoded_in_one_pass() {
        let columns = text();
        let mut row = Row::parse(b"\x02ab\xfb", &columns, false).expect("valid header");
        assert_eq!(row.len(), 2);
        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
        assert_eq!(row.len(), 1);
        assert_eq!(row.next(), Some(Ok(RawValue::Null)));
        assert_eq!(row.next(), None);
    }
    /// Values are validated as they are reached; nothing after the first error
    /// is decoded or yielded.
    #[test]
    fn a_malformed_value_ends_the_row() {
        let columns = text();
        // Second value claims 9 bytes but only 2 remain.
        let mut row = Row::parse(b"\x02ab\x09cd", &columns, false)
            .expect("parse no longer decodes values ahead of the host");
        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
        assert_eq!(row.next(), Some(Err(Error::Protocol("truncated packet"))));
        assert_eq!(row.len(), 0);
        assert_eq!(row.next(), None);
    }
    #[test]
    fn trailing_bytes_fail_the_last_value() {
        let columns = text();
        let mut row = Row::parse(b"\x02ab\x01c!", &columns, false).expect("valid header");
        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
        assert_eq!(
            row.next(),
            Some(Err(Error::Protocol("trailing packet bytes")))
        );
        assert_eq!(row.next(), None);
    }
    #[test]
    fn rows_carry_column_type_metadata_alongside_values() {
        use mysql_common::proto::MySerialize;
        let mut bytes = Vec::new();
        mysql_common::packets::Column::new(ColumnType::MYSQL_TYPE_DATETIME)
            .with_decimals(3)
            .serialize(&mut bytes);
        let column = Column::parse(&bytes).expect("valid column");
        let datetime = column.type_info;
        assert_eq!(datetime.column_type, ColumnType::MYSQL_TYPE_DATETIME);
        assert_eq!(datetime.decimals, 3);
        assert_eq!(column.decimals, 3);
        let columns = [
            ColumnTypeInfo {
                character_set: 63,
                ..info(ColumnType::MYSQL_TYPE_TIME)
            },
            ColumnTypeInfo {
                character_set: 63,
                ..info(ColumnType::MYSQL_TYPE_BIT)
            },
            datetime,
        ];
        let row = Row::parse(b"\x0801:02:03\x01\x01\xfb", &columns, false).expect("valid");
        assert_eq!(row.columns(), columns);
        let typed = row.typed();
        assert_eq!(typed.len(), 3);
        let typed: Vec<_> = typed.collect::<Result<_>>().expect("valid row");
        assert_eq!(
            typed,
            [
                (columns[0], RawValue::Bytes(b"01:02:03")),
                (columns[1], RawValue::Bytes(b"\x01")),
                (columns[2], RawValue::Null),
            ]
        );
    }
    #[test]
    fn binary_rows_validate_the_header_eagerly_and_scalars_lazily() {
        let long = [info(ColumnType::MYSQL_TYPE_LONG)];
        assert_eq!(
            Row::parse(&[1, 0, 42, 0, 0, 0], &long, true).err(),
            Some(Error::Protocol("invalid binary row marker"))
        );
        assert_eq!(
            Row::parse(&[0], &long, true).err(),
            Some(Error::Protocol("truncated packet"))
        );
        let mut row = Row::parse(&[0, 0, 42, 0, 0, 0], &long, true).expect("valid row");
        assert_eq!(row.next(), Some(Ok(RawValue::Scalar(Value::Int(42)))));
        assert_eq!(row.next(), None);
        // A LONG needs four bytes; two are present.
        let mut row = Row::parse(&[0, 0, 42, 0], &long, true).expect("valid header");
        assert_eq!(
            row.next(),
            Some(Err(Error::Protocol("invalid binary scalar")))
        );
        assert_eq!(row.next(), None);
    }
}