Skip to main content

tank_postgres/
prepared.rs

1use crate::{ValueWrap, util::postgres_type_to_value};
2use anyhow::anyhow;
3use std::{
4    borrow::Cow,
5    fmt::{self, Debug, Display},
6    mem,
7};
8use tank_core::{AsValue, Prepared, Result, RowLabels, ValueOwned};
9use tokio_postgres::Statement;
10
11/// Postgres prepared statement.
12#[derive(Debug)]
13pub struct PostgresPrepared {
14    pub(crate) statement: Statement,
15    pub(crate) labels: RowLabels,
16    pub(crate) params: Vec<ValueOwned>,
17    pub(crate) index: u64,
18}
19
20impl PostgresPrepared {
21    pub(crate) fn new(statement: Statement) -> Self {
22        let labels = statement
23            .columns()
24            .iter()
25            .map(|c| c.name().to_string())
26            .collect();
27        Self {
28            statement,
29            labels,
30            params: Vec::new(),
31            index: 0,
32        }
33    }
34
35    #[inline]
36    pub(crate) fn take_params(&mut self) -> Result<Vec<ValueWrap<'static>>> {
37        self.index = 0;
38        if self.params.is_empty() {
39            return Ok(Vec::new());
40        }
41        let types = self.statement.params();
42        mem::take(&mut self.params)
43            .into_iter()
44            .enumerate()
45            .map(|(i, param)| {
46                let Some(t) = types.get(i) else {
47                    return Err(anyhow!(
48                        "Parameter {i} has no corresponding PostgreSQL type"
49                    ));
50                };
51                Ok(ValueWrap(Cow::Owned(
52                    param.try_as(&postgres_type_to_value(t))?,
53                )))
54            })
55            .collect()
56    }
57}
58
59impl Prepared for PostgresPrepared {
60    #[inline(always)]
61    fn as_any(self: Box<Self>) -> Box<dyn std::any::Any> {
62        self
63    }
64
65    #[inline(always)]
66    fn is_empty(&self) -> bool {
67        false
68    }
69
70    #[inline(always)]
71    fn clear_bindings(&mut self) -> Result<&mut Self> {
72        self.params.clear();
73        self.index = 0;
74        Ok(self)
75    }
76
77    #[inline(always)]
78    fn bind(&mut self, value: impl AsValue) -> Result<&mut Self> {
79        self.bind_index(value, self.index)
80    }
81
82    fn bind_index(&mut self, value: impl AsValue, index: u64) -> Result<&mut Self> {
83        let len = self.statement.params().len();
84        self.params.resize_with(len, Default::default);
85        let target = self.params.get_mut(index as usize).ok_or_else(|| {
86            anyhow!("Index {index} cannot be bound, the query has only {len} parameters")
87        })?;
88        *target = value.as_value().into_owned();
89        self.index = index + 1;
90        Ok(self)
91    }
92}
93
94impl Display for PostgresPrepared {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        f.write_str("PostgresPrepared: ")?;
97        self.statement.fmt(f)
98    }
99}