qusql-mysql 0.1.0

Async mysql connector
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Provide support for binding arguments to queries
use crate::constants::type_;
use bytes::{BufMut, BytesMut};
use thiserror::Error;

/// Error type returned by [Bind::bind]
#[derive(Error, Debug)]
pub enum BindError {
    /// To many argument has been bound to the query
    #[error("to many arguments given")]
    TooManyArgumentsBound,
    /// Not enough arguments has been bound to the query
    #[error("missing argument")]
    TooFewArgumentsBound,
    /// Error converting between
    #[error("try from int")]
    TryFromInt(#[from] std::num::TryFromIntError),
}

const _: () = {
    assert!(size_of::<BindError>() <= 8);
};

/// Result type returned by [Bind::bind]
pub type BindResult<T> = Result<T, BindError>;

/// Writer used to to compose packages to
pub struct Writer<'a>(&'a mut BytesMut);

impl<'a> Writer<'a> {
    /// Construct a new writer writing into w
    #[allow(unused)]
    pub(crate) fn new(w: &'a mut BytesMut) -> Self {
        Writer(w)
    }

    /// Append a u8 to the package
    #[inline]
    pub fn put_u8(&mut self, v: u8) {
        self.0.put_u8(v);
    }

    /// Append a u16 to the package
    #[inline]
    pub fn put_u16(&mut self, v: u16) {
        self.0.put_u16_le(v);
    }

    /// Append a u24 to the package
    #[inline]
    pub fn put_u24(&mut self, v: u32) {
        self.0.put_u8((v & 0xFF) as u8);
        self.0.put_u8(((v >> 8) & 0xFF) as u8);
        self.0.put_u8(((v >> 16) & 0xFF) as u8);
    }

    /// Append a u32 to the package
    #[inline]
    pub fn put_u32(&mut self, v: u32) {
        self.0.put_u32_le(v);
    }

    /// Append a u64 to the package
    #[inline]
    pub fn put_u64(&mut self, v: u64) {
        self.0.put_u64_le(v);
    }

    /// Append a i8 to the package
    #[inline]
    pub fn put_i8(&mut self, v: i8) {
        self.0.put_i8(v);
    }

    /// Append a i16 to the package
    #[inline]
    pub fn put_i16(&mut self, v: i16) {
        self.0.put_i16_le(v);
    }

    /// Append a i32 to the package
    #[inline]
    pub fn put_i32(&mut self, v: i32) {
        self.0.put_i32_le(v);
    }

    /// Append a i64 to the package
    #[inline]
    pub fn put_i64(&mut self, v: i64) {
        self.0.put_i64_le(v);
    }

    /// Append a f32 to the package
    #[inline]
    pub fn put_f32(&mut self, v: f32) {
        self.0.put_f32_le(v);
    }

    /// Append a f64 to the package
    #[inline]
    pub fn put_f64(&mut self, v: f64) {
        self.0.put_f64_le(v);
    }

    /// Append a variable encode length to the package
    ///
    /// See <https://mariadb.com/docs/server/reference/clientserver-protocol/protocol-data-types#length-encoded-integers>
    #[inline]
    pub fn put_lenenc(&mut self, v: u64) {
        if v < 0xFB {
            self.put_u8(v as u8);
        } else if v <= 0xFFFF {
            self.put_u8(0xFC);
            self.put_u16(v as u16);
        } else if v <= 0xFFFFFF {
            self.put_u8(0xFD);
            self.put_u24(v as u32);
        } else {
            self.put_u8(0xFE);
            self.put_u64(v);
        }
    }

    /// Append the bytes in the slice to the package
    pub fn put_slice(&mut self, src: &[u8]) {
        self.0.put_slice(src);
    }
}

/// Bind a parameter to a query.
///
/// See <https://mariadb.com/docs/server/reference/clientserver-protocol/3-binary-protocol-prepared-statements/server-response-packets-binary-protocol/packet_bindata>
/// to see how each type should be encoded
pub trait Bind {
    /// Should the unsigned flag be set for the value
    const UNSIGNED: bool = false;
    /// The type of the value encode as defined in [crate::constants::type_]
    const TYPE: u8;
    /// Bind this value as the next value to the query.
    ///
    /// Return true if the value is set, and false it it is null.
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool>;
}

/// Bind a [u8] as a unsigned [type_::TINY]
impl Bind for u8 {
    const UNSIGNED: bool = true;
    const TYPE: u8 = type_::TINY;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_u8(*self);
        Ok(true)
    }
}

/// Bind a [i8] as a signed [type_::TINY]
impl Bind for i8 {
    const TYPE: u8 = type_::TINY;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_i8(*self);
        Ok(true)
    }
}

/// Bind a [u16] as a unsigned [type_::SHORT]
impl Bind for u16 {
    const UNSIGNED: bool = true;
    const TYPE: u8 = type_::SHORT;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_u16(*self);
        Ok(true)
    }
}

/// Bind a [i16] as a signed [type_::SHORT]
impl Bind for i16 {
    const TYPE: u8 = type_::SHORT;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_i16(*self);
        Ok(true)
    }
}

/// Bind a [u32] as a unsigned [type_::LONG]
impl Bind for u32 {
    const UNSIGNED: bool = true;
    const TYPE: u8 = type_::LONG;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_u32(*self);
        Ok(true)
    }
}

/// Bind a [i32] as a signed [type_::LONG]
impl Bind for i32 {
    const TYPE: u8 = type_::LONG;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_i32(*self);
        Ok(true)
    }
}

/// Bind a [u64] as a unsigned [type_::LONG_LONG]
impl Bind for u64 {
    const UNSIGNED: bool = true;
    const TYPE: u8 = type_::LONG_LONG;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_u64(*self);
        Ok(true)
    }
}

/// Bind a [i64] as a signed [type_::LONG_LONG]
impl Bind for i64 {
    const TYPE: u8 = type_::LONG_LONG;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_i64(*self);
        Ok(true)
    }
}

/// Bind a [f32] as a [type_::FLOAT]
impl Bind for f32 {
    const TYPE: u8 = type_::FLOAT;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_f32(*self);
        Ok(true)
    }
}

/// Bind a [f64] as a [type_::DOUBLE]
impl Bind for f64 {
    const TYPE: u8 = type_::DOUBLE;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_f64(*self);
        Ok(true)
    }
}

/// Bind a [bool] as a [type_::TINY]
impl Bind for bool {
    const UNSIGNED: bool = true;
    const TYPE: u8 = type_::TINY;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_u8(*self as u8);
        Ok(true)
    }
}

/// Bind a [String] as a [type_::STRING]
impl Bind for String {
    const TYPE: u8 = type_::STRING;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_lenenc(self.len() as u64);
        writer.put_slice(self.as_bytes());
        Ok(true)
    }
}

/// Bind a &[str] as a [type_::STRING]
impl Bind for str {
    const TYPE: u8 = type_::STRING;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_lenenc(self.len() as u64);
        writer.put_slice(self.as_bytes());
        Ok(true)
    }
}

/// Bind a [`Vec<u8>`] as a [type_::BLOB]
impl Bind for Vec<u8> {
    const TYPE: u8 = type_::BLOB;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_lenenc(self.len() as u64);
        writer.put_slice(self);
        Ok(true)
    }
}

/// Bind a &[[u8]] as a [type_::BLOB]
impl Bind for [u8] {
    const TYPE: u8 = type_::BLOB;
    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        writer.put_lenenc(self.len() as u64);
        writer.put_slice(self);
        Ok(true)
    }
}

/// Bind an [`Option<T>`] as T if it is [Some], otherwise as Null
impl<T: Bind> Bind for Option<T> {
    const TYPE: u8 = T::TYPE;
    const UNSIGNED: bool = T::UNSIGNED;

    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        match self {
            Some(v) => v.bind(writer),
            None => Ok(false),
        }
    }
}

/// Bind arbitrary references
impl<T: Bind + ?Sized> Bind for &T {
    const TYPE: u8 = T::TYPE;
    const UNSIGNED: bool = T::UNSIGNED;

    #[inline]
    fn bind(&self, writer: &mut Writer<'_>) -> BindResult<bool> {
        (*self).bind(writer)
    }
}

/// Bind used for args that can also handle lists
pub trait ListBind {
    /// The contained bind type
    type T: Bind + ?Sized;

    /// Get the singular bind value.
    /// Panics if list_length is not None
    fn single(&self) -> &Self::T;

    /// Get a bind bind value. Panics if list_length is None or if idx >= list_length
    fn get(&self, idx: usize) -> &Self::T;

    /// If the value is a list return the length of the list
    fn list_length(&self) -> Option<usize>;
}

impl<T: Bind + ?Sized> ListBind for T {
    type T = T;

    #[inline]
    fn single(&self) -> &Self::T {
        self
    }

    #[inline]
    fn get(&self, _: usize) -> &Self::T {
        panic!("Singular")
    }

    #[inline]
    fn list_length(&self) -> Option<usize> {
        None
    }
}

/// Bind to a _LIST_
pub struct List<'a, T> {
    /// The content of the list
    inner: &'a [T],
}

impl<'a, T: Bind> ListBind for List<'a, T> {
    type T = T;

    #[inline]
    fn single(&self) -> &Self::T {
        panic!("List")
    }

    #[inline]
    fn get(&self, idx: usize) -> &Self::T {
        &self.inner[idx]
    }

    #[inline]
    fn list_length(&self) -> Option<usize> {
        Some(self.inner.len())
    }
}

impl<'a, T: Bind> ListBind for &List<'a, T> {
    type T = T;

    #[inline]
    fn single(&self) -> &Self::T {
        panic!("List")
    }

    #[inline]
    fn get(&self, idx: usize) -> &Self::T {
        &self.inner[idx]
    }

    #[inline]
    fn list_length(&self) -> Option<usize> {
        Some(self.inner.len())
    }
}

/// Produce a [List] object that can be used as an argument to a _LIST_ argument
/// Assuming that the `list_hack` feature is set
/// ```no_run
/// use qusql_mysql::{Connection, ExecutorExt, Executor, list, ConnectionError};
///
/// async fn test(conn: &mut Connection) -> Result<(), ConnectionError> {
///     let vs: &[i32] = &[1,2,55];
///     let rows: Vec<(&str, )> = conn.fetch_all(
///         "SELECT `t` FROM `table` WHERE v IN (_LIST_)", (list(vs), )).await?;
///     Ok(())
/// }
/// ```
#[cfg(feature = "list_hack")]
pub fn list<'a, T: Bind>(v: &'a [T]) -> List<'a, T> {
    List { inner: v }
}

/// Produce a [List] object that can be used as an argument to a _LIST_ argument
/// Assuming that the `list_hack` feature is set
#[cfg(not(feature = "list_hack"))]
pub fn list<'a, T: Bind>(_: &'a [T]) -> std::convert::Infallible {
    panic!("The list_hack feature is not")
}