postro 0.1.1

Asynchronous Postgres Driver and Utility
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
//! Postgres row operation.
//!
//! - [`Row`]
//! - [`Column`]
//! - [`FromRow`]
//! - [`Decode`]
//!
//! - [`Index`]
//! - [`DecodeError`]
use bytes::{Buf, Bytes};
use std::{borrow::Cow, fmt, str::Utf8Error, string::FromUtf8Error};

use crate::{
    common::ByteStr,
    ext::{BytesExt, FmtExt},
    postgres::{Oid, PgType},
};

// <https://www.postgresql.org/docs/current/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-ROWDESCRIPTION>
// table_oid
// attribute_len
// oid
// data_type_size
// type_modifier
// format_code
const SUFFIX: usize = size_of::<u32>()
    + size_of::<u16>()
    + size_of::<u32>()
    + size_of::<i16>()
    + size_of::<i32>()
    + size_of::<u16>();

const OID_OFFSET: usize = size_of::<u32>() + size_of::<u16>();

/// Postgres row.
pub struct Row {
    field_len: u16,
    body: Bytes,
    values: Bytes,
}

impl Row {
    /// `RowDescription` message
    pub(crate) fn new(mut bytes: Bytes) -> Self {
        Self {
            field_len: bytes.get_u16(),
            body: bytes,
            values: Bytes::new(),
        }
    }

    /// `DataRow` message
    pub(crate) fn inner_clone(&self, mut bytes: Bytes) -> Row {
        assert_eq!(
            self.field_len, bytes.get_u16(),
            "RowDescription len missmatch with DataRow len"
        );
        Self {
            field_len: self.field_len,
            body: self.body.clone(),
            values: bytes,
        }
    }

    /// Returns `true` if row contains no columns.
    pub const fn is_empty(&self) -> bool {
        self.field_len == 0
    }

    /// Returns the number of fields/column.
    pub const fn len(&self) -> u16 {
        self.field_len
    }

    /// Try get and decode column.
    pub fn try_get<I: Index, R: Decode>(&self, idx: I) -> Result<R, DecodeError> {
        let (offset,nul,nth) = idx.position(&self.body, self.field_len)?;

        let name = ByteStr::from_utf8(self.body.slice(offset..nul))?;

        let mut i = 0;
        let mut values = self.values.clone();
        let value = loop {
            let len = values.get_u32();
            let value = values.split_to(len as _);
            if i == nth {
                break value;
            }
            i += 1;
        };

        R::decode(Column::new(name, &self.body[nul + 1..], value))
    }

    /// Try decode type using [`FromRow`] implementation.
    pub fn decode<D: FromRow>(self) -> Result<D, DecodeError> {
        D::from_row(self)
    }
}

impl IntoIterator for Row {
    type Item = Result<Column, DecodeError>;

    type IntoIter = IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            field_len: self.field_len,
            body: self.body,
            values: self.values,
            iter_n: 0,
        }
    }
}

/// [`IntoIterator`] implementation from [`Row`].
#[derive(Debug)]
pub struct IntoIter {
    field_len: u16,
    body: Bytes,
    values: Bytes,

    iter_n: u16,
}

impl IntoIter {
    /// Same as [`Iterator::next`] but returns [`Result`] instead.
    pub fn try_next(&mut self) -> Result<Column, DecodeError> {
        match self.next() {
            Some(ok) => ok,
            None => Err(DecodeError::IndexOutOfBounds(self.iter_n as _)),
        }
    }
}

impl Iterator for IntoIter {
    type Item = Result<Column, DecodeError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.iter_n == self.field_len {
            return None
        }

        let field_name = match self.body.get_nul_bytestr() {
            Ok(ok) => ok,
            Err(err) => {
                self.iter_n = self.field_len;
                return Some(Err(err.into()))
            },
        };
        let column = self.body.split_to(SUFFIX);
        let len = self.values.get_u32();
        let value = self.values.split_to(len as _);
        self.iter_n += 1;

        Some(Ok(Column::new(field_name, &column, value)))
    }
}

impl fmt::Debug for Row {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut dbg = f.debug_map();
        let mut b = self.body.clone();
        let mut v = self.values.clone();
        for _ in 0..self.field_len {
            let Ok(key) = b.get_nul_bytestr() else { break };
            b.advance(SUFFIX);
            let len = v.get_u32();
            let value = v.split_to(len as _);
            dbg.key(&key);
            dbg.value(&value.lossy());
        }
        dbg.finish()
    }
}

/// Postgres column.
#[derive(Debug, Clone)]
pub struct Column {
    oid: Oid,
    value: Bytes,
    name: ByteStr,
}

impl Column {
    /// `body` is start of data **after** field name
    fn new(name: ByteStr, body: &[u8], value: Bytes) -> Self {
        Self {
            name,
            oid: (&mut &body[OID_OFFSET..]).get_u32(),
            value
        }
    }

    /// Returns column [`Oid`].
    pub const fn oid(&self) -> Oid {
        self.oid
    }

    /// Returns column name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Extract the inner bytes as slice.
    pub fn as_slice(&self) -> &[u8] {
        &self.value
    }

    /// Clone the inner [`Bytes`].
    pub fn value(&self) -> Bytes {
        self.value.clone()
    }

    /// Consume self into the inner [`Bytes`].
    pub fn into_value(self) -> Bytes {
        self.value
    }

    /// Try decode type using [`Decode`] implementation.
    pub fn decode<D: Decode>(self) -> Result<D, DecodeError> {
        D::decode(self)
    }
}

/// Query result with its rows affected.
#[derive(Debug)]
pub struct RowResult {
    pub rows_affected: u64,
}

// ===== Traits =====

/// Type that can be constructed from a row.
pub trait FromRow: Sized {
    /// Construct self from row.
    fn from_row(row: Row) -> Result<Self, DecodeError>;
}

impl FromRow for Row {
    fn from_row(row: Row) -> Result<Self, DecodeError> {
        Ok(row)
    }
}

impl FromRow for () {
    fn from_row(_: Row) -> Result<Self, DecodeError> {
        Ok(())
    }
}

macro_rules! from_row_tuple {
    ($($t:ident $i:literal),*) => {
        impl<$($t),*> FromRow for ($($t),*,)
        where
            $($t: Decode),*
        {
            fn from_row(row: Row) -> Result<Self, DecodeError> {
                Ok((
                    $(row.try_get($i)?),*,
                ))
            }
        }
    };
}

from_row_tuple!(T0 0);
from_row_tuple!(T0 0, T1 1);
from_row_tuple!(T0 0, T1 1, T2 2);
from_row_tuple!(T0 0, T1 1, T2 2, T3 3);

/// A type that can be constructed from [`Column`].
pub trait Decode: Sized {
    /// Try decode self from column.
    fn decode(column: Column) -> Result<Self, DecodeError>;
}

impl Decode for Column {
    fn decode(column: Column) -> Result<Self, DecodeError> {
        Ok(column)
    }
}

impl Decode for () {
    fn decode(_: Column) -> Result<Self, DecodeError> {
        Ok(())
    }
}

impl Decode for i32 {
    fn decode(col: Column) -> Result<Self, DecodeError> {
        if col.oid() != Self::OID {
            return Err(DecodeError::OidMissmatch);
        }
        let mut be = [0u8;size_of::<Self>()];
        be.copy_from_slice(&col.as_slice()[..size_of::<Self>()]);
        Ok(i32::from_be_bytes(be))
    }
}

impl Decode for String {
    fn decode(col: Column) -> Result<Self, DecodeError> {
        if col.oid() != Self::OID {
            return Err(DecodeError::OidMissmatch);
        }
        Ok(String::from_utf8(col.into_value().into())?)
    }
}

/// Type that can be used for indexing column.
pub trait Index: Sized + sealed::Sealed {
    /// Returns (bytes start offset, nul string index, nth column).
    fn position(self, body: &[u8], len: u16) -> Result<(usize,usize,u16), DecodeError>;
}

macro_rules! position {
    (
        $self:pat, $body:ident, $len:ident,
        ($offset:ident,$i_nul:ident,$nth:ident) => $test:expr,
        () => $into:expr
    ) => {
        let mut iter = $body.iter().copied().enumerate();
        let mut $offset = 0;

        for $nth in 0..$len {
            let Some(($i_nul, _)) = iter.find(|(_, e)| matches!(e, b'\0')) else {
                break;
            };

            if $test {
                return Ok(($offset,$i_nul,$nth));
            }

            match iter.$nth(SUFFIX) {
                Some((i,_)) => {
                    $offset = i;
                },
                None => break,
            }
        }

        Err(DecodeError::ColumnNotFound($into))
    };
}

impl Index for usize {
    fn position(self, body: &[u8], len: u16) -> Result<(usize,usize,u16), DecodeError> {
        position! {
            self, body, len,
            (off,i_nul,nth) => self == nth as usize,
            () => String::from(itoa::Buffer::new().format(self)).into()
        }
    }
}

impl Index for &str {
    fn position(self, body: &[u8], len: u16) -> Result<(usize,usize,u16), DecodeError> {
        position! {
            self, body, len,
            (off,i_nul,nth) => self.as_bytes() == &body[off..i_nul],
            () => String::from(self).into()
        }
    }
}

mod sealed {
    pub trait Sealed { }
    impl Sealed for usize { }
    impl Sealed for &str { }
}

macro_rules! from {
    (<$ty:ty>$pat:pat => $body:expr) => {
        impl From<$ty> for DecodeError {
            fn from($pat: $ty) -> Self {
                $body
            }
        }
    };
}

/// An error when decoding row value.
pub enum DecodeError {
    /// Postgres return non utf8 string.
    Utf8(Utf8Error),
    /// Column requested not found.
    ColumnNotFound(Cow<'static,str>),
    /// Index requested is out of bounds.
    IndexOutOfBounds(usize),
    /// Oid requested missmatch.
    OidMissmatch,
    /// Failed to deserialize using `serde_json`.
    #[cfg(feature = "json")]
    Json(serde_json::error::Error),
    /// Failed to parse timestamp.
    #[cfg(feature = "time")]
    Time(time::error::Parse)
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("failed to decode value, ")?;
        match self {
            Self::Utf8(e) => write!(f, "{e}"),
            Self::ColumnNotFound(name) => write!(f, "column not found: {name:?}"),
            Self::IndexOutOfBounds(u) => write!(f, "index out of bounds: {u:?}"),
            Self::OidMissmatch => write!(f, "data type missmatch"),
            #[cfg(feature = "json")]
            Self::Json(e) => write!(f, "{e}"),
            #[cfg(feature = "time")]
            Self::Time(e) => write!(f, "{e}"),
        }
    }
}

from!(<Utf8Error>e => Self::Utf8(e));
from!(<FromUtf8Error>e => Self::Utf8(e.utf8_error()));
#[cfg(feature = "json")]
from!(<serde_json::error::Error>e => Self::Json(e));
#[cfg(feature = "time")]
from!(<time::error::Parse>e => Self::Time(e));

impl std::error::Error for DecodeError { }

impl fmt::Debug for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{self}\"")
    }
}