diesel/row.rs
1//! Contains the `Row` trait
2
3use backend::Backend;
4use deserialize::{self, FromSql};
5
6/// Represents a single database row.
7/// Apps should not need to concern themselves with this trait.
8///
9/// This trait is only used as an argument to [`FromSqlRow`].
10///
11/// [`FromSqlRow`]: ../deserialize/trait.FromSqlRow.html
12pub trait Row<DB: Backend> {
13 /// Returns the value of the next column in the row.
14 fn take(&mut self) -> Option<&DB::RawValue>;
15
16 /// Returns whether the next `count` columns are all `NULL`.
17 ///
18 /// If this method returns `true`, then the next `count` calls to `take`
19 /// would all return `None`.
20 fn next_is_null(&self, count: usize) -> bool;
21
22 /// Skips the next `count` columns. This method must be called if you are
23 /// choosing not to call `take` as a result of `next_is_null` returning
24 /// `true`.
25 fn advance(&mut self, count: usize) {
26 for _ in 0..count {
27 self.take();
28 }
29 }
30}
31
32/// Represents a row of a SQL query, where the values are accessed by name
33/// rather than by index.
34///
35/// This trait is used by implementations of
36/// [`QueryableByName`](../deserialize/trait.QueryableByName.html)
37pub trait NamedRow<DB: Backend> {
38 /// Retrieve and deserialize a single value from the query
39 ///
40 /// Note that `ST` *must* be the exact type of the value with that name in
41 /// the query. The compiler will not be able to verify that you have
42 /// provided the correct type. If there is a mismatch, you may receive an
43 /// incorrect value, or a runtime error.
44 ///
45 /// If two or more fields in the query have the given name, the result of
46 /// this function is undefined.
47 fn get<ST, T>(&self, column_name: &str) -> deserialize::Result<T>
48 where
49 T: FromSql<ST, DB>,
50 {
51 let idx = self
52 .index_of(column_name)
53 .ok_or_else(|| format!("Column `{}` was not present in query", column_name).into());
54 let idx = match idx {
55 Ok(x) => x,
56 Err(e) => return Err(e),
57 };
58 let raw_value = self.get_raw_value(idx);
59 T::from_sql(raw_value)
60 }
61
62 #[doc(hidden)]
63 fn index_of(&self, column_name: &str) -> Option<usize>;
64 #[doc(hidden)]
65 fn get_raw_value(&self, index: usize) -> Option<&DB::RawValue>;
66}