use std::collections::BTreeMap;
use std::fmt;
use id_effect::schema::Unknown;
use crate::error::SqlError;
mod encode;
#[cfg(any(feature = "pg", feature = "mysql"))]
pub(crate) mod time_conv;
pub use encode::Json;
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SqlValue {
Null,
Bool(bool),
I16(i16),
I32(i32),
I64(i64),
F32(f32),
F64(f64),
Text(String),
Bytes(Vec<u8>),
Uuid(uuid::Uuid),
Timestamp(jiff::Timestamp),
DateTime(jiff::civil::DateTime),
Date(jiff::civil::Date),
Time(jiff::civil::Time),
Decimal(rust_decimal::Decimal),
Json(serde_json::Value),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SqlType {
Null,
Bool,
I16,
I32,
I64,
F32,
F64,
Text,
Bytes,
Uuid,
Timestamp,
DateTime,
Date,
Time,
Decimal,
Json,
}
impl SqlValue {
pub fn sql_type(&self) -> SqlType {
match self {
SqlValue::Null => SqlType::Null,
SqlValue::Bool(_) => SqlType::Bool,
SqlValue::I16(_) => SqlType::I16,
SqlValue::I32(_) => SqlType::I32,
SqlValue::I64(_) => SqlType::I64,
SqlValue::F32(_) => SqlType::F32,
SqlValue::F64(_) => SqlType::F64,
SqlValue::Text(_) => SqlType::Text,
SqlValue::Bytes(_) => SqlType::Bytes,
SqlValue::Uuid(_) => SqlType::Uuid,
SqlValue::Timestamp(_) => SqlType::Timestamp,
SqlValue::DateTime(_) => SqlType::DateTime,
SqlValue::Date(_) => SqlType::Date,
SqlValue::Time(_) => SqlType::Time,
SqlValue::Decimal(_) => SqlType::Decimal,
SqlValue::Json(_) => SqlType::Json,
}
}
#[inline]
pub fn is_null(&self) -> bool {
matches!(self, SqlValue::Null)
}
pub fn json<T: serde::Serialize + ?Sized>(value: &T) -> Result<Self, SqlError> {
serde_json::to_value(value)
.map(SqlValue::Json)
.map_err(|e| SqlError::Decode(format!("cannot encode the value as JSON: {e}")))
}
pub fn to_unknown(&self) -> Unknown {
match self {
SqlValue::Null => Unknown::Null,
SqlValue::Bool(b) => Unknown::Bool(*b),
SqlValue::I16(n) => Unknown::I64(i64::from(*n)),
SqlValue::I32(n) => Unknown::I64(i64::from(*n)),
SqlValue::I64(n) => Unknown::I64(*n),
SqlValue::F32(x) => Unknown::F64(f64::from(*x)),
SqlValue::F64(x) => Unknown::F64(*x),
SqlValue::Bytes(b) => Unknown::Array(b.iter().map(|&x| Unknown::I64(i64::from(x))).collect()),
SqlValue::Json(j) => json_to_unknown(j),
other => Unknown::String(other.render()),
}
}
pub(crate) fn render(&self) -> String {
match self {
SqlValue::Null => String::new(),
SqlValue::Bool(b) => b.to_string(),
SqlValue::I16(n) => n.to_string(),
SqlValue::I32(n) => n.to_string(),
SqlValue::I64(n) => n.to_string(),
SqlValue::F32(x) => x.to_string(),
SqlValue::F64(x) => x.to_string(),
SqlValue::Text(s) => s.clone(),
SqlValue::Bytes(b) => format!("{b:?}"),
SqlValue::Uuid(u) => u.to_string(),
SqlValue::Timestamp(t) => t.to_string(),
SqlValue::DateTime(t) => t.to_string(),
SqlValue::Date(d) => d.to_string(),
SqlValue::Time(t) => t.to_string(),
SqlValue::Decimal(d) => d.to_string(),
SqlValue::Json(j) => j.to_string(),
}
}
}
fn json_to_unknown(value: &serde_json::Value) -> Unknown {
match value {
serde_json::Value::Null => Unknown::Null,
serde_json::Value::Bool(b) => Unknown::Bool(*b),
serde_json::Value::Number(n) => match n.as_i64() {
Some(i) => Unknown::I64(i),
None => Unknown::F64(n.as_f64().unwrap_or(f64::NAN)),
},
serde_json::Value::String(s) => Unknown::String(s.clone()),
serde_json::Value::Array(items) => Unknown::Array(items.iter().map(json_to_unknown).collect()),
serde_json::Value::Object(map) => Unknown::Object(
map
.iter()
.map(|(k, v)| (k.clone(), json_to_unknown(v)))
.collect::<BTreeMap<_, _>>(),
),
}
}
pub trait ToSqlValue {
fn to_sql_value(&self) -> SqlValue;
}
pub trait FromSqlValue: Sized {
fn from_sql_value(v: &SqlValue) -> Result<Self, ValueError>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ValueError {
UnexpectedNull,
Mismatch {
expected: SqlType,
found: SqlType,
},
OutOfRange(String),
Invalid(String),
}
impl fmt::Display for ValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValueError::UnexpectedNull => write!(f, "unexpected NULL"),
ValueError::Mismatch { expected, found } => {
write!(f, "expected {expected:?}, found {found:?}")
}
ValueError::OutOfRange(m) => write!(f, "out of range: {m}"),
ValueError::Invalid(m) => write!(f, "invalid: {m}"),
}
}
}
impl std::error::Error for ValueError {}
#[macro_export]
macro_rules! params {
() => {
::std::vec::Vec::<$crate::SqlValue>::new()
};
($($v:expr),+ $(,)?) => {
::std::vec![$($crate::ToSqlValue::to_sql_value(&$v)),+]
};
}
#[allow(deprecated)]
impl From<crate::client::SqlParam> for SqlValue {
fn from(p: crate::client::SqlParam) -> Self {
use crate::client::SqlParam;
match p {
SqlParam::Null => SqlValue::Null,
SqlParam::Bool(b) => SqlValue::Bool(b),
SqlParam::Int(n) => SqlValue::I64(n),
SqlParam::Text(s) => SqlValue::Text(s),
SqlParam::Bytes(b) => SqlValue::Bytes(b),
}
}
}
#[allow(deprecated)]
impl PartialEq<crate::client::SqlParam> for SqlValue {
fn eq(&self, other: &crate::client::SqlParam) -> bool {
use crate::client::SqlParam;
match (self, other) {
(SqlValue::Null, SqlParam::Null) => true,
(SqlValue::Bool(a), SqlParam::Bool(b)) => a == b,
(SqlValue::I64(a), SqlParam::Int(b)) => a == b,
(SqlValue::Text(a), SqlParam::Text(b)) => a == b,
(SqlValue::Bytes(a), SqlParam::Bytes(b)) => a == b,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use id_effect::schema::Unknown;
use serde_json::json;
use super::*;
fn samples() -> Vec<SqlValue> {
vec![
SqlValue::Null,
SqlValue::Bool(true),
SqlValue::I16(-2),
SqlValue::I32(3),
SqlValue::I64(4),
SqlValue::F32(1.5),
SqlValue::F64(2.25),
SqlValue::Text("t".into()),
SqlValue::Bytes(vec![1, 2]),
SqlValue::Uuid(uuid::Uuid::nil()),
SqlValue::Timestamp(jiff::Timestamp::UNIX_EPOCH),
SqlValue::DateTime(jiff::civil::date(2024, 2, 29).at(13, 4, 5, 0)),
SqlValue::Date(jiff::civil::date(2024, 2, 29)),
SqlValue::Time(jiff::civil::time(13, 4, 5, 6_000)),
SqlValue::Decimal(rust_decimal::Decimal::new(12345, 2)),
SqlValue::Json(json!({"a": [1, 2.5, "x", null, true]})),
]
}
#[test]
fn every_variant_has_its_own_type() {
let types: Vec<SqlType> = samples().iter().map(SqlValue::sql_type).collect();
let distinct: std::collections::HashSet<_> = types.iter().copied().collect();
assert_eq!(distinct.len(), types.len());
assert!(SqlValue::Null.is_null());
assert!(!SqlValue::I64(0).is_null());
}
#[test]
fn render_matches_the_0_8_strings_for_the_legacy_kinds() {
let rendered: Vec<String> = samples().iter().map(SqlValue::render).collect();
assert_eq!(
rendered,
[
"",
"true",
"-2",
"3",
"4",
"1.5",
"2.25",
"t",
"[1, 2]",
"00000000-0000-0000-0000-000000000000",
"1970-01-01T00:00:00Z",
"2024-02-29T13:04:05",
"2024-02-29",
"13:04:05.000006",
"123.45",
r#"{"a":[1,2.5,"x",null,true]}"#,
]
);
}
#[test]
fn to_unknown_maps_every_variant() {
let unknowns: Vec<Unknown> = samples().iter().map(SqlValue::to_unknown).collect();
assert_eq!(unknowns[0], Unknown::Null);
assert_eq!(unknowns[1], Unknown::Bool(true));
assert_eq!(
unknowns[2..5],
[Unknown::I64(-2), Unknown::I64(3), Unknown::I64(4)]
);
assert_eq!(unknowns[5..7], [Unknown::F64(1.5), Unknown::F64(2.25)]);
assert_eq!(unknowns[7], Unknown::String("t".into()));
assert_eq!(
unknowns[8],
Unknown::Array(vec![Unknown::I64(1), Unknown::I64(2)])
);
assert_eq!(unknowns[10], Unknown::String("1970-01-01T00:00:00Z".into()));
assert_eq!(unknowns[14], Unknown::String("123.45".into()));
assert_eq!(
unknowns[15],
Unknown::Object(BTreeMap::from([(
"a".to_owned(),
Unknown::Array(vec![
Unknown::I64(1),
Unknown::F64(2.5),
Unknown::String("x".into()),
Unknown::Null,
Unknown::Bool(true),
])
)]))
);
assert_eq!(
SqlValue::Json(json!(u64::MAX)).to_unknown(),
Unknown::F64(u64::MAX as f64)
);
}
#[test]
fn json_constructor_serializes_or_fails() {
#[derive(serde::Serialize)]
struct Tag {
name: &'static str,
}
assert_eq!(
SqlValue::json(&Tag { name: "x" }).unwrap(),
SqlValue::Json(json!({"name": "x"}))
);
let bad = BTreeMap::from([((1, 2), 3)]);
assert!(matches!(SqlValue::json(&bad), Err(SqlError::Decode(_))));
}
#[test]
fn value_errors_display() {
assert_eq!(ValueError::UnexpectedNull.to_string(), "unexpected NULL");
assert_eq!(
ValueError::Mismatch {
expected: SqlType::Uuid,
found: SqlType::I64
}
.to_string(),
"expected Uuid, found I64"
);
assert_eq!(
ValueError::OutOfRange("x".into()).to_string(),
"out of range: x"
);
assert_eq!(ValueError::Invalid("y".into()).to_string(), "invalid: y");
}
#[test]
#[allow(deprecated)]
fn sql_param_converts_and_compares() {
use crate::client::SqlParam;
let pairs = [
(SqlParam::Null, SqlValue::Null),
(SqlParam::Bool(true), SqlValue::Bool(true)),
(SqlParam::Int(1), SqlValue::I64(1)),
(SqlParam::Text("t".into()), SqlValue::Text("t".into())),
(SqlParam::Bytes(vec![1]), SqlValue::Bytes(vec![1])),
];
for (param, value) in pairs {
assert_eq!(value, param);
assert_eq!(SqlValue::from(param), value);
}
assert_ne!(SqlValue::I32(1), SqlParam::Int(1));
let recorded = vec![SqlValue::I64(1), SqlValue::Text("a".into())];
assert_eq!(recorded, [SqlParam::Int(1), SqlParam::Text("a".into())]);
}
}