1use crate::row::sealed::{AsName, Sealed};
4use crate::simple_query::SimpleColumn;
5use crate::statement::Column;
6use crate::types::{FromSql, Type, WrongType};
7use crate::{Error, Statement};
8use fallible_iterator::FallibleIterator;
9use postgres_protocol::message::backend::DataRowBody;
10use std::fmt;
11use std::ops::Range;
12use std::str;
13use std::sync::Arc;
14
15mod sealed {
16 pub trait Sealed {}
17
18 pub trait AsName {
19 fn as_name(&self) -> &str;
20 }
21}
22
23impl AsName for Column {
24 fn as_name(&self) -> &str {
25 self.name()
26 }
27}
28
29impl AsName for String {
30 fn as_name(&self) -> &str {
31 self
32 }
33}
34
35pub trait RowIndex: Sealed {
39 #[doc(hidden)]
40 fn __idx<T>(&self, columns: &[T]) -> Option<usize>
41 where
42 T: AsName;
43}
44
45impl Sealed for usize {}
46
47impl RowIndex for usize {
48 #[inline]
49 fn __idx<T>(&self, columns: &[T]) -> Option<usize>
50 where
51 T: AsName,
52 {
53 if *self >= columns.len() {
54 None
55 } else {
56 Some(*self)
57 }
58 }
59}
60
61impl Sealed for str {}
62
63impl RowIndex for str {
64 #[inline]
65 fn __idx<T>(&self, columns: &[T]) -> Option<usize>
66 where
67 T: AsName,
68 {
69 if let Some(idx) = columns.iter().position(|d| d.as_name() == self) {
70 return Some(idx);
71 };
72
73 columns
77 .iter()
78 .position(|d| d.as_name().eq_ignore_ascii_case(self))
79 }
80}
81
82impl<'a, T> Sealed for &'a T where T: ?Sized + Sealed {}
83
84impl<'a, T> RowIndex for &'a T
85where
86 T: ?Sized + RowIndex,
87{
88 #[inline]
89 fn __idx<U>(&self, columns: &[U]) -> Option<usize>
90 where
91 U: AsName,
92 {
93 T::__idx(*self, columns)
94 }
95}
96
97pub struct Row {
99 statement: Statement,
100 body: DataRowBody,
101 ranges: Vec<Option<Range<usize>>>,
102}
103
104impl fmt::Debug for Row {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.debug_struct("Row")
107 .field("columns", &self.columns())
108 .finish()
109 }
110}
111
112impl Row {
113 pub(crate) fn new(statement: Statement, body: DataRowBody) -> Result<Row, Error> {
114 let ranges = body.ranges().collect().map_err(Error::parse)?;
115 Ok(Row {
116 statement,
117 body,
118 ranges,
119 })
120 }
121
122 pub fn columns(&self) -> &[Column] {
124 self.statement.columns()
125 }
126
127 pub fn is_empty(&self) -> bool {
129 self.len() == 0
130 }
131
132 pub fn len(&self) -> usize {
134 self.columns().len()
135 }
136
137 pub fn get<'a, I, T>(&'a self, idx: I) -> T
145 where
146 I: RowIndex + fmt::Display,
147 T: FromSql<'a>,
148 {
149 match self.get_inner(&idx) {
150 Ok(ok) => ok,
151 Err(err) => panic!("error retrieving column {}: {}", idx, err),
152 }
153 }
154
155 pub fn try_get<'a, I, T>(&'a self, idx: I) -> Result<T, Error>
157 where
158 I: RowIndex + fmt::Display,
159 T: FromSql<'a>,
160 {
161 self.get_inner(&idx)
162 }
163
164 fn get_inner<'a, I, T>(&'a self, idx: &I) -> Result<T, Error>
165 where
166 I: RowIndex + fmt::Display,
167 T: FromSql<'a>,
168 {
169 let idx = match idx.__idx(self.columns()) {
170 Some(idx) => idx,
171 None => return Err(Error::column(idx.to_string())),
172 };
173
174 let ty = self.columns()[idx].type_();
175 if !T::accepts(ty) {
176 return Err(Error::from_sql(
177 Box::new(WrongType::new::<T>(ty.clone())),
178 idx,
179 ));
180 }
181
182 FromSql::from_sql_nullable(ty, self.col_buffer(idx)).map_err(|e| Error::from_sql(e, idx))
183 }
184
185 fn col_buffer(&self, idx: usize) -> Option<&[u8]> {
187 let range = self.ranges[idx].to_owned()?;
188 Some(&self.body.buffer()[range])
189 }
190}
191
192impl AsName for SimpleColumn {
193 fn as_name(&self) -> &str {
194 self.name()
195 }
196}
197
198#[derive(Debug)]
200pub struct SimpleQueryRow {
201 columns: Arc<[SimpleColumn]>,
202 body: DataRowBody,
203 ranges: Vec<Option<Range<usize>>>,
204}
205
206impl SimpleQueryRow {
207 #[allow(clippy::new_ret_no_self)]
208 pub(crate) fn new(
209 columns: Arc<[SimpleColumn]>,
210 body: DataRowBody,
211 ) -> Result<SimpleQueryRow, Error> {
212 let ranges = body.ranges().collect().map_err(Error::parse)?;
213 Ok(SimpleQueryRow {
214 columns,
215 body,
216 ranges,
217 })
218 }
219
220 pub fn columns(&self) -> &[SimpleColumn] {
222 &self.columns
223 }
224
225 pub fn is_empty(&self) -> bool {
227 self.len() == 0
228 }
229
230 pub fn len(&self) -> usize {
232 self.columns.len()
233 }
234
235 pub fn get<I>(&self, idx: I) -> Option<&str>
243 where
244 I: RowIndex + fmt::Display,
245 {
246 match self.get_inner(&idx) {
247 Ok(ok) => ok,
248 Err(err) => panic!("error retrieving column {}: {}", idx, err),
249 }
250 }
251
252 pub fn try_get<I>(&self, idx: I) -> Result<Option<&str>, Error>
254 where
255 I: RowIndex + fmt::Display,
256 {
257 self.get_inner(&idx)
258 }
259
260 fn get_inner<I>(&self, idx: &I) -> Result<Option<&str>, Error>
261 where
262 I: RowIndex + fmt::Display,
263 {
264 let idx = match idx.__idx(&self.columns) {
265 Some(idx) => idx,
266 None => return Err(Error::column(idx.to_string())),
267 };
268
269 let buf = self.ranges[idx].clone().map(|r| &self.body.buffer()[r]);
270 FromSql::from_sql_nullable(&Type::TEXT, buf).map_err(|e| Error::from_sql(e, idx))
271 }
272}