encore-tokio-postgres 2.0.0-beta.13

A native, asynchronous PostgreSQL client
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
use crate::client::{InnerClient, Responses};
use crate::codec::FrontendMessage;
use crate::connection::RequestMessages;
use crate::prepare::get_type;
use crate::types::{BorrowToSql, IsNull};
use crate::{Column, Error, Portal, Row, Statement};
use bytes::{Bytes, BytesMut};
use fallible_iterator::FallibleIterator;
use futures_util::{ready, Stream};
use log::{debug, log_enabled, Level};
use pin_project_lite::pin_project;
use postgres_protocol::message::backend::{CommandCompleteBody, Message};
use postgres_protocol::message::frontend;
use postgres_types::Type;
use std::fmt;
use std::io;
use std::marker::PhantomPinned;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

/// The format used to encode result column values in the PostgreSQL wire protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResultFormat {
    /// Text format — values are returned as UTF-8 strings,
    /// the same format the pg Node.js library receives.
    Text,
    /// Binary format — values are returned in PostgreSQL's binary encoding.
    /// This is more efficient but requires type-aware deserialization.
    Binary,
}

impl ResultFormat {
    fn format_code(self) -> i16 {
        match self {
            ResultFormat::Text => 0,
            ResultFormat::Binary => 1,
        }
    }
}

/// The formats a query's result columns come back in: one for them all, or
/// one per column. Cheap to clone, as every row of a query holds it.
#[derive(Debug, Clone)]
pub(crate) enum ResultFormats {
    /// Every column in one format.
    All(ResultFormat),
    /// Each column in its own, in the order of the statement's columns.
    Columns(Arc<[ResultFormat]>),
}

impl ResultFormats {
    /// The format of column `idx`.
    pub(crate) fn get(&self, idx: usize) -> ResultFormat {
        match self {
            ResultFormats::All(format) => *format,
            ResultFormats::Columns(formats) => formats[idx],
        }
    }

    /// The result format codes a Bind message carries: a single code applies
    /// to every column, otherwise there is one per column.
    fn codes(&self) -> impl ExactSizeIterator<Item = i16> + '_ {
        let formats: &[ResultFormat] = match self {
            ResultFormats::All(format) => std::slice::from_ref(format),
            ResultFormats::Columns(formats) => formats,
        };
        formats.iter().map(|format| format.format_code())
    }
}

impl From<ResultFormat> for ResultFormats {
    fn from(format: ResultFormat) -> Self {
        ResultFormats::All(format)
    }
}

struct BorrowToSqlParamsDebug<'a, T>(&'a [T]);

impl<T> fmt::Debug for BorrowToSqlParamsDebug<'_, T>
where
    T: BorrowToSql,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.0.iter().map(|x| x.borrow_to_sql()))
            .finish()
    }
}

pub async fn query<P, I>(
    client: &InnerClient,
    statement: Statement,
    params: I,
) -> Result<RowStream, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    query_with_format(client, statement, params, ResultFormat::Binary).await
}

pub async fn query_with_format<P, I>(
    client: &InnerClient,
    statement: Statement,
    params: I,
    result_format: ResultFormat,
) -> Result<RowStream, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    query_with_formats(client, statement, params, result_format.into()).await
}

/// Like [`query_with_format`], with each result column in its own format:
/// `formats` has one per column of `statement`.
pub async fn query_with_column_formats<P, I>(
    client: &InnerClient,
    statement: Statement,
    params: I,
    formats: &[ResultFormat],
) -> Result<RowStream, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    let result_formats = column_formats(&statement, formats)?;
    query_with_formats(client, statement, params, result_formats).await
}

/// `formats` for the columns of `statement`, which it must have one of each.
fn column_formats(statement: &Statement, formats: &[ResultFormat]) -> Result<ResultFormats, Error> {
    let columns = statement.columns().len();
    if formats.len() != columns {
        return Err(Error::encode(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "{} result formats given for a statement of {columns} columns",
                formats.len()
            ),
        )));
    }
    Ok(ResultFormats::Columns(formats.into()))
}

async fn query_with_formats<P, I>(
    client: &InnerClient,
    statement: Statement,
    params: I,
    result_formats: ResultFormats,
) -> Result<RowStream, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    let buf = if log_enabled!(Level::Debug) {
        let params = params.into_iter().collect::<Vec<_>>();
        debug!(
            "executing statement {} with parameters: {:?}",
            statement.name(),
            BorrowToSqlParamsDebug(params.as_slice()),
        );
        encode_with_formats(client, &statement, params, &result_formats)?
    } else {
        encode_with_formats(client, &statement, params, &result_formats)?
    };
    let responses = start(client, buf).await?;
    Ok(RowStream {
        statement,
        responses,
        result_formats,
        rows_affected: None,
        command_tag: None,
        _p: PhantomPinned,
    })
}

pub async fn query_typed<P, I>(
    client: &Arc<InnerClient>,
    query: &str,
    params: I,
) -> Result<RowStream, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = (P, Type)>,
{
    let buf = {
        let params = params.into_iter().collect::<Vec<_>>();
        let param_oids = params.iter().map(|(_, t)| t.oid()).collect::<Vec<_>>();

        client.with_buf(|buf| {
            frontend::parse("", query, param_oids, buf).map_err(Error::parse)?;
            encode_bind_raw("", params, "", &ResultFormat::Binary.into(), buf)?;
            frontend::describe(b'S', "", buf).map_err(Error::encode)?;
            frontend::execute("", 0, buf).map_err(Error::encode)?;
            frontend::sync(buf);

            Ok(buf.split().freeze())
        })?
    };

    let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;

    loop {
        match responses.next().await? {
            Message::ParseComplete | Message::BindComplete | Message::ParameterDescription(_) => {}
            Message::NoData => {
                return Ok(RowStream {
                    statement: Statement::unnamed(vec![], vec![]),
                    responses,
                    result_formats: ResultFormat::Binary.into(),
                    rows_affected: None,
                    command_tag: None,
                    _p: PhantomPinned,
                });
            }
            Message::RowDescription(row_description) => {
                let mut columns: Vec<Column> = vec![];
                let mut it = row_description.fields();
                while let Some(field) = it.next().map_err(Error::parse)? {
                    let type_ = get_type(client, field.type_oid()).await?;
                    let column = Column {
                        name: field.name().to_string(),
                        table_oid: Some(field.table_oid()).filter(|n| *n != 0),
                        column_id: Some(field.column_id()).filter(|n| *n != 0),
                        r#type: type_,
                    };
                    columns.push(column);
                }
                return Ok(RowStream {
                    statement: Statement::unnamed(vec![], columns),
                    responses,
                    result_formats: ResultFormat::Binary.into(),
                    rows_affected: None,
                    command_tag: None,
                    _p: PhantomPinned,
                });
            }
            _ => return Err(Error::unexpected_message()),
        }
    }
}

pub async fn query_portal(
    client: &InnerClient,
    portal: &Portal,
    max_rows: i32,
) -> Result<RowStream, Error> {
    let buf = client.with_buf(|buf| {
        frontend::execute(portal.name(), max_rows, buf).map_err(Error::encode)?;
        frontend::sync(buf);
        Ok(buf.split().freeze())
    })?;

    let responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;

    Ok(RowStream {
        statement: portal.statement().clone(),
        responses,
        result_formats: ResultFormat::Binary.into(),
        rows_affected: None,
        command_tag: None,
        _p: PhantomPinned,
    })
}

/// Extract the number of rows affected from [`CommandCompleteBody`].
pub fn extract_row_affected(body: &CommandCompleteBody) -> Result<u64, Error> {
    let rows = body
        .tag()
        .map_err(Error::parse)?
        .rsplit(' ')
        .next()
        .unwrap()
        .parse()
        .unwrap_or(0);
    Ok(rows)
}

pub async fn execute<P, I>(
    client: &InnerClient,
    statement: Statement,
    params: I,
) -> Result<u64, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    let buf = if log_enabled!(Level::Debug) {
        let params = params.into_iter().collect::<Vec<_>>();
        debug!(
            "executing statement {} with parameters: {:?}",
            statement.name(),
            BorrowToSqlParamsDebug(params.as_slice()),
        );
        encode(client, &statement, params, ResultFormat::Binary)?
    } else {
        encode(client, &statement, params, ResultFormat::Binary)?
    };
    let mut responses = start(client, buf).await?;

    let mut rows = 0;
    loop {
        match responses.next().await? {
            Message::DataRow(_) => {}
            Message::CommandComplete(body) => {
                rows = extract_row_affected(&body)?;
            }
            Message::EmptyQueryResponse => rows = 0,
            Message::ReadyForQuery(_) => return Ok(rows),
            _ => return Err(Error::unexpected_message()),
        }
    }
}

async fn start(client: &InnerClient, buf: Bytes) -> Result<Responses, Error> {
    let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;

    match responses.next().await? {
        Message::BindComplete => {}
        _ => return Err(Error::unexpected_message()),
    }

    Ok(responses)
}

pub fn encode<P, I>(
    client: &InnerClient,
    statement: &Statement,
    params: I,
    result_format: ResultFormat,
) -> Result<Bytes, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    encode_with_formats(client, statement, params, &result_format.into())
}

fn encode_with_formats<P, I>(
    client: &InnerClient,
    statement: &Statement,
    params: I,
    result_formats: &ResultFormats,
) -> Result<Bytes, Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    client.with_buf(|buf| {
        encode_bind_with_formats(statement, params, "", result_formats, buf)?;
        frontend::execute("", 0, buf).map_err(Error::encode)?;
        frontend::sync(buf);
        Ok(buf.split().freeze())
    })
}

pub fn encode_bind<P, I>(
    statement: &Statement,
    params: I,
    portal: &str,
    result_format: ResultFormat,
    buf: &mut BytesMut,
) -> Result<(), Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    encode_bind_with_formats(statement, params, portal, &result_format.into(), buf)
}

fn encode_bind_with_formats<P, I>(
    statement: &Statement,
    params: I,
    portal: &str,
    result_formats: &ResultFormats,
    buf: &mut BytesMut,
) -> Result<(), Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = P>,
    I::IntoIter: ExactSizeIterator,
{
    let params = params.into_iter();
    if params.len() != statement.params().len() {
        return Err(Error::parameters(params.len(), statement.params().len()));
    }

    encode_bind_raw(
        statement.name(),
        params.zip(statement.params().iter().cloned()),
        portal,
        result_formats,
        buf,
    )
}

fn encode_bind_raw<P, I>(
    statement_name: &str,
    params: I,
    portal: &str,
    result_formats: &ResultFormats,
    buf: &mut BytesMut,
) -> Result<(), Error>
where
    P: BorrowToSql,
    I: IntoIterator<Item = (P, Type)>,
    I::IntoIter: ExactSizeIterator,
{
    let (param_formats, params): (Vec<_>, Vec<_>) = params
        .into_iter()
        .map(|(p, ty)| (p.borrow_to_sql().encode_format(&ty) as i16, (p, ty)))
        .unzip();

    let mut error_idx = 0;
    let r = frontend::bind(
        portal,
        statement_name,
        param_formats,
        params.into_iter().enumerate(),
        |(idx, (param, ty)), buf| match param.borrow_to_sql().to_sql_checked(&ty, buf) {
            Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),
            Ok(IsNull::Yes) => Ok(postgres_protocol::IsNull::Yes),
            Err(e) => {
                error_idx = idx;
                Err(e)
            }
        },
        result_formats.codes(),
        buf,
    );
    match r {
        Ok(()) => Ok(()),
        Err(frontend::BindError::Conversion(e)) => Err(Error::to_sql(e, error_idx)),
        Err(frontend::BindError::Serialization(e)) => Err(Error::encode(e)),
    }
}

pin_project! {
    /// A stream of table rows.
    pub struct RowStream {
        statement: Statement,
        responses: Responses,
        result_formats: ResultFormats,
        rows_affected: Option<u64>,
        command_tag: Option<String>,
        #[pin]
        _p: PhantomPinned,
    }
}

impl Stream for RowStream {
    type Item = Result<Row, Error>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.project();
        loop {
            match ready!(this.responses.poll_next(cx)?) {
                Message::DataRow(body) => {
                    return Poll::Ready(Some(Ok(Row::new(
                        this.statement.clone(),
                        this.result_formats.clone(),
                        body,
                    )?)))
                }
                Message::CommandComplete(body) => {
                    *this.rows_affected = Some(extract_row_affected(&body)?);
                    *this.command_tag = extract_command_tag(&body).ok();
                }
                Message::EmptyQueryResponse | Message::PortalSuspended => {}
                Message::ReadyForQuery(_) => return Poll::Ready(None),
                _ => return Poll::Ready(Some(Err(Error::unexpected_message()))),
            }
        }
    }
}

/// Extract the command name (e.g. "SELECT", "INSERT") from a command complete tag.
fn extract_command_tag(body: &CommandCompleteBody) -> Result<String, Error> {
    let tag = body.tag().map_err(Error::parse)?;
    // Tags look like "SELECT 5", "INSERT 0 1", "UPDATE 3", "DELETE 2", "CREATE TABLE"
    // The command is everything before the last space-separated number(s).
    Ok(tag
        .split(' ')
        .take_while(|part| part.parse::<u64>().is_err())
        .collect::<Vec<_>>()
        .join(" "))
}

impl RowStream {
    /// Returns information about the columns of data in the rows.
    pub fn columns(&self) -> &[Column] {
        self.statement.columns()
    }

    /// Returns the number of rows affected by the query.
    ///
    /// This function will return `None` until the stream has been exhausted.
    pub fn rows_affected(&self) -> Option<u64> {
        self.rows_affected
    }

    /// Returns the command tag from the query (e.g. "SELECT", "INSERT", "UPDATE").
    ///
    /// This function will return `None` until the stream has been exhausted.
    pub fn command_tag(&self) -> Option<&str> {
        self.command_tag.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use postgres_protocol::message::backend::Message;

    fn column(name: &str, ty: Type) -> Column {
        Column {
            name: name.to_string(),
            table_oid: None,
            column_id: None,
            r#type: ty,
        }
    }

    /// A statement of three columns and one `int4` parameter.
    fn statement() -> Statement {
        Statement::unnamed(
            vec![Type::INT4],
            vec![
                column("a", Type::INT4),
                column("b", Type::INTERVAL),
                column("c", Type::TEXT),
            ],
        )
    }

    /// The result format codes at the end of a Bind message.
    fn result_codes(bind: &[u8]) -> Vec<i16> {
        let mut bind = bind;
        assert_eq!(bind[0], b'B');
        bind = &bind[5..];
        // Portal and statement names.
        for _ in 0..2 {
            let end = bind.iter().position(|b| *b == 0).unwrap();
            bind = &bind[end + 1..];
        }
        let read_i16 = |b: &mut &[u8]| {
            let v = i16::from_be_bytes([b[0], b[1]]);
            *b = &b[2..];
            v
        };
        let param_formats = read_i16(&mut bind);
        bind = &bind[2 * param_formats as usize..];
        let params = read_i16(&mut bind);
        for _ in 0..params {
            let len = i32::from_be_bytes([bind[0], bind[1], bind[2], bind[3]]);
            bind = &bind[4 + len.max(0) as usize..];
        }
        let count = read_i16(&mut bind);
        let codes = (0..count).map(|_| read_i16(&mut bind)).collect();
        assert!(bind.is_empty(), "trailing bytes: {:?}", bind);
        codes
    }

    fn bind(formats: &ResultFormats) -> BytesMut {
        let mut buf = BytesMut::new();
        encode_bind_with_formats(
            &statement(),
            [&7i32 as &dyn crate::types::ToSql],
            "",
            formats,
            &mut buf,
        )
        .unwrap();
        buf
    }

    #[test]
    fn one_format_for_every_column_is_a_single_code() {
        assert_eq!(result_codes(&bind(&ResultFormat::Binary.into())), [1]);
        assert_eq!(result_codes(&bind(&ResultFormat::Text.into())), [0]);
    }

    #[test]
    fn a_query_with_one_format_binds_as_it_did() {
        let mut want = BytesMut::new();
        encode_bind(
            &statement(),
            [&7i32 as &dyn crate::types::ToSql],
            "",
            ResultFormat::Binary,
            &mut want,
        )
        .unwrap();
        assert_eq!(bind(&ResultFormat::Binary.into()), want);
    }

    #[test]
    fn per_column_formats_are_a_code_each() {
        use ResultFormat::{Binary, Text};
        let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
        assert_eq!(result_codes(&bind(&formats)), [1, 0, 1]);
        assert_eq!(
            (0..3).map(|i| formats.get(i)).collect::<Vec<_>>(),
            [Binary, Text, Binary]
        );
    }

    #[test]
    fn per_column_formats_must_match_the_columns() {
        use ResultFormat::{Binary, Text};
        for formats in [
            &[][..],
            &[Binary, Text][..],
            &[Binary, Text, Text, Binary][..],
        ] {
            let err = column_formats(&statement(), formats).unwrap_err();
            assert!(
                err.to_string()
                    .contains("result formats given for a statement of 3 columns"),
                "{}",
                err
            );
        }
    }

    #[test]
    fn a_row_tells_each_columns_format() {
        use ResultFormat::{Binary, Text};
        // A DataRow of three values: an int4, an interval's text, and a NULL.
        let mut msg = BytesMut::new();
        let mut body = Vec::new();
        body.extend_from_slice(&3i16.to_be_bytes());
        body.extend_from_slice(&4i32.to_be_bytes());
        body.extend_from_slice(&7i32.to_be_bytes());
        body.extend_from_slice(&5i32.to_be_bytes());
        body.extend_from_slice(b"1 day");
        body.extend_from_slice(&(-1i32).to_be_bytes());
        msg.extend_from_slice(b"D");
        msg.extend_from_slice(&(4 + body.len() as i32).to_be_bytes());
        msg.extend_from_slice(&body);
        let Some(Message::DataRow(body)) = Message::parse(&mut msg).unwrap() else {
            panic!("not a data row");
        };
        let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
        let row = Row::new(statement(), formats, body).unwrap();
        assert_eq!(row.format(0), Binary);
        assert_eq!(row.get::<_, i32>(0), 7);
        assert_eq!(row.format(1), Text);
        assert_eq!(row.col_buffer(1), Some(&b"1 day"[..]));
        assert_eq!(row.col_buffer(2), None);
    }
}