1use 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
36pub 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 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#[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 pub fn columns(&self) -> &[Column] {
132 self.statement.columns()
133 }
134
135 pub fn is_empty(&self) -> bool {
137 self.len() == 0
138 }
139
140 pub fn len(&self) -> usize {
142 self.columns().len()
143 }
144
145 #[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 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 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 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#[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 pub fn columns(&self) -> &[SimpleColumn] {
251 &self.columns
252 }
253
254 pub fn is_empty(&self) -> bool {
256 self.len() == 0
257 }
258
259 pub fn len(&self) -> usize {
261 self.columns.len()
262 }
263
264 #[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 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}