rok_db/lib.rs
1//! # rok-db
2//!
3//! An ergonomic, type-safe async ORM for PostgreSQL, built on [`sqlx`].
4//!
5//! ```no_run
6//! use rok_db::prelude::*;
7//!
8//! #[derive(Debug, Clone, Model)]
9//! struct User {
10//! #[rok(primary_key, generated)]
11//! id: i64,
12//! email: String,
13//! name: Option<String>,
14//! age: i32,
15//! }
16//!
17//! # async fn run() -> rok_db::Result<()> {
18//! let db = Db::connect("postgres://postgres@localhost/app").await?;
19//!
20//! // Create
21//! let ann = User { id: 0, email: "ann@example.com".into(), name: None, age: 31 }
22//! .insert(&db)
23//! .await?;
24//!
25//! // Read with typed, model-scoped columns
26//! let adults = User::filter(User::AGE.gte(18))
27//! .filter(User::EMAIL.ends_with("@example.com"))
28//! .order_by(User::AGE.desc())
29//! .limit(10)
30//! .all(&db)
31//! .await?;
32//!
33//! // Update
34//! let mut ann = User::find_or_fail(&db, ann.id).await?;
35//! ann.name = Some("Ann".into());
36//! let ann = ann.save(&db).await?;
37//!
38//! // Bulk update & delete
39//! User::filter(User::AGE.lt(18)).update().set(User::NAME, None::<String>).exec(&db).await?;
40//! User::filter(User::EMAIL.is_null()).delete(&db).await?;
41//!
42//! // Pagination (one round trip)
43//! let page = User::order_by(User::ID).paginate(&db, 1, 20).await?;
44//! println!("{} of {} users", page.len(), page.total);
45//!
46//! // Transactions
47//! db.transaction(|tx| Box::pin(async move {
48//! ann.delete(&mut *tx).await?;
49//! Ok::<_, rok_db::Error>(())
50//! })).await?;
51//! # Ok(()) }
52//! ```
53//!
54//! ## Defining models
55//!
56//! `#[derive(Model)]` implements [`Model`] and `sqlx::FromRow`, and adds one
57//! typed [`Column`] constant per field (`User::EMAIL`, …). See
58//! [`derive@Model`] for every attribute.
59//!
60//! ## Relations
61//!
62//! `#[rok(belongs_to = User)]`, `#[rok(has_many(posts = Post::USER_ID))]` and
63//! `#[rok(has_one(..))]` generate relation constants ([`BelongsTo`],
64//! [`HasMany`], [`HasOne`]) and lazy query methods. Eager-load related
65//! records for many parents with one extra query: see [`relation`].
66//!
67//! ## More features
68//!
69//! - **Streaming**: [`Select::stream`] yields rows one at a time.
70//! - **Aggregates & projections**: [`Select::sum`], [`Select::avg`],
71//! [`Select::group_by`], [`Select::having`] and [`Select::select`] with
72//! [`Projection`]s, decoded into tuples or [`derive@FromRow`] structs.
73//! - **Timestamps**: `#[rok(timestamps)]` manages `created_at`/`updated_at`.
74//! - **Keyset pagination**: [`Select::cursor_paginate`] with opaque
75//! [`Cursor`]s.
76//! - **Soft deletes**: `#[rok(soft_delete)]`, [`Select::with_trashed`],
77//! [`Model::restore`], [`Model::force_delete`].
78//! - **Optimistic locking**: `#[rok(version)]`; stale writes fail with
79//! [`Error::Conflict`].
80//! - **Upserts**: [`Model::upsert_on`], [`Model::insert_many`] and
81//! [`Insert::on_conflict`] with `do_nothing`/`do_update`/`do_update_all`.
82//! - **Subqueries**: [`Column::in_subquery`], [`Expr::exists`] and
83//! [`Column::eq_outer`] for correlation.
84//! - **Custom column types**: [`derive@DbEnum`], [`derive@DbNewtype`] and
85//! [`impl_value!`].
86//! - **Validation & hooks**: `#[rok(validate(…))]` rules ([`validate`]) and
87//! the [`Hooks`] trait.
88//! - **Scopes**: `#[rok(default_scope = …)]`, [`Select::scope`],
89//! [`Select::unscoped`].
90//! - **Retrying transactions**: [`Db::transaction_with`] with [`TxOptions`].
91//! - **Change tracking**: [`Model::track`] / [`Tracked`] and
92//! [`Model::save_only`].
93//! - **Bulk loading**: [`Model::copy_in`] with binary `COPY`.
94//! - **Web & metrics**: the [`web`] module (`serde`, `axum` features) and
95//! [`metrics`] (`metrics` feature).
96//! - **PostgreSQL types**: arrays (`Vec<T>` fields, [`Column::array_has`],
97//! [`Column::eq_any`]), JSONB ([`Column::json_text`],
98//! [`Column::json_has_key`]) and full-text search ([`Column::search`],
99//! [`Column::search_rank`]).
100//! - **Read replicas**: [`DbBuilder::read_replica`], [`Select::on_primary`],
101//! [`Db::primary`].
102//! - **LISTEN/NOTIFY**: [`Db::listen`], [`Db::notify`] and model change
103//! feeds ([`Model::changes`], see [`notify`]).
104//! - **Multi-instance caching**: [`DbBuilder::shared_cache_invalidation`].
105//! - **Multi-tenancy**: `#[rok(tenant)]` and [`tenant::with_tenant`].
106//! - **Audit log** (feature `json`): the [`audit`] module.
107//! - **Joins**: [`Select::join`] / [`Select::left_join`] with compile-time
108//! checked columns across models (see [`join`]).
109//! - **Composite primary keys**: several `#[rok(primary_key)]` fields;
110//! look records up with tuples ([`IntoKey`]).
111//! - **Memoization**: [`Select::memoize`] caches results in the pool's
112//! [`QueryCache`] with automatic invalidation on writes.
113//! - **Query logging**: every statement is logged through `tracing`
114//! (`rok_db::query` at DEBUG, `rok_db::slow_query` at WARN; see
115//! [`DbBuilder::slow_query_threshold`]).
116//!
117//! ## Executors
118//!
119//! Every query method accepts any [`Executor`]: `&Db`, `&mut Tx` (write
120//! `&mut *tx` inside a transaction closure), or a plain sqlx `&PgPool` /
121//! `&mut PgConnection` — so rok-db slots into existing sqlx code.
122//!
123//! ## Raw SQL
124//!
125//! When the builder isn't enough, [`raw()`] runs any SQL with `?` placeholders
126//! and decodes into models or any `FromRow` type; [`Expr::raw`] embeds a raw
127//! condition in a builder query. Every builder has a `to_sql()` method for
128//! inspecting the generated statement.
129//!
130//! ## Cargo features
131//!
132//! | feature | enables |
133//! |-----------|------------------------------------------------------|
134//! | `chrono` | `chrono` date/time column types |
135//! | `uuid` | `uuid::Uuid` columns |
136//! | `json` | `serde_json::Value` and `sqlx::types::Json<T>` columns |
137//! | `migrate` | [`Db::migrate`] for running sqlx migrations |
138//! | `testing` | [`macro@test`] and [`testing::TestDb`]: a temporary database per test |
139//! | `serde` | `Serialize` for pages, cursors and validation errors |
140//! | `axum` | [`Error`] implements axum's `IntoResponse` (implies `serde`) |
141//! | `metrics` | query, cache and pool metrics, see [`metrics`] |
142//! | `full` | all of the above except `testing` |
143
144pub use rok_db_core::*;
145
146/// Derive [`Model`] for a struct. See the [crate docs](crate) for an example.
147pub use rok_db_macros::Model;
148
149/// Derive `sqlx::FromRow` for a plain struct, without depending on sqlx.
150pub use rok_db_macros::FromRow;
151
152/// Derive a column type for a field-less enum (stored as `TEXT` or a
153/// PostgreSQL enum).
154pub use rok_db_macros::DbEnum;
155
156/// Derive a column type for a single-field tuple struct.
157pub use rok_db_macros::DbNewtype;
158
159/// Run an async test against a fresh, temporary database (feature `testing`).
160#[cfg(feature = "testing")]
161pub use rok_db_macros::test;
162
163/// Everything you need for day-to-day use: `use rok_db::prelude::*;`
164pub mod prelude {
165 pub use crate::{
166 Column, Db, DbEnum, DbNewtype, Executor, Expr, Model, Page, Projection, Select, Tx,
167 };
168 pub use futures_util_reexports::*;
169
170 mod futures_util_reexports {
171 pub use crate::{StreamExt as _, TryStreamExt as _};
172 }
173}
174
175/// Compile-time guarantees, checked by doctests.
176///
177/// A joined query rejects columns of models that aren't part of it:
178///
179/// ```compile_fail
180/// use rok_db::prelude::*;
181/// #[derive(Model)] struct User { id: i64, name: String }
182/// #[derive(Model)] struct Post { id: i64, #[rok(belongs_to = User)] user_id: i64 }
183/// #[derive(Model)] struct Tag { id: i64, label: String }
184///
185/// // `Tag` was never joined.
186/// let _ = Post::query().join(Post::USER).filter(Tag::LABEL.eq("x"));
187/// ```
188///
189/// while the same filter on a joined model compiles:
190///
191/// ```
192/// use rok_db::prelude::*;
193/// #[derive(Model)] struct User { id: i64, name: String }
194/// #[derive(Model)] struct Post { id: i64, #[rok(belongs_to = User)] user_id: i64 }
195///
196/// let _ = Post::query().join(Post::USER).filter(User::NAME.eq("x"));
197/// ```
198///
199/// Only joined models can be fetched as tuples:
200///
201/// ```compile_fail
202/// use rok_db::prelude::*;
203/// #[derive(Model)] struct User { id: i64, name: String }
204/// #[derive(Model)] struct Post { id: i64, #[rok(belongs_to = User)] user_id: i64 }
205/// #[derive(Model)] struct Tag { id: i64, label: String }
206///
207/// let _ = Post::query().join(Post::USER).with_sql::<Tag, _>();
208/// ```
209///
210/// ```
211/// use rok_db::prelude::*;
212/// #[derive(Model)] struct User { id: i64, name: String }
213/// #[derive(Model)] struct Post { id: i64, #[rok(belongs_to = User)] user_id: i64 }
214///
215/// let _ = Post::query().join(Post::USER).with_sql::<(User, Option<User>), _>();
216/// ```
217#[doc(hidden)]
218pub mod __compile_checks {}