Skip to main content

rainier_database/
lib.rs

1//! # rainier-database
2//!
3//! Rainier's data layer, built on **[Rainier ORM]** — the multi-dialect DBAL
4//! where one `#[derive(Entity)]` serves SQLite, Cloudflare D1, MySQL and
5//! Postgres, and where the stack of hand-written per-engine repositories
6//! collapses to zero.
7//!
8//! This crate adds the four things a framework needs on top of that:
9//!
10//! | | |
11//! |---|---|
12//! | [`Connection`] / [`Database`] | a `dyn`-safe port over Rainier ORM's `Executor`, so a backend can live in the IoC container |
13//! | [`Model`] | an entity the framework manages, with lifecycle **hooks** |
14//! | [`Repository`] / [`EntityRepository`] | a contract to depend on, implemented once for every model |
15//! | [`Criteria`] / [`Paginated`] | composable scopes and paging |
16//!
17//! ```ignore
18//! use rainier_orm::{repo, Entity, SeaOrmExecutor, PoolConfig};
19//! use rainier_database::{bind_executor, Criteria, Database, EntityRepository, Model, Repository};
20//!
21//! #[derive(Entity, Clone)]
22//! #[orm(table = "posts")]
23//! struct Post {
24//!     #[orm(pk, auto_increment)] id: u64,
25//!     title: String,
26//!     published: bool,
27//! }
28//! impl Model for Post {}
29//!
30//! bind_executor!(SeaOrmExecutor);
31//!
32//! # async fn run() -> rainier_support::Result<()> {
33//! let executor = SeaOrmExecutor::connect("sqlite::memory:", &PoolConfig::default()).await?;
34//! let db = Database::new(executor);
35//! let posts = EntityRepository::<Post>::new(db.clone());
36//!
37//! // Through the repository contract…
38//! let page = posts
39//!     .paginate_matching(Criteria::new().where_eq("published", true), 1, 20)
40//!     .await?;
41//!
42//! // …or straight through Rainier ORM, since `Database` is an `Executor`.
43//! let newest: Option<Post> = repo::query::<Post>().order_by_desc("id").first(&db).await?;
44//! # Ok(()) }
45//! ```
46//!
47//! ## The `Executor` problem, and how it is solved
48//!
49//! Rainier ORM's `Executor` uses `async fn` in trait and carries no `Send + Sync`
50//! bound — deliberately, so the same code runs in a single-threaded Cloudflare
51//! Worker over a `!Send` D1 binding. That makes it unusable as `dyn Executor`,
52//! which is exactly what a container needs to store.
53//!
54//! [`Database`] resolves this by holding an `Arc<dyn Connection>` (Rainier's
55//! `dyn`-safe mirror) and **re-implementing `Executor` on top of it**. The
56//! whole ORM surface therefore works against a `Database` unchanged — no
57//! wrapper per operation, and no gap between what Rainier ORM can do and what
58//! Rainier exposes. Register a concrete backend with
59//! [`bind_executor!`].
60//!
61//! [Rainier ORM]: https://github.com/safewords/rainier-framework/tree/main/crates/rainier-orm
62
63#![deny(missing_docs)]
64#![deny(rustdoc::broken_intra_doc_links)]
65
66pub mod connection;
67pub mod criteria;
68pub mod migrator;
69pub mod model;
70pub mod pagination;
71pub mod raw;
72pub mod relation;
73pub mod repository;
74pub mod row;
75pub mod statement;
76pub mod testing;
77
78pub use connection::{Connection, Database};
79pub use criteria::{Constraint, Criteria};
80pub use migrator::{Down, Migration, Migrator, Step};
81pub use model::{Created, Creating, Deleted, Deleting, Model, Updated, Updating};
82pub use pagination::Paginated;
83pub use raw::RawQuery;
84pub use relation::{
85    BelongsTo, BelongsToMany, HasMany, HasOne, PivotQuery, Related, RelatedCounts, Relation,
86    RelationKey,
87};
88pub use repository::{EntityRepository, Repository};
89pub use row::{Cell, ColumnRequest, OwnedRow};
90pub use statement::Prepared;
91
92// The ORM, re-exported so an application depends on one Rainier ORM version and
93// gets the derive, the query builder and the migrator without naming it twice.
94pub use rainier_orm;
95pub use rainier_orm::{
96    ddl, migrate, repo, schema, Action, Blueprint, ColumnKind, Dialect, Entity, Executor, IndexDef,
97    Query, TableChanges,
98};
99
100/// What [`bind_executor!`] expands to. Not a stable API.
101#[doc(hidden)]
102pub mod reexport {
103    pub use crate::row::{ColumnRequest, OwnedRow};
104    pub use rainier_orm::sea_query::Value;
105    pub use rainier_orm::{Dialect, ExecOutcome, Executor, Row, ShardRoute};
106    pub use rainier_support::{BoxFuture, Error, LocalBoxFuture, Result};
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::testing::{fake_database, MemoryConnection};
113
114    #[derive(rainier_orm::Entity, Clone, Debug, PartialEq)]
115    #[orm(table = "users")]
116    struct User {
117        #[orm(pk, auto_increment)]
118        id: u64,
119        #[orm(unique)]
120        email: String,
121    }
122
123    impl Model for User {}
124
125    #[tokio::test]
126    async fn the_orm_surface_is_reachable_through_the_executor_impl() {
127        // Implementing `Executor` for `Database` keeps Rainier ORM's own API
128        // available: `repo::` and the query builder take it with no adapter.
129        // These futures are `Send` — see the assertion in
130        // `the_orms_own_futures_are_send_once_upstream_scopes_its_statements`
131        // below — so this path is usable from a request handler too.
132        let (db, connection) = fake_database(
133            MemoryConnection::new(Dialect::Sqlite)
134                .returning([OwnedRow::new().with("id", 1_u64).with("email", "a@b.c")]),
135        );
136
137        let found: Option<User> = repo::find_one_by(&db, "email", "a@b.c").await.unwrap();
138        assert_eq!(found.unwrap().email, "a@b.c");
139
140        let sql = connection.last_statement().unwrap();
141        assert!(sql.contains("users"), "{sql}");
142        assert!(sql.contains("email"), "{sql}");
143    }
144
145    #[tokio::test]
146    async fn the_query_builder_works_against_a_database() {
147        let (db, connection) = fake_database(MemoryConnection::new(Dialect::Sqlite));
148
149        let _: Vec<User> = repo::query::<User>()
150            .where_like("email", "%@example.com")
151            .order_by_desc("id")
152            .limit(5)
153            .all(&db)
154            .await
155            .unwrap();
156
157        let sql = connection.last_statement().unwrap();
158        assert!(sql.contains("LIKE"), "{sql}");
159        assert!(sql.contains("ORDER BY"), "{sql}");
160    }
161
162    #[tokio::test]
163    async fn the_repository_path_covers_the_same_ground_and_stays_send() {
164        let (db, connection) = fake_database(
165            MemoryConnection::new(Dialect::Sqlite)
166                .returning([OwnedRow::new().with("id", 1_u64).with("email", "a@b.c")]),
167        );
168        let users = EntityRepository::<User>::new(db);
169
170        let found = users.first_by("email", "a@b.c".into()).await.unwrap();
171        assert_eq!(found.unwrap().email, "a@b.c");
172        assert!(connection.last_statement().unwrap().contains("users"));
173    }
174
175    #[test]
176    fn the_orms_own_futures_are_send_once_upstream_scopes_its_statements() {
177        // The property `rainier-database::statement` exists to work around.
178        // While Rainier ORM holds a `sea_query` statement across its awaits
179        // these futures are `!Send` and this does not compile; once it does,
180        // the request path could call `repo::` directly and that module could
181        // be retired.
182        //
183        // Kept as a live check rather than a comment so the answer is never
184        // stale: it tracks whichever Rainier ORM the build resolves.
185        fn assert_send<T: Send>(_: T) {}
186
187        let (db, _) = fake_database(MemoryConnection::new(Dialect::Sqlite));
188        assert_send(async move {
189            let found: rainier_orm::Result<Option<User>> =
190                repo::find_one_by(&db, "email", "a@b.c").await;
191            let listed: rainier_orm::Result<Vec<User>> =
192                repo::query::<User>().where_eq("id", 1_i64).all(&db).await;
193            (found.is_ok(), listed.is_ok())
194        });
195    }
196
197    #[tokio::test]
198    async fn schema_ddl_renders_for_the_connections_dialect() {
199        let ddl = schema::create_table_ddl::<User>(Dialect::Sqlite);
200        assert!(ddl.contains("users"), "{ddl}");
201        assert!(ddl.contains("email"), "{ddl}");
202    }
203}