Skip to main content

tokio_postgres/
row.rs

1//! Rows.
2
3use crate::query::ResultFormats;
4use crate::row::sealed::{AsName, Sealed};
5use crate::simple_query::SimpleColumn;
6use crate::statement::Column;
7use crate::types::{FromSql, Type, WrongType};
8use crate::{Error, ResultFormat, Statement};
9use fallible_iterator::FallibleIterator;
10use postgres_protocol::message::backend::DataRowBody;
11use std::fmt;
12use std::ops::Range;
13use std::str;
14use std::sync::Arc;
15
16mod sealed {
17    pub trait Sealed {}
18
19    pub trait AsName {
20        fn as_name(&self) -> &str;
21    }
22}
23
24impl AsName for Column {
25    fn as_name(&self) -> &str {
26        self.name()
27    }
28}
29
30impl AsName for String {
31    fn as_name(&self) -> &str {
32        self
33    }
34}
35
36/// A trait implemented by types that can index into columns of a row.
37///
38/// This cannot be implemented outside of this crate.
39pub trait RowIndex: Sealed {
40    #[doc(hidden)]
41    fn __idx<T>(&self, columns: &[T]) -> Option<usize>
42    where
43        T: AsName;
44}
45
46impl Sealed for usize {}
47
48impl RowIndex for usize {
49    #[inline]
50    fn __idx<T>(&self, columns: &[T]) -> Option<usize>
51    where
52        T: AsName,
53    {
54        if *self >= columns.len() {
55            None
56        } else {
57            Some(*self)
58        }
59    }
60}
61
62impl Sealed for str {}
63
64impl RowIndex for str {
65    #[inline]
66    fn __idx<T>(&self, columns: &[T]) -> Option<usize>
67    where
68        T: AsName,
69    {
70        if let Some(idx) = columns.iter().position(|d| d.as_name() == self) {
71            return Some(idx);
72        };
73
74        // FIXME ASCII-only case insensitivity isn't really the right thing to
75        // do. Postgres itself uses a dubious wrapper around tolower and JDBC
76        // uses the US locale.
77        columns
78            .iter()
79            .position(|d| d.as_name().eq_ignore_ascii_case(self))
80    }
81}
82
83impl<T> Sealed for &T where T: ?Sized + Sealed {}
84
85impl<T> RowIndex for &T
86where
87    T: ?Sized + RowIndex,
88{
89    #[inline]
90    fn __idx<U>(&self, columns: &[U]) -> Option<usize>
91    where
92        U: AsName,
93    {
94        T::__idx(*self, columns)
95    }
96}
97
98/// A row of data returned from the database by a query.
99#[derive(Clone)]
100pub struct Row {
101    statement: Statement,
102    formats: ResultFormats,
103    body: DataRowBody,
104    ranges: Vec<Option<Range<usize>>>,
105}
106
107impl fmt::Debug for Row {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.debug_struct("Row")
110            .field("columns", &self.columns())
111            .finish()
112    }
113}
114
115impl Row {
116    pub(crate) fn new(
117        statement: Statement,
118        formats: ResultFormats,
119        body: DataRowBody,
120    ) -> Result<Row, Error> {
121        let ranges = body.ranges().collect().map_err(Error::parse)?;
122        Ok(Row {
123            statement,
124            formats,
125            body,
126            ranges,
127        })
128    }
129
130    /// Returns information about the columns of data in the row.
131    pub fn columns(&self) -> &[Column] {
132        self.statement.columns()
133    }
134
135    /// Determines if the row contains no values.
136    pub fn is_empty(&self) -> bool {
137        self.len() == 0
138    }
139
140    /// Returns the number of values in the row.
141    pub fn len(&self) -> usize {
142        self.columns().len()
143    }
144
145    /// Deserializes a value from the row.
146    ///
147    /// The value can be specified either by its numeric index in the row, or by its column name.
148    ///
149    /// # Panics
150    ///
151    /// Panics if the index is out of bounds or if the value cannot be converted to the specified type.
152    #[track_caller]
153    pub fn get<'a, I, T>(&'a self, idx: I) -> T
154    where
155        I: RowIndex + fmt::Display,
156        T: FromSql<'a>,
157    {
158        match self.get_inner(&idx) {
159            Ok(ok) => ok,
160            Err(err) => panic!("error retrieving column {}: {}", idx, err),
161        }
162    }
163
164    /// Like `Row::get`, but returns a `Result` rather than panicking.
165    pub fn try_get<'a, I, T>(&'a self, idx: I) -> Result<T, Error>
166    where
167        I: RowIndex + fmt::Display,
168        T: FromSql<'a>,
169    {
170        self.get_inner(&idx)
171    }
172
173    fn get_inner<'a, I, T>(&'a self, idx: &I) -> Result<T, Error>
174    where
175        I: RowIndex + fmt::Display,
176        T: FromSql<'a>,
177    {
178        let idx = match idx.__idx(self.columns()) {
179            Some(idx) => idx,
180            None => return Err(Error::column(idx.to_string())),
181        };
182
183        let ty = self.columns()[idx].type_();
184        if !T::accepts(ty) {
185            return Err(Error::from_sql(
186                Box::new(WrongType::new::<T>(ty.clone())),
187                idx,
188            ));
189        }
190
191        FromSql::from_sql_nullable(ty, self.col_buffer(idx)).map_err(|e| Error::from_sql(e, idx))
192    }
193
194    /// Returns the format the value of the column at the given index came in,
195    /// as the query asked for it: see `Client::query_raw_with_formats`.
196    ///
197    /// `get` and `try_get` decode a column as binary whatever its format, so
198    /// read a text column with `col_buffer`.
199    ///
200    /// # Panics
201    ///
202    /// Panics if the index is out of bounds.
203    pub fn format(&self, idx: usize) -> ResultFormat {
204        assert!(idx < self.len(), "column index {} out of bounds", idx);
205        self.formats.get(idx)
206    }
207
208    /// Returns the raw bytes for the column at the given index.
209    ///
210    /// Returns `None` if the value is SQL NULL.
211    /// With `ResultFormat::Text`, the bytes are the UTF-8 text representation
212    /// of the value — the same format PostgreSQL sends to text-mode clients.
213    /// With `ResultFormat::Binary`, the bytes are binary-encoded. `format`
214    /// says which the column is in.
215    pub fn col_buffer(&self, idx: usize) -> Option<&[u8]> {
216        let range = self.ranges[idx].to_owned()?;
217        Some(&self.body.buffer()[range])
218    }
219}
220
221impl AsName for SimpleColumn {
222    fn as_name(&self) -> &str {
223        self.name()
224    }
225}
226
227/// A row of data returned from the database by a simple query.
228#[derive(Debug)]
229pub struct SimpleQueryRow {
230    columns: Arc<[SimpleColumn]>,
231    body: DataRowBody,
232    ranges: Vec<Option<Range<usize>>>,
233}
234
235impl SimpleQueryRow {
236    #[allow(clippy::new_ret_no_self)]
237    pub(crate) fn new(
238        columns: Arc<[SimpleColumn]>,
239        body: DataRowBody,
240    ) -> Result<SimpleQueryRow, Error> {
241        let ranges = body.ranges().collect().map_err(Error::parse)?;
242        Ok(SimpleQueryRow {
243            columns,
244            body,
245            ranges,
246        })
247    }
248
249    /// Returns information about the columns of data in the row.
250    pub fn columns(&self) -> &[SimpleColumn] {
251        &self.columns
252    }
253
254    /// Determines if the row contains no values.
255    pub fn is_empty(&self) -> bool {
256        self.len() == 0
257    }
258
259    /// Returns the number of values in the row.
260    pub fn len(&self) -> usize {
261        self.columns.len()
262    }
263
264    /// Returns a value from the row.
265    ///
266    /// The value can be specified either by its numeric index in the row, or by its column name.
267    ///
268    /// # Panics
269    ///
270    /// Panics if the index is out of bounds or if the value cannot be converted to the specified type.
271    #[track_caller]
272    pub fn get<I>(&self, idx: I) -> Option<&str>
273    where
274        I: RowIndex + fmt::Display,
275    {
276        match self.get_inner(&idx) {
277            Ok(ok) => ok,
278            Err(err) => panic!("error retrieving column {}: {}", idx, err),
279        }
280    }
281
282    /// Like `SimpleQueryRow::get`, but returns a `Result` rather than panicking.
283    pub fn try_get<I>(&self, idx: I) -> Result<Option<&str>, Error>
284    where
285        I: RowIndex + fmt::Display,
286    {
287        self.get_inner(&idx)
288    }
289
290    fn get_inner<I>(&self, idx: &I) -> Result<Option<&str>, Error>
291    where
292        I: RowIndex + fmt::Display,
293    {
294        let idx = match idx.__idx(&self.columns) {
295            Some(idx) => idx,
296            None => return Err(Error::column(idx.to_string())),
297        };
298
299        let buf = self.ranges[idx].clone().map(|r| &self.body.buffer()[r]);
300        FromSql::from_sql_nullable(&Type::TEXT, buf).map_err(|e| Error::from_sql(e, idx))
301    }
302}