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