1use std::fmt;
2use std::sync::Arc;
3
4use serde::de::DeserializeOwned;
5use serde::{Deserialize, Serialize};
6use time::OffsetDateTime;
7
8use crate::crypto::Hash;
9use crate::schema::{ColumnType, TableDef};
10
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13#[serde(tag = "t", content = "v")]
14pub enum Value {
15 Null,
16 Bool(bool),
17 Int(i64),
18 Text(String),
19 Bytes(Vec<u8>),
20 Timestamp(#[serde(with = "time::serde::rfc3339")] OffsetDateTime),
21 Json(serde_json::Value),
22}
23
24impl Value {
25 pub fn is_null(&self) -> bool {
26 matches!(self, Value::Null)
27 }
28
29 pub fn to_json(&self) -> serde_json::Value {
31 match self {
32 Value::Null => serde_json::Value::Null,
33 Value::Bool(b) => (*b).into(),
34 Value::Int(i) => (*i).into(),
35 Value::Text(s) => s.clone().into(),
36 Value::Bytes(_) => serde_json::Value::Null,
37 Value::Timestamp(t) => t
38 .format(&time::format_description::well_known::Rfc3339)
39 .map(serde_json::Value::String)
40 .unwrap_or(serde_json::Value::Null),
41 Value::Json(j) => j.clone(),
42 }
43 }
44
45 pub fn from_json(ty: ColumnType, json: &serde_json::Value) -> Option<Value> {
47 use serde_json::Value as J;
48 Some(match (ty, json) {
49 (_, J::Null) => Value::Null,
50 (ColumnType::Bool, J::Bool(b)) => Value::Bool(*b),
51 (ColumnType::Int, J::Number(n)) => Value::Int(n.as_i64()?),
52 (ColumnType::Text | ColumnType::Id, J::String(s)) => Value::Text(s.clone()),
53 (ColumnType::Timestamp, J::String(s)) => Value::Timestamp(
54 OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339).ok()?,
55 ),
56 (ColumnType::Json, j) => Value::Json(j.clone()),
57 _ => return None,
58 })
59 }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
63#[error("column `{column}`: {message}")]
64pub struct DecodeError {
65 pub column: String,
66 pub message: String,
67}
68
69impl DecodeError {
70 pub fn new(column: impl Into<String>, message: impl Into<String>) -> Self {
71 Self {
72 column: column.into(),
73 message: message.into(),
74 }
75 }
76}
77
78pub trait ColumnValue: Sized + Send + Sync + 'static {
80 const TYPE: ColumnType;
81 const NULLABLE: bool = false;
82 fn into_value(self) -> Value;
83 fn from_value(value: Value) -> Result<Self, String>;
84}
85
86macro_rules! column_value {
87 ($ty:ty, $col:ident, $variant:ident) => {
88 impl ColumnValue for $ty {
89 const TYPE: ColumnType = ColumnType::$col;
90 fn into_value(self) -> Value {
91 Value::$variant(self)
92 }
93 fn from_value(value: Value) -> Result<Self, String> {
94 match value {
95 Value::$variant(v) => Ok(v),
96 other => Err(format!("expected {}, got {other:?}", stringify!($variant))),
97 }
98 }
99 }
100 };
101}
102
103column_value!(bool, Bool, Bool);
104column_value!(i64, Int, Int);
105column_value!(String, Text, Text);
106column_value!(Vec<u8>, Bytes, Bytes);
107column_value!(OffsetDateTime, Timestamp, Timestamp);
108
109impl<T: ColumnValue> ColumnValue for Option<T> {
110 const TYPE: ColumnType = T::TYPE;
111 const NULLABLE: bool = true;
112 fn into_value(self) -> Value {
113 self.map_or(Value::Null, ColumnValue::into_value)
114 }
115 fn from_value(value: Value) -> Result<Self, String> {
116 match value {
117 Value::Null => Ok(None),
118 v => T::from_value(v).map(Some),
119 }
120 }
121}
122
123#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
125#[serde(transparent)]
126pub struct Json<T>(pub T);
127
128impl<T: Serialize + DeserializeOwned + Send + Sync + 'static> ColumnValue for Json<T> {
129 const TYPE: ColumnType = ColumnType::Json;
130 fn into_value(self) -> Value {
131 Value::Json(serde_json::to_value(self.0).unwrap_or(serde_json::Value::Null))
132 }
133 fn from_value(value: Value) -> Result<Self, String> {
134 match value {
135 Value::Json(j) => serde_json::from_value(j)
136 .map(Json)
137 .map_err(|e| e.to_string()),
138 Value::Text(s) => serde_json::from_str(&s)
139 .map(Json)
140 .map_err(|e| e.to_string()),
141 other => Err(format!("expected json, got {other:?}")),
142 }
143 }
144}
145
146#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
148#[serde(transparent)]
149pub struct Id(String);
150
151impl Id {
152 pub fn new_v7() -> Self {
153 Id(uuid::Uuid::now_v7().to_string())
154 }
155
156 pub fn as_str(&self) -> &str {
157 &self.0
158 }
159}
160
161impl From<String> for Id {
162 fn from(s: String) -> Self {
163 Id(s)
164 }
165}
166
167impl From<&str> for Id {
168 fn from(s: &str) -> Self {
169 Id(s.to_owned())
170 }
171}
172
173impl From<&Id> for Id {
174 fn from(id: &Id) -> Self {
175 id.clone()
176 }
177}
178
179impl fmt::Display for Id {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 f.write_str(&self.0)
182 }
183}
184
185impl fmt::Debug for Id {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 write!(f, "Id({})", self.0)
188 }
189}
190
191impl ColumnValue for Id {
192 const TYPE: ColumnType = ColumnType::Id;
193 fn into_value(self) -> Value {
194 Value::Text(self.0)
195 }
196 fn from_value(value: Value) -> Result<Self, String> {
197 match value {
198 Value::Text(s) => Ok(Id(s)),
199 other => Err(format!("expected id, got {other:?}")),
200 }
201 }
202}
203
204impl ColumnValue for Hash {
205 const TYPE: ColumnType = ColumnType::Bytes;
206 fn into_value(self) -> Value {
207 Value::Bytes(self.as_bytes().to_vec())
208 }
209 fn from_value(value: Value) -> Result<Self, String> {
210 match value {
211 Value::Bytes(b) => Hash::from_slice(&b).ok_or_else(|| "expected 32 bytes".to_owned()),
212 other => Err(format!("expected hash bytes, got {other:?}")),
213 }
214 }
215}
216
217#[derive(Clone, Debug)]
219pub struct Row {
220 table: Arc<TableDef>,
221 values: Vec<Value>,
222}
223
224impl Row {
225 pub fn new(table: Arc<TableDef>, values: Vec<Value>) -> Self {
227 debug_assert_eq!(
228 table.columns.len(),
229 values.len(),
230 "row width for {}",
231 table.name
232 );
233 Self { table, values }
234 }
235
236 pub fn table(&self) -> &Arc<TableDef> {
237 &self.table
238 }
239
240 pub fn values(&self) -> &[Value] {
241 &self.values
242 }
243
244 pub fn into_values(self) -> Vec<Value> {
245 self.values
246 }
247
248 pub fn value(&self, column: &str) -> Option<&Value> {
249 self.table.position(column).map(|i| &self.values[i])
250 }
251
252 pub fn get<T: ColumnValue>(&self, column: &str) -> Result<T, DecodeError> {
253 let value = self.value(column).ok_or_else(|| {
254 DecodeError::new(column, format!("no such column on `{}`", self.table.name))
255 })?;
256 T::from_value(value.clone()).map_err(|m| DecodeError::new(column, m))
257 }
258
259 pub(crate) fn set(&mut self, column: &str, value: Value) {
260 if let Some(i) = self.table.position(column) {
261 self.values[i] = value;
262 }
263 }
264
265 pub fn to_client_json(&self) -> serde_json::Map<String, serde_json::Value> {
267 self.table
268 .columns
269 .iter()
270 .zip(&self.values)
271 .filter(|(c, _)| c.returned)
272 .map(|(c, v)| (camel_case(c.name), v.to_json()))
273 .collect()
274 }
275}
276
277pub(crate) fn camel_case(snake: &str) -> String {
278 let mut out = String::with_capacity(snake.len());
279 let mut upper = false;
280 for ch in snake.chars() {
281 if ch == '_' {
282 upper = true;
283 } else if upper {
284 out.extend(ch.to_uppercase());
285 upper = false;
286 } else {
287 out.push(ch);
288 }
289 }
290 out
291}