Skip to main content

tokio_postgres/
query.rs

1use crate::client::{InnerClient, Responses};
2use crate::codec::FrontendMessage;
3use crate::connection::RequestMessages;
4use crate::prepare::get_type;
5use crate::types::{BorrowToSql, IsNull};
6use crate::{Column, Error, Portal, Row, Statement};
7use bytes::{Bytes, BytesMut};
8use fallible_iterator::FallibleIterator;
9use futures_util::{ready, Stream};
10use log::{debug, log_enabled, Level};
11use pin_project_lite::pin_project;
12use postgres_protocol::message::backend::{CommandCompleteBody, Message};
13use postgres_protocol::message::frontend;
14use postgres_types::Type;
15use std::fmt;
16use std::io;
17use std::marker::PhantomPinned;
18use std::pin::Pin;
19use std::sync::Arc;
20use std::task::{Context, Poll};
21
22/// The format used to encode result column values in the PostgreSQL wire protocol.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum ResultFormat {
25    /// Text format — values are returned as UTF-8 strings,
26    /// the same format the pg Node.js library receives.
27    Text,
28    /// Binary format — values are returned in PostgreSQL's binary encoding.
29    /// This is more efficient but requires type-aware deserialization.
30    Binary,
31}
32
33impl ResultFormat {
34    fn format_code(self) -> i16 {
35        match self {
36            ResultFormat::Text => 0,
37            ResultFormat::Binary => 1,
38        }
39    }
40}
41
42/// The formats a query's result columns come back in: one for them all, or
43/// one per column. Cheap to clone, as every row of a query holds it.
44#[derive(Debug, Clone)]
45pub(crate) enum ResultFormats {
46    /// Every column in one format.
47    All(ResultFormat),
48    /// Each column in its own, in the order of the statement's columns.
49    Columns(Arc<[ResultFormat]>),
50}
51
52impl ResultFormats {
53    /// The format of column `idx`.
54    pub(crate) fn get(&self, idx: usize) -> ResultFormat {
55        match self {
56            ResultFormats::All(format) => *format,
57            ResultFormats::Columns(formats) => formats[idx],
58        }
59    }
60
61    /// The result format codes a Bind message carries: a single code applies
62    /// to every column, otherwise there is one per column.
63    fn codes(&self) -> impl ExactSizeIterator<Item = i16> + '_ {
64        let formats: &[ResultFormat] = match self {
65            ResultFormats::All(format) => std::slice::from_ref(format),
66            ResultFormats::Columns(formats) => formats,
67        };
68        formats.iter().map(|format| format.format_code())
69    }
70}
71
72impl From<ResultFormat> for ResultFormats {
73    fn from(format: ResultFormat) -> Self {
74        ResultFormats::All(format)
75    }
76}
77
78struct BorrowToSqlParamsDebug<'a, T>(&'a [T]);
79
80impl<T> fmt::Debug for BorrowToSqlParamsDebug<'_, T>
81where
82    T: BorrowToSql,
83{
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_list()
86            .entries(self.0.iter().map(|x| x.borrow_to_sql()))
87            .finish()
88    }
89}
90
91pub async fn query<P, I>(
92    client: &InnerClient,
93    statement: Statement,
94    params: I,
95) -> Result<RowStream, Error>
96where
97    P: BorrowToSql,
98    I: IntoIterator<Item = P>,
99    I::IntoIter: ExactSizeIterator,
100{
101    query_with_format(client, statement, params, ResultFormat::Binary).await
102}
103
104pub async fn query_with_format<P, I>(
105    client: &InnerClient,
106    statement: Statement,
107    params: I,
108    result_format: ResultFormat,
109) -> Result<RowStream, Error>
110where
111    P: BorrowToSql,
112    I: IntoIterator<Item = P>,
113    I::IntoIter: ExactSizeIterator,
114{
115    query_with_formats(client, statement, params, result_format.into()).await
116}
117
118/// Like [`query_with_format`], with each result column in its own format:
119/// `formats` has one per column of `statement`.
120pub async fn query_with_column_formats<P, I>(
121    client: &InnerClient,
122    statement: Statement,
123    params: I,
124    formats: &[ResultFormat],
125) -> Result<RowStream, Error>
126where
127    P: BorrowToSql,
128    I: IntoIterator<Item = P>,
129    I::IntoIter: ExactSizeIterator,
130{
131    let result_formats = column_formats(&statement, formats)?;
132    query_with_formats(client, statement, params, result_formats).await
133}
134
135/// `formats` for the columns of `statement`, which it must have one of each.
136fn column_formats(statement: &Statement, formats: &[ResultFormat]) -> Result<ResultFormats, Error> {
137    let columns = statement.columns().len();
138    if formats.len() != columns {
139        return Err(Error::encode(io::Error::new(
140            io::ErrorKind::InvalidInput,
141            format!(
142                "{} result formats given for a statement of {columns} columns",
143                formats.len()
144            ),
145        )));
146    }
147    Ok(ResultFormats::Columns(formats.into()))
148}
149
150async fn query_with_formats<P, I>(
151    client: &InnerClient,
152    statement: Statement,
153    params: I,
154    result_formats: ResultFormats,
155) -> Result<RowStream, Error>
156where
157    P: BorrowToSql,
158    I: IntoIterator<Item = P>,
159    I::IntoIter: ExactSizeIterator,
160{
161    let buf = if log_enabled!(Level::Debug) {
162        let params = params.into_iter().collect::<Vec<_>>();
163        debug!(
164            "executing statement {} with parameters: {:?}",
165            statement.name(),
166            BorrowToSqlParamsDebug(params.as_slice()),
167        );
168        encode_with_formats(client, &statement, params, &result_formats)?
169    } else {
170        encode_with_formats(client, &statement, params, &result_formats)?
171    };
172    let responses = start(client, buf).await?;
173    Ok(RowStream {
174        statement,
175        responses,
176        result_formats,
177        rows_affected: None,
178        command_tag: None,
179        _p: PhantomPinned,
180    })
181}
182
183pub async fn query_typed<P, I>(
184    client: &Arc<InnerClient>,
185    query: &str,
186    params: I,
187) -> Result<RowStream, Error>
188where
189    P: BorrowToSql,
190    I: IntoIterator<Item = (P, Type)>,
191{
192    let buf = {
193        let params = params.into_iter().collect::<Vec<_>>();
194        let param_oids = params.iter().map(|(_, t)| t.oid()).collect::<Vec<_>>();
195
196        client.with_buf(|buf| {
197            frontend::parse("", query, param_oids, buf).map_err(Error::parse)?;
198            encode_bind_raw("", params, "", &ResultFormat::Binary.into(), buf)?;
199            frontend::describe(b'S', "", buf).map_err(Error::encode)?;
200            frontend::execute("", 0, buf).map_err(Error::encode)?;
201            frontend::sync(buf);
202
203            Ok(buf.split().freeze())
204        })?
205    };
206
207    let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
208
209    loop {
210        match responses.next().await? {
211            Message::ParseComplete | Message::BindComplete | Message::ParameterDescription(_) => {}
212            Message::NoData => {
213                return Ok(RowStream {
214                    statement: Statement::unnamed(vec![], vec![]),
215                    responses,
216                    result_formats: ResultFormat::Binary.into(),
217                    rows_affected: None,
218                    command_tag: None,
219                    _p: PhantomPinned,
220                });
221            }
222            Message::RowDescription(row_description) => {
223                let mut columns: Vec<Column> = vec![];
224                let mut it = row_description.fields();
225                while let Some(field) = it.next().map_err(Error::parse)? {
226                    let type_ = get_type(client, field.type_oid()).await?;
227                    let column = Column {
228                        name: field.name().to_string(),
229                        table_oid: Some(field.table_oid()).filter(|n| *n != 0),
230                        column_id: Some(field.column_id()).filter(|n| *n != 0),
231                        r#type: type_,
232                    };
233                    columns.push(column);
234                }
235                return Ok(RowStream {
236                    statement: Statement::unnamed(vec![], columns),
237                    responses,
238                    result_formats: ResultFormat::Binary.into(),
239                    rows_affected: None,
240                    command_tag: None,
241                    _p: PhantomPinned,
242                });
243            }
244            _ => return Err(Error::unexpected_message()),
245        }
246    }
247}
248
249pub async fn query_portal(
250    client: &InnerClient,
251    portal: &Portal,
252    max_rows: i32,
253) -> Result<RowStream, Error> {
254    let buf = client.with_buf(|buf| {
255        frontend::execute(portal.name(), max_rows, buf).map_err(Error::encode)?;
256        frontend::sync(buf);
257        Ok(buf.split().freeze())
258    })?;
259
260    let responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
261
262    Ok(RowStream {
263        statement: portal.statement().clone(),
264        responses,
265        result_formats: ResultFormat::Binary.into(),
266        rows_affected: None,
267        command_tag: None,
268        _p: PhantomPinned,
269    })
270}
271
272/// Extract the number of rows affected from [`CommandCompleteBody`].
273pub fn extract_row_affected(body: &CommandCompleteBody) -> Result<u64, Error> {
274    let rows = body
275        .tag()
276        .map_err(Error::parse)?
277        .rsplit(' ')
278        .next()
279        .unwrap()
280        .parse()
281        .unwrap_or(0);
282    Ok(rows)
283}
284
285pub async fn execute<P, I>(
286    client: &InnerClient,
287    statement: Statement,
288    params: I,
289) -> Result<u64, Error>
290where
291    P: BorrowToSql,
292    I: IntoIterator<Item = P>,
293    I::IntoIter: ExactSizeIterator,
294{
295    let buf = if log_enabled!(Level::Debug) {
296        let params = params.into_iter().collect::<Vec<_>>();
297        debug!(
298            "executing statement {} with parameters: {:?}",
299            statement.name(),
300            BorrowToSqlParamsDebug(params.as_slice()),
301        );
302        encode(client, &statement, params, ResultFormat::Binary)?
303    } else {
304        encode(client, &statement, params, ResultFormat::Binary)?
305    };
306    let mut responses = start(client, buf).await?;
307
308    let mut rows = 0;
309    loop {
310        match responses.next().await? {
311            Message::DataRow(_) => {}
312            Message::CommandComplete(body) => {
313                rows = extract_row_affected(&body)?;
314            }
315            Message::EmptyQueryResponse => rows = 0,
316            Message::ReadyForQuery(_) => return Ok(rows),
317            _ => return Err(Error::unexpected_message()),
318        }
319    }
320}
321
322async fn start(client: &InnerClient, buf: Bytes) -> Result<Responses, Error> {
323    let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;
324
325    match responses.next().await? {
326        Message::BindComplete => {}
327        _ => return Err(Error::unexpected_message()),
328    }
329
330    Ok(responses)
331}
332
333pub fn encode<P, I>(
334    client: &InnerClient,
335    statement: &Statement,
336    params: I,
337    result_format: ResultFormat,
338) -> Result<Bytes, Error>
339where
340    P: BorrowToSql,
341    I: IntoIterator<Item = P>,
342    I::IntoIter: ExactSizeIterator,
343{
344    encode_with_formats(client, statement, params, &result_format.into())
345}
346
347fn encode_with_formats<P, I>(
348    client: &InnerClient,
349    statement: &Statement,
350    params: I,
351    result_formats: &ResultFormats,
352) -> Result<Bytes, Error>
353where
354    P: BorrowToSql,
355    I: IntoIterator<Item = P>,
356    I::IntoIter: ExactSizeIterator,
357{
358    client.with_buf(|buf| {
359        encode_bind_with_formats(statement, params, "", result_formats, buf)?;
360        frontend::execute("", 0, buf).map_err(Error::encode)?;
361        frontend::sync(buf);
362        Ok(buf.split().freeze())
363    })
364}
365
366pub fn encode_bind<P, I>(
367    statement: &Statement,
368    params: I,
369    portal: &str,
370    result_format: ResultFormat,
371    buf: &mut BytesMut,
372) -> Result<(), Error>
373where
374    P: BorrowToSql,
375    I: IntoIterator<Item = P>,
376    I::IntoIter: ExactSizeIterator,
377{
378    encode_bind_with_formats(statement, params, portal, &result_format.into(), buf)
379}
380
381fn encode_bind_with_formats<P, I>(
382    statement: &Statement,
383    params: I,
384    portal: &str,
385    result_formats: &ResultFormats,
386    buf: &mut BytesMut,
387) -> Result<(), Error>
388where
389    P: BorrowToSql,
390    I: IntoIterator<Item = P>,
391    I::IntoIter: ExactSizeIterator,
392{
393    let params = params.into_iter();
394    if params.len() != statement.params().len() {
395        return Err(Error::parameters(params.len(), statement.params().len()));
396    }
397
398    encode_bind_raw(
399        statement.name(),
400        params.zip(statement.params().iter().cloned()),
401        portal,
402        result_formats,
403        buf,
404    )
405}
406
407fn encode_bind_raw<P, I>(
408    statement_name: &str,
409    params: I,
410    portal: &str,
411    result_formats: &ResultFormats,
412    buf: &mut BytesMut,
413) -> Result<(), Error>
414where
415    P: BorrowToSql,
416    I: IntoIterator<Item = (P, Type)>,
417    I::IntoIter: ExactSizeIterator,
418{
419    let (param_formats, params): (Vec<_>, Vec<_>) = params
420        .into_iter()
421        .map(|(p, ty)| (p.borrow_to_sql().encode_format(&ty) as i16, (p, ty)))
422        .unzip();
423
424    let mut error_idx = 0;
425    let r = frontend::bind(
426        portal,
427        statement_name,
428        param_formats,
429        params.into_iter().enumerate(),
430        |(idx, (param, ty)), buf| match param.borrow_to_sql().to_sql_checked(&ty, buf) {
431            Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),
432            Ok(IsNull::Yes) => Ok(postgres_protocol::IsNull::Yes),
433            Err(e) => {
434                error_idx = idx;
435                Err(e)
436            }
437        },
438        result_formats.codes(),
439        buf,
440    );
441    match r {
442        Ok(()) => Ok(()),
443        Err(frontend::BindError::Conversion(e)) => Err(Error::to_sql(e, error_idx)),
444        Err(frontend::BindError::Serialization(e)) => Err(Error::encode(e)),
445    }
446}
447
448pin_project! {
449    /// A stream of table rows.
450    pub struct RowStream {
451        statement: Statement,
452        responses: Responses,
453        result_formats: ResultFormats,
454        rows_affected: Option<u64>,
455        command_tag: Option<String>,
456        #[pin]
457        _p: PhantomPinned,
458    }
459}
460
461impl Stream for RowStream {
462    type Item = Result<Row, Error>;
463
464    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
465        let this = self.project();
466        loop {
467            match ready!(this.responses.poll_next(cx)?) {
468                Message::DataRow(body) => {
469                    return Poll::Ready(Some(Ok(Row::new(
470                        this.statement.clone(),
471                        this.result_formats.clone(),
472                        body,
473                    )?)))
474                }
475                Message::CommandComplete(body) => {
476                    *this.rows_affected = Some(extract_row_affected(&body)?);
477                    *this.command_tag = extract_command_tag(&body).ok();
478                }
479                Message::EmptyQueryResponse | Message::PortalSuspended => {}
480                Message::ReadyForQuery(_) => return Poll::Ready(None),
481                _ => return Poll::Ready(Some(Err(Error::unexpected_message()))),
482            }
483        }
484    }
485}
486
487/// Extract the command name (e.g. "SELECT", "INSERT") from a command complete tag.
488fn extract_command_tag(body: &CommandCompleteBody) -> Result<String, Error> {
489    let tag = body.tag().map_err(Error::parse)?;
490    // Tags look like "SELECT 5", "INSERT 0 1", "UPDATE 3", "DELETE 2", "CREATE TABLE"
491    // The command is everything before the last space-separated number(s).
492    Ok(tag
493        .split(' ')
494        .take_while(|part| part.parse::<u64>().is_err())
495        .collect::<Vec<_>>()
496        .join(" "))
497}
498
499impl RowStream {
500    /// Returns information about the columns of data in the rows.
501    pub fn columns(&self) -> &[Column] {
502        self.statement.columns()
503    }
504
505    /// Returns the number of rows affected by the query.
506    ///
507    /// This function will return `None` until the stream has been exhausted.
508    pub fn rows_affected(&self) -> Option<u64> {
509        self.rows_affected
510    }
511
512    /// Returns the command tag from the query (e.g. "SELECT", "INSERT", "UPDATE").
513    ///
514    /// This function will return `None` until the stream has been exhausted.
515    pub fn command_tag(&self) -> Option<&str> {
516        self.command_tag.as_deref()
517    }
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523    use postgres_protocol::message::backend::Message;
524
525    fn column(name: &str, ty: Type) -> Column {
526        Column {
527            name: name.to_string(),
528            table_oid: None,
529            column_id: None,
530            r#type: ty,
531        }
532    }
533
534    /// A statement of three columns and one `int4` parameter.
535    fn statement() -> Statement {
536        Statement::unnamed(
537            vec![Type::INT4],
538            vec![
539                column("a", Type::INT4),
540                column("b", Type::INTERVAL),
541                column("c", Type::TEXT),
542            ],
543        )
544    }
545
546    /// The result format codes at the end of a Bind message.
547    fn result_codes(bind: &[u8]) -> Vec<i16> {
548        let mut bind = bind;
549        assert_eq!(bind[0], b'B');
550        bind = &bind[5..];
551        // Portal and statement names.
552        for _ in 0..2 {
553            let end = bind.iter().position(|b| *b == 0).unwrap();
554            bind = &bind[end + 1..];
555        }
556        let read_i16 = |b: &mut &[u8]| {
557            let v = i16::from_be_bytes([b[0], b[1]]);
558            *b = &b[2..];
559            v
560        };
561        let param_formats = read_i16(&mut bind);
562        bind = &bind[2 * param_formats as usize..];
563        let params = read_i16(&mut bind);
564        for _ in 0..params {
565            let len = i32::from_be_bytes([bind[0], bind[1], bind[2], bind[3]]);
566            bind = &bind[4 + len.max(0) as usize..];
567        }
568        let count = read_i16(&mut bind);
569        let codes = (0..count).map(|_| read_i16(&mut bind)).collect();
570        assert!(bind.is_empty(), "trailing bytes: {:?}", bind);
571        codes
572    }
573
574    fn bind(formats: &ResultFormats) -> BytesMut {
575        let mut buf = BytesMut::new();
576        encode_bind_with_formats(
577            &statement(),
578            [&7i32 as &dyn crate::types::ToSql],
579            "",
580            formats,
581            &mut buf,
582        )
583        .unwrap();
584        buf
585    }
586
587    #[test]
588    fn one_format_for_every_column_is_a_single_code() {
589        assert_eq!(result_codes(&bind(&ResultFormat::Binary.into())), [1]);
590        assert_eq!(result_codes(&bind(&ResultFormat::Text.into())), [0]);
591    }
592
593    #[test]
594    fn a_query_with_one_format_binds_as_it_did() {
595        let mut want = BytesMut::new();
596        encode_bind(
597            &statement(),
598            [&7i32 as &dyn crate::types::ToSql],
599            "",
600            ResultFormat::Binary,
601            &mut want,
602        )
603        .unwrap();
604        assert_eq!(bind(&ResultFormat::Binary.into()), want);
605    }
606
607    #[test]
608    fn per_column_formats_are_a_code_each() {
609        use ResultFormat::{Binary, Text};
610        let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
611        assert_eq!(result_codes(&bind(&formats)), [1, 0, 1]);
612        assert_eq!(
613            (0..3).map(|i| formats.get(i)).collect::<Vec<_>>(),
614            [Binary, Text, Binary]
615        );
616    }
617
618    #[test]
619    fn per_column_formats_must_match_the_columns() {
620        use ResultFormat::{Binary, Text};
621        for formats in [
622            &[][..],
623            &[Binary, Text][..],
624            &[Binary, Text, Text, Binary][..],
625        ] {
626            let err = column_formats(&statement(), formats).unwrap_err();
627            assert!(
628                err.to_string()
629                    .contains("result formats given for a statement of 3 columns"),
630                "{}",
631                err
632            );
633        }
634    }
635
636    #[test]
637    fn a_row_tells_each_columns_format() {
638        use ResultFormat::{Binary, Text};
639        // A DataRow of three values: an int4, an interval's text, and a NULL.
640        let mut msg = BytesMut::new();
641        let mut body = Vec::new();
642        body.extend_from_slice(&3i16.to_be_bytes());
643        body.extend_from_slice(&4i32.to_be_bytes());
644        body.extend_from_slice(&7i32.to_be_bytes());
645        body.extend_from_slice(&5i32.to_be_bytes());
646        body.extend_from_slice(b"1 day");
647        body.extend_from_slice(&(-1i32).to_be_bytes());
648        msg.extend_from_slice(b"D");
649        msg.extend_from_slice(&(4 + body.len() as i32).to_be_bytes());
650        msg.extend_from_slice(&body);
651        let Some(Message::DataRow(body)) = Message::parse(&mut msg).unwrap() else {
652            panic!("not a data row");
653        };
654        let formats = column_formats(&statement(), &[Binary, Text, Binary]).unwrap();
655        let row = Row::new(statement(), formats, body).unwrap();
656        assert_eq!(row.format(0), Binary);
657        assert_eq!(row.get::<_, i32>(0), 7);
658        assert_eq!(row.format(1), Text);
659        assert_eq!(row.col_buffer(1), Some(&b"1 day"[..]));
660        assert_eq!(row.col_buffer(2), None);
661    }
662}