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 relation;
72pub mod repository;
73pub mod row;
74pub mod statement;
75pub mod testing;
76
77pub use connection::{Connection, Database};
78pub use criteria::{Constraint, Criteria};
79pub use migrator::{Down, Migration, Migrator, Step};
80pub use model::{Created, Creating, Deleted, Deleting, Model, Updated, Updating};
81pub use pagination::Paginated;
82pub use relation::{
83 BelongsTo, BelongsToMany, HasMany, HasOne, PivotQuery, Related, RelatedCounts, Relation,
84 RelationKey,
85};
86pub use repository::{EntityRepository, Repository};
87pub use row::{Cell, ColumnRequest, OwnedRow};
88pub use statement::Prepared;
89
90// The ORM, re-exported so an application depends on one Rainier ORM version and
91// gets the derive, the query builder and the migrator without naming it twice.
92pub use rainier_orm;
93pub use rainier_orm::{
94 ddl, migrate, repo, schema, Action, Blueprint, ColumnKind, Dialect, Entity, Executor, IndexDef,
95 Query, TableChanges,
96};
97
98/// What [`bind_executor!`] expands to. Not a stable API.
99#[doc(hidden)]
100pub mod reexport {
101 pub use crate::row::{ColumnRequest, OwnedRow};
102 pub use rainier_orm::sea_query::Value;
103 pub use rainier_orm::{Dialect, ExecOutcome, Executor, Row, ShardRoute};
104 pub use rainier_support::{BoxFuture, Error, LocalBoxFuture, Result};
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110 use crate::testing::{fake_database, MemoryConnection};
111
112 #[derive(rainier_orm::Entity, Clone, Debug, PartialEq)]
113 #[orm(table = "users")]
114 struct User {
115 #[orm(pk, auto_increment)]
116 id: u64,
117 #[orm(unique)]
118 email: String,
119 }
120
121 impl Model for User {}
122
123 #[tokio::test]
124 async fn the_orm_surface_is_reachable_through_the_executor_impl() {
125 // Implementing `Executor` for `Database` keeps Rainier ORM's own API
126 // available: `repo::` and the query builder take it with no adapter.
127 // These futures are `Send` — see the assertion in
128 // `the_orms_own_futures_are_send_once_upstream_scopes_its_statements`
129 // below — so this path is usable from a request handler too.
130 let (db, connection) = fake_database(
131 MemoryConnection::new(Dialect::Sqlite)
132 .returning([OwnedRow::new().with("id", 1_u64).with("email", "a@b.c")]),
133 );
134
135 let found: Option<User> = repo::find_one_by(&db, "email", "a@b.c").await.unwrap();
136 assert_eq!(found.unwrap().email, "a@b.c");
137
138 let sql = connection.last_statement().unwrap();
139 assert!(sql.contains("users"), "{sql}");
140 assert!(sql.contains("email"), "{sql}");
141 }
142
143 #[tokio::test]
144 async fn the_query_builder_works_against_a_database() {
145 let (db, connection) = fake_database(MemoryConnection::new(Dialect::Sqlite));
146
147 let _: Vec<User> = repo::query::<User>()
148 .where_like("email", "%@example.com")
149 .order_by_desc("id")
150 .limit(5)
151 .all(&db)
152 .await
153 .unwrap();
154
155 let sql = connection.last_statement().unwrap();
156 assert!(sql.contains("LIKE"), "{sql}");
157 assert!(sql.contains("ORDER BY"), "{sql}");
158 }
159
160 #[tokio::test]
161 async fn the_repository_path_covers_the_same_ground_and_stays_send() {
162 let (db, connection) = fake_database(
163 MemoryConnection::new(Dialect::Sqlite)
164 .returning([OwnedRow::new().with("id", 1_u64).with("email", "a@b.c")]),
165 );
166 let users = EntityRepository::<User>::new(db);
167
168 let found = users.first_by("email", "a@b.c".into()).await.unwrap();
169 assert_eq!(found.unwrap().email, "a@b.c");
170 assert!(connection.last_statement().unwrap().contains("users"));
171 }
172
173 #[test]
174 fn the_orms_own_futures_are_send_once_upstream_scopes_its_statements() {
175 // The property `rainier-database::statement` exists to work around.
176 // While Rainier ORM holds a `sea_query` statement across its awaits
177 // these futures are `!Send` and this does not compile; once it does,
178 // the request path could call `repo::` directly and that module could
179 // be retired.
180 //
181 // Kept as a live check rather than a comment so the answer is never
182 // stale: it tracks whichever Rainier ORM the build resolves.
183 fn assert_send<T: Send>(_: T) {}
184
185 let (db, _) = fake_database(MemoryConnection::new(Dialect::Sqlite));
186 assert_send(async move {
187 let found: rainier_orm::Result<Option<User>> =
188 repo::find_one_by(&db, "email", "a@b.c").await;
189 let listed: rainier_orm::Result<Vec<User>> =
190 repo::query::<User>().where_eq("id", 1_i64).all(&db).await;
191 (found.is_ok(), listed.is_ok())
192 });
193 }
194
195 #[tokio::test]
196 async fn schema_ddl_renders_for_the_connections_dialect() {
197 let ddl = schema::create_table_ddl::<User>(Dialect::Sqlite);
198 assert!(ddl.contains("users"), "{ddl}");
199 assert!(ddl.contains("email"), "{ddl}");
200 }
201}