Skip to main content

id_effect_sql/
repository.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//!
27//! Dialects: PostgreSQL and SQLite insert with `RETURNING`; MySQL inserts and then reads the row
28//! back by id, so a `generated` id is [`SqlError::Unsupported`] there.
29//!
30//! ```rust
31//! use id_effect::Exit;
32//! use id_effect_sql::{
33//!   Dialect, Entity, FromRow, Repository, SqlClientEnv, SqlError, SqlRow, SqlValue, TestSqlClient,
34//!   sql_client_layer,
35//! };
36//!
37//! #[derive(Clone, Debug, PartialEq, FromRow, Entity)]
38//! #[entity(table = "accounts", soft_delete = "deleted_at", tenant = "org_id")]
39//! struct Account {
40//!   #[entity(id)]
41//!   id: i64,
42//!   name: String,
43//!   #[entity(version)]
44//!   version: i64,
45//! }
46//!
47//! let repo = Repository::<Account>::new(Dialect::Postgres).with_tenant(7i64);
48//! let test = TestSqlClient::new();
49//! test.script_query(
50//!   r#"SELECT "id", "name", "version" FROM "accounts" WHERE "org_id" = $1 AND "deleted_at" IS NULL AND "id" = $2 LIMIT $3"#,
51//!   vec![SqlRow::from_pairs([
52//!     ("id", SqlValue::I64(1)),
53//!     ("name", "ada".into()),
54//!     ("version", SqlValue::I64(3)),
55//!   ])],
56//! );
57//! let found = repo
58//!   .find::<SqlClientEnv, _>(1)
59//!   .provide_layer(sql_client_layer::<SqlError>(test));
60//! assert!(matches!(found.block_on(), Exit::Success(Some(a)) if a.name == "ada" && a.version == 3));
61//! assert_eq!(Account::TABLE, "accounts");
62//! ```
63
64use 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
79/// A struct mapped to a table: what `#[derive(Entity)]` generates (see the [module docs](self)).
80///
81/// The constants are the mapping; [`values`](Self::values) are the column values to write.
82pub trait Entity: FromRow + Send + 'static {
83  /// The primary key's type (`Debug` names it in [`SqlError::StaleVersion`]).
84  type Id: ToSqlValue + fmt::Debug + Send + 'static;
85
86  /// The Rust type name, for errors.
87  const NAME: &'static str;
88  /// The table.
89  const TABLE: &'static str;
90  /// Every mapped column, in field order (the `SELECT` list).
91  const COLUMNS: &'static [&'static str];
92  /// The primary key column.
93  const ID: &'static str;
94  /// Whether the database assigns the primary key (inserts omit it and read it back).
95  const ID_GENERATED: bool = false;
96  /// The optimistic-locking version column (an integer), if any.
97  const VERSION: Option<&'static str> = None;
98  /// The soft-delete column (NULL while the row is live, the deletion time after), if any.
99  /// It need not be a field.
100  const SOFT_DELETE: Option<&'static str> = None;
101  /// The tenant (or owner) column every statement is scoped to, if any. It need not be a field.
102  const TENANT: Option<&'static str> = None;
103
104  /// The primary key.
105  fn id(&self) -> Self::Id;
106
107  /// Every mapped column with its value, in [`COLUMNS`](Self::COLUMNS) order.
108  fn values(&self) -> Vec<(&'static str, SqlValue)>;
109
110  /// Add one to the version field (what a successful [`Repository::update`] wrote). The default
111  /// does nothing (no version column).
112  fn bump_version(&mut self) {}
113
114  /// The custom filters (`#[entity(scope = ..)]`), AND-ed into every statement. The default is
115  /// no filter.
116  fn scope() -> Condition {
117    Condition::all()
118  }
119}
120
121/// Capability: the tenant (or owner) value tenant-scoped entities are filtered by
122/// ([`Repository::for_current_tenant`]), e.g. provided per request from the authenticated
123/// principal.
124#[derive(Clone, Debug, PartialEq)]
125pub struct CurrentTenant(pub SqlValue);
126
127impl CurrentTenant {
128  /// The tenant `value` (`CurrentTenant::new(org_id)`).
129  #[inline]
130  pub fn new(value: impl ToSqlValue) -> Self {
131    Self(value.to_sql_value())
132  }
133}
134
135/// Something statements run on: the client ([`SqlClientService`], `Arc<dyn SqlClient>`) or an
136/// open transaction ([`SqlTransactionService`], `Arc<dyn SqlTransaction>`).
137pub trait SqlExecutor: Send + Sync + 'static {
138  /// Run a read query and collect its rows.
139  fn query(&self, sql: &str, params: &[SqlValue]) -> Effect<Vec<SqlRow>, SqlError>;
140  /// Run a write statement; the affected row count.
141  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/// One page of rows ([`Repository::find_page`]): at most `limit` rows after skipping `offset`,
164/// in primary-key order.
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
166pub struct Page {
167  /// The most rows returned.
168  pub limit: u64,
169  /// The rows skipped first.
170  pub offset: u64,
171}
172
173impl Page {
174  /// `limit` rows after skipping `offset`.
175  #[inline]
176  pub fn new(limit: u64, offset: u64) -> Self {
177    Self { limit, offset }
178  }
179
180  /// Page `number` (0-based) of `size` rows.
181  #[inline]
182  pub fn number(number: u64, size: u64) -> Self {
183    Self::new(size, number.saturating_mul(size))
184  }
185}
186
187/// Which global filters apply.
188#[derive(Clone, Copy, Debug, PartialEq, Eq)]
189enum Filters {
190  /// Soft delete, tenant and custom scopes.
191  All,
192  /// Tenant and custom scopes ([`Repository::with_deleted`]).
193  WithDeleted,
194  /// None ([`Repository::unscoped`]).
195  None,
196}
197
198/// A statement rendered for the repository's dialect.
199type Stmt = (String, Vec<SqlValue>);
200
201/// An operation ready to run on an executor.
202type 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
211/// The rows of `stmt`, then `f`.
212fn 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, &params).flat_map(|rows| ready(f(rows))))
217}
218
219/// Whether `stmt` affected a row.
220fn affected_any((sql, params): Stmt) -> Run<bool> {
221  Box::new(move |ex| ex.execute(&sql, &params).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
232/// `base AND cond`, leaving out an empty `cond`.
233fn and(base: Condition, cond: Condition) -> Condition {
234  if cond.is_empty() {
235    base
236  } else {
237    base.add(cond)
238  }
239}
240
241/// CRUD for the entity `T` (see the [module docs](self)): statements in its dialect, with the
242/// global filters it is configured with.
243///
244/// Methods run on the [`SqlClientService`] in the environment `R`; [`on`](Self::on) binds the
245/// same operations to a transaction. Every method renders its statement when called, so a
246/// rendering or scope error fails the returned effect.
247pub 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
276/// A [`Repository`] bound to one executor ([`Repository::on`]): the same operations, as
277/// environment-free effects (inside a transaction: `.narrow()` them into its environment).
278pub 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  /// A repository rendering statements for `dialect`, with every filter on and no tenant.
300  pub fn new(dialect: Dialect) -> Self {
301    Self {
302      dialect,
303      tenant: None,
304      filters: Filters::All,
305      entity: PhantomData,
306    }
307  }
308
309  /// A repository for `dialect` scoped to the [`CurrentTenant`] in the environment `R`.
310  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  /// This repository scoped to `tenant` (tenant-scoped statements filter by it, inserts write
318  /// it).
319  #[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  /// This repository including soft-deleted rows (the tenant and custom filters still apply).
328  #[must_use]
329  pub fn with_deleted(&self) -> Self {
330    Self {
331      filters: Filters::WithDeleted,
332      ..self.clone()
333    }
334  }
335
336  /// This repository with no global filter: soft-deleted rows, every tenant and rows outside the
337  /// custom scopes included. The explicit escape hatch (admin tools, data migrations). A tenant
338  /// set with [`with_tenant`](Self::with_tenant) is still written on insert.
339  #[must_use]
340  pub fn unscoped(&self) -> Self {
341    Self {
342      filters: Filters::None,
343      ..self.clone()
344    }
345  }
346
347  /// The dialect statements are rendered in.
348  #[inline]
349  pub fn dialect(&self) -> Dialect {
350    self.dialect
351  }
352
353  /// The tenant statements are scoped to, if any.
354  #[inline]
355  pub fn tenant(&self) -> Option<&SqlValue> {
356    self.tenant.as_ref()
357  }
358
359  /// The same operations on `executor`, e.g. a transaction: `repo.on(tx).update(account)`.
360  pub fn on(&self, executor: impl SqlExecutor) -> BoundRepository<T> {
361    BoundRepository {
362      repo: self.clone(),
363      ex: Arc::new(executor),
364    }
365  }
366
367  /// The tenant to scope by and write: `None` without a tenant column, or when unscoped without
368  /// a tenant; an error when a scoped repository of a tenant-scoped entity has none.
369  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  /// The global filters, without the soft-delete one when `soft_delete` is false.
383  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  /// `SELECT <columns> FROM <table> WHERE <filters> AND <cond>`.
407  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  /// `WHERE <filters> AND <cond>`, left out when both are empty (sea-query would render
415  /// `WHERE TRUE`).
416  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, &params)
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    // Zero rows: with a version column, tell a stale version from a missing row.
525    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, &params).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, &params).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  /// Run `op` on the [`SqlClientService`] in `R`.
578  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  /// The repository this is bound from.
592  #[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
605/// The operations, once: [`Repository`] runs them on the client in the environment,
606/// [`BoundRepository`] on its executor.
607macro_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  /// The row with primary key `id`, or `None` (also when a filter hides it).
637  fn find(id: T::Id) -> Option<T> = find_op(&id);
638  /// Every row the filters let through, in primary-key order.
639  fn find_all() -> Vec<T> = find_by_op(Condition::all(), None);
640  /// The rows matching `cond` (a sea-query condition or expression, e.g.
641  /// `Expr::col("name").eq("ada")`), in primary-key order.
642  fn find_by(cond: impl IntoCondition) -> Vec<T> = find_by_op(cond.into_condition(), None);
643  /// One [`Page`] of the rows matching `cond`, in primary-key order.
644  fn find_page(cond: impl IntoCondition, page: Page) -> Vec<T> =
645    find_by_op(cond.into_condition(), Some(page));
646  /// The number of rows the filters let through.
647  fn count() -> u64 = count_op(Condition::all());
648  /// The number of rows matching `cond`.
649  fn count_by(cond: impl IntoCondition) -> u64 = count_op(cond.into_condition());
650  /// Whether the row with primary key `id` exists (and the filters let it through).
651  fn exists(id: T::Id) -> bool = exists_op(&id);
652  /// Insert `entity` (without a `generated` id; with the repository's tenant) and return the
653  /// stored row, generated id and column defaults included.
654  fn insert(entity: T) -> T = insert_op(entity);
655  /// Write every column of `entity` but the id, tenant and soft-delete columns, by id and
656  /// within the filters. With a version column the update also requires the version `entity`
657  /// was read with and increments it: the returned entity carries the new version, and a
658  /// concurrent change fails with [`SqlError::StaleVersion`]. No such row:
659  /// [`SqlError::RowNotFound`].
660  fn update(entity: T) -> T = update_op(entity);
661  /// Delete the row with primary key `id` — a soft delete (the soft-delete column set to now,
662  /// the version incremented) when the entity has one. `false` when no row was deleted.
663  fn delete(id: T::Id) -> bool = delete_op(&id);
664  /// `DELETE` the row with primary key `id` even when the entity soft-deletes, soft-deleted or
665  /// not (the tenant and custom filters still apply). `false` when no row was deleted.
666  fn hard_delete(id: T::Id) -> bool = hard_delete_op(&id);
667}