use serde_json::Value;
use std::collections::BTreeMap;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Row {
columns: BTreeMap<String, Value>,
order: Vec<String>,
}
impl Row {
pub fn new() -> Self {
Row::default()
}
pub fn add(&mut self, name: impl Into<String>, value: Value) {
let name = name.into();
if !self.columns.contains_key(&name) {
self.order.push(name.clone());
}
self.columns.insert(name, value);
}
pub fn column_names(&self) -> &[String] {
&self.order
}
pub fn raw(&self, name: &str) -> Option<&Value> {
self.columns.get(name)
}
pub fn len(&self) -> usize {
self.order.len()
}
pub fn is_empty(&self) -> bool {
self.order.is_empty()
}
pub fn get<T: FromColumn>(&self, name: &str) -> Result<T, ColumnLookupError> {
match self.lookup(name) {
Some((actual, value)) => T::from_column(actual, value).map_err(ColumnLookupError::Type),
None => Err(ColumnLookupError::NotFound(name.to_string())),
}
}
pub fn try_get<T: FromColumn>(&self, name: &str) -> Result<Option<T>, ColumnLookupError> {
match self.lookup(name) {
Some((_, Value::Null)) => Ok(None),
Some((actual, value)) => T::from_column(actual, value)
.map(Some)
.map_err(ColumnLookupError::Type),
None => Err(ColumnLookupError::NotFound(name.to_string())),
}
}
fn lookup(&self, name: &str) -> Option<(&str, &Value)> {
if let Some((key, value)) = self.columns.get_key_value(name) {
return Some((key.as_str(), value));
}
let wanted = normalize_name(name);
for candidate in &self.order {
if normalize_name(candidate) == wanted {
return Some((candidate.as_str(), &self.columns[candidate]));
}
}
None
}
}
pub fn normalize_name(name: &str) -> String {
name.chars()
.filter(|ch| *ch != '_' && *ch != '-')
.flat_map(|ch| ch.to_lowercase())
.collect()
}
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnLookupError {
NotFound(String),
Type(TypeMismatch),
}
#[derive(Debug, Clone, PartialEq)]
pub struct TypeMismatch {
pub column: String,
pub expected: &'static str,
pub got: Value,
}
impl std::fmt::Display for ColumnLookupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ColumnLookupError::NotFound(name) => write!(f, "column {name} not found in row"),
ColumnLookupError::Type(mismatch) => write!(
f,
"column {}: expected {}, got {}",
mismatch.column, mismatch.expected, mismatch.got
),
}
}
}
impl std::error::Error for ColumnLookupError {}
pub trait FromColumn: Sized {
fn type_name() -> &'static str;
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch>;
}
macro_rules! int_column {
($($kind:ty),* $(,)?) => {
$(
impl FromColumn for $kind {
fn type_name() -> &'static str {
stringify!($kind)
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
let mismatch = || TypeMismatch {
column: column.to_string(),
expected: Self::type_name(),
got: value.clone(),
};
match value {
Value::Number(number) => number
.as_i64()
.and_then(|raw| <$kind>::try_from(raw).ok())
.or_else(|| {
number.as_u64().and_then(|raw| <$kind>::try_from(raw).ok())
})
.ok_or_else(mismatch),
Value::String(text) => text.parse::<$kind>().map_err(|_| mismatch()),
_ => Err(mismatch()),
}
}
}
)*
};
}
int_column!(i8, i16, i32, i64, u8, u16, u32, u64);
impl FromColumn for f32 {
fn type_name() -> &'static str {
"f32"
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
f64::from_column(column, value)
.map(|raw| raw as f32)
.map_err(|mut mismatch| {
mismatch.expected = "f32";
mismatch
})
}
}
impl FromColumn for f64 {
fn type_name() -> &'static str {
"f64"
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
let mismatch = || TypeMismatch {
column: column.to_string(),
expected: Self::type_name(),
got: value.clone(),
};
match value {
Value::Number(number) => number.as_f64().ok_or_else(mismatch),
Value::String(text) => text.parse::<f64>().map_err(|_| mismatch()),
_ => Err(mismatch()),
}
}
}
impl FromColumn for bool {
fn type_name() -> &'static str {
"bool"
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
let mismatch = || TypeMismatch {
column: column.to_string(),
expected: "bool",
got: value.clone(),
};
match value {
Value::Bool(flag) => Ok(*flag),
Value::Number(number) if number.as_i64() == Some(0) => Ok(false),
Value::Number(number) if number.as_i64() == Some(1) => Ok(true),
Value::String(text) => match text.to_ascii_lowercase().as_str() {
"true" | "1" | "y" | "yes" => Ok(true),
"false" | "0" | "n" | "no" => Ok(false),
_ => Err(mismatch()),
},
_ => Err(mismatch()),
}
}
}
impl FromColumn for String {
fn type_name() -> &'static str {
"String"
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
match value {
Value::String(text) => Ok(text.clone()),
Value::Number(number) => Ok(number.to_string()),
Value::Bool(flag) => Ok(flag.to_string()),
_ => Err(TypeMismatch {
column: column.to_string(),
expected: "String",
got: value.clone(),
}),
}
}
}
impl FromColumn for Value {
fn type_name() -> &'static str {
"Value"
}
fn from_column(_column: &str, value: &Value) -> Result<Self, TypeMismatch> {
Ok(value.clone())
}
}
impl<T: FromColumn> FromColumn for Option<T> {
fn type_name() -> &'static str {
T::type_name()
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
match value {
Value::Null => Ok(None),
other => T::from_column(column, other).map(Some),
}
}
}
impl FromColumn for Vec<u8> {
fn type_name() -> &'static str {
"Vec<u8>"
}
fn from_column(column: &str, value: &Value) -> Result<Self, TypeMismatch> {
match value {
Value::Array(items) => items
.iter()
.map(|item| {
item.as_u64()
.and_then(|raw| u8::try_from(raw).ok())
.ok_or_else(|| TypeMismatch {
column: column.to_string(),
expected: "Vec<u8>",
got: item.clone(),
})
})
.collect(),
Value::String(text) => Ok(text.as_bytes().to_vec()),
_ => Err(TypeMismatch {
column: column.to_string(),
expected: "Vec<u8>",
got: value.clone(),
}),
}
}
}