use std::borrow::Cow;
use crate::attributes::CastContext;
use crate::cast::CastError;
use crate::row::Row;
use crate::value::{Field, FieldError, FieldKind, Value};
pub trait StoredColumns: Sized + 'static {
const COUNT: usize;
fn to_values(&self) -> Vec<Value>;
fn from_values(values: Vec<Value>) -> Result<Self, (usize, FieldError)>;
fn from_row(row: &Row, columns: &[&str]) -> Result<Self, (usize, FieldError)>;
fn from_row_option(row: &Row, columns: &[&str]) -> Result<Option<Self>, (usize, FieldError)>;
fn nulls() -> Vec<Value>;
fn type_name(index: usize) -> Cow<'static, str>;
}
fn column<'a>(columns: &[&'a str], index: usize) -> Result<&'a str, (usize, FieldError)> {
columns
.get(index)
.copied()
.ok_or((index, FieldError::Missing))
}
macro_rules! stored_columns {
($count:literal => $($ty:ident $index:tt),+) => {
impl<$($ty: Field),+> StoredColumns for ($($ty,)+) {
const COUNT: usize = $count;
fn to_values(&self) -> Vec<Value> {
vec![$(self.$index.to_value()),+]
}
fn from_values(values: Vec<Value>) -> Result<Self, (usize, FieldError)> {
if values.len() != $count {
return Err((values.len().min($count - 1), FieldError::Missing));
}
let mut values = values.into_iter();
Ok(($(
$ty::from_value(values.next().unwrap_or_else($ty::null))
.map_err(|error| ($index, error))?,
)+))
}
fn from_row(row: &Row, columns: &[&str]) -> Result<Self, (usize, FieldError)> {
Ok(($(
row.field::<$ty>(column(columns, $index)?).map_err(|error| ($index, error))?,
)+))
}
fn from_row_option(
row: &Row,
columns: &[&str],
) -> Result<Option<Self>, (usize, FieldError)> {
let values = ($(
row.field::<Option<$ty>>(column(columns, $index)?).map_err(|error| ($index, error))?,
)+);
let nulls = [$(values.$index.is_none()),+];
if nulls.iter().all(|null| *null) {
return Ok(None);
}
Ok(Some(($(
values.$index.ok_or(($index, FieldError::Null))?,
)+)))
}
fn nulls() -> Vec<Value> {
vec![$($ty::null()),+]
}
fn type_name(index: usize) -> Cow<'static, str> {
match index {
$($index => $ty::type_name(),)+
_ => Cow::Borrowed("?"),
}
}
}
};
}
stored_columns!(1 => A 0);
stored_columns!(2 => A 0, B 1);
stored_columns!(3 => A 0, B 1, C 2);
stored_columns!(4 => A 0, B 1, C 2, D 3);
stored_columns!(5 => A 0, B 1, C 2, D 3, E 4);
stored_columns!(6 => A 0, B 1, C 2, D 3, E 4, F 5);
stored_columns!(7 => A 0, B 1, C 2, D 3, E 4, F 5, G 6);
stored_columns!(8 => A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
pub trait MultiColumnCast<T>: 'static {
type Stored: StoredColumns;
const CONTEXT: bool = false;
const KIND: FieldKind = FieldKind::Any;
fn get(stored: Self::Stored) -> Result<T, CastError>;
fn set(value: &T) -> Result<Self::Stored, CastError>;
fn get_with(stored: Self::Stored, context: &CastContext) -> Result<T, CastError> {
let _ = context;
Self::get(stored)
}
fn set_with(value: &T, context: &CastContext) -> Result<Self::Stored, CastError> {
let _ = context;
Self::set(value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tuples_convert_and_report_the_failing_column() {
let stored = (7_i64, "EUR".to_owned());
let values = stored.to_values();
assert_eq!(values, [Value::I64(7), Value::from("EUR")]);
assert_eq!(<(i64, String)>::from_values(values).unwrap(), stored);
let (index, error) =
<(i64, String)>::from_values(vec![Value::from("x"), Value::from("EUR")]).unwrap_err();
assert_eq!(index, 0);
assert_eq!(error, FieldError::Invalid("`x` is not an integer".into()));
assert_eq!(
<(i64, String)>::from_values(vec![Value::I64(1)])
.unwrap_err()
.0,
1
);
assert_eq!(
<(i64, String)>::nulls(),
[
Value::Null(crate::Kind::I64),
Value::Null(crate::Kind::String)
]
);
assert_eq!(<(i64, Option<String>)>::type_name(1), "Option<String>");
}
#[test]
fn rows_read_every_column_or_none_when_all_are_null() {
let row = Row::from_values(vec![
("cents".into(), Value::I64(5)),
("currency".into(), Value::from("USD")),
]);
let read = <(i64, String)>::from_row(&row, &["cents", "currency"]).unwrap();
assert_eq!(read, (5, "USD".to_owned()));
let nulls = Row::from_values(vec![
("cents".into(), Value::Null(crate::Kind::I64)),
("currency".into(), Value::Null(crate::Kind::String)),
]);
assert_eq!(
<(i64, String)>::from_row_option(&nulls, &["cents", "currency"]).unwrap(),
None
);
let half = Row::from_values(vec![
("cents".into(), Value::I64(5)),
("currency".into(), Value::Null(crate::Kind::String)),
]);
assert_eq!(
<(i64, String)>::from_row_option(&half, &["cents", "currency"]).unwrap_err(),
(1, FieldError::Null)
);
assert_eq!(
<(i64, String)>::from_row(&row, &["cents"]).unwrap_err(),
(1, FieldError::Missing)
);
}
}