navree_orm/lib.rs
1//! # navree-orm
2//!
3//! Navree's ORM: active-record models on PostgreSQL / TimescaleDB, MySQL /
4//! MariaDB and SQLite (and document stores through [`DocumentDriver`]),
5//! running on navree-db's pool and unit of work.
6//!
7//! Items hidden from this documentation are not public API: Navree's own
8//! macros and crates use them, and they can change in any release.
9//!
10//! - **Models** are plain structs with `#[derive(Model)]`: a typed key
11//! (integers the database assigns, UUID v7 / v4 and [`Ulid`]s generated
12//! on insert, or keys the application sets), timestamps, soft deletes,
13//! casts, and one typed [`Column`] constant per column.
14//! - **Queries** chain on [`Builder`]: every where variant, nested groups,
15//! selects and subqueries, joins, groups, havings, orders, limits,
16//! unions, locks, scopes, and TimescaleDB's `time_bucket`, `first` and
17//! `last`. [`TableBuilder`] queries tables without a model.
18//! - **Records** ([`Record`]) carry dirty tracking, extras and loaded
19//! relations; saving inserts or updates, with lifecycle [`hooks`].
20//! - **Relationships** ([`relations`](mod@relations)) are methods of a
21//! `#[relations]` impl block (belongs to, has one/many, many to many
22//! with pivots, through, polymorphic): query them like builders, eager
23//! load them in batches (`with("company.owner")`), check their existence
24//! (`where_has`), aggregate them (`with_count`), and write through them
25//! (`attach`, `sync`, `associate`).
26//! - **The lifecycle**: model [`events`] heard by observers, closures,
27//! typed application events and [`broadcast`]s (after the commit inside a
28//! unit of work), quiet operations, soft deletes (`restore`,
29//! `force_delete`, `only_trashed`), global scopes registered at boot,
30//! [`strict`] modes, and [`prune`] (`model:prune`), configured by
31//! [`OrmModule`].
32//! - **Streams and bulk writes**: chunks, lazy streams and cursors
33//! ([`streams`]), raw statements ([`raw()`]), multi-row inserts,
34//! insert-or-ignore, upserts and the other writes without events
35//! ([`Builder::insert`], [`TableBuilder::upsert`], ...).
36//! - **Executors**: every terminal method takes the executor first — a
37//! [`Db`](navree_db::Db) or a [`Uow`](navree_db::Uow) — so statements run
38//! in the request's transaction, with its actor, workspace settings and
39//! change events (the audit trail).
40//! Models and queries can live on named connections
41//! (`#[model(connection = "..")]`, `on_connection`, [`using_connection`])
42//! and read from the writer when replicas exist (`use_write`,
43//! [`using_writer`]); see [`Route`].
44//! - **In apps**: model [`factory`] builders for tests and seeders, the
45//! database assertions and test databases of [`testing`], route model
46//! [`binding`] (`Bound<Deal>`), [`workspace`] scoping
47//! (`#[model(workspace)]`), access control (`#[model(subject, policy)]`,
48//! feature `access`), validation rules on models (feature `validation`)
49//! and `model:show` ([`OrmModule`]).
50//!
51//! ```
52//! use chrono::{DateTime, Utc};
53//! use navree_db::{Db, DbOptions, Executor};
54//! use navree_orm::prelude::*;
55//! use serde::{Deserialize, Serialize};
56//!
57//! #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
58//! #[serde(rename_all = "snake_case")]
59//! enum Stage {
60//! #[default]
61//! Open,
62//! Won,
63//! }
64//!
65//! #[derive(Model, Clone, Debug, Default, Serialize)]
66//! #[model(table = "deals", timestamps)]
67//! struct Deal {
68//! id: i64,
69//! title: String,
70//! amount_cents: i64,
71//! #[model(cast = "string_enum")]
72//! stage: Stage,
73//! created_at: DateTime<Utc>,
74//! updated_at: DateTime<Utc>,
75//! }
76//!
77//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
78//! # let dir = tempfile::tempdir().unwrap();
79//! # let url = format!("sqlite://{}?mode=rwc", dir.path().join("doc.db").display());
80//! let db = Db::connect(&DbOptions { url, ..DbOptions::default() }).await?;
81//! db.execute_script(
82//! "CREATE TABLE deals (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL,
83//! amount_cents INTEGER NOT NULL, stage TEXT NOT NULL,
84//! created_at TEXT NOT NULL, updated_at TEXT NOT NULL)",
85//! )
86//! .await?;
87//!
88//! let mut deal = Deal::create(&db, Deal {
89//! title: "Renewal".into(),
90//! amount_cents: 120_000,
91//! ..Default::default()
92//! })
93//! .await?;
94//! assert_eq!(deal.id, 1); // the database assigned the key
95//!
96//! deal.stage = Stage::Won;
97//! assert!(deal.is_dirty_on([Deal::STAGE]));
98//! deal.save(&db).await?;
99//!
100//! let won = Deal::query()
101//! .where_(Deal::STAGE.eq(Stage::Won))
102//! .where_(Deal::AMOUNT_CENTS.gte(100_000))
103//! .latest()
104//! .get(&db)
105//! .await?;
106//! assert_eq!(won[0].title, "Renewal");
107//! assert_eq!(Deal::query().sum::<i64>(&db, Deal::AMOUNT_CENTS).await?, 120_000);
108//! # Ok::<(), Box<dyn std::error::Error>>(())
109//! # }).unwrap();
110//! ```
111//!
112//! The architecture, and where each later feature plugs in, is in the
113//! crate's `DESIGN.md`.
114#![forbid(unsafe_code)]
115#![cfg_attr(docsrs, feature(doc_cfg))]
116
117extern crate self as navree_orm;
118
119#[cfg(feature = "access")]
120pub mod access;
121pub mod attributes;
122pub mod binding;
123pub mod broadcast;
124pub mod cast;
125mod collection;
126mod column;
127mod driver;
128mod error;
129pub mod events;
130mod exec;
131mod expr;
132pub mod factory;
133mod global_scopes;
134pub mod hooks;
135pub mod ir;
136mod lifecycle;
137pub mod list;
138mod model;
139mod module;
140mod operators;
141mod options;
142pub mod pagination;
143mod persist;
144pub mod prelude;
145pub mod prune;
146mod query;
147mod quiet;
148mod raw;
149mod record;
150pub mod relations;
151pub mod render;
152mod row;
153mod scope;
154pub mod show;
155mod soft_deletes;
156pub mod sql;
157pub mod streams;
158pub mod strict;
159pub mod testing;
160mod ulid;
161#[cfg(feature = "validation")]
162pub mod validation;
163mod value;
164pub mod workspace;
165
166pub use collection::Collection;
167pub use column::{
168 Assignment, Column, ColumnName, ColumnOf, Decoder, Encoder, Filter, IntoExpr, IntoQuery,
169 Untyped, col, col_as,
170};
171pub use driver::{DocumentDriver, InsertOutcome};
172pub use error::{OrmError, Result};
173pub use events::{Observer, ObserverHook, without_events};
174pub use exec::{
175 Access, ChangeRecorder, DocumentTarget, ExecContext, Executor, Route, RowsStream, SqlTarget,
176 Target, scoped_connection, using_connection, using_writer,
177};
178pub use global_scopes::ClosureScope;
179pub use ir::{Expr, LockMode, VectorMetric};
180pub use lifecycle::ModelLifecycle;
181pub use model::{
182 ColumnMeta, DateSerializer, KeyKind, Model, ModelMeta, PartialSchemaFn, PrimaryKey, Timestamp,
183};
184pub use module::{
185 ConfiguredOrmModule, ModuleBuilderOrmExt, OrmModule, OrmRuntime, RegisteredModel,
186 registered_models,
187};
188pub use options::{DEFAULT_PRUNE_CHUNK, OrmOptions};
189pub use pagination::{
190 CursorPage, CursorRequest, Page, PageMeta, PageQuery, PageRequest, SimplePage, SimplePageMeta,
191};
192pub use query::{
193 Builder, ConflictUpdate, HasQuery, HasWheres, IntoSelect, JoinClause, Selectable, TableBuilder,
194 WhereGroup, table,
195};
196pub use raw::{Raw, affecting_statement, raw, scalar, select, select_one, statement, unprepared};
197pub use record::Record;
198pub use row::Row;
199pub use scope::{GlobalScope, Scoped, SoftDeletes};
200pub use soft_deletes::SoftDeleting;
201pub use sql::{Dialect, Statement, Syntax};
202pub use streams::{RowStream, cursor};
203pub use ulid::{Ulid, UlidError};
204pub use value::{
205 Decimal, Field, FieldError, FieldKind, Kind, Numeric, Value, ValueFor, is_null, same_value,
206 to_json,
207};
208
209/// `#[derive(Model)]`, `#[scopes]`, `#[relations]`, `#[accessors]` and
210/// `#[test]` (see their documentation in navree-orm-macros; `#[test]` needs
211/// the `testing` feature for its databases).
212pub use navree_orm_macros::{Model, accessor, accessors, relations, scopes, test};
213
214/// What the macros expand to. Not part of the API.
215#[doc(hidden)]
216pub mod __private {
217 pub use crate::attributes::{CastContext, NoAccessors, has_accessor};
218 pub use crate::cast::{decode, decode_option, encode, encode_option};
219 pub use crate::model::derive_support::*;
220 pub use crate::relations::derive_support as relations;
221 pub use chrono::{DateTime, FixedOffset, Utc};
222 pub use navree_kernel::BoxFuture;
223 pub use navree_openapi;
224 pub use serde;
225 pub use serde_json;
226 pub use std::sync::{Arc, OnceLock};
227 pub use tokio;
228}
229
230/// The models the documentation examples use, so every example compiles.
231/// Not part of the API.
232#[doc(hidden)]
233#[path = "doc_models.rs"]
234pub mod __doc_models;
235
236/// The models and factories the factory, testing, binding and workspace
237/// examples use. Not part of the API.
238#[doc(hidden)]
239#[path = "doc_factories.rs"]
240pub mod __doc_factories;
241
242/// The model the access-control examples use. Not part of the API.
243#[cfg(feature = "access")]
244#[doc(hidden)]
245#[path = "doc_access.rs"]
246pub mod __doc_access;