1use luxid_core::error::{Error, Result};
4use sea_orm::{
5 ActiveModelBehavior, ActiveModelTrait, ColumnTrait, EntityTrait, FromQueryResult,
6 IntoActiveModel, Order, PaginatorTrait, PrimaryKeyTrait, QueryFilter, QueryOrder, QuerySelect,
7 Select, Value,
8};
9use serde::Serialize;
10
11use crate::db;
12use crate::hooks::Hooks;
13use crate::relations::Relations;
14use crate::with_connection;
15use luxid_core::middleware::BoxFuture;
16
17pub type PrimaryKeyOf<E> = <<E as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType;
19
20pub(crate) fn database_error(err: sea_orm::DbErr) -> Error {
21 Error::internal(format!("database error: {err}"))
22}
23
24pub trait ColumnRef<E: EntityTrait> {
32 type Value;
34
35 fn column(&self) -> E::Column;
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize)]
41pub struct Paginated<T> {
42 pub data: Vec<T>,
43 pub page: u64,
44 pub per_page: u64,
45 pub total: u64,
46 pub last_page: u64,
47}
48
49impl<T> Paginated<T> {
50 pub fn is_empty(&self) -> bool {
51 self.data.is_empty()
52 }
53
54 pub fn len(&self) -> usize {
55 self.data.len()
56 }
57
58 pub fn has_more(&self) -> bool {
59 self.page < self.last_page
60 }
61}
62
63type Loader<M> = Box<dyn for<'a> Fn(&'a mut Vec<M>) -> BoxFuture<'a, Result<()>> + Send + Sync>;
67
68pub struct Query<E: EntityTrait> {
69 select: Select<E>,
70 loaders: Vec<Loader<E::Model>>,
71}
72
73impl<E> Query<E>
74where
75 E: EntityTrait,
76 E::Model: FromQueryResult + Send + Sync,
77{
78 pub fn new(select: Select<E>) -> Self {
79 Self {
80 select,
81 loaders: Vec::new(),
82 }
83 }
84
85 pub fn into_inner(self) -> Select<E> {
88 self.select
89 }
90
91 #[must_use]
92 pub fn where_eq<C, V>(mut self, column: C, value: V) -> Self
93 where
94 C: ColumnRef<E>,
95 V: Into<C::Value>,
96 C::Value: Into<Value>,
97 {
98 let target = column.column();
99 self.select = self.select.filter(target.eq(value.into().into()));
100 self
101 }
102
103 #[must_use]
104 pub fn where_ne<C, V>(mut self, column: C, value: V) -> Self
105 where
106 C: ColumnRef<E>,
107 V: Into<C::Value>,
108 C::Value: Into<Value>,
109 {
110 let target = column.column();
111 self.select = self.select.filter(target.ne(value.into().into()));
112 self
113 }
114
115 #[must_use]
116 pub fn where_gt<C, V>(mut self, column: C, value: V) -> Self
117 where
118 C: ColumnRef<E>,
119 V: Into<C::Value>,
120 C::Value: Into<Value>,
121 {
122 let target = column.column();
123 self.select = self.select.filter(target.gt(value.into().into()));
124 self
125 }
126
127 #[must_use]
128 pub fn where_lt<C, V>(mut self, column: C, value: V) -> Self
129 where
130 C: ColumnRef<E>,
131 V: Into<C::Value>,
132 C::Value: Into<Value>,
133 {
134 let target = column.column();
135 self.select = self.select.filter(target.lt(value.into().into()));
136 self
137 }
138
139 #[must_use]
140 pub fn where_in<C, V>(mut self, column: C, values: impl IntoIterator<Item = V>) -> Self
141 where
142 C: ColumnRef<E>,
143 V: Into<C::Value>,
144 C::Value: Into<Value>,
145 {
146 let target = column.column();
147 let values: Vec<Value> = values.into_iter().map(|v| v.into().into()).collect();
148
149 self.select = self.select.filter(target.is_in(values));
150 self
151 }
152
153 #[must_use]
154 pub fn where_like<C>(mut self, column: C, pattern: impl Into<String>) -> Self
155 where
156 C: ColumnRef<E>,
157 {
158 let target = column.column();
159 self.select = self.select.filter(target.like(pattern.into()));
160 self
161 }
162
163 #[must_use]
164 pub fn where_null<C: ColumnRef<E>>(mut self, column: C) -> Self {
165 let target = column.column();
166 self.select = self.select.filter(target.is_null());
167 self
168 }
169
170 #[must_use]
171 pub fn where_not_null<C: ColumnRef<E>>(mut self, column: C) -> Self {
172 let target = column.column();
173 self.select = self.select.filter(target.is_not_null());
174 self
175 }
176
177 #[must_use]
178 pub fn order_by_asc<C: ColumnRef<E>>(mut self, column: C) -> Self {
179 let target = column.column();
180 self.select = self.select.order_by(target, Order::Asc);
181 self
182 }
183
184 #[must_use]
185 pub fn order_by_desc<C: ColumnRef<E>>(mut self, column: C) -> Self {
186 let target = column.column();
187 self.select = self.select.order_by(target, Order::Desc);
188 self
189 }
190
191 #[must_use]
192 pub fn limit(mut self, limit: u64) -> Self {
193 self.select = self.select.limit(limit);
194 self
195 }
196
197 #[must_use]
198 pub fn offset(mut self, offset: u64) -> Self {
199 self.select = self.select.offset(offset);
200 self
201 }
202
203 pub async fn all(self) -> Result<Vec<E::Model>> {
204 let Self { select, loaders } = self;
205 let handle = db::current()?;
206
207 let mut rows = with_connection!(handle, |conn| select
208 .all(conn)
209 .await
210 .map_err(database_error))?;
211
212 load_all(&loaders, &mut rows).await?;
213 Ok(rows)
214 }
215
216 pub async fn first(self) -> Result<Option<E::Model>> {
217 let Self { select, loaders } = self;
218 let handle = db::current()?;
219
220 let found = with_connection!(handle, |conn| select
221 .one(conn)
222 .await
223 .map_err(database_error))?;
224
225 let Some(row) = found else {
226 return Ok(None);
227 };
228
229 let mut rows = vec![row];
232 load_all(&loaders, &mut rows).await?;
233
234 Ok(rows.pop())
235 }
236
237 pub async fn first_or_fail(self) -> Result<E::Model>
239 where
240 E::Model: Record<Entity = E>,
241 {
242 self.first()
243 .await?
244 .ok_or_else(|| Error::not_found(<E::Model as Record>::MODEL, "?"))
245 }
246
247 pub async fn count(self) -> Result<u64> {
248 let handle = db::current()?;
249 let select = self.select;
250
251 with_connection!(handle, |conn| select
252 .count(conn)
253 .await
254 .map_err(database_error))
255 }
256
257 pub async fn exists(self) -> Result<bool> {
258 Ok(self.count().await? > 0)
259 }
260
261 pub async fn paginate(self, page: u64, per_page: u64) -> Result<Paginated<E::Model>> {
264 let per_page = per_page.max(1);
265 let page = page.max(1);
266
267 let handle = db::current()?;
268
269 let Self { select, loaders } = self;
270
271 let (mut data, counts) = with_connection!(handle, |conn| {
272 let paginator = select.paginate(conn, per_page);
273
274 let counts = paginator
275 .num_items_and_pages()
276 .await
277 .map_err(database_error)?;
278 let data = paginator
279 .fetch_page(page - 1)
280 .await
281 .map_err(database_error)?;
282
283 Ok::<_, Error>((data, counts))
284 })?;
285
286 load_all(&loaders, &mut data).await?;
287
288 Ok(Paginated {
289 data,
290 page,
291 per_page,
292 total: counts.number_of_items,
293 last_page: counts.number_of_pages.max(1),
294 })
295 }
296}
297
298impl<E> Query<E>
299where
300 E: EntityTrait,
301 E::Model: Relatable + FromQueryResult + Send + Sync,
302{
303 #[must_use]
309 pub fn with(mut self, name: impl Into<String>) -> Self {
310 let name = name.into();
311
312 self.loaders.push(Box::new(move |rows| {
313 E::Model::load_relation(name.clone(), rows)
314 }));
315 self
316 }
317}
318
319async fn load_all<M>(loaders: &[Loader<M>], rows: &mut Vec<M>) -> Result<()> {
320 if rows.is_empty() {
321 return Ok(());
322 }
323
324 for loader in loaders {
325 loader(rows).await?;
326 }
327 Ok(())
328}
329
330pub trait Relatable: Record {
332 fn relations(&self) -> &Relations;
333
334 fn relations_mut(&mut self) -> &mut Relations;
335
336 fn load_relation(name: String, parents: &mut Vec<Self>) -> BoxFuture<'_, Result<()>>;
338}
339
340pub trait Record: FromQueryResult + Send + Sync + Sized + 'static {
345 type Entity: EntityTrait<Model = Self>;
346
347 const MODEL: &'static str;
349
350 fn query() -> Query<Self::Entity> {
351 Query::new(Self::Entity::find())
352 }
353
354 fn find(id: PrimaryKeyOf<Self::Entity>) -> impl Future<Output = Result<Option<Self>>> + Send {
355 async move {
356 let handle = db::current()?;
357 let select = Self::Entity::find_by_id(id);
358
359 with_connection!(handle, |conn| select
360 .one(conn)
361 .await
362 .map_err(database_error))
363 }
364 }
365
366 fn find_or_fail(id: PrimaryKeyOf<Self::Entity>) -> impl Future<Output = Result<Self>> + Send
369 where
370 PrimaryKeyOf<Self::Entity>: Clone + std::fmt::Display,
371 {
372 async move {
373 let requested = id.clone();
374
375 Self::find(id)
376 .await?
377 .ok_or_else(|| Error::not_found(Self::MODEL, requested))
378 }
379 }
380
381 fn all() -> impl Future<Output = Result<Vec<Self>>> + Send {
382 async move { Self::query().all().await }
383 }
384
385 fn count_all() -> impl Future<Output = Result<u64>> + Send {
386 async move { Self::query().count().await }
387 }
388}
389
390pub async fn insert<A>(active: A) -> Result<<A::Entity as EntityTrait>::Model>
393where
394 A: ActiveModelTrait + ActiveModelBehavior + Send,
395 <A::Entity as EntityTrait>::Model: IntoActiveModel<A> + Hooks<Active = A>,
396{
397 type Model<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::Model;
398
399 let mut active = active;
400
401 Model::<A>::before_save(&mut active).await?;
402 Model::<A>::before_create(&mut active).await?;
403
404 let handle = db::current()?;
405 let stored = with_connection!(handle, |conn| active
406 .insert(conn)
407 .await
408 .map_err(database_error))?;
409
410 Model::<A>::after_create(&stored).await?;
411 Model::<A>::after_save(&stored).await?;
412
413 Ok(stored)
414}
415
416pub async fn update<A>(active: A) -> Result<<A::Entity as EntityTrait>::Model>
419where
420 A: ActiveModelTrait + ActiveModelBehavior + Send,
421 <A::Entity as EntityTrait>::Model: IntoActiveModel<A> + Hooks<Active = A>,
422{
423 type Model<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::Model;
424
425 let mut active = active;
426
427 Model::<A>::before_save(&mut active).await?;
428 Model::<A>::before_update(&mut active).await?;
429
430 let handle = db::current()?;
431 let stored = with_connection!(handle, |conn| active
432 .update(conn)
433 .await
434 .map_err(database_error))?;
435
436 Model::<A>::after_update(&stored).await?;
437 Model::<A>::after_save(&stored).await?;
438
439 Ok(stored)
440}
441
442pub async fn insert_without_hooks<A>(active: A) -> Result<<A::Entity as EntityTrait>::Model>
447where
448 A: ActiveModelTrait + ActiveModelBehavior + Send,
449 <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
450{
451 let handle = db::current()?;
452 with_connection!(handle, |conn| active
453 .insert(conn)
454 .await
455 .map_err(database_error))
456}
457
458pub async fn delete_by_id<E: EntityTrait>(id: PrimaryKeyOf<E>) -> Result<bool> {
460 let handle = db::current()?;
461
462 with_connection!(handle, |conn| {
463 E::delete_by_id(id)
464 .exec(conn)
465 .await
466 .map(|outcome| outcome.rows_affected > 0)
467 .map_err(database_error)
468 })
469}