Skip to main content

Crate navree_orm

Crate navree_orm 

Source
Expand description

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 Ulids 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) 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 broadcasts (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 or a 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>,
}

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§

accessaccess
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, and BoundChild<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 not Fields 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::list applies a ListQuery that navree-http read against a ListSpec (the filters, the search and the order), and ListQueryExt turns its paging into PageRequest or CursorRequest for paginate and cursor_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, the Statements 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.
validationvalidation
Validation rules that query models (feature validation): unique and exists build navree-validation AsyncRules, checked by ValidAsync in 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)], a workspace_id column) 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
Attributes from "column" => value pairs. Keys are string literals; each value is what serde_json::json! takes: an expression of any serializable type, null, or JSON written inline.
morph_types
Declares an enum of the models a morph_to relation can load, with a conversion from AnyRecord and a function registering every model in the MorphMap.

Structs§

Assignment
SET column = value in a mass update, or an attribute of first_or_create and 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.
ClosureScope
A global scope that is a named function of the builder: what ModuleBuilderOrmExt::global_scope registers.
Collection
The records of a query, in order.
Column
A column of model M holding values of type T.
ColumnMeta
One column of a model, as #[derive(Model)] describes it.
ConfiguredOrmModule
OrmModule::for_root(..) / OrmModule::from_config(): the module with its options and strict-mode handlers.
CursorPage
One page of cursor-paginated results: {"data": [...], "next_cursor", "prev_cursor"}, what navree-orm’s cursor_paginate answers. Pass a cursor back as ?cursor= for the next or the previous page; null means there is none. A page that only goes forward (a CursorQuery over a UUID v7 key) has no prev_cursor.
Decimal
Decimal represents a 128 bit representation of a fixed-precision decimal number. The finite set of values of type Decimal are 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.
DocumentTarget
A document store, the app it belongs to, and where the change events of its writes go.
ExecContext
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_, having and join clauses.
InsertOutcome
The result of an insert.
JoinClause
The conditions of a join: column comparisons (on, or_on) and every where method, all combined into the join’s ON.
ModelMeta
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.
PageMeta
The pagination metadata of a Page.
PageQuery
?page=&per_page= (defaults 1 and 15; per_page is 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 with raw.
Record
A model instance as the ORM knows it: the model itself (a Record<M> dereferences to M, 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.
RegisteredModel
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 to Executor::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.
SoftDeletes
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.
TableBuilder
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.
UlidError
Why a text is not a ULID.
Untyped
The model type of columns that belong to no model: col and column names given as strings.
WhereGroup
A parenthesised group of conditions, built in a closure: .where_group(|g| g.where_(a).or_where(b)) is AND (a OR b).

Enums§

Access
What an operation does, which decides where &Db runs it.
ConflictUpdate
What an upsert sets 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.
FieldError
Why a column value could not become a field.
FieldKind
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 typed NULL is, 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:prune handles per chunk.

Traits§

ChangeRecorder
Where the writes through a DocumentTarget record their ChangeEvents 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. See DocumentTarget::recording_changes.
ColumnName
A column given by name or as a typed constant, for methods that only need its name (is_dirty_on, extra, …).
ColumnOf
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, …
DocumentDriver
A document store under the model API. See the module docs.
Executor
Something ORM operations run on: Db, Uow, a document store (see DocumentDriver), or an Arc of one.
Field
A Rust type a model field (or a column read with Row::get) can have.
GlobalScope
A constraint every query of model M gets, 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).
IntoExpr
Something that names a column or computes a value in SQL: a typed Column, a column name ("title", "deals.title", "meta->status"), or an Expr. Select lists, orders and groups take these.
IntoQuery
A query usable as a subquery: model builders, table builders and IR.
IntoSelect
An item of a select list: a typed column, a column name ("title", "deals.*", "title as name"), an Expr, or an (item, alias) pair.
Model
An ORM model: a plain struct with #[derive(Model)].
ModelLifecycle
The lifecycle’s methods on models themselves (Deal::create_quietly, Note::force_destroy, …), implemented for every Model. Bring it into scope with use navree_orm::prelude::*;.
ModuleBuilderOrmExt
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).
PrimaryKey
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 every Scoped<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 typed Column<M, T> gives T (decoded as the field is, casts included); a column name or an Expr gives a Value.
SoftDeleting
A model that soft-deletes: #[model(soft_deletes)] implements it. It unlocks Record::restore, Builder::only_trashed, Builder::restore and the restore-or-create family.
Timestamp
The Rust type of a timestamp column (created_at, updated_at, deleted_at).
ValueFor
A value a column holding T accepts in conditions and assignments (Deal::TITLE.eq("Renewal"), Company::COUNTRY.eq("US"), Deal::AMOUNT_CENTS.gte(10_000)).

Functions§

affecting_statement
Runs raw statement statement where 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 value is a NULL (of any kind).
raw
Raw SQL with ? placeholders for values (?? 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.5 and 12.50), date-times by instant, JSON structurally, anything else exactly.
scalar
The first column of the first row of raw query query, read as T; None when the query returns no row.
scoped_connection
The connection using_connection set 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 statement where 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
value as 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 as null. Non-finite floats become null.
unprepared
Runs sql as written, without binding values: several statements may be separated by ;. For DDL and scripts; never put user input in it.
using_connection
Runs future with connection name standing in for the default one: operations given the default Db run on name, unless their query or model names another connection. Task-local, like using_writer: tasks spawned inside start without it.
using_writer
Runs future with every read of the task going to the writer, even where read replicas exist (see Db::using_writer): for reads that must see a write made outside the task’s unit of work.

Type Aliases§

DateSerializer
How a model writes its date-times in serialized records (#[model(serialize_dates_with = path)]): the instant, with the offset the field had (UTC for DateTime<Utc> and NaiveDateTime fields), 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).
PartialSchemaFn
The OpenAPI schema of a column or appended value (#[model(schema = Type)] gives Type’s ToSchema::schema).
Result
The result type of ORM operations.
RowsStream
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 the testing feature 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 the testing feature 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 the testing feature 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 (so deal.company() and with("company") mean the same relation).
scopes
#[derive(Model)], #[scopes], #[relations], #[accessors] and #[test] (see their documentation in navree-orm-macros; #[test] needs the testing feature for its databases). Turns the #[scope] functions of an impl block into methods of the model’s query builders, through a generated trait ({Model}Scopes, public unless vis = "..." says otherwise; name it with name = "...").
test
#[derive(Model)], #[scopes], #[relations], #[accessors] and #[test] (see their documentation in navree-orm-macros; #[test] needs the testing feature for its databases). An async fn test, run on a runtime of its own (no #[tokio::test] needed), given a database of its own when it takes one (navree-orm’s testing feature; see navree_orm::testing::database):

Derive Macros§

Model
#[derive(Model)], #[scopes], #[relations], #[accessors] and #[test] (see their documentation in navree-orm-macros; #[test] needs the testing feature for its databases). Implements Model for a struct with named fields.