Skip to main content

larust_repository/
lib.rs

1//! A storage-agnostic CRUD contract - the "any backend, including a
2//! non-SQL one" half of Larust's persistence story. `#[derive(Model)]`/
3//! `QueryBuilder` (in `larust-orm`) remain the SQL-family story - SQLite,
4//! MySQL, and (as of this session) Postgres, all via `sqlx::Any`. Adding
5//! Postgres was real, structurally significant work, not a footnote: `Any`
6//! does not rewrite `?` placeholders to Postgres's `$1, $2, ...` syntax
7//! (confirmed by reading `sqlx`'s own source), so every SQL string and
8//! `QueryBuilder`'s own dynamic condition-rendering needed real
9//! backend-aware placeholder handling - see `query_builder.rs`'s own doc
10//! comment for the full account, including the empirically-confirmed
11//! finding that Postgres, unlike SQLite/MySQL, has *no* `bool`/`TEXT`
12//! decode gap through `Any`. This crate and `Repository<T>` are unaffected
13//! by any of that - `Repository<T>` exists for everything `sqlx::Any`
14//! structurally cannot reach at all, not for another SQL dialect: a
15//! document store like Firestore, DynamoDB, or MongoDB has no SQL text,
16//! no columns, and no shared wire protocol with a SQL database, so that
17//! abstraction has to live above sqlx entirely, as a plain trait an app
18//! implements by hand. SQL Server is the concrete, now-shipped example:
19//! `sqlx` has no driver for it at all (confirmed - no vendored
20//! `sqlx-mssql`/`tiberius` integration exists anywhere), so it can never
21//! become a `Backend` variant the way Postgres did - the `larust-mssql`
22//! crate implements `Repository<T>` by hand against `tiberius` instead,
23//! with a real worked example (`larust-mssql/tests/widget_repository.rs`)
24//! verified end to end against a real local SQL Server server, proving
25//! this crate's whole premise concretely, not just for a hypothetical
26//! Firestore/DynamoDB. That verification pass caught a real SQL Server
27//! semantics gotcha along the way - see `widget_repository.rs`'s own
28//! `create()` for what `SCOPE_IDENTITY()` gets wrong through `tiberius`
29//! and why `OUTPUT INSERTED.id` is the correct fix.
30//!
31//! This mirrors `larust_auth::Authenticatable`'s own existing shape (see
32//! that trait's doc comment): a small, storage-agnostic interface that a
33//! SQL-family app satisfies with a two-line delegation into
34//! `#[derive(Model)]`'s generated methods, and that a non-SQL app
35//! implements directly against its own store. `larust-orm`'s
36//! `AnyRepository<T>` is the SQL-family delegation; a Firestore-backed
37//! app writes its own implementation the same way it already hand-writes
38//! `Authenticatable::find_for_auth` today.
39//!
40//! **Deliberately out of scope, on purpose, not as an oversight:**
41//! - **No relations.** `has_many`/`belongs_to`/`belongs_to_many`-style
42//!   loading is entirely `QueryBuilder`-coupled (`WHERE IN (...)` batch
43//!   loaders, hand-written `JOIN`s for many-to-many) and doesn't
44//!   generalize to a document store, which usually models relations as
45//!   reference fields or subcollections looked up in backend-specific
46//!   ways. A non-SQL app hand-writes its own relation-loading methods
47//!   directly on its model type.
48//! - **No migrations.** `larust_orm::migrate` is inherently SQL-text
49//!   oriented (`.sql` files, a bookkeeping table). A document store is
50//!   schemaless - collections appear implicitly on first write - so
51//!   there is nothing for a non-SQL app to migrate; it simply never
52//!   calls `xr migrate`.
53//! - **No pagination, sorting, or aggregate helpers.** Those stay
54//!   backend-specific methods an app adds to its own repository type,
55//!   same as `belongs_to_many`'s attach/detach/sync methods already live
56//!   outside `QueryBuilder`'s scope for the SQL-family case.
57//!
58//! `Filter` is deliberately opaque to this trait rather than a shared
59//! query DSL: an SQL-family implementation might use a small enum of
60//! (column, value) conditions (or, as `larust-orm`'s own `AnyRepository<T>`
61//! does, a partially-built `QueryBuilder<T>`); a Firestore implementation
62//! might use a native query type. Callers of a *specific* `Repository`
63//! implementation are expected to know its concrete `Filter` type, the
64//! same way calling code today already commits to `QueryBuilder`'s own
65//! calling convention.
66
67use larust_core::AppError;
68use std::future::Future;
69
70/// Storage-agnostic CRUD contract. Implemented automatically for any
71/// `#[derive(Model)]` SQL-family struct via `larust_orm::AnyRepository<T>`
72/// (a thin wrapper over the existing `QueryBuilder`/`Model` machinery -
73/// see that type's own doc comment), and by hand for a non-SQL backend
74/// such as Firestore, DynamoDB, or MongoDB.
75///
76/// `-> impl Future<...> + Send` (rather than a plain `async fn`) matches
77/// `larust_auth::Authenticatable`'s own established reasoning: native
78/// async-fn-in-traits doesn't propagate the `Send` bound on its returned
79/// future by default, and this trait needs to be usable from axum
80/// handlers that require `Send` futures. An implementation can still be
81/// written as an ordinary `async fn` - its desugared return type already
82/// satisfies `-> impl Future<...>`; only the trait's own declaration
83/// needs the explicit spelling.
84pub trait Repository<T>: Send + Sync {
85    /// Opaque to this trait - see the module doc comment.
86    type Filter: Send;
87
88    /// The value used to look a single record up and to target
89    /// `update`/`delete` - typically a primary key or document id.
90    type Id: Send + Sync + Clone;
91
92    /// Looks a single record up by id. Returns `Ok(None)` (not an error)
93    /// when the id doesn't resolve to a record.
94    fn find(&self, id: Self::Id) -> impl Future<Output = Result<Option<T>, AppError>> + Send;
95
96    /// Returns every record matching `filter`.
97    fn query(&self, filter: Self::Filter) -> impl Future<Output = Result<Vec<T>, AppError>> + Send;
98
99    /// Creates a new record, returning it as actually stored (e.g. with a
100    /// generated id populated).
101    fn create(&self, value: T) -> impl Future<Output = Result<T, AppError>> + Send;
102
103    /// Replaces the record at `id` with `value` in full, returning the
104    /// stored result. Not a partial/dirty-tracking update - the same
105    /// "replace every field" contract `#[derive(Model)]`'s `create()`
106    /// already has for inserts.
107    fn update(&self, id: Self::Id, value: T) -> impl Future<Output = Result<T, AppError>> + Send;
108
109    /// Deletes the record at `id`. Not an error if it didn't exist.
110    fn delete(&self, id: Self::Id) -> impl Future<Output = Result<(), AppError>> + Send;
111}