1use std::fmt;
65use std::marker::PhantomData;
66use std::sync::Arc;
67
68use id_effect::{Effect, HList, Selector, fail, need, succeed};
69use sea_query::{Condition, Expr, ExprTrait, IntoCondition, Order, Query, SelectStatement, Value};
70
71use crate::client::{SqlClient, SqlClientService};
72use crate::error::SqlError;
73use crate::from_row::{FromRow, from_rows};
74use crate::query_builder::{BuildSql, Dialect};
75use crate::row::SqlRow;
76use crate::transaction::{SqlTransaction, SqlTransactionService};
77use crate::value::{SqlValue, ToSqlValue};
78
79pub trait Entity: FromRow + Send + 'static {
83 type Id: ToSqlValue + fmt::Debug + Send + 'static;
85
86 const NAME: &'static str;
88 const TABLE: &'static str;
90 const COLUMNS: &'static [&'static str];
92 const ID: &'static str;
94 const ID_GENERATED: bool = false;
96 const VERSION: Option<&'static str> = None;
98 const SOFT_DELETE: Option<&'static str> = None;
101 const TENANT: Option<&'static str> = None;
103
104 fn id(&self) -> Self::Id;
106
107 fn values(&self) -> Vec<(&'static str, SqlValue)>;
109
110 fn bump_version(&mut self) {}
113
114 fn scope() -> Condition {
117 Condition::all()
118 }
119}
120
121#[derive(Clone, Debug, PartialEq)]
125pub struct CurrentTenant(pub SqlValue);
126
127impl CurrentTenant {
128 #[inline]
130 pub fn new(value: impl ToSqlValue) -> Self {
131 Self(value.to_sql_value())
132 }
133}
134
135pub trait SqlExecutor: Send + Sync + 'static {
138 fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError>;
140 fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError>;
142}
143
144macro_rules! executor {
145 ($ty:ty) => {
146 impl SqlExecutor for $ty {
147 fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError> {
148 (**self).query(sql, params)
149 }
150
151 fn execute(&self, sql: &str, params: &[SqlValue]) -> Effect<u64, SqlError> {
152 (**self).execute(sql, params)
153 }
154 }
155 };
156}
157
158executor!(SqlClientService);
159executor!(SqlTransactionService);
160executor!(Arc<dyn SqlClient>);
161executor!(Arc<dyn SqlTransaction>);
162
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166pub struct Page {
167 pub limit: u64,
169 pub offset: u64,
171}
172
173impl Page {
174 #[inline]
176 pub fn new(limit: u64, offset: u64) -> Self {
177 Self { limit, offset }
178 }
179
180 #[inline]
182 pub fn number(number: u64, size: u64) -> Self {
183 Self::new(size, number.saturating_mul(size))
184 }
185}
186
187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189enum Filters {
190 All,
192 WithDeleted,
194 None,
196}
197
198type Stmt = (String, Vec<SqlValue>);
200
201type Run<A> = Box<dyn FnOnce(Arc<dyn SqlExecutor>) -> Effect<A, SqlError> + Send>;
203
204fn ready<A: Send + 'static>(r: Result<A, SqlError>) -> Effect<A, SqlError> {
205 match r {
206 Ok(a) => succeed(a),
207 Err(e) => fail(e),
208 }
209}
210
211fn rows<A: Send + 'static>(
213 (sql, params): Stmt,
214 f: impl FnOnce(Vec<SqlRow>) -> Result<A, SqlError> + Send + 'static,
215) -> Run<A> {
216 Box::new(move |ex| ex.query(&sql, ¶ms).flat_map(|rows| ready(f(rows))))
217}
218
219fn affected_any((sql, params): Stmt) -> Run<bool> {
221 Box::new(move |ex| ex.execute(&sql, ¶ms).map(|n| n > 0))
222}
223
224fn first<T: FromRow>(rows: Vec<SqlRow>) -> Result<Option<T>, SqlError> {
225 rows.first().map(T::from_row).transpose()
226}
227
228fn the_row<T: FromRow>(rows: Vec<SqlRow>) -> Result<T, SqlError> {
229 first(rows)?.ok_or(SqlError::RowNotFound)
230}
231
232fn and(base: Condition, cond: Condition) -> Condition {
234 if cond.is_empty() {
235 base
236 } else {
237 base.add(cond)
238 }
239}
240
241pub struct Repository<T> {
248 dialect: Dialect,
249 tenant: Option<SqlValue>,
250 filters: Filters,
251 entity: PhantomData<fn() -> T>,
252}
253
254impl<T> Clone for Repository<T> {
255 fn clone(&self) -> Self {
256 Self {
257 dialect: self.dialect,
258 tenant: self.tenant.clone(),
259 filters: self.filters,
260 entity: PhantomData,
261 }
262 }
263}
264
265impl<T> fmt::Debug for Repository<T> {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 f.debug_struct("Repository")
268 .field("entity", &std::any::type_name::<T>())
269 .field("dialect", &self.dialect)
270 .field("tenant", &self.tenant)
271 .field("filters", &self.filters)
272 .finish()
273 }
274}
275
276pub struct BoundRepository<T> {
279 repo: Repository<T>,
280 ex: Arc<dyn SqlExecutor>,
281}
282
283impl<T> Clone for BoundRepository<T> {
284 fn clone(&self) -> Self {
285 Self {
286 repo: self.repo.clone(),
287 ex: Arc::clone(&self.ex),
288 }
289 }
290}
291
292impl<T> fmt::Debug for BoundRepository<T> {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 f.debug_tuple("BoundRepository").field(&self.repo).finish()
295 }
296}
297
298impl<T: Entity> Repository<T> {
299 pub fn new(dialect: Dialect) -> Self {
301 Self {
302 dialect,
303 tenant: None,
304 filters: Filters::All,
305 entity: PhantomData,
306 }
307 }
308
309 pub fn for_current_tenant<R, J>(dialect: Dialect) -> Effect<Self, SqlError, R>
311 where
312 R: Selector<CurrentTenant, J> + HList,
313 {
314 need::<CurrentTenant>().flat_map(move |t| succeed(Self::new(dialect).with_tenant(t.0.clone())))
315 }
316
317 #[must_use]
320 pub fn with_tenant(&self, tenant: impl ToSqlValue) -> Self {
321 Self {
322 tenant: Some(tenant.to_sql_value()),
323 ..self.clone()
324 }
325 }
326
327 #[must_use]
329 pub fn with_deleted(&self) -> Self {
330 Self {
331 filters: Filters::WithDeleted,
332 ..self.clone()
333 }
334 }
335
336 #[must_use]
340 pub fn unscoped(&self) -> Self {
341 Self {
342 filters: Filters::None,
343 ..self.clone()
344 }
345 }
346
347 #[inline]
349 pub fn dialect(&self) -> Dialect {
350 self.dialect
351 }
352
353 #[inline]
355 pub fn tenant(&self) -> Option<&SqlValue> {
356 self.tenant.as_ref()
357 }
358
359 pub fn on(&self, executor: impl SqlExecutor) -> BoundRepository<T> {
361 BoundRepository {
362 repo: self.clone(),
363 ex: Arc::new(executor),
364 }
365 }
366
367 fn tenant_value(&self) -> Result<Option<SqlValue>, SqlError> {
370 match (T::TENANT, &self.tenant) {
371 (None, _) => Ok(None),
372 (Some(_), Some(v)) => Ok(Some(v.clone())),
373 (Some(_), None) if self.filters == Filters::None => Ok(None),
374 (Some(col), None) => Err(SqlError::Unsupported(format!(
375 "entity `{}` is scoped by tenant column `{col}` but the repository has no tenant \
376 (Repository::with_tenant / for_current_tenant, or unscoped())",
377 T::NAME
378 ))),
379 }
380 }
381
382 fn scope(&self, soft_delete: bool) -> Result<Condition, SqlError> {
384 let tenant = self.tenant_value()?;
385 let mut cond = Condition::all();
386 if self.filters == Filters::None {
387 return Ok(cond);
388 }
389 if let (Some(col), Some(v)) = (T::TENANT, tenant) {
390 cond = cond.add(Expr::col(col).eq(Value::from(v)));
391 }
392 if let (Some(col), true, Filters::All) = (T::SOFT_DELETE, soft_delete, self.filters) {
393 cond = cond.add(Expr::col(col).is_null());
394 }
395 Ok(and(cond, T::scope()))
396 }
397
398 fn id_is(id: &T::Id) -> Condition {
399 Condition::all().add(Expr::col(T::ID).eq(Value::from(id.to_sql_value())))
400 }
401
402 fn render(&self, stmt: &impl BuildSql) -> Result<Stmt, SqlError> {
403 stmt.build_sql(self.dialect)
404 }
405
406 fn select(&self, cond: Condition) -> Result<SelectStatement, SqlError> {
408 let mut stmt = Query::select();
409 stmt.columns(T::COLUMNS.iter().copied()).from(T::TABLE);
410 self.filter(&mut stmt, cond)?;
411 Ok(stmt)
412 }
413
414 fn filter(&self, stmt: &mut SelectStatement, cond: Condition) -> Result<(), SqlError> {
417 let cond = and(self.scope(true)?, cond);
418 if !cond.is_empty() {
419 stmt.cond_where(cond);
420 }
421 Ok(())
422 }
423
424 fn find_op(&self, id: &T::Id) -> Result<Run<Option<T>>, SqlError> {
425 let stmt = self.select(Self::id_is(id))?.limit(1).to_owned();
426 Ok(rows(self.render(&stmt)?, first))
427 }
428
429 fn find_by_op(&self, cond: Condition, page: Option<Page>) -> Result<Run<Vec<T>>, SqlError> {
430 let mut stmt = self.select(cond)?;
431 stmt.order_by(T::ID, Order::Asc);
432 if let Some(page) = page {
433 stmt.limit(page.limit).offset(page.offset);
434 }
435 Ok(rows(self.render(&stmt)?, |rows| from_rows(&rows)))
436 }
437
438 fn count_op(&self, cond: Condition) -> Result<Run<u64>, SqlError> {
439 let mut stmt = Query::select();
440 stmt.expr(Expr::cust("COUNT(*)")).from(T::TABLE);
441 self.filter(&mut stmt, cond)?;
442 Ok(rows(self.render(&stmt)?, |rows| {
443 let n = rows
444 .first()
445 .ok_or(SqlError::RowNotFound)?
446 .get::<i64>(0usize)?;
447 Ok(u64::try_from(n).unwrap_or_default())
448 }))
449 }
450
451 fn exists_stmt(&self, id: &T::Id) -> Result<Stmt, SqlError> {
452 let stmt = Query::select()
453 .column(T::ID)
454 .from(T::TABLE)
455 .cond_where(and(self.scope(true)?, Self::id_is(id)))
456 .limit(1)
457 .to_owned();
458 self.render(&stmt)
459 }
460
461 fn exists_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
462 Ok(rows(self.exists_stmt(id)?, |rows| Ok(!rows.is_empty())))
463 }
464
465 fn insert_op(&self, entity: T) -> Result<Run<T>, SqlError> {
466 let tenant = self.tenant_value()?;
467 let (mut columns, mut values) = (Vec::new(), Vec::new());
468 for (col, v) in entity.values() {
469 let generated = col == T::ID && T::ID_GENERATED;
470 if generated || (tenant.is_some() && Some(col) == T::TENANT) {
471 continue;
472 }
473 columns.push(col);
474 values.push(Expr::val(Value::from(v)));
475 }
476 if let (Some(col), Some(v)) = (T::TENANT, tenant) {
477 columns.push(col);
478 values.push(Expr::val(Value::from(v)));
479 }
480 let mut stmt = Query::insert();
481 stmt
482 .into_table(T::TABLE)
483 .columns(columns)
484 .values_panic(values);
485 if self.dialect != Dialect::MySql {
486 stmt.returning(Query::returning().columns(T::COLUMNS.iter().copied()));
487 return Ok(rows(self.render(&stmt)?, the_row));
488 }
489 if T::ID_GENERATED {
490 return Err(SqlError::Unsupported(format!(
491 "entity `{}`: MySQL has no RETURNING, so a generated id cannot be read back on insert",
492 T::NAME
493 )));
494 }
495 let (sql, params) = self.render(&stmt)?;
496 let read_back = Query::select()
497 .columns(T::COLUMNS.iter().copied())
498 .from(T::TABLE)
499 .cond_where(Self::id_is(&entity.id()))
500 .to_owned();
501 let read_back = rows(self.render(&read_back)?, the_row);
502 Ok(Box::new(move |ex| {
503 let again = Arc::clone(&ex);
504 ex.execute(&sql, ¶ms)
505 .flat_map(move |_| read_back(again))
506 }))
507 }
508
509 fn update_op(&self, mut entity: T) -> Result<Run<T>, SqlError> {
510 let id = entity.id();
511 let mut cond = and(self.scope(true)?, Self::id_is(&id));
512 let mut stmt = Query::update();
513 stmt.table(T::TABLE);
514 for (col, v) in entity.values() {
515 if Some(col) == T::VERSION {
516 cond = cond.add(Expr::col(col).eq(Value::from(v)));
517 stmt.value(col, Expr::col(col).add(1));
518 } else if col != T::ID && Some(col) != T::TENANT && Some(col) != T::SOFT_DELETE {
519 stmt.value(col, Value::from(v));
520 }
521 }
522 stmt.cond_where(cond);
523 let (sql, params) = self.render(&stmt)?;
524 let stale = match T::VERSION {
526 Some(_) => Some(self.exists_stmt(&id)?),
527 None => None,
528 };
529 let id = format!("{id:?}");
530 Ok(Box::new(move |ex| {
531 ex.execute(&sql, ¶ms).flat_map(move |n| {
532 if n > 0 {
533 entity.bump_version();
534 return succeed(entity);
535 }
536 let Some((sql, params)) = stale else {
537 return fail(SqlError::RowNotFound);
538 };
539 ex.query(&sql, ¶ms).flat_map(move |rows| {
540 fail(if rows.is_empty() {
541 SqlError::RowNotFound
542 } else {
543 SqlError::StaleVersion {
544 entity: T::NAME.to_owned(),
545 id,
546 }
547 })
548 })
549 })
550 }))
551 }
552
553 fn delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
554 let Some(col) = T::SOFT_DELETE else {
555 return self.hard_delete_op(id);
556 };
557 let mut stmt = Query::update();
558 stmt.table(T::TABLE).value(
559 col,
560 Value::from(SqlValue::Timestamp(jiff::Timestamp::now())),
561 );
562 if let Some(version) = T::VERSION {
563 stmt.value(version, Expr::col(version).add(1));
564 }
565 stmt.cond_where(and(self.scope(true)?, Self::id_is(id)));
566 Ok(affected_any(self.render(&stmt)?))
567 }
568
569 fn hard_delete_op(&self, id: &T::Id) -> Result<Run<bool>, SqlError> {
570 let stmt = Query::delete()
571 .from_table(T::TABLE)
572 .cond_where(and(self.scope(false)?, Self::id_is(id)))
573 .to_owned();
574 Ok(affected_any(self.render(&stmt)?))
575 }
576
577 fn in_env<A, R, I>(op: Result<Run<A>, SqlError>) -> Effect<A, SqlError, R>
579 where
580 A: Send + 'static,
581 R: Selector<SqlClientService, I> + HList,
582 {
583 match op {
584 Ok(run) => need::<SqlClientService>().flat_map(move |svc| run(svc).narrow()),
585 Err(e) => fail(e),
586 }
587 }
588}
589
590impl<T: Entity> BoundRepository<T> {
591 #[inline]
593 pub fn repository(&self) -> &Repository<T> {
594 &self.repo
595 }
596
597 fn run<A: Send + 'static>(&self, op: Result<Run<A>, SqlError>) -> Effect<A, SqlError> {
598 match op {
599 Ok(run) => run(Arc::clone(&self.ex)),
600 Err(e) => fail(e),
601 }
602 }
603}
604
605macro_rules! operations {
608 ($(
609 $(#[$doc:meta])*
610 fn $name:ident($($arg:ident: $ty:ty),*) -> $ret:ty = $op:ident($($call:expr),*);
611 )*) => {
612 impl<T: Entity> Repository<T> {
613 $(
614 $(#[$doc])*
615 pub fn $name<R, I>(&self, $($arg: $ty),*) -> Effect<$ret, SqlError, R>
616 where
617 R: Selector<SqlClientService, I> + HList,
618 {
619 Self::in_env(self.$op($($call),*))
620 }
621 )*
622 }
623
624 impl<T: Entity> BoundRepository<T> {
625 $(
626 $(#[$doc])*
627 pub fn $name(&self, $($arg: $ty),*) -> Effect<$ret, SqlError> {
628 self.run(self.repo.$op($($call),*))
629 }
630 )*
631 }
632 };
633}
634
635operations! {
636 fn find(id: T::Id) -> Option<T> = find_op(&id);
638 fn find_all() -> Vec<T> = find_by_op(Condition::all(), None);
640 fn find_by(cond: impl IntoCondition) -> Vec<T> = find_by_op(cond.into_condition(), None);
643 fn find_page(cond: impl IntoCondition, page: Page) -> Vec<T> =
645 find_by_op(cond.into_condition(), Some(page));
646 fn count() -> u64 = count_op(Condition::all());
648 fn count_by(cond: impl IntoCondition) -> u64 = count_op(cond.into_condition());
650 fn exists(id: T::Id) -> bool = exists_op(&id);
652 fn insert(entity: T) -> T = insert_op(entity);
655 fn update(entity: T) -> T = update_op(entity);
661 fn delete(id: T::Id) -> bool = delete_op(&id);
664 fn hard_delete(id: T::Id) -> bool = hard_delete_op(&id);
667}