Skip to main content

id_effect_sql/repository/
mod.rs

1//! Entities and repositories (feature `repository`): `#[derive(Entity)]` maps a struct to a
2//! table, and [`Repository<T>`] runs its CRUD statements — built with [`sea_query`] and rendered
3//! for a [`Dialect`] — over the [`SqlClient`] in the environment, or over any [`SqlExecutor`]
4//! (an open transaction) with [`Repository::on`].
5//!
6//! - **Mapping** (data.orm #1). The table is `#[entity(table = "..")]` (default: the type name in
7//!   snake case), the columns are the [`FromRow`] columns (`#[from_row(rename = "..")]`, else
8//!   `#[schema("..")]`, else the field name), and `#[entity(id)]` marks the primary key
9//!   (`#[entity(id, generated)]`: the database assigns it, so inserts omit it and read it back).
10//!   `#[derive(Entity)]` needs `#[derive(FromRow)]` next to it; each column is written with
11//!   [`ToSqlValue`].
12//! - **Optimistic locking** (data.orm #5). An `#[entity(version)]` integer column is checked and
13//!   incremented by every [`update`](Repository::update) (`UPDATE … SET version = version + 1
14//!   WHERE id = ? AND version = ?`); when another writer got there first the update fails with
15//!   [`SqlError::StaleVersion`] naming the entity and id (and [`SqlError::RowNotFound`] when the
16//!   row is gone or filtered out).
17//! - **Global filters** (data.orm #8) are AND-ed into every `SELECT`, `UPDATE` and `DELETE` the
18//!   repository generates: `#[entity(soft_delete = "deleted_at")]` (rows whose column is not NULL
19//!   are hidden, and [`delete`](Repository::delete) sets it to the current time),
20//!   `#[entity(tenant = "org_id")]` (only the repository's tenant — [`Repository::with_tenant`],
21//!   or [`CurrentTenant`] from the environment with [`Repository::for_current_tenant`] — and
22//!   inserts write it), and `#[entity(scope = path::to::fn)]` (a `fn() -> impl
23//!   Into<Condition>`, repeatable). A tenant-scoped entity without a tenant fails closed
24//!   ([`SqlError::Unsupported`]). [`Repository::with_deleted`] lifts the soft-delete filter only;
25//!   [`Repository::unscoped`] lifts every filter (the explicit escape hatch).
26//! - **Relations and eager loading** (data.orm #3). `#[entity(belongs_to(..))]`,
27//!   `#[entity(has_many(..))]` and `#[entity(many_to_many(.., through = ".."))]` declare
28//!   [`Relation`]s; [`Repository::with`] loads them with the rows, one `IN (…)` query per relation
29//!   per level (no N+1), nested at most [`MAX_EAGER_DEPTH`] levels, into [`Loaded`] values. The
30//!   children are read the way the parent repository reads: with the child entity's tenant,
31//!   soft-delete and custom filters, so a relation never returns another tenant's row. See
32//!   [`Relation`].
33//! - **Field metadata**. [`Entity::FIELDS`] ([`FieldMeta`]: column, type, nullability,
34//!   `#[entity(editable)]`, `#[entity(label = "..")]`, relation) and [`Entity::RELATIONS`]
35//!   ([`RelationMeta`]) describe the entity to generic tools such as an admin; both default to
36//!   empty, so a hand-written `impl Entity` needs neither.
37//!
38//! Dialects: PostgreSQL and SQLite insert with `RETURNING`; MySQL inserts and then reads the row
39//! back by id, so a `generated` id is [`SqlError::Unsupported`] there.
40//!
41//! ```rust
42//! use id_effect::Exit;
43//! use id_effect_sql::{
44//!   Dialect, Entity, FromRow, Repository, SqlClientEnv, SqlError, SqlRow, SqlValue, TestSqlClient,
45//!   sql_client_layer,
46//! };
47//!
48//! #[derive(Clone, Debug, PartialEq, FromRow, Entity)]
49//! #[entity(table = "accounts", soft_delete = "deleted_at", tenant = "org_id")]
50//! struct Account {
51//!   #[entity(id)]
52//!   id: i64,
53//!   name: String,
54//!   #[entity(version)]
55//!   version: i64,
56//! }
57//!
58//! let repo = Repository::<Account>::new(Dialect::Postgres).with_tenant(7i64);
59//! let test = TestSqlClient::new();
60//! test.script_query(
61//!   r#"SELECT "id", "name", "version" FROM "accounts" WHERE "org_id" = $1 AND "deleted_at" IS NULL AND "id" = $2 LIMIT $3"#,
62//!   vec![SqlRow::from_pairs([
63//!     ("id", SqlValue::I64(1)),
64//!     ("name", "ada".into()),
65//!     ("version", SqlValue::I64(3)),
66//!   ])],
67//! );
68//! let found = repo
69//!   .find::<SqlClientEnv, _>(1)
70//!   .provide_layer(sql_client_layer::<SqlError>(test));
71//! assert!(matches!(found.block_on(), Exit::Success(Some(a)) if a.name == "ada" && a.version == 3));
72//! assert_eq!(Account::TABLE, "accounts");
73//! ```
74
75use 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
90// Keyset pagination (r13-e3-3-pagination) and lifecycle hooks (r13-e3-3-hooks) land here.
91pub 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
104/// A struct mapped to a table: what `#[derive(Entity)]` generates (see the [module docs](self)).
105///
106/// The constants are the mapping; [`values`](Self::values) are the column values to write.
107pub trait Entity: FromRow + Send + 'static {
108  /// The primary key's type (`Debug` names it in [`SqlError::StaleVersion`]).
109  type Id: ToSqlValue + fmt::Debug + Send + 'static;
110
111  /// The Rust type name, for errors.
112  const NAME: &'static str;
113  /// The table.
114  const TABLE: &'static str;
115  /// Every mapped column, in field order (the `SELECT` list).
116  const COLUMNS: &'static [&'static str];
117  /// The primary key column.
118  const ID: &'static str;
119  /// Whether the database assigns the primary key (inserts omit it and read it back).
120  const ID_GENERATED: bool = false;
121  /// The optimistic-locking version column (an integer), if any.
122  const VERSION: Option<&'static str> = None;
123  /// The soft-delete column (NULL while the row is live, the deletion time after), if any.
124  /// It need not be a field.
125  const SOFT_DELETE: Option<&'static str> = None;
126  /// The tenant (or owner) column every statement is scoped to, if any. It need not be a field.
127  const TENANT: Option<&'static str> = None;
128  /// The entity's label key (`#[entity(label = "..")]`; the derive defaults to the type name
129  /// in snake case), e.g. a translation key for an admin. Defaults to [`NAME`](Self::NAME).
130  const LABEL: &'static str = Self::NAME;
131  /// What each field is ([`FieldMeta`]), in field order. The derive fills it; the default is
132  /// empty (no metadata), so a hand-written impl compiles without it.
133  const FIELDS: &'static [FieldMeta] = &[];
134  /// The declared relations ([`RelationMeta`]). The derive fills it; the default is empty.
135  const RELATIONS: &'static [RelationMeta] = &[];
136
137  /// The primary key.
138  fn id(&self) -> Self::Id;
139
140  /// Every mapped column with its value, in [`COLUMNS`](Self::COLUMNS) order.
141  fn values(&self) -> Vec<(&'static str, SqlValue)>;
142
143  /// Add one to the version field (what a successful [`Repository::update`] wrote). The default
144  /// does nothing (no version column).
145  fn bump_version(&mut self) {}
146
147  /// The custom filters (`#[entity(scope = ..)]`), AND-ed into every statement. The default is
148  /// no filter.
149  fn scope() -> Condition {
150    Condition::all()
151  }
152}
153
154/// Capability: the tenant (or owner) value tenant-scoped entities are filtered by
155/// ([`Repository::for_current_tenant`]), e.g. provided per request from the authenticated
156/// principal.
157#[derive(Clone, Debug, PartialEq)]
158pub struct CurrentTenant(pub SqlValue);
159
160impl CurrentTenant {
161  /// The tenant `value` (`CurrentTenant::new(org_id)`).
162  #[inline]
163  pub fn new(value: impl ToSqlValue) -> Self {
164    Self(value.to_sql_value())
165  }
166}
167
168/// Something statements run on: the client ([`SqlClientService`], `Arc<dyn SqlClient>`) or an
169/// open transaction ([`SqlTransactionService`], `Arc<dyn SqlTransaction>`).
170pub trait SqlExecutor: Send + Sync + 'static {
171  /// Run a read query and collect its rows.
172  fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError>;
173  /// Run a write statement; the affected row count.
174  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/// One page of rows ([`Repository::find_page`]): at most `limit` rows after skipping `offset`,
197/// in primary-key order.
198#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
199pub struct Page {
200  /// The most rows returned.
201  pub limit: u64,
202  /// The rows skipped first.
203  pub offset: u64,
204}
205
206impl Page {
207  /// `limit` rows after skipping `offset`.
208  #[inline]
209  pub fn new(limit: u64, offset: u64) -> Self {
210    Self { limit, offset }
211  }
212
213  /// Page `number` (0-based) of `size` rows.
214  #[inline]
215  pub fn number(number: u64, size: u64) -> Self {
216    Self::new(size, number.saturating_mul(size))
217  }
218}
219
220/// Which global filters apply.
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222enum Filters {
223  /// Soft delete, tenant and custom scopes.
224  All,
225  /// Tenant and custom scopes ([`Repository::with_deleted`]).
226  WithDeleted,
227  /// None ([`Repository::unscoped`]).
228  None,
229}
230
231/// A statement rendered for the repository's dialect.
232type Stmt = (String, Vec<SqlValue>);
233
234/// An operation ready to run on an executor.
235type 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
244/// The rows of `stmt`, then `f`.
245fn 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, &params).flat_map(|rows| ready(f(rows))))
250}
251
252/// Whether `stmt` affected a row.
253fn affected_any((sql, params): Stmt) -> Run<bool> {
254  Box::new(move |ex| ex.execute(&sql, &params).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
265/// `base AND cond`, leaving out an empty `cond`.
266fn and(base: Condition, cond: Condition) -> Condition {
267  if cond.is_empty() {
268    base
269  } else {
270    base.add(cond)
271  }
272}
273
274/// CRUD for the entity `T` (see the [module docs](self)): statements in its dialect, with the
275/// global filters it is configured with.
276///
277/// Methods run on the [`SqlClientService`] in the environment `R`; [`on`](Self::on) binds the
278/// same operations to a transaction. Every method renders its statement when called, so a
279/// rendering or scope error fails the returned effect.
280pub 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
309/// A [`Repository`] bound to one executor ([`Repository::on`]): the same operations, as
310/// environment-free effects (inside a transaction: `.narrow()` them into its environment).
311pub 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  /// A repository rendering statements for `dialect`, with every filter on and no tenant.
333  pub fn new(dialect: Dialect) -> Self {
334    Self {
335      dialect,
336      tenant: None,
337      filters: Filters::All,
338      entity: PhantomData,
339    }
340  }
341
342  /// A repository for `dialect` scoped to the [`CurrentTenant`] in the environment `R`.
343  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  /// This repository scoped to `tenant` (tenant-scoped statements filter by it, inserts write
351  /// it).
352  #[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  /// This repository including soft-deleted rows (the tenant and custom filters still apply).
361  #[must_use]
362  pub fn with_deleted(&self) -> Self {
363    Self {
364      filters: Filters::WithDeleted,
365      ..self.clone()
366    }
367  }
368
369  /// This repository with no global filter: soft-deleted rows, every tenant and rows outside the
370  /// custom scopes included. The explicit escape hatch (admin tools, data migrations). A tenant
371  /// set with [`with_tenant`](Self::with_tenant) is still written on insert.
372  #[must_use]
373  pub fn unscoped(&self) -> Self {
374    Self {
375      filters: Filters::None,
376      ..self.clone()
377    }
378  }
379
380  /// The dialect statements are rendered in.
381  #[inline]
382  pub fn dialect(&self) -> Dialect {
383    self.dialect
384  }
385
386  /// The tenant statements are scoped to, if any.
387  #[inline]
388  pub fn tenant(&self) -> Option<&SqlValue> {
389    self.tenant.as_ref()
390  }
391
392  /// The same operations on `executor`, e.g. a transaction: `repo.on(tx).update(account)`.
393  pub fn on(&self, executor: impl SqlExecutor) -> BoundRepository<T> {
394    BoundRepository {
395      repo: self.clone(),
396      ex: Arc::new(executor),
397    }
398  }
399
400  /// The tenant to scope by and write: `None` without a tenant column, or when unscoped without
401  /// a tenant; an error when a scoped repository of a tenant-scoped entity has none.
402  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  /// The global filters, without the soft-delete one when `soft_delete` is false.
416  fn scope(&self, soft_delete: bool) -> Result<Condition, SqlError> {
417    self.scope_in(None, soft_delete)
418  }
419
420  /// [`scope`](Self::scope) with the tenant and soft-delete columns qualified by `table` (for a
421  /// join). Custom scopes are added as they are.
422  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  /// The same dialect, tenant and filters for the entity `C` (how relations read children).
446  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  /// `SELECT <columns> FROM <table> WHERE <filters> AND <cond>`.
464  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  /// `WHERE <filters> AND <cond>`, left out when both are empty (sea-query would render
472  /// `WHERE TRUE`).
473  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, &params)
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    // Zero rows: with a version column, tell a stale version from a missing row.
582    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, &params).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, &params).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  /// Run `op` on the [`SqlClientService`] in `R`.
635  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  /// The repository this is bound from.
649  #[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
662/// The operations, once: [`Repository`] runs them on the client in the environment,
663/// [`BoundRepository`] on its executor.
664macro_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  /// The row with primary key `id`, or `None` (also when a filter hides it).
694  fn find(id: T::Id) -> Option<T> = find_op(&id);
695  /// Every row the filters let through, in primary-key order.
696  fn find_all() -> Vec<T> = find_by_op(Condition::all(), None);
697  /// The rows matching `cond` (a sea-query condition or expression, e.g.
698  /// `Expr::col("name").eq("ada")`), in primary-key order.
699  fn find_by(cond: impl IntoCondition) -> Vec<T> = find_by_op(cond.into_condition(), None);
700  /// One [`Page`] of the rows matching `cond`, in primary-key order.
701  fn find_page(cond: impl IntoCondition, page: Page) -> Vec<T> =
702    find_by_op(cond.into_condition(), Some(page));
703  /// The number of rows the filters let through.
704  fn count() -> u64 = count_op(Condition::all());
705  /// The number of rows matching `cond`.
706  fn count_by(cond: impl IntoCondition) -> u64 = count_op(cond.into_condition());
707  /// Whether the row with primary key `id` exists (and the filters let it through).
708  fn exists(id: T::Id) -> bool = exists_op(&id);
709  /// Insert `entity` (without a `generated` id; with the repository's tenant) and return the
710  /// stored row, generated id and column defaults included.
711  fn insert(entity: T) -> T = insert_op(entity);
712  /// Write every column of `entity` but the id, tenant and soft-delete columns, by id and
713  /// within the filters. With a version column the update also requires the version `entity`
714  /// was read with and increments it: the returned entity carries the new version, and a
715  /// concurrent change fails with [`SqlError::StaleVersion`]. No such row:
716  /// [`SqlError::RowNotFound`].
717  fn update(entity: T) -> T = update_op(entity);
718  /// Delete the row with primary key `id` — a soft delete (the soft-delete column set to now,
719  /// the version incremented) when the entity has one. `false` when no row was deleted.
720  fn delete(id: T::Id) -> bool = delete_op(&id);
721  /// `DELETE` the row with primary key `id` even when the entity soft-deletes, soft-deleted or
722  /// not (the tenant and custom filters still apply). `false` when no row was deleted.
723  fn hard_delete(id: T::Id) -> bool = hard_delete_op(&id);
724}