Skip to main content

giong_postgres/
row.rs

1//! Rows and columns of a result.
2
3use std::fmt;
4use std::rc::Rc;
5
6use crate::error::{Error, ErrorKind};
7use crate::protocol;
8use crate::types::{Format, FromSql, Type};
9
10/// A column of a result.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Column {
13    name: Box<str>,
14    ty: Type,
15}
16
17impl Column {
18    pub(crate) fn new(name: &str, ty: Type) -> Self {
19        Self {
20            name: name.into(),
21            ty,
22        }
23    }
24
25    /// The column's name, as the SQL names it (`AS` included).
26    pub fn name(&self) -> &str {
27        &self.name
28    }
29
30    /// The column's type.
31    pub fn ty(&self) -> Type {
32        self.ty
33    }
34
35    /// The format this crate asks the server to send the column in.
36    pub(crate) fn format(&self) -> Format {
37        if self.ty.binary_result() {
38            Format::Binary
39        } else {
40            Format::Text
41        }
42    }
43}
44
45/// All the rows of one result, in one allocation.
46pub(crate) struct ResultSet {
47    columns: Rc<[Column]>,
48    /// For each value, row by row: where it starts in `data` and its length,
49    /// or -1 for `NULL`.
50    values: Vec<(u32, i32)>,
51    data: Vec<u8>,
52}
53
54/// Collects rows as they arrive, up to a size limit.
55#[derive(Default)]
56pub(crate) struct RowsBuilder {
57    values: Vec<(u32, i32)>,
58    data: Vec<u8>,
59    rows: usize,
60    pub(crate) overflow: bool,
61}
62
63impl RowsBuilder {
64    /// Adds the row in a `DataRow` body, or notes that the result outgrew
65    /// `limit` bytes and drops what was collected.
66    pub(crate) fn push(&mut self, body: &[u8], columns: usize, limit: usize) -> Result<(), Error> {
67        if self.overflow {
68            return protocol::data_row(body, columns, |_| {});
69        }
70        let base = self.data.len();
71        let size = base + body.len() + (self.values.len() + columns) * 8;
72        if size > limit || u32::try_from(base + body.len()).is_err() {
73            protocol::data_row(body, columns, |_| {})?;
74            self.set_overflow();
75            return Ok(());
76        }
77        let values = &mut self.values;
78        protocol::data_row(body, columns, |v| {
79            values.push(match v {
80                Some(r) => ((base + r.start) as u32, r.len() as i32),
81                None => (0, -1),
82            })
83        })?;
84        self.data.extend_from_slice(body);
85        self.rows += 1;
86        Ok(())
87    }
88
89    pub(crate) fn set_overflow(&mut self) {
90        self.overflow = true;
91        self.values = Vec::new();
92        self.data = Vec::new();
93        self.rows = 0;
94    }
95
96    pub(crate) fn finish(self, columns: Rc<[Column]>) -> ResultSet {
97        ResultSet {
98            columns,
99            values: self.values,
100            data: self.data,
101        }
102    }
103}
104
105impl ResultSet {
106    pub(crate) fn into_rows(self) -> Vec<Row> {
107        let count = if self.columns.is_empty() {
108            0
109        } else {
110            self.values.len() / self.columns.len()
111        };
112        let set = Rc::new(self);
113        (0..count)
114            .map(|index| Row {
115                set: set.clone(),
116                index,
117            })
118            .collect()
119    }
120}
121
122/// A column position or name, for [`Row::get`].
123pub trait RowIndex: sealed::Sealed {
124    #[doc(hidden)]
125    fn position(&self, columns: &[Column]) -> Option<usize>;
126    #[doc(hidden)]
127    fn describe(&self) -> String;
128}
129
130mod sealed {
131    pub trait Sealed {}
132    impl Sealed for usize {}
133    impl Sealed for &str {}
134}
135
136impl RowIndex for usize {
137    fn position(&self, columns: &[Column]) -> Option<usize> {
138        (*self < columns.len()).then_some(*self)
139    }
140
141    fn describe(&self) -> String {
142        format!("number {self}")
143    }
144}
145
146impl RowIndex for &str {
147    fn position(&self, columns: &[Column]) -> Option<usize> {
148        columns.iter().position(|c| &*c.name == *self)
149    }
150
151    fn describe(&self) -> String {
152        format!("{self:?}")
153    }
154}
155
156/// A row of a result.
157///
158/// The rows of one result share one buffer, so a `Row` is cheap to keep and
159/// to clone.
160#[derive(Clone)]
161pub struct Row {
162    set: Rc<ResultSet>,
163    index: usize,
164}
165
166impl Row {
167    /// Reads a column, by name or by position (from 0), as `T`.
168    ///
169    /// ```no_run
170    /// # async fn f(client: &giong_postgres::Client) -> Result<(), giong_postgres::Error> {
171    /// let row = client.query_one("SELECT id, email FROM users WHERE id = $1", &[&7i64]).await?;
172    /// let id: i64 = row.get("id")?;
173    /// let email: &str = row.get(1)?;
174    /// # Ok(()) }
175    /// ```
176    ///
177    /// The error names the column and says what it can be read as when the
178    /// type does not fit, or that the value is `NULL` and needs an `Option`.
179    pub fn get<'a, T: FromSql<'a>>(&'a self, column: impl RowIndex) -> Result<T, Error> {
180        let columns = &self.set.columns;
181        let i = column.position(columns).ok_or_else(|| {
182            let names: Vec<&str> = columns.iter().map(|c| c.name()).collect();
183            Error::new(
184                ErrorKind::Type,
185                format!(
186                    "there is no column {} in this row; its columns are {names:?}",
187                    column.describe()
188                ),
189            )
190        })?;
191        let col = &columns[i];
192        let (start, len) = self.set.values[self.index * columns.len() + i];
193        let value = if len < 0 {
194            T::from_null(col.ty)
195        } else {
196            let start = start as usize;
197            T::from_sql(
198                col.ty,
199                col.format(),
200                &self.set.data[start..start + len as usize],
201            )
202        };
203        value.map_err(|e| e.context(&format!("column {:?}", col.name())))
204    }
205
206    /// Whether the column holds `NULL`.
207    pub fn is_null(&self, column: impl RowIndex) -> Result<bool, Error> {
208        self.get::<Option<Ignored>>(column).map(|v| v.is_none())
209    }
210
211    /// The columns of the result.
212    pub fn columns(&self) -> &[Column] {
213        &self.set.columns
214    }
215
216    /// The number of columns.
217    pub fn len(&self) -> usize {
218        self.set.columns.len()
219    }
220
221    /// Whether the row has no columns.
222    pub fn is_empty(&self) -> bool {
223        self.set.columns.is_empty()
224    }
225}
226
227/// Accepts any value, for [`Row::is_null`].
228struct Ignored;
229
230impl FromSql<'_> for Ignored {
231    fn from_sql(_: Type, _: Format, _: &[u8]) -> Result<Self, Error> {
232        Ok(Ignored)
233    }
234}
235
236impl fmt::Debug for Row {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        let mut map = f.debug_map();
239        for (i, col) in self.set.columns.iter().enumerate() {
240            let (start, len) = self.set.values[self.index * self.set.columns.len() + i];
241            if len < 0 {
242                map.entry(&col.name(), &"NULL");
243            } else if col.format() == Format::Text {
244                let start = start as usize;
245                let raw = &self.set.data[start..start + len as usize];
246                map.entry(&col.name(), &String::from_utf8_lossy(raw));
247            } else {
248                map.entry(
249                    &col.name(),
250                    &format_args!("<{} bytes of {}>", len, col.ty()),
251                );
252            }
253        }
254        map.finish()
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    fn row_body(values: &[Option<&[u8]>]) -> Vec<u8> {
263        let mut b = (values.len() as i16).to_be_bytes().to_vec();
264        for v in values {
265            match v {
266                Some(v) => {
267                    b.extend_from_slice(&(v.len() as i32).to_be_bytes());
268                    b.extend_from_slice(v);
269                }
270                None => b.extend_from_slice(&(-1i32).to_be_bytes()),
271            }
272        }
273        b
274    }
275
276    fn columns() -> Rc<[Column]> {
277        vec![
278            Column::new("id", Type::INT4),
279            Column::new("name", Type::TEXT),
280        ]
281        .into()
282    }
283
284    #[test]
285    fn rows_share_one_buffer_and_read_by_name_or_position() {
286        let mut b = RowsBuilder::default();
287        b.push(
288            &row_body(&[Some(&7i32.to_be_bytes()), Some(b"ana")]),
289            2,
290            1 << 20,
291        )
292        .unwrap();
293        b.push(&row_body(&[Some(&8i32.to_be_bytes()), None]), 2, 1 << 20)
294            .unwrap();
295        let rows = b.finish(columns()).into_rows();
296        assert_eq!(rows.len(), 2);
297        assert_eq!(rows[0].get::<i32>("id").unwrap(), 7);
298        assert_eq!(rows[0].get::<&str>(1).unwrap(), "ana");
299        assert_eq!(rows[1].get::<i64>(0).unwrap(), 8);
300        assert_eq!(rows[1].get::<Option<String>>("name").unwrap(), None);
301        assert!(rows[1].is_null("name").unwrap());
302        assert!(!rows[1].is_null("id").unwrap());
303
304        let e = rows[1].get::<String>("name").unwrap_err();
305        assert!(
306            e.to_string()
307                .starts_with("GIONG-E3005: column \"name\": the value is NULL"),
308            "{e}"
309        );
310        let e = rows[0].get::<String>("id").unwrap_err();
311        assert!(e.to_string().contains("read it as i16, i32 or i64"), "{e}");
312        let e = rows[0].get::<i32>("nope").unwrap_err();
313        assert!(e.to_string().contains("[\"id\", \"name\"]"), "{e}");
314        assert!(rows[0].get::<i32>(5).is_err());
315        assert_eq!(
316            format!("{:?}", rows[0]),
317            "{\"id\": <4 bytes of integer>, \"name\": \"ana\"}"
318        );
319    }
320
321    #[test]
322    fn a_result_over_the_limit_is_dropped() {
323        let mut b = RowsBuilder::default();
324        let body = row_body(&[Some(&7i32.to_be_bytes()), Some(&[b'x'; 100])]);
325        b.push(&body, 2, 250).unwrap();
326        assert!(!b.overflow);
327        b.push(&body, 2, 250).unwrap();
328        assert!(b.overflow);
329        b.push(&body, 2, 250).unwrap();
330        assert!(b.finish(columns()).into_rows().is_empty());
331        // Malformed rows are still caught after the overflow.
332        let mut b = RowsBuilder::default();
333        b.set_overflow();
334        assert!(b.push(&[0, 3], 2, 300).is_err());
335    }
336}