sqlx_core_guts/postgres/
statement.rs

1use super::{PgColumn, PgTypeInfo};
2use crate::column::ColumnIndex;
3use crate::error::Error;
4use crate::ext::ustr::UStr;
5use crate::postgres::{PgArguments, Postgres};
6use crate::statement::Statement;
7use crate::HashMap;
8use either::Either;
9use std::borrow::Cow;
10use std::sync::Arc;
11
12#[derive(Debug, Clone)]
13pub struct PgStatement<'q> {
14    pub(crate) sql: Cow<'q, str>,
15    pub(crate) metadata: Arc<PgStatementMetadata>,
16}
17
18#[derive(Debug, Default)]
19pub(crate) struct PgStatementMetadata {
20    pub(crate) columns: Vec<PgColumn>,
21    pub(crate) column_names: HashMap<UStr, usize>,
22    pub(crate) parameters: Vec<PgTypeInfo>,
23}
24
25impl<'q> Statement<'q> for PgStatement<'q> {
26    type Database = Postgres;
27
28    fn to_owned(&self) -> PgStatement<'static> {
29        PgStatement::<'static> {
30            sql: Cow::Owned(self.sql.clone().into_owned()),
31            metadata: self.metadata.clone(),
32        }
33    }
34
35    fn sql(&self) -> &str {
36        &self.sql
37    }
38
39    fn parameters(&self) -> Option<Either<&[PgTypeInfo], usize>> {
40        Some(Either::Left(&self.metadata.parameters))
41    }
42
43    fn columns(&self) -> &[PgColumn] {
44        &self.metadata.columns
45    }
46
47    impl_statement_query!(PgArguments);
48}
49
50impl ColumnIndex<PgStatement<'_>> for &'_ str {
51    fn index(&self, statement: &PgStatement<'_>) -> Result<usize, Error> {
52        statement
53            .metadata
54            .column_names
55            .get(*self)
56            .ok_or_else(|| Error::ColumnNotFound((*self).into()))
57            .map(|v| *v)
58    }
59}
60
61#[cfg(feature = "any")]
62impl<'q> From<PgStatement<'q>> for crate::any::AnyStatement<'q> {
63    #[inline]
64    fn from(statement: PgStatement<'q>) -> Self {
65        crate::any::AnyStatement::<'q> {
66            columns: statement
67                .metadata
68                .columns
69                .iter()
70                .map(|col| col.clone().into())
71                .collect(),
72            column_names: std::sync::Arc::new(statement.metadata.column_names.clone()),
73            parameters: Some(Either::Left(
74                statement
75                    .metadata
76                    .parameters
77                    .iter()
78                    .map(|ty| ty.clone().into())
79                    .collect(),
80            )),
81            sql: statement.sql,
82        }
83    }
84}