1use std::marker::PhantomData;
4use std::sync::Arc;
5
6use crate::adapter::{
7 DbError, DbResult, Delete, Filter, Insert, Op, Order, Queries, Select, Update,
8};
9use crate::model::{Col, Model, OnTable};
10use crate::schema::{DefaultValue, Schema, TableDef};
11use crate::value::{ColumnValue, Row, Value};
12
13#[derive(Clone, Debug, PartialEq)]
14enum Expr {
15 All,
16 Cmp(&'static str, Op, Value),
17 In(&'static str, Vec<Value>),
18 Null(&'static str, bool),
19 StartsWith(&'static str, String),
20 And(Vec<Expr>),
21 Or(Vec<Expr>),
22}
23
24#[derive(Clone, Debug, PartialEq)]
26pub struct Where<M> {
27 expr: Expr,
28 _model: PhantomData<fn() -> M>,
29}
30
31impl<M> Where<M> {
32 fn wrap(expr: Expr) -> Self {
33 Self {
34 expr,
35 _model: PhantomData,
36 }
37 }
38
39 pub fn all() -> Self {
40 Self::wrap(Expr::All)
41 }
42
43 pub(crate) fn cmp(column: &'static str, op: Op, value: Value) -> Self {
44 Self::wrap(Expr::Cmp(column, op, value))
45 }
46
47 pub(crate) fn in_list(column: &'static str, values: Vec<Value>) -> Self {
48 Self::wrap(Expr::In(column, values))
49 }
50
51 pub(crate) fn null(column: &'static str, is_null: bool) -> Self {
52 Self::wrap(Expr::Null(column, is_null))
53 }
54
55 pub(crate) fn starts_with(column: &'static str, prefix: String) -> Self {
56 Self::wrap(Expr::StartsWith(column, prefix))
57 }
58
59 pub fn and(self, other: Where<M>) -> Self {
60 Self::wrap(Expr::And(vec![self.expr, other.expr]))
61 }
62
63 pub fn or(self, other: Where<M>) -> Self {
64 Self::wrap(Expr::Or(vec![self.expr, other.expr]))
65 }
66
67 pub(crate) fn resolve(&self, table: &TableDef) -> DbResult<Filter> {
68 resolve(&self.expr, table)
69 }
70}
71
72fn position(table: &TableDef, column: &str) -> DbResult<usize> {
73 table
74 .position(column)
75 .ok_or_else(|| DbError::Schema(format!("`{}` has no column `{column}`", table.name)))
76}
77
78fn resolve(expr: &Expr, table: &TableDef) -> DbResult<Filter> {
79 Ok(match expr {
80 Expr::All => Filter::All,
81 Expr::Cmp(c, op, v) => Filter::Cmp {
82 column: position(table, c)?,
83 op: *op,
84 value: v.clone(),
85 },
86 Expr::In(c, vs) => Filter::In {
87 column: position(table, c)?,
88 values: vs.clone(),
89 },
90 Expr::Null(c, n) => Filter::Null {
91 column: position(table, c)?,
92 is_null: *n,
93 },
94 Expr::StartsWith(c, p) => Filter::StartsWith {
95 column: position(table, c)?,
96 prefix: p.clone(),
97 },
98 Expr::And(es) => Filter::And(
99 es.iter()
100 .map(|e| resolve(e, table))
101 .collect::<DbResult<_>>()?,
102 ),
103 Expr::Or(es) => Filter::Or(
104 es.iter()
105 .map(|e| resolve(e, table))
106 .collect::<DbResult<_>>()?,
107 ),
108 })
109}
110
111pub(crate) fn full_row(table: &TableDef, given: Vec<(&str, Value)>) -> DbResult<Vec<Value>> {
113 let mut values: Vec<Option<Value>> = vec![None; table.columns.len()];
114 for (name, value) in given {
115 values[position(table, name)?] = Some(value);
116 }
117 let now = time::OffsetDateTime::now_utc();
118 table
119 .columns
120 .iter()
121 .zip(values)
122 .map(|(column, value)| {
123 Ok(match (value, column.default) {
124 (Some(v), _) => v,
125 (None, Some(DefaultValue::Bool(b))) => Value::Bool(b),
126 (None, Some(DefaultValue::Int(i))) => Value::Int(i),
127 (None, Some(DefaultValue::Text(s))) => Value::Text(s.to_owned()),
128 (None, Some(DefaultValue::Now)) => Value::Timestamp(now),
129 (None, None) if column.nullable => Value::Null,
130 (None, None) => {
131 return Err(DbError::Schema(format!(
132 "`{}.{}` needs a value",
133 table.name, column.name
134 )));
135 }
136 })
137 })
138 .collect()
139}
140
141pub struct Db<'a, Q: ?Sized> {
143 queries: &'a Q,
144 schema: &'a Schema,
145}
146
147impl<Q: ?Sized> Clone for Db<'_, Q> {
148 fn clone(&self) -> Self {
149 *self
150 }
151}
152
153impl<Q: ?Sized> Copy for Db<'_, Q> {}
154
155impl<'a, Q: Queries + ?Sized> Db<'a, Q> {
156 pub fn new(queries: &'a Q, schema: &'a Schema) -> Self {
157 Self { queries, schema }
158 }
159
160 pub fn schema(&self) -> &'a Schema {
161 self.schema
162 }
163
164 pub fn raw(&self) -> &'a Q {
165 self.queries
166 }
167
168 fn table<M: Model>(&self) -> DbResult<&'a Arc<TableDef>> {
169 self.schema
170 .table(M::TABLE)
171 .ok_or_else(|| DbError::Schema(format!("table `{}` is not registered", M::TABLE)))
172 }
173
174 pub fn find<M: Model>(&self, filter: Where<M>) -> Find<'a, Q, M> {
175 Find {
176 db: *self,
177 filter,
178 order: Vec::new(),
179 limit: None,
180 offset: None,
181 }
182 }
183
184 pub async fn insert<M: Model>(&self, model: &M) -> DbResult<M> {
185 let table = self.table::<M>()?;
186 let values = full_row(table, model.encode())?;
187 let row = self.queries.insert(Insert { table, values }).await?;
188 Ok(M::decode(&row)?)
189 }
190
191 pub async fn insert_row<M: Model>(&self, values: Vec<(&str, Value)>) -> DbResult<Row> {
193 let table = self.table::<M>()?;
194 let values = full_row(table, values)?;
195 self.queries.insert(Insert { table, values }).await
196 }
197
198 pub fn update<M: Model>(&self, filter: Where<M>) -> UpdateBuilder<'a, Q, M> {
199 UpdateBuilder {
200 db: *self,
201 filter,
202 set: Vec::new(),
203 }
204 }
205
206 pub async fn delete<M: Model>(&self, filter: Where<M>) -> DbResult<u64> {
207 let table = self.table::<M>()?;
208 let filter = filter.resolve(table)?;
209 self.queries.delete(Delete { table, filter }).await
210 }
211
212 pub async fn count<M: Model>(&self, filter: Where<M>) -> DbResult<u64> {
213 let table = self.table::<M>()?;
214 let filter = filter.resolve(table)?;
215 self.queries
216 .count(Select {
217 table,
218 filter,
219 order: Vec::new(),
220 limit: None,
221 offset: None,
222 })
223 .await
224 }
225}
226
227pub struct Find<'a, Q: ?Sized, M> {
228 db: Db<'a, Q>,
229 filter: Where<M>,
230 order: Vec<(&'static str, Order)>,
231 limit: Option<u64>,
232 offset: Option<u64>,
233}
234
235impl<'a, Q: Queries + ?Sized, M: Model> Find<'a, Q, M> {
236 pub fn order_by(mut self, (column, order): (&'static str, Order)) -> Self {
237 self.order.push((column, order));
238 self
239 }
240
241 pub fn limit(mut self, limit: u64) -> Self {
242 self.limit = Some(limit);
243 self
244 }
245
246 pub fn offset(mut self, offset: u64) -> Self {
247 self.offset = Some(offset);
248 self
249 }
250
251 fn select(&self, limit: Option<u64>) -> DbResult<Select<'a>> {
252 let table = self.db.table::<M>()?;
253 let order = self
254 .order
255 .iter()
256 .map(|(c, o)| Ok((position(table, c)?, *o)))
257 .collect::<DbResult<_>>()?;
258 Ok(Select {
259 table,
260 filter: self.filter.resolve(table)?,
261 order,
262 limit,
263 offset: self.offset,
264 })
265 }
266
267 pub async fn one(self) -> DbResult<Option<M>> {
268 Ok(self.one_row().await?.map(|r| M::decode(&r)).transpose()?)
269 }
270
271 pub async fn all(self) -> DbResult<Vec<M>> {
272 let rows = self.db.queries.find_many(self.select(self.limit)?).await?;
273 Ok(rows.iter().map(M::decode).collect::<Result<_, _>>()?)
274 }
275
276 pub async fn one_row(self) -> DbResult<Option<Row>> {
278 self.db.queries.find_one(self.select(Some(1))?).await
279 }
280
281 pub async fn all_rows(self) -> DbResult<Vec<Row>> {
282 self.db.queries.find_many(self.select(self.limit)?).await
283 }
284}
285
286pub struct UpdateBuilder<'a, Q: ?Sized, M> {
287 db: Db<'a, Q>,
288 filter: Where<M>,
289 set: Vec<(&'static str, Value)>,
290}
291
292impl<Q: Queries + ?Sized, M: Model> UpdateBuilder<'_, Q, M> {
293 pub fn set<O: OnTable<Table = M>, T: ColumnValue>(
294 mut self,
295 column: Col<O, T>,
296 value: impl Into<T>,
297 ) -> Self {
298 self.set.push((column.name(), value.into().into_value()));
299 self
300 }
301
302 pub fn set_raw(mut self, column: &'static str, value: Value) -> Self {
304 self.set.push((column, value));
305 self
306 }
307
308 pub async fn exec(self) -> DbResult<u64> {
309 let table = self.db.table::<M>()?;
310 let mut set = self
311 .set
312 .iter()
313 .map(|(c, v)| Ok((position(table, c)?, v.clone())))
314 .collect::<DbResult<Vec<_>>>()?;
315 if let Some(updated_at) = table.position("updated_at")
316 && !set.iter().any(|(i, _)| *i == updated_at)
317 {
318 set.push((
319 updated_at,
320 Value::Timestamp(time::OffsetDateTime::now_utc()),
321 ));
322 }
323 let filter = self.filter.resolve(table)?;
324 self.db.queries.update(Update { table, filter, set }).await
325 }
326}