Expand description
§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 andUlids generated on insert, or keys the application sets), timestamps, soft deletes, casts, and one typedColumnconstant per column. - Queries chain on
Builder: every where variant, nested groups, selects and subqueries, joins, groups, havings, orders, limits, unions, locks, scopes, and TimescaleDB’stime_bucket,firstandlast.TableBuilderqueries tables without a model. - Records (
Record) carry dirty tracking, extras and loaded relations; saving inserts or updates, with lifecyclehooks. - Relationships (
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
eventsheard by observers, closures, typed application events andbroadcasts (after the commit inside a unit of work), quiet operations, soft deletes (restore,force_delete,only_trashed), global scopes registered at boot,strictmodes, andprune(model:prune), configured byOrmModule. - 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
Dbor aUow— 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); seeRoute. - In apps: model
factorybuilders for tests and seeders, the database assertions and test databases oftesting, route modelbinding(Bound<Deal>),workspacescoping (#[model(workspace)]), access control (#[model(subject, policy)], featureaccess), validation rules on models (featurevalidation) andmodel: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>,
}
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);The architecture, and where each later feature plugs in, is in the
crate’s DESIGN.md.
Re-exports§
pub use events::Observer;pub use events::ObserverHook;pub use events::without_events;pub use ir::Expr;pub use ir::LockMode;pub use ir::VectorMetric;pub use pagination::CursorRequest;pub use pagination::PageRequest;pub use pagination::SimplePage;pub use pagination::SimplePageMeta;pub use sql::Dialect;pub use sql::Statement;pub use sql::Syntax;pub use streams::RowStream;pub use streams::cursor;
Modules§
- access
access - Access control on models (feature
access): navree-access’s abilities as query filters and record checks on ORM models. - attributes
- The attribute layer of models: how values get in (mass assignment, mutators, casts), what they are stored as (casts that need the app: the encrypter, the hasher), and how records go out (accessors, visibility, serialization, API resources, OpenAPI schemas, references in queued jobs).
- binding
- Route model binding:
Bound<M>loads the record a route’s path parameter names, andBoundChild<P, C>a record under its parent (/companies/{company}/deals/{deal}), as handler arguments. - broadcast
- Broadcasting model changes on real-time channels.
- cast
Cast: converting a field between its Rust type and its stored column value, for types that are notFields themselves.- events
- Model events: how they reach listeners, and silencing them.
- factory
- Model factories: records for tests and seeders, built from a definition with fake data, states, sequences and relationships.
- hooks
- Lifecycle hooks: what runs around retrieval, saves and deletes.
- ir
- The driver-neutral query representation (IR).
- list
- List queries on models:
Builder::listapplies aListQuerythat navree-http read against aListSpec(the filters, the search and the order), andListQueryExtturns its paging intoPageRequestorCursorRequestforpaginateandcursor_paginate. - pagination
- Pagination of model queries.
- prelude
- The names an app uses with models:
use navree_orm::prelude::*;. - prune
- Pruning: deleting records that are no longer needed.
- relations
- Relationships between models.
- render
- navree-orm’s own SQL renderer: a syntax tree that is the same for
every database, grammars that write it for PostgreSQL /
TimescaleDB, MySQL / MariaDB and SQLite, and a lowering from
the ORM’s IR (
render_select,render_insert, …), which writes every statement the ORM runs. - show
model:show: what the app knows about a model, from its metadata and its registrations: table, key, columns with their types and casts, timestamps, soft deletes, workspace, factory and the relationships it declares, access subject and policy, global scopes and hooks.- sql
- SQL for PostgreSQL / TimescaleDB, MySQL and SQLite: the
Dialects, theStatements the ORM runs, and the functions that write the IR as statements (render_select,render_insert, …). - streams
- Reading large results without holding them in memory: chunks, lazy streams and cursors.
- strict
- Strict modes: mistakes that are errors in development and tests, and tolerated (or only reported) in production.
- testing
- Assertions on the database for tests: rows and records that exist or not, row counts, soft deletes, and the number of queries a piece of code runs.
- validation
validation - Validation rules that query models (feature
validation):uniqueandexistsbuild navree-validationAsyncRules, checked byValidAsyncin the request’s unit of work after the input’s other rules pass. - workspace
- Workspace scoping: models whose records belong to a workspace
(
#[model(workspace)], aworkspace_idcolumn) see the current workspace’s records only, fill it on the records they create, and refuse to move or touch another workspace’s records.
Macros§
- attrs
Attributesfrom"column" => valuepairs. Keys are string literals; each value is whatserde_json::json!takes: an expression of any serializable type,null, or JSON written inline.- morph_
types - Declares an enum of the models a
morph_torelation can load, with a conversion fromAnyRecordand a function registering every model in theMorphMap.
Structs§
- Assignment
SET column = valuein a mass update, or an attribute offirst_or_createand friends:Column::set.- Builder
- A query of model
M: the where family, selects, joins, groups, orders, limits, scopes, and the retrieval, aggregate, pagination and mass-write methods that run it. - Closure
Scope - A global scope that is a named function of the builder:
what
ModuleBuilderOrmExt::global_scoperegisters. - Collection
- The records of a query, in order.
- Column
- A column of model
Mholding values of typeT. - Column
Meta - One column of a model, as
#[derive(Model)]describes it. - Configured
OrmModule OrmModule::for_root(..)/OrmModule::from_config(): the module with its options and strict-mode handlers.- Cursor
Page - One page of cursor-paginated results:
{"data": [...], "next_cursor", "prev_cursor"}, what navree-orm’scursor_paginateanswers. Pass a cursor back as?cursor=for the next or the previous page;nullmeans there is none. A page that only goes forward (aCursorQueryover a UUID v7 key) has noprev_cursor. - Decimal
Decimalrepresents a 128 bit representation of a fixed-precision decimal number. The finite set of values of typeDecimalare of the form m / 10e, where m is an integer such that -296 < m < 296, and e is an integer between 0 and 28 inclusive.- Document
Target - A document store, the app it belongs to, and where the change events of its writes go.
- Exec
Context - What a running operation knows about where it runs: the app (for its clock and other services), the unit of work, the dialect, the precision the database keeps in date-times. Lifecycle hooks and casts receive it.
- Filter
- A condition for
where_,havingand join clauses. - Insert
Outcome - The result of an insert.
- Join
Clause - The conditions of a join: column comparisons (
on,or_on) and every where method, all combined into the join’sON. - Model
Meta - What
#[derive(Model)]knows about a model: its name, table, key, columns, timestamps, soft-delete column, connection and page size. - OrmModule
- The ORM’s module. Global; provides and exports
OrmRuntime. - OrmOptions
- The ORM’s options, the
[orm]section of the configuration. - OrmRuntime
- The ORM of a booted app: its options and resolved strict modes.
Provided by
OrmModule. - Page
- One page of results:
{"data": [...], "meta": {"current_page", "per_page", "total", "last_page"}}. Handlers can return it directly. - Page
Meta - The pagination metadata of a
Page. - Page
Query ?page=&per_page=(defaults 1 and 15;per_pageis clamped to 100).- Raw
- Raw SQL with portable
?placeholders and the values bound to them: a fragment (an expression, a condition, a select item) or a whole statement. Built withraw. - Record
- A model instance as the ORM knows it: the model itself (a
Record<M>dereferences toM, so fields read and write directly), whether it is stored, the values it was last synced with (for dirty tracking), the changes its last save made, the extra columns its query selected (aggregates, computed columns) and its loaded relations. - Registered
Model - A model a module registered (see
ModuleBuilderOrmExt::model). - Route
- Where an operation asks to run, beyond its
Access: the connection its query names (on_connection), its model’s connection (#[model(connection = "..")]), and whether its reads go to the writer (use_write). Terminal methods hand it toExecutor::target_routed. - Row
- One result row: navree-db’s row of an SQL query (each column read by its
own type), or the
(column, value)pairs a document driver returns. - Soft
Deletes - The built-in global scope of soft-deleting models: rows whose
deleted-at column is set are left out.
with_trashed()removes it. - SqlTarget
- An SQL connection or transaction, with the unit of work it belongs to.
- Table
Builder - A query of any table: the same where, select, join, group, order and
limit methods as a model query, returning
Rows, plus inserts, updates and deletes of rows. For pivot tables, reports and tables without a model. - Ulid
- A ULID: a 48-bit millisecond timestamp followed by 80 random bits,
written as 26 characters of Crockford’s base32
(
01JB3QG8ZK0000000000000000). ULIDs sort by creation time, as text and as numbers, which keeps indexes on time-series tables compact. - Ulid
Error - Why a text is not a ULID.
- Untyped
- The model type of columns that belong to no model:
coland column names given as strings. - Where
Group - A parenthesised group of conditions, built in a closure:
.where_group(|g| g.where_(a).or_where(b))isAND (a OR b).
Enums§
- Access
- What an operation does, which decides where
&Dbruns it. - Conflict
Update - What an
upsertsets on a row that already exists: a column (set to the value the row would have been inserted with), an assignment, or every inserted column. - Field
Error - Why a column value could not become a field.
- Field
Kind - What a field’s values are, as JSON and OpenAPI see them: the shape serialized records write and schemas describe. A nullable field has the kind of its inner type.
- KeyKind
- How a model’s key gets its value.
- Kind
- The kind of a
Value: what a typedNULLis, and what a column holds. - OrmError
- An ORM error.
- Target
- Where one operation runs.
- Value
- A value a statement binds or a row holds.
Constants§
- DEFAULT_
PRUNE_ CHUNK - The default number of records
model:prunehandles per chunk.
Traits§
- Change
Recorder - Where the writes through a
DocumentTargetrecord theirChangeEvents when the target joins no navree-db unit of work: a document store’s own unit of work (MongoDB’s) collects them for its observers. SeeDocumentTarget::recording_changes. - Column
Name - A column given by name or as a typed constant, for methods that only
need its name (
is_dirty_on,extra, …). - Column
Of - A column of values of type
T, typed (Column<M, T>) or named by a string (any value), for the builder methods that take a column and values:where_in,where_between,where_date, … - Document
Driver - A document store under the model API. See the module docs.
- Executor
- Something ORM operations run on:
Db,Uow, a document store (seeDocumentDriver), or anArcof one. - Field
- A Rust type a model field (or a column read with
Row::get) can have. - Global
Scope - A constraint every query of model
Mgets, unless removed. - HasQuery
- A builder with a query (implemented by every builder).
- HasWheres
- A builder with a list of where clauses (implemented by every builder).
- Into
Expr - Something that names a column or computes a value in SQL: a typed
Column, a column name ("title","deals.title","meta->status"), or anExpr. Select lists, orders and groups take these. - Into
Query - A query usable as a subquery: model builders, table builders and IR.
- Into
Select - An item of a select list: a typed column, a column name (
"title","deals.*","title as name"), anExpr, or an(item, alias)pair. - Model
- An ORM model: a plain struct with
#[derive(Model)]. - Model
Lifecycle - The lifecycle’s methods on models themselves (
Deal::create_quietly,Note::force_destroy, …), implemented for everyModel. Bring it into scope withuse navree_orm::prelude::*;. - Module
Builder OrmExt - ORM registrations on a
ModuleBuilder: observers and closure listeners of model events, global scopes, and the app’s models. - Numeric
- A number a column can be incremented or decremented by
(
Record::increment,Builder::increment). - Primary
Key - The Rust type of a model’s key.
- Scoped
- A builder that model
M’s local scopes apply to:Builder<M>(and relation builders).#[scopes]implements its generated trait for everyScoped<M>. - Selectable
- A column or expression whose values a query can return one by one
(
value,pluck), with the Rust type they come back as: a typedColumn<M, T>givesT(decoded as the field is, casts included); a column name or anExprgives aValue. - Soft
Deleting - A model that soft-deletes:
#[model(soft_deletes)]implements it. It unlocksRecord::restore,Builder::only_trashed,Builder::restoreand the restore-or-create family. - Timestamp
- The Rust type of a timestamp column (
created_at,updated_at,deleted_at). - Value
For - A value a column holding
Taccepts in conditions and assignments (Deal::TITLE.eq("Renewal"),Company::COUNTRY.eq("US"),Deal::AMOUNT_CENTS.gte(10_000)).
Functions§
- affecting_
statement - Runs raw statement
statementwhere the executor writes; returns how many rows it changed (inserted, updated or deleted). - col
- An untyped column:
"title","deals.title", or a JSON path"meta->status". Its conditions take any value. - col_as
- An untyped column whose values are read as
T: for plucks and single values of tables without a model. - is_null
- Whether
valueis a NULL (of any kind). - raw
- Raw SQL with
?placeholders forvalues(??for a literal?). - registered_
models - The models the app’s modules registered, in module dependency order (each once).
- same_
value - Whether two stored values of a column hold the same thing (what dirty
tracking asks): NULLs are equal whatever their kind, floats within a
small relative tolerance, decimals numerically (
12.5and12.50), date-times by instant, JSON structurally, anything else exactly. - scalar
- The first column of the first row of raw query
query, read asT;Nonewhen the query returns no row. - scoped_
connection - The connection
using_connectionset for the running task. - select
- The rows of raw query
query. - select_
one - The first row of raw query
query, if any. - statement
- Runs raw statement
statementwhere the executor writes (inside the unit of work); returns how many rows it changed. - table
- A query of table
name("deals","deals as d"). - to_json
valueas JSON, the way the field would serialize: numbers as numbers, decimals as exact strings ("12.50"), UUIDs and date-times as their serde text (RFC 3339), JSON as itself, bytes and vectors as arrays of numbers, an enum value as its text, NULL asnull. Non-finite floats becomenull.- unprepared
- Runs
sqlas written, without binding values: several statements may be separated by;. For DDL and scripts; never put user input in it. - using_
connection - Runs
futurewith connectionnamestanding in for the default one: operations given the defaultDbrun onname, unless their query or model names another connection. Task-local, likeusing_writer: tasks spawned inside start without it. - using_
writer - Runs
futurewith every read of the task going to the writer, even where read replicas exist (seeDb::using_writer): for reads that must see a write made outside the task’s unit of work.
Type Aliases§
- Date
Serializer - How a model writes its date-times in serialized records
(
#[model(serialize_dates_with = path)]): the instant, with the offset the field had (UTC forDateTime<Utc>andNaiveDateTimefields), to any JSON value. - Decoder
- Reads a column value as a field (with the field’s cast, if any).
- Encoder
- Encodes a field value as a column value (with the field’s cast, if any).
- Partial
Schema Fn - The OpenAPI schema of a column or appended value
(
#[model(schema = Type)]givesType’sToSchema::schema). - Result
- The result type of ORM operations.
- Rows
Stream - Rows read one by one as the database sends them (see
Target::stream).
Attribute Macros§
- accessor
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). Marks an accessor inside an#[accessors]impl block (on its own it only reports where it belongs).- accessors
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). Registers the#[accessor]methods of an impl block as the model’s accessors: computed values serialized records append, by default (#[model(appends(name))]) or per record (record.append(["name"])).- relations
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). Declares a model’s relations: each method of the impl block,fn name(&self) -> RelationType, is a relation, named after the method (sodeal.company()andwith("company")mean the same relation).- scopes
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). Turns the#[scope]functions of animplblock into methods of the model’s query builders, through a generated trait ({Model}Scopes, public unlessvis = "..."says otherwise; name it withname = "...").- test
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). Anasync fntest, run on a runtime of its own (no#[tokio::test]needed), given a database of its own when it takes one (navree-orm’stestingfeature; seenavree_orm::testing::database):
Derive Macros§
- Model
#[derive(Model)],#[scopes],#[relations],#[accessors]and#[test](see their documentation in navree-orm-macros;#[test]needs thetestingfeature for its databases). ImplementsModelfor a struct with named fields.