1use std::fmt;
76use std::marker::PhantomData;
77use std::sync::Arc;
78
79use id_effect::{Effect, HList, Selector, fail, need, succeed};
80use sea_query::{Condition, Expr, ExprTrait, IntoCondition, Order, Query, SelectStatement, Value};
81
82use crate::client::{SqlClient, SqlClientService};
83use crate::error::SqlError;
84use crate::from_row::{FromRow, from_rows};
85use crate::query_builder::{BuildSql, Dialect};
86use crate::row::SqlRow;
87use crate::transaction::{SqlTransaction, SqlTransactionService};
88use crate::value::{SqlValue, ToSqlValue};
89
90pub mod hooks;
92#[cfg(feature = "outbox")]
93pub mod outbox;
94pub mod page;
95pub mod relations;
96
97pub use hooks::{BoundHookedRepository, EntityHooks, HookContext, HookedRepository};
98pub use page::{Keyset, PageCursor, PageCursorError, PageLimits, Paged, SortOrder};
99pub use relations::{
100 BoundEagerRepository, EagerRepository, FieldMeta, Loaded, MAX_EAGER_DEPTH, Relation,
101 RelationKind, RelationMeta,
102};
103
104pub trait Entity: FromRow + Send + 'static {
108 type Id: ToSqlValue + fmt::Debug + Send + 'static;
110
111 const NAME: &'static str;
113 const TABLE: &'static str;
115 const COLUMNS: &'static [&'static str];
117 const ID: &'static str;
119 const ID_GENERATED: bool = false;
121 const VERSION: Option<&'static str> = None;
123 const SOFT_DELETE: Option<&'static str> = None;
126 const TENANT: Option<&'static str> = None;
128 const LABEL: &'static str = Self::NAME;
131 const FIELDS: &'static [FieldMeta] = &[];
134 const RELATIONS: &'static [RelationMeta] = &[];
136
137 fn id(&self) -> Self::Id;
139
140 fn values(&self) -> Vec<(&'static str, SqlValue)>;
142
143 fn bump_version(&mut self) {}
146
147 fn scope() -> Condition {
150 Condition::all()
151 }
152}
153
154#[derive(Clone, Debug, PartialEq)]
158pub struct CurrentTenant(pub SqlValue);
159
160impl CurrentTenant {
161 #[inline]
163 pub fn new(value: impl ToSqlValue) -> Self {
164 Self(value.to_sql_value())
165 }
166}
167
168pub trait SqlExecutor: Send + Sync + 'static {
171 fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError>;
173 fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError>;
175}
176
177macro_rules! executor {
178 ($ty:ty) => {
179 impl SqlExecutor for $ty {
180 fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError> {
181 (**self).query(sql, params)
182 }
183
184 fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError> {
185 (**self).execute(sql, params)
186 }
187 }
188 };
189}
190
191executor!(SqlClientService);
192executor!(SqlTransactionService);
193executor!(Arc<dyn SqlClient>);
194executor!(Arc<dyn SqlTransaction>);
195
196#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
199pub struct Page {
200 pub limit: u64,
202 pub offset: u64,
204}
205
206impl Page {
207 #[inline]
209 pub fn new(limit: u64, offset: u64) -> Self {
210 Self { limit, offset }
211 }
212
213 #[inline]
215 pub fn number(number: u64, size: u64) -> Self {
216 Self::new(size, number.saturating_mul(size))
217 }
218}
219
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222enum Filters {
223 All,
225 WithDeleted,
227 None,
229}
230
231type Stmt = (String, Vec<SqlValue>);
233
234type Run<A> = Box<dyn FnOnce(Arc<dyn SqlExecutor>) -> Effect<A, SqlError> + Send>;
236
237fn ready<A: Send + 'static>(r: Result<A, SqlError>) -> Effect<A, SqlError> {
238 match r {
239 Ok(a) => succeed(a),
240 Err(e) => fail(e),
241 }
242}
243
244fn rows<A: Send + 'static>(
246 (sql, params): Stmt,
247 f: impl FnOnce(Vec<SqlRow>) -> Result<A, SqlError> + Send + 'static,
248) -> Run<A> {
249 Box::new(move |ex| ex.query(&sql, ¶ms).flat_map(|rows| ready(f(rows))))
250}
251
252fn affected_any((sql, params): Stmt) -> Run<bool> {
254 Box::new(move |ex| ex.execute(&sql, ¶ms).map(|n| n > 0))
255}
256
257fn first<T: FromRow>(rows: Vec<SqlRow>) -> Result<Option<T>, SqlError> {
258 rows.first().map(T::from_row).transpose()
259}
260
261fn the_row<T: FromRow>(rows: Vec<SqlRow>) -> Result<T, SqlError> {
262 first(rows)?.ok_or(SqlError::RowNotFound)
263}
264
265fn and(base: Condition, cond: Condition) -> Condition {
267 if cond.is_empty() {
268 base
269 } else {
270 base.add(cond)
271 }
272}
273
274pub struct Repository<T> {
281 dialect: Dialect,
282 tenant: Option<SqlValue>,
283 filters: Filters,
284 entity: PhantomData<fn() -> T>,
285}
286
287impl<T> Clone for Repository<T> {
288 fn clone(&self) -> Self {
289 Self {
290 dialect: self.dialect,
291 tenant: self.tenant.clone(),
292 filters: self.filters,
293 entity: PhantomData,
294 }
295 }
296}
297
298impl<T> fmt::Debug for Repository<T> {
299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300 f.debug_struct("Repository")
301 .field("entity", &std::any::type_name::<T>())
302 .field("dialect", &self.dialect)
303 .field("tenant", &self.tenant)
304 .field("filters", &self.filters)
305 .finish()
306 }
307}
308
309pub struct BoundRepository<T> {
312 repo: Repository<T>,
313 ex: Arc<dyn SqlExecutor>,
314}
315
316impl<T> Clone for BoundRepository<T> {
317 fn clone(&self) -> Self {
318 Self {
319 repo: self.repo.clone(),
320 ex: Arc::clone(&self.ex),
321 }
322 }
323}
324
325impl<T> fmt::Debug for BoundRepository<T> {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 f.debug_tuple("BoundRepository").field(&self.repo).finish()
328 }
329}
330
331impl<T: Entity> Repository<T> {
332 pub fn new(dialect: Dialect) -> Self {
334 Self {
335 dialect,
336 tenant: None,
337 filters: Filters::All,
338 entity: PhantomData,
339 }
340 }
341
342 pub fn for_current_tenant<R, J>(dialect: Dialect) -> Effect<Self, SqlError, R>
344 where
345 R: Selector<CurrentTenant, J> + HList,
346 {
347 need::<CurrentTenant>().flat_map(move |t| succeed(Self::new(dialect).with_tenant(t.0.clone())))
348 }
349
350 #[must_use]
353 pub fn with_tenant(&self, tenant: impl ToSqlValue) -> Self {
354 Self {
355 tenant: Some(tenant.to_sql_value()),
356 ..self.clone()
357 }
358 }
359
360 #[must_use]
362 pub fn with_deleted(&self) -> Self {
363 Self {
364 filters: Filters::WithDeleted,
365 ..self.clone()
366 }
367 }
368
369 #[must_use]
373 pub fn unscoped(&self) -> Self {
374 Self {
375 filters: Filters::None,
376 ..self.clone()
377 }
378 }
379
380 #[inline]
382 pub fn dialect(&self) -> Dialect {
383 self.dialect
384 }
385
386 #[inline]
388 pub fn tenant(&self) -> Option<&SqlValue> {
389 self.tenant.as_ref()
390 }
391
392 pub fn on(&self, executor: impl SqlExecutor) -> BoundRepository<T> {
394 BoundRepository {
395 repo: self.clone(),
396 ex: Arc::new(executor),
397 }
398 }
399
400 fn tenant_value(&self) -> Result<Option<SqlValue>, SqlError> {
403 match (T::TENANT, &self.tenant) {
404 (None, _) => Ok(None),
405 (Some(_), Some(v)) => Ok(Some(v.clone())),
406 (Some(_), None) if self.filters == Filters::None => Ok(None),
407 (Some(col), None) => Err(SqlError::Unsupported(format!(
408 "entity `{}` is scoped by tenant column `{col}` but the repository has no tenant \
409 (Repository::with_tenant / for_current_tenant, or unscoped())",
410 T::NAME
411 ))),
412 }
413 }
414
415 fn scope(&self, soft_delete: bool) -> Result<Condition, SqlError> {
417 self.scope_in(None, soft_delete)
418 }
419
420 fn scope_in(
423 &self,
424 table: Option<&'static str>,
425 soft_delete: bool,
426 ) -> Result<Condition, SqlError> {
427 let tenant = self.tenant_value()?;
428 let mut cond = Condition::all();
429 if self.filters == Filters::None {
430 return Ok(cond);
431 }
432 let column = |col: &'static str| match table {
433 Some(table) => Expr::col((table, col)),
434 None => Expr::col(col),
435 };
436 if let (Some(col), Some(v)) = (T::TENANT, tenant) {
437 cond = cond.add(column(col).eq(Value::from(v)));
438 }
439 if let (Some(col), true, Filters::All) = (T::SOFT_DELETE, soft_delete, self.filters) {
440 cond = cond.add(column(col).is_null());
441 }
442 Ok(and(cond, T::scope()))
443 }
444
445 fn cast<C: Entity>(&self) -> Repository<C> {
447 Repository {
448 dialect: self.dialect,
449 tenant: self.tenant.clone(),
450 filters: self.filters,
451 entity: PhantomData,
452 }
453 }
454
455 fn id_is(id: &T::Id) -> Condition {
456 Condition::all().add(Expr::col(T::ID).eq(Value::from(id.to_sql_value())))
457 }
458
459 fn render(&self, stmt: &impl BuildSql) -> Result<Stmt, SqlError> {
460 stmt.build_sql(self.dialect)
461 }
462
463 fn select(&self, cond: Condition) -> Result<SelectStatement, SqlError> {
465 let mut stmt = Query::select();
466 stmt.columns(T::COLUMNS.iter().copied()).from(T::TABLE);
467 self.filter(&mut stmt, cond)?;
468 Ok(stmt)
469 }
470
471 fn filter(&self, stmt: &mut SelectStatement, cond: Condition) -> Result<(), SqlError> {
474 let cond = and(self.scope(true)?, cond);
475 if !cond.is_empty() {
476 stmt.cond_where(cond);
477 }
478 Ok(())
479 }
480
481 fn find_op(&self, id: &T::Id) -> Result<Run<Option<T>>, SqlError> {
482 let stmt = self.select(Self::id_is(id))?.limit(1).to_owned();
483 Ok(rows(self.render(&stmt)?, first))
484 }
485
486 fn find_by_op(&self, cond: Condition, page: Option<Page>) -> Result<Run<Vec<T>>, SqlError> {
487 let mut stmt = self.select(cond)?;
488 stmt.order_by(T::ID, Order::Asc);
489 if let Some(page) = page {
490 stmt.limit(page.limit).offset(page.offset);
491 }
492 Ok(rows(self.render(&stmt)?, |rows| from_rows(&rows)))
493 }
494
495 fn count_op(&self, cond: Condition) -> Result<Run<u64>, SqlError> {
496 let mut stmt = Query::select();
497 stmt.expr(Expr::cust("COUNT(*)")).from(T::TABLE);
498 self.filter(&mut stmt, cond)?;
499 Ok(rows(self.render(&stmt)?, |rows| {
500 let n = rows
501 .first()
502 .ok_or(SqlError::RowNotFound)?
503 .get::<i64>(0usize)?;
504 Ok(u64::try_from(n).unwrap_or_default())
505 }))
506 }
507
508 fn exists_stmt(&self, id: &T::Id) -> Result<Stmt, SqlError> {
509 let stmt = Query::select()
510 .column(T::ID)
511 .from(T::TABLE)
512 .cond_where(and(self.scope(true)?, Self::id_is(id)))
513 .limit(1)
514 .to_owned();
515 self.render(&stmt)
516 }
517
518 fn exists_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
519 Ok(rows(self.exists_stmt(id)?, |rows| Ok(!rows.is_empty())))
520 }
521
522 fn insert_op(&self, entity: T) -> Result<Run<T>, SqlError> {
523 let tenant = self.tenant_value()?;
524 let (mut columns, mut values) = (Vec::new(), Vec::new());
525 for (col, v) in entity.values() {
526 let generated = col == T::ID && T::ID_GENERATED;
527 if generated || (tenant.is_some() && Some(col) == T::TENANT) {
528 continue;
529 }
530 columns.push(col);
531 values.push(Expr::val(Value::from(v)));
532 }
533 if let (Some(col), Some(v)) = (T::TENANT, tenant) {
534 columns.push(col);
535 values.push(Expr::val(Value::from(v)));
536 }
537 let mut stmt = Query::insert();
538 stmt
539 .into_table(T::TABLE)
540 .columns(columns)
541 .values_panic(values);
542 if self.dialect != Dialect::MySql {
543 stmt.returning(Query::returning().columns(T::COLUMNS.iter().copied()));
544 return Ok(rows(self.render(&stmt)?, the_row));
545 }
546 if T::ID_GENERATED {
547 return Err(SqlError::Unsupported(format!(
548 "entity `{}`: MySQL has no RETURNING, so a generated id cannot be read back on insert",
549 T::NAME
550 )));
551 }
552 let (sql, params) = self.render(&stmt)?;
553 let read_back = Query::select()
554 .columns(T::COLUMNS.iter().copied())
555 .from(T::TABLE)
556 .cond_where(Self::id_is(&entity.id()))
557 .to_owned();
558 let read_back = rows(self.render(&read_back)?, the_row);
559 Ok(Box::new(move |ex| {
560 let again = Arc::clone(&ex);
561 ex.execute(&sql, ¶ms)
562 .flat_map(move |_| read_back(again))
563 }))
564 }
565
566 fn update_op(&self, mut entity: T) -> Result<Run<T>, SqlError> {
567 let id = entity.id();
568 let mut cond = and(self.scope(true)?, Self::id_is(&id));
569 let mut stmt = Query::update();
570 stmt.table(T::TABLE);
571 for (col, v) in entity.values() {
572 if Some(col) == T::VERSION {
573 cond = cond.add(Expr::col(col).eq(Value::from(v)));
574 stmt.value(col, Expr::col(col).add(1));
575 } else if col != T::ID && Some(col) != T::TENANT && Some(col) != T::SOFT_DELETE {
576 stmt.value(col, Value::from(v));
577 }
578 }
579 stmt.cond_where(cond);
580 let (sql, params) = self.render(&stmt)?;
581 let stale = match T::VERSION {
583 Some(_) => Some(self.exists_stmt(&id)?),
584 None => None,
585 };
586 let id = format!("{id:?}");
587 Ok(Box::new(move |ex| {
588 ex.execute(&sql, ¶ms).flat_map(move |n| {
589 if n > 0 {
590 entity.bump_version();
591 return succeed(entity);
592 }
593 let Some((sql, params)) = stale else {
594 return fail(SqlError::RowNotFound);
595 };
596 ex.query(&sql, ¶ms).flat_map(move |rows| {
597 fail(if rows.is_empty() {
598 SqlError::RowNotFound
599 } else {
600 SqlError::StaleVersion {
601 entity: T::NAME.to_owned(),
602 id,
603 }
604 })
605 })
606 })
607 }))
608 }
609
610 fn delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
611 let Some(col) = T::SOFT_DELETE else {
612 return self.hard_delete_op(id);
613 };
614 let mut stmt = Query::update();
615 stmt.table(T::TABLE).value(
616 col,
617 Value::from(SqlValue::Timestamp(jiff::Timestamp::now())),
618 );
619 if let Some(version) = T::VERSION {
620 stmt.value(version, Expr::col(version).add(1));
621 }
622 stmt.cond_where(and(self.scope(true)?, Self::id_is(id)));
623 Ok(affected_any(self.render(&stmt)?))
624 }
625
626 fn hard_delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
627 let stmt = Query::delete()
628 .from_table(T::TABLE)
629 .cond_where(and(self.scope(false)?, Self::id_is(id)))
630 .to_owned();
631 Ok(affected_any(self.render(&stmt)?))
632 }
633
634 fn in_env<A, R, I>(op: Result<Run<A>, SqlError>) -> Effect<A, SqlError, R>
636 where
637 A: Send + 'static,
638 R: Selector<SqlClientService, I> + HList,
639 {
640 match op {
641 Ok(run) => need::<SqlClientService>().flat_map(move |svc| run(svc).narrow()),
642 Err(e) => fail(e),
643 }
644 }
645}
646
647impl<T: Entity> BoundRepository<T> {
648 #[inline]
650 pub fn repository(&self) -> &Repository<T> {
651 &self.repo
652 }
653
654 fn run<A: Send + 'static>(&self, op: Result<Run<A>, SqlError>) -> Effect<A, SqlError> {
655 match op {
656 Ok(run) => run(Arc::clone(&self.ex)),
657 Err(e) => fail(e),
658 }
659 }
660}
661
662macro_rules! operations {
665 ($(
666 $(#[$doc:meta])*
667 fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty = $op:ident($($call:expr),*);
668 )*) => {
669 impl<T: Entity> Repository<T> {
670 $(
671 $(#[$doc])*
672 pub fn $name<R, I>(&self, $($arg: $ty),*) -> Effect<$ret, SqlError, R>
673 where
674 R: Selector<SqlClientService, I> + HList,
675 {
676 Self::in_env(self.$op($($call),*))
677 }
678 )*
679 }
680
681 impl<T: Entity> BoundRepository<T> {
682 $(
683 $(#[$doc])*
684 pub fn $name(&self, $($arg: $ty),*) -> Effect<$ret, SqlError> {
685 self.run(self.repo.$op($($call),*))
686 }
687 )*
688 }
689 };
690}
691
692operations! {
693 fn find(id: T::Id) -> Option<T> = find_op(&id);
695 fn find_all() -> Vec<T> = find_by_op(Condition::all(), None);
697 fn find_by(cond: impl IntoCondition) -> Vec<T> = find_by_op(cond.into_condition(), None);
700 fn find_page(cond: impl IntoCondition, page: Page) -> Vec<T> =
702 find_by_op(cond.into_condition(), Some(page));
703 fn count() -> u64 = count_op(Condition::all());
705 fn count_by(cond: impl IntoCondition) -> u64 = count_op(cond.into_condition());
707 fn exists(id: T::Id) -> bool = exists_op(&id);
709 fn insert(entity: T) -> T = insert_op(entity);
712 fn update(entity: T) -> T = update_op(entity);
718 fn delete(id: T::Id) -> bool = delete_op(&id);
721 fn hard_delete(id: T::Id) -> bool = hard_delete_op(&id);
724}