Models, fields and method overrides
Status: M1 slices S1 (scalar fields, create/read/write, method chains), S2 (domains on scalar
fields, search, order, prefetch), S3 (relational fields, commands, _inherits, unlink), S4a
(computed fields, constraints, inverses, new records, savepoints), S4b (dependencies and related
fields through relations, relational fields and commands on new records, parent store) and S5
(grouped reads, the web client’s methods, onchange).
Every Rust example in this guide is compiled and run as a doctest of erp-test-models
(cargo test --doc, part of scripts/ci.sh): the declarations go through the same registry,
method-chain and dependency checks a server runs at startup, so an example that drifts from the
API fails CI. Lines starting with # in the source of this file are hidden setup (the models an
example refers to, and the async fn that gives it a transaction); rustdoc compiles them, the
rendered guide leaves them out.
For developers coming from Odoo, see Odoo compatibility for a concept map, worked example, and fail-loudly differences.
Declaring an addon
Section titled “Declaring an addon”Each addon crate declares itself once, at its crate root:
erp_sdk::addon!(name = "sale_stock", depends = ["sale", "stock"]);# fn main() {}base is always a dependency. The load order of addons is (depth, name) over the dependency graph,
identical after install, upgrade and restart (ADR 0009 §3).
Declaring a model
Section titled “Declaring a model”# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;
#[model(name = "library.book", description = "Book")]pub struct Book { #[field(char, required)] pub name: Option<Arc<str>>, #[field(integer, default = 1)] pub copies: i32, #[field(selection, selection = [("draft", "Draft"), ("done", "Done")], default = "draft")] pub state: Option<Arc<str>>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Book is a declaration type: it has no values and is never a record. Records are RecordSet<Book>
values; the fields are associated constants (Book::NAME, Book::COPIES, Book::STATE) used to read
and write typed values:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char, required)]# pub name: Option<Arc<str>>,# #[field(integer, default = 1)]# pub copies: i32,# #[field(selection, selection = [("draft", "Draft"), ("done", "Done")], default = "draft")]# pub state: Option<Arc<str>>,# }# async fn example(mut tx: Transaction) -> Result<()> {let books = tx.env().model::<Book>()?;let book = books.create(&mut tx, vec![books.vals().set(Book::NAME, "Dune")]).await?;let copies: i32 = book.get(&mut tx, Book::COPIES).await?;book.set(&mut tx, Book::COPIES, copies + 1).await?;book.write(&mut tx, books.vals().set(Book::COPIES, 5).set(Book::STATE, "done")).await?;book.unlink(&mut tx).await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }books.vals() builds typed values for Book: only field handles of Book and of the models it
inherits are accepted, and create/write validate every value against its field (selection keys,
Char(size), digits) whichever API built it.
Every data operation takes tx: &mut Transaction: one task owns a transaction, and its cache is
shared by every environment (sudo, with_user, with_context). Run units of work through
Orm::run, which commits and retries serialization failures and deadlocks (ADR 0008 §5); register
side effects that must only happen after a successful commit with tx.after_commit(...).
Eventful models
Section titled “Eventful models”A regular model opts into transactional event metadata with eventful = true. The default is
false; enabling it on any loaded declaration or extension enables the composed model. A later
eventful = false does not disable another declaration’s opt-in. Rebuilding the registry after the
opting-in addon is uninstalled removes that contribution; existing event rows are retained.
Classical _inherit also contributes the parent declaration’s opt-in through the named child’s
method resolution order: an eventful parent enables the named child, even if the child declares
eventful = false. Delegation with _inherits does not compose this flag; the parent and child
opt in independently, and a delegated-field mutation belongs to the parent model’s capture.
# erp_sdk::addon!(name = "eventful_guide");# use erp_sdk::prelude::*;#[model(name = "eventful_guide.item", eventful = true)]pub struct EventfulItem { #[field(char)] pub name: Option<Arc<str>>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Native code may also use ModelDecl::eventful(true); owned declarations use
ModelDef::eventful(true). Data-only addons set eventful = true in their [[model]] table;
non-boolean values are refused. Described WebAssembly declarations preserve the same boolean.
The registry refuses opt-in on abstract models, transient models and the closed event namespace,
with a diagnostic naming the model and enabling addon. General auto = false and SQL-view model
declarations are not supported: their attributes are refused rather than treated as ordinary tables.
The current candidate captures creates, scalar writes/upserts, stored computes scheduled by admitted mutations and supported eventful-root unlinks. X2many/relation and reserved-range bulk capture remain unfinished. A persisted event-relevant mutation requires an immutable operation identity from its entry point, including a non-eventful source whose changed dependency reaches an eventful stored compute. Events contain names and identifiers, not field values. Delegated fields belong to the parent model’s capture, and each model opts in independently.
Delegation capture follows physical ownership even when one write supplies both inherited and local values. Each owner opts in independently. When a write also changes the delegation link, inherited values apply to the new parent; changing only the link does not invent a parent event. Equal physical business values emit nothing. Parent changes precede local child changes, and envelopes share the transaction’s final outbox INSERT. Shared-parent batches capture each actual parent target once.
The bounded delegation acceptance also covers an ordinary authorized writer, explicit impersonation, a different flushing environment, effective company attribution, access denials and child-constraint rollback. These are specific tested paths, rather than every authority/company combination. See the current OUTBOX report for source-qualified evidence and remaining reentrancy limitations.
Write capture compares actual database OLD/NEW values. An equal business write emits no event;
automatic log-access and row-version bookkeeping does not itself create a business event. Stored
computed/generated changes are included. The originating actor, operation and effective companies
are retained when another environment later flushes or computes. Compute execution authority and
the existing recompute-only write_uid rule remain separate from event attribution.
A later event-relevant operation can settle earlier pending changes before staging its values, so repeated changes to one record retain operation order. Scalar batches remain set-based; all captured envelopes still share one final transaction INSERT. Nested event-relevant side-effect mutations inside an active mutation or compute currently refuse with a named S7 reentrancy error. This includes an inverse or async compute that tries to create/write another event-relevant record; ordinary computed output assignment is supported by the candidate. This refusal is an incomplete S7 case, not full outbox acceptance. No context flag disables required capture. See ADR 0126 for the contract.
Scalar upsert on a declared business key captures returned physical outcomes: new rows emit
create metadata, changed existing rows emit only actual business field names, and unchanged
rows emit nothing. Overwrite, accumulation and floor actions retain their existing upsert
semantics. Duplicate input keys map back to every input position but produce one capture per
physical row; IDs are actual returned IDs, never inferred sequence ranges. Generated changes
and deferred stored-compute writes retain the upsert writer’s attribution. Create/write overrides
still do not run; an upsert override may wrap the base operation through super as before.
Explicit input fields, conflict targets and context defaults obey the ordinary field write mask. Capture admission, callback/constraint/access failure after SQL, or cancellation prevents partial business/event commit. Envelopes split at the existing limits and share the final transaction INSERT. Relation commands, partitioned models and other pre-existing unsupported upsert shapes remain refused. See ADR 0134 and the source-qualified S9 report; this is producer support, not consumer delivery or full OUTBOX acceptance.
An unlink tombstone contains only root IDs actually returned by PostgreSQL, with no field values or changed-field list. Missing rows and repeated deletions emit nothing. Batches split at 256 IDs per envelope and share the transaction’s final outbox INSERT. The actor, operation and companies come from the deleting environment, even when another environment commits.
cascade_models names physical FK cascade/set-null targets, following cascade edges transitively.
This summary comes from the current registry snapshot, including cold-cache targets; it does not
list exact child IDs. Cycles and duplicate paths are deduplicated. More than 64 affected models
refuses the unlink before destructive work; metadata is never truncated. Exact child IDs are planned.
The candidate still refuses non-eventful roots that could indirectly change eventful rows, and eventful x2many or ancillary company-dependent/default/follow-delete effects outside the supported FK contract. These are explicit limitations. Deletion-triggered surviving stored computes retain the deleting origin; pending computes for records being deleted are dropped. Cancellation, caught capture refusal or a failed post-delete hook prevents the deletion from committing without capture. See ADR 0133 for this unlink boundary. Consumers, notifications and retention remain unfinished; this producer API does not establish event delivery.
Field kinds and Rust types
Section titled “Field kinds and Rust types”| Kind | Rust type | NULL reads as |
|---|---|---|
boolean | bool | false |
integer | i32 | 0 |
bigint | BigInt / Option<BigInt> | bigint zero / None |
float | f64 | 0.0 |
float, digits = (p, s) / digits = 0, monetary | Decimal | 0 |
char, text, html, selection | Option<Arc<str>> (or Option<String>) | None |
date / datetime | Option<Date> / Option<DateTime> (naive UTC) | None |
json | Option<serde_json::Value> | None |
many2one, comodel = "..." | Option<RecId> or Many2one<C> | None |
one2many, comodel = "...", inverse_name = "..." / many2many, comodel = "..." | Vec<RecId> or X2many<C> | [] |
reference, selection = [...] | Option<Arc<str>> ("model,id") | None |
many2one_reference, model_field = "..." | i64 | 0 |
date_range, bounds = "[)" / datetime_range, bounds = "[]" (exclusions.md) | Option<DateRange> / Option<DatetimeRange> | None |
A mismatch between the kind and the Rust type is a compile error at the field.
Exact signed bigint
Section titled “Exact signed bigint”#[field(bigint)] stores a signed PostgreSQL int8 using erp_sdk::BigInt (ADR 0210). Construct native values with BigInt::from_i64(value) and retrieve the exact i64 with .get(). Zero is a stored value. Option<BigInt>::None stores SQL NULL; ordinary dynamic reads map NULL to bigint zero, while typed optional reads retain None.
A static default can be a safe integer such as default = 0, or canonical decimal text such as default = "9223372036854775807". Dynamic values accept tagged BigInt, safe integers and canonical decimal strings. Floats refuse. Text has no plus sign, whitespace, redundant leading zeros or negative zero. Full-width domain operands use decimal strings and compare numerically, including IN/NOT IN and keyset/order operations. Company-dependent maps store bigint values as strings, with the same exact decoder.
JSON-2 emits bigint values as decimal strings at every magnitude; see RPC. Grouping and aggregation are unavailable in this scalar delivery. Frozen WASM ABI1 also refuses the new scalar explicitly. A browser widget is not supplied by this scalar slice.
Changing an ordinary stored field declaration from integer to bigint widens its column during module upgrade. Back up the database and use the normal module upgrade operation; schema changes and data loading share its transaction. Existing values and NULLs survive; declared indexes/constraints remain. Adopting a non-integer physical column also refuses and requires an explicit migration. Reverting the declaration to integer refuses: any narrowing requires an explicit migration that first checks every value. Do not use a relation field to store an unrelated 64-bit counter or job id.
Native scalar prerequisite (in progress)
Section titled “Native scalar prerequisite (in progress)”The outbox work adds purpose-neutral Uuid, Xid8 and TimestampTz scalar types and
uuid, xid8, timestamptz field identities. This branch has focused prerequisite
proof; it does not deliver an outbox, generated native fields, UI widgets or a
complete native-field integration contract. Whole native-field integration and outbox acceptance remain incomplete.
| Scalar | Value and input contract |
|---|---|
Uuid | All 128-bit values, including nil; text requires lowercase canonical 8-4-4-4-12. No version, correlation or authorization policy is inferred. |
Xid8 | Exact unsigned 64-bit value; canonical decimal text, with no sign, leading zeroes (except zero itself), floating-point or signed intermediary. |
TimestampTz | Finite whole-microsecond instant with explicit Z or numeric offset, normalized to UTC. The supported range is MIN_UNIX_MICROS through max_unix_micros() in its rustdoc, bounded by the pinned time library; full PostgreSQL extremes/infinity are unsupported. |
SQL NULL is distinct from nil UUID, zero xid8 and the Unix epoch. There is no
implicit scalar default. Native literal field defaults refuse pending the future
native static-default slice; explicit null/removal retains its meaning. A native
schema type mismatch in either direction requires an explicit migration, including
on an empty table. Schema sync never silently casts text to UUID/xid8 or attaches
a timezone to existing naive Datetime values. Existing DateTime remains naive UTC;
there is no implicit conversion to TimestampTz. Legacy RPC CorrelationId and
IdempotencyKey parsers retain their existing case-insensitive UUID behavior.
Frozen WASM ABI1 cannot discriminate these native kinds from ordinary strings.
Explicit native fields, including NULL/empty requests, therefore refuse after the
caller’s existing access checks, naming a future typed ABI major. Ordinary fields
on the same model remain usable. The refusal follows the method chain, not the caller:
once a WASM addon overrides create or write on a model, a create or write that sets
one of that model’s native UUID, xid8 or timezone-aware timestamp fields is refused for
every caller, native code and RPC included, because the value would have to cross the
frozen ABI (a guest sees Unsupported; native code gets a Programming error naming the
field and the future ABI major; an RPC client sees erp.programming). Install such an override only on models whose native fields
are set elsewhere, or wait for the typed ABI major. Generic CRUD JSON, nested command ownership,
compute metadata and tagged context values have separate admission boundaries;
arbitrary user JSON strings are not guessed to be native values. The frozen WIT ABI remains unchanged.
Native server_set, physical defaults, grant-contract publication and outbox
storage remain disabled until a reviewed operational publisher identity boundary is enforced.
No operational role migration or activation is authorized by this prerequisite.
Common parameters: string, help, required, readonly, store, copy, index (index,
index = "btree_not_null", index = "trigram", index = "brin", index = "gin", index = false;
see Index kinds), default = <literal>,
default = none (drop an inherited default), default_fn = path, db_default (keep a boolean’s
static default as the column’s database default; see
Database default of a fail-closed flag), compute,
inverse, related,
depends = [...], reads = [...], depends_context = [...], precompute, compute_sudo,
groups. Kind parameters: size (char), digits (float), currency_field (monetary), selection,
selection_method, selection_add, ondelete (selection: policies for added values at module uninstall; see Extending other addons), comodel, ondelete (many2one, many2many), delegate,
bypass_search_access (many2one), inverse_name (one2many), relation, column1, column2,
ondelete (many2many), domain = [("name", "ilike", "a")], context = {...}, check_company
(relational fields).
Model parameters: name, description, inherit = [OtherModel], kind = "abstract" | "transient",
transient_max_age_seconds / transient_max_count (transient models only; declared policy, cleanup is not
active yet, see Wizard dialogs), table, log_access, inherits = [("parent.model", "parent_id")], check_company_auto,
parent_name, parent_store, rec_name (the field that names a record; a many2one names it by its target’s name), rec_names_search = ["name", "code"] (fields a name
search looks at; default: rec_name), active_name, order, constraints = [("_name", "CHECK(...)", "message")], indexes = [("_name", "(a, b)")] (raw) or indexes = [index(name = "_name", fields = [...], method = "...", include = [...])] (typed, Index kinds),
unique_indexes = [("_name", "(a, b)", "message")], fillfactor = 80 (see below),
id_sequence = "my_seq" or = MY_SEQ (a &str constant; see below),
signal_triggers = [("_name", "policy")] and follow_deletes = [("_name", cache = "my_cache")] (see
below), addon = "name" (only needed when one crate
declares several addons in modules; by default the declaration belongs to the crate’s addon!).
Exclusion constraints (exclusions = [exclude(...)]), WITHOUT OVERLAPS keys (keys = [key(..., without_overlaps = "...")]) and extensions = [...]: see exclusions.md.
Fill factor (ERPForAll only, ADR 0017 §1). fillfactor = N (10–100, percent) keeps 100 - N
percent of each table page free so an UPDATE can put the new row version on the same page (a
HOT update: no index entries written, less WAL). Without it the table keeps PostgreSQL’s default
(100) or whatever a DBA set; with it, schema sync creates the table WITH (fillfactor = N) and
applies changes with ALTER TABLE … SET, which affects pages written afterwards (existing pages
keep their layout until the table is rewritten, e.g. VACUUM FULL). Measured on a 100,000-row
table (docs/bench/m1-s7-orm-perf.md): scattered updates are all HOT from 90 down; rewriting every
row in one statement (a mass recompute) needs about 50 to stay HOT and then runs 3–4× faster with
a quarter of the WAL. Lower values cost disk and scan time, so use them for tables whose rows are
updated often (order lines, stock quants), not for append-mostly tables (logs, posted journal
items). Resolution follows the model’s declaration order (MRO) like order: the newest
declaration that sets fillfactor wins, so an #[extend] in an addon loaded later can tune a model
it does not own, and an addon loaded earlier cannot override it.
Shared id sequence (ERPForAll only, ADR 0058). id_sequence = "ir_actions_id_seq" makes the
table’s id draw from that named sequence instead of its own identity; every model naming the same
sequence shares it, so their ids never collide (the action models use it to share one id space, as
Odoo’s table inheritance does). Schema sync creates the sequence (bigint, increment 1, no cycle, owned
by no column; an existing sequence of another shape is refused) and sets it as the id default of new
tables. The name is checked at compile time (a PostgreSQL identifier of at most 63 bytes, given once). It is set per model, never inherited
through inherit, and refused on abstract and partitioned models, on a name that is a table, a
many2many relation table or a table’s own identity sequence (<table>_id_seq), and on an existing
table whose id is an identity or draws another sequence (converting a populated table is a data
migration). It costs one shared sequence per insert batch, so keep it to low-volume tables.
Signal triggers (ERPForAll only, ADR 0035 decision 4). The access policy every process serves is
compiled from database rows (ir.access, groups, capability mappings, field groups); when one of
those rows changes, every process must rebuild it. signal_triggers = [("_name", "policy")] makes
schema sync put a statement-level trigger on the model’s table that records one policy change per
transaction, whoever writes: the ORM, raw SQL, a foreign-key action. Add relation = "<many2many field>" to put it on that field’s relation table instead, and update = false to leave updates
out (inserts and removals still count). The function the trigger runs belongs to the core: you name
the table and the signal, never SQL. base declares them on its policy tables; an addon needs one
only for a table whose rows are compiled into the policy. A table an access rule reads through a
sub-select (a share table read by a grant) needs none: the predicate reads it fresh in every
statement.
erp_sdk::addon!(name = "library_policy", depends = ["base"]);
use erp_sdk::prelude::*;
/// Rows compiled into the access policy (an illustration).#[model( name = "library.policy_row", description = "Library policy row", signal_triggers = [ ("_policy_bump", "policy"), // every write ("_policy_bump_readers", "policy", relation = "reader_ids"), // the relation table ],)]pub struct PolicyRow { #[field(char, required = true)] pub name: Option<Arc<str>>, #[field(many2many, comodel = "res.users")] pub reader_ids: Vec<RecId>,}
fn main() {}A relation trigger must name a stored many2many of the model itself (not one inherited through
_inherits); anything else fails the registry build with a Programming error naming the field.
A process that changes such rows decides correctly inside its own transaction only if the model is
also registered in erp_sdk::access::POLICY_SOURCE_WRITES (see security.md).
Follow-delete triggers (ERPForAll only, design m2-s3.md §6.1). A table whose rows are mirrored
in a key table (the action types and ir_actions) or summarized in a named cache must follow every
deletion, also the ones the database makes by itself through ondelete = "cascade", which run no
unlink override. follow_deletes = [("_keys_follow", cache = "actions", key_table = "ir_actions")]
puts a statement-level AFTER DELETE trigger on the model’s table that deletes the key table’s rows
with the deleted ids and bumps the named cache’s generation once per transaction (every process drops
its cached values at its next transaction); relation = "<many2many field>" puts one that only bumps
the generation on that field’s relation table (its rows go when either side is deleted). The ORM’s
unlink follows the cascades of the registry into such tables and invalidates the cache in the
deleting transaction too. cache and key_table may name &str constants; the cache name is
[a-z0-9_], at most 40 bytes, and the key table the table of another model of the registry, checked
when the registry is built; the key table needs a stored char field type naming each key row’s
model (only the trigger’s own model’s key rows are deleted). TRUNCATE of a followed table is
refused (it cannot be followed), and a DELETE your transaction sends as SQL on one invalidates
the cache in that transaction too.
Default values and default_get
Section titled “Default values and default_get”A field’s default is a literal (default = <literal>) or a function (default_fn = path). The
ORM asks for defaults through the model’s default_get method: create for every field the values
leave out, the web client’s forms and onchange for a new record (CRUD §4.5, SPEC-CRUD-005 to
SPEC-CRUD-008).
A default function has the signature fn(&DefaultContext) -> Value: it receives the current user
id (ctx.uid) and returns a dynamic value, which is normalized like any other default (below).
# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;use erp_sdk::{DefaultContext, ValueMap};
fn current_user(ctx: &DefaultContext) -> Value { Value::Int(ctx.uid)}
#[model(name = "library.book", description = "Book")]pub struct Book { #[field(char, required)] pub name: Option<Arc<str>>, #[field(integer, default = 1)] pub copies: i32, #[field(selection, selection = [("draft", "Draft"), ("done", "Done")], default = "draft")] pub state: Option<Arc<str>>, #[field(many2one, comodel = "res.users", default_fn = current_user)] pub user_id: Many2one<ResUsers>,}
# async fn example(mut tx: Transaction) -> Result<()> {let books = tx.env().model::<Book>()?;
// What a new record would get:let defaults: ValueMap = books.default_get(&mut tx, &["copies", "state", "user_id"]).await?;assert_eq!(defaults.get("state"), Some(&Value::from("draft")));
// A `default_<field>` context key wins over the declaration:let with_ctx = books.with_context([("default_state", Value::from("done"))]);let custom = with_ctx.default_get(&mut tx, &["state"]).await?;assert_eq!(custom.get("state"), Some(&Value::from("done")));# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Resolution order (CRUD §4.5)
Section titled “Resolution order (CRUD §4.5)”For each requested name, the first matching rule wins:
- Context key
default_<name>(SPEC-CRUD-006), set withwith_context([("default_state", Value::from("done"))]). Returned even when the name is not a field of the model. - Other names that are not fields of the model are skipped (never an error).
- Stored overrides from
ir.defaultfor non-company-dependent fields, when that model is installed. Applicable user, company and global scopes are resolved by the ORM. - The field’s declared default (
SPEC-CRUD-005):default = <literal>, ordefault_fn = path(fn(&DefaultContext) -> Value).default = nonein an extension drops an inherited default. - Company-dependent fallbacks from
ir.default, when that model is installed and the environment has a current company. - Fields delegated to an
_inheritsparent (SPEC-CRUD-007): the parent model’s owndefault_get(its overrides included), unless the field is Odoo’sNO_ACCESS(groups = ".") outside superuser mode.
Normalization and overrides
Section titled “Normalization and overrides”- Normalization: scalar values are converted to the field’s type (a value of the wrong shape
is a
Validationerror naming the field). x2many defaults become command triples: oneSETof the linked records followed by oneCREATEper new line (Falsegives[[6, 0, []]]). - Overriding
default_get: an addon can overridedefault_getlike any model method;createand the web client go through the override too:Only add names that were asked for:# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# use erp_sdk::ValueMap;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(integer)]# pub copies: i32,# }#[methods(Book)]impl Book {#[method(override)]async fn default_get(this: &RecordSet<Book>,tx: &mut Transaction,names: Vec<String>,sup: Super,) -> Result<ValueMap> {let asked_copies = names.iter().any(|n| n == "copies");let mut defaults: ValueMap = sup.call(tx, this.as_records(), (names,)).await?;if asked_copies && !defaults.contains_key("copies") {defaults.insert("copies".into(), Value::from(5));}Ok(defaults)}}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }createwrites every field of the result that its values leave out, and a returned name that is not a field is aProgrammingerror.
Defaults for internally generated records
Section titled “Defaults for internally generated records”Native addon code can derive env.without_default_overrides() after admitting the source
records and inputs of an internal workflow. Use that environment for the generated recordsets,
for example records.with_env(records.env().without_default_overrides()). The ordinary
create and default_get lifecycle still runs. The derived environment removes context
default_* keys and suppresses the base default_get lookup of stored ir.default overrides
at global, company and user scope, including company-dependent creation fallbacks. Declared
field defaults still apply, and explicit creation values retain their normal precedence.
The policy survives with_user, sudo, with_company, context updates and context replacement;
new default_* keys supplied to those context operations are removed. It participates in
Env equality and hashing. Calling it again is idempotent, and the original environment keeps
its ordinary default behavior. Use the original environment for source-record admission and
ordinary interactive creation. A JSON/RPC context key cannot enable or disable this native
policy.
This is a default-resolution choice, not an access grant: it does not change the principal,
permissions or company restrictions, and it does not alter property reads on existing records.
It does not bypass addon default_get overrides or sanitize explicitly supplied creation
values. Addon overrides and internal workflow code remain responsible for their own input
validation and authorization. See ADR 0262.
Database default of a fail-closed flag
Section titled “Database default of a fail-closed flag”ORM columns have no database default: the ORM applies defaults before the INSERT (ADR 0017 §5).
A row written with plain SQL (bootstrap statements, migrations, an operator’s script, a test
fixture) therefore gets NULL in a column it leaves out, and a required column refuses it. For a
boolean that must fail closed whoever writes the row, such as the share flag the company
restriction of res.users escapes through, declare db_default (ERPForAll only, ADR 0171):
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;#[model(name = "library.member", description = "Member")]pub struct Member { /// External member until computed otherwise; a raw INSERT without the column stores `true`. #[field(boolean, required, default = true, db_default)] pub external: bool,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Schema sync keeps the static default as the column’s
DEFAULT: on a new table, on a new column (the fast default is not dropped) and on an existing column that lacks it or has another value (ALTER COLUMN … SET DEFAULT, catalog-only). An extension that declaresdb_default = falsemakes the next sync drop it again. - Only a stored, required
booleanwithdefault = trueordefault = false, not company-dependent and not generated; anything else is aProgrammingerror at registry build that names the field and the missing condition. Models declared inmodels/*.tomland WebAssembly addons cannot set it. - The ORM still writes the column in every
create(the static default when the caller leaves it out), so ORM and SQL writers store the same value. Use it for fail-closed flags only, not to move ordinary defaults into the database.
Searching
Section titled “Searching”Domains are Odoo’s: build them in Rust or parse list syntax sent by a client.
# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(integer)]# pub copies: i32,# }# async fn example(mut tx: Transaction, body: erp_sdk::serde_json::Value) -> Result<()> {
let books = tx.env().model::<Book>()?;let dune = Domain::field("name")?.ilike("dune") & Domain::field("copies")?.gt(0);let found = books.search(&mut tx, &dune).await?; // the model's `order`let page = books .search_with(&mut tx, &dune, &SearchOptions::new().order("name desc").limit(20).offset(40)) .await?;let n = books.search_count(&mut tx, &dune, None).await?;let fetched = books // ids + columns, one query .search_with(&mut tx, &dune, &SearchOptions::new().fetch_fields(["name", "copies"])) .await?; // Odoo's search_fetchlet pairs = books.name_search(&mut tx, "du").await?; // ilike, 100 resultslet pairs = books .name_search_with(&mut tx, "du", &NameSearch::new().operator(Operator::EqILike).limit(None)) .await?;let rows = books.search_read(&mut tx, &dune, &["name"], &SearchOptions::new()).await?;let from_client = Domain::from_json(&body["domain"])?; // 422 on malformed inputbooks.fetch(&mut tx, Some(&["name"])).await?; // prefetch missing columns# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Archived records (
active/x_activefalse) are left out unless the domain mentions the active field, the context setsactive_testto false, orSearchOptions::active_test(false)is given. - The access policy’s record rules are added to the domain and evaluated in SQL; nothing is filtered in memory.
- Relative dates (
'today','now -1d','=1d'…) are resolved in the user’s timezone (contexttz).=week_startuses Sunday until languages arrive. - Every operator on stored fields, paths (
partner_id.country_id.code),any/not any,child_of/parent_of,display_namethroughrec_names_search, andorderon columns, selections (declaration order) and many2one fields (by the comodel’sorder). Fieldsearch=methods are refused with a “not supported until” error. records.fetch(&mut tx, Some(&["name"]))loads what is missing for a recordset in one query per batch;readleaves out records that were deleted. Outside superuser mode both evaluate the record rules in SQL even when every value is already cached.- Order of ties. Unless the order already contains
id,idis added as the last sort key, so records with equal keys come back in the same order on every page. Odoo leaves ties to PostgreSQL (undefined and possibly different between pages); this only fixes what Odoo leaves open. - Negations are not index-friendly.
!=,not in,not likeandnot ilikeon a nullable column compile to(… OR col IS NULL)so that records without a value match, as in Odoo; such conditions usually scan. Prefer a positive condition when a selective index matters. likepatterns.like/ilikewrap the value in%…%;%and_inside the value are wildcards and\escapes them (name like '50\%'finds a literal50%).=like/=ilikeuse the pattern exactly as given. Escape user input before using it as a literal.- Accents. With
OrmConfig::unaccenton,ilikeignores accents. Schema sync then creates an immutableerp_unaccent()over theunaccentextension (it must be installed) and trigram indexes use the same expression, so they serve those searches. - Plans. A search whose domain has values runs as an unnamed statement that PostgreSQL plans for those values (as it plans Odoo’s literal SQL); reads by id and searches without values are prepared once per connection and reused (ADR 0017 §3). Nothing to do in addon code.
- “queries overflow the depth limit”. An addon crate that awaits a search deep inside its own
async code (several layers of
async fnaroundsearch,search_withorsearch_read) can stop compiling with rustc’serror: queries overflow the depth limit!while rustc lays out the nested future. Until a boxed boundary is put at the search entry (planned), raise the limit at the top of the addon crate’slib.rs(#![recursion_limit = "256"], as the base addon’sres_usersdoctest does), or box the awaited call in your own code (Box::pin(books.search(&mut tx, &dune)).await?). Neither changes what runs.
Deep pages: keyset pagination
Section titled “Deep pages: keyset pagination”OFFSET 40000 makes PostgreSQL read and throw away 40,000 rows; search_after continues from
the last record of the previous page instead, so page 1,000 costs what page 1 costs (measured on
1,000,000 rows: 0.12 ms instead of 307 ms, docs/bench/m1-s7-orm-perf.md §4), and records
created or deleted before the cursor do not shift the pages.
# erp_sdk::addon!(name = "sale");# use erp_sdk::prelude::*;# #[model(name = "sale.order", description = "Order")]# pub struct Order {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(datetime, index)]# pub date_order: Option<DateTime>,# }# async fn example(# mut tx: Transaction,# domain: Domain,# order_from_client: String,# values_from_client: Vec<Value>,# ) -> Result<()> {# let orders = tx.env().model::<Order>()?;let opts = SearchOptions::new().order("date_order desc, name").limit(80);let mut page = orders.as_records().search_after(&mut tx, &domain, &opts, None).await?;while let Some(cursor) = page.next.take() { // … show page.records …; a client sends back cursor.order() and cursor.values() page = orders.as_records().search_after(&mut tx, &domain, &opts, Some(&cursor)).await?;}let resumed = Cursor::new(order_from_client, values_from_client); // checked when used# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }nextisNoneon the last page (a page shorter than the limit). The cursor holds the order and the last record’s key (one value per order term,idlast); a cursor of another order, or whose values do not fit, is aValidationerror.offsetmust be 0 andlimitpositive.- Order terms: the model’s stored columns (text, numbers, dates, booleans, selections) and
many2one fields by id (
partner_id.id, or a comodel whose order isid). Ordering through a comodel’s order (partner_idwhen partners are ordered by name) is refused: order by a field of the model instead. - Index use: give the leading order term an index. When every term has the same direction the
next page is one range scan (
(a, id) > ($1, $2)); a nullable leading term whose NULLs come last adds a second,IS NULLquery on the one page that reaches them. Orders mixing directions are bounded by their leading term and filtered within it.
Reading large results in windows
Section titled “Reading large results in windows”search_with and read_rows keep every record they read in the transaction’s cache until it
ends: right for a page or a form, wrong for an export, a report over a year of lines or a batch
job over a whole table. stream reads the records of a domain window by window instead. Each
window is a Rows batch equal to read_rows of its records; before the next window is read,
the window’s records leave the cache and its buffers are reused, so a stream holds one window
whatever the result size (measured: the same peak for 20,000 and 40,000 lines,
docs/design/perf-stream-window.md §5).
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(integer)]# pub copies: i32,# }# async fn example(mut tx: Transaction, domain: Domain) -> Result<()> {let books = tx.env().model::<Book>()?;let opts = erp_sdk::StreamOptions::new().order("id").load(erp_sdk::Load::Raw);let mut stream = books.as_records().stream(&mut tx, &domain, &["name", "copies"], &opts).await?;let mut copies = 0i64;while let Some(window) = stream.next(&mut tx).await? { for i in window.indices() { copies += window.i64(i, "copies")?.unwrap_or(0); let _name: Option<&str> = window.str(i, "name")?; }}// explicit records, in their order, by id chunks (no cursor; no order or active test option)let picked = books.as_records().browse([3, 1, 2])?;let chunk_opts = erp_sdk::StreamOptions::new().load(erp_sdk::Load::Raw);let mut chunks = picked.stream_records(&["name"], &chunk_opts)?;while let Some(window) = chunks.next(&mut tx).await? { let _ = window.len();}// raw SQL without collecting the answer: each row is lent, nothing is keptlet mut total = 0i64;let n = tx .query_each("SELECT copies FROM library_book WHERE copies > $1", &[&0i32], |row| { total += i64::from(row.try_get::<i32>(0)?); Ok(()) }) .await?;# let _ = (copies, n, total);# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- What a domain stream sends. The first window rides one flight:
DECLARE erp_cN NO SCROLL CURSOR WITHOUT HOLD FOR <the search>andFETCH, withSET LOCAL cursor_tuple_fraction = 1in front for the transaction’s first stream (the setting lasts until the transaction ends, so it is sent once per transaction, and again only after a rollback to a savepoint opened before it undid it; it steers the planner of every later cursor of the transaction too,DECLAREs only, plain queries are not affected). Every further window is oneFETCH, one round trip. The search issearch_with’s: record rules, the active test and the order (the model’s unlessStreamOptions::orderis given). Pending writes are flushed before the cursor is declared.stream_recordsreads its recordset as it is and refusesorderandactive_test(false). - Snapshot. The cursor reads the transaction’s snapshot: rows other transactions commit while
you read are not seen, rows this transaction wrote before
streamare. - Writes inside the loop. A cursor keeps the rows of its
DECLARE, also for what the transaction itself writes later. So once the transaction changed the streamed model after theDECLARE(an ORM write or unlink once flushed, a stored compute written back, a rawUPDATE,DELETE,INSERTorMERGEof its table or of a many2many link table it is a side of, aDELETEof a table whose rows its many2one points at withondeletecascadeorset null, followed through further cascades, a data statement on a table the registry does not know, any other raw statement the ORM cannot attribute, an invalidation, a rollback to a savepoint), each later window takes only the ids from the cursor and reads its values fresh by id, exactly asstream_recordsdoes: one more statement per window, values current. What happens to the rows the writes touch, on both sources: a record changed so that it no longer matches the domain still arrives, with its new values (the record list is the one of theDECLARE;stream_recordshas no domain); a record deleted is left out (likeread_rowsof a deleted record); a record created is not in a domain stream (it was not in theDECLARE’s result) and is instream_recordsonly if it is in the recordset. For a restricted user, once the policy or a row its record rule reads changed (the streamed model or a model the rule reads), each window’s ids are checked against the rule again (one statement) before it is lent: a record the rule no longer lets the user read is refused with theAccesserrorread_rowsgives, the same on both sources. A window whose every record was deleted is skipped: the next one is read. - What the ORM does not see. The ORM knows what a statement may change from the statement
itself. Two kinds of writes do not show in it: a function called from a
SELECTthat writes (SELECT my_function(...)), and a database trigger that writes other tables. After such a statement the cursor would lend the rows of itsDECLAREfor the tables written behind the ORM’s back. Code that runs one inside a stream loop, and an addon that installs such a trigger, must callRecords::modified_externalfor affected stored scalar columns after settling prior ORM work, so source caches and dependents update. When no dependency notification is needed,Transaction::invalidate_model(orinvalidate_records) remains available. These operations move the model’s tick and the next window reads fresh values. - Raw SQL the ORM cannot read with certainty. The ORM reads raw SQL with PostgreSQL’s own
lexical rules. What it is not certain about it treats as a statement that may change anything
(every stream reads fresh afterwards, an onchange scope opens its savepoint), and a read-intent
transaction refuses it with an error saying so: a
U&'…'string orU&"…"name, a backslash outside anE'…'string (writeE'a\\b', as the ORM’s own literals do), a stray$, and unterminated text. The ORM reads statements as a connection withstandard_conforming_strings = onandclient_encoding = UTF8does: the pool refuses a connection that opens with other values, with an error naming the setting (forstandard_conforming_stringsa role or database default;client_encodingalways opens asUTF8, since the driver asks for it at connect, which outranks role and database defaults, and the server applies it after the connection’soptions). When the server reports a new value of either setting on the connection (whatever caused it:SET,set_config,RESET, a function, dynamic SQL in aDOblock; also before the transaction got the connection, by code that used a pooled connection directly), every later raw statement of the transaction object is treated as one that may change anything, a read-intent transaction refuses raw SQL from then on, and the connection is closed instead of going back to the pool. Code that takes a connection from the pool directly (outside a transaction object) may get such a connection before a transaction closes it: write text in its SQL asE'…'(aserp_sql::literaldoes) or bind it as a parameter, never as a plain'…'string with a backslash. - Functions a read-intent transaction refuses by name.
pg_notify,set_config, the advisory lock and unlock functions,pg_terminate_backend,pg_cancel_backendand thedblinkfunctions:READ ONLYallows them, but their effect outlives the call or reaches past the transaction. A function of your own that calls one of them inside is not seen; declareeffect = writefor an entry point that calls it. - Savepoints. A rollback to a savepoint ends the cursors declared under it (using the stream
then is a
Programmingerror). AFETCHmade inside a savepoint that is rolled back is not undone by the server: a cursor does not rewind, so the nextnextrefuses (fetch outside the savepoint, or start a new stream). AFETCHinside a savepoint that is released is kept. - Window size. By default 2,000 rows first (1,000 when a field is text, html or json), then
about 1 MiB of rows per window, between 1,000 rows and
OrmConfig::prefetch_chunk.StreamOptions::fixed_window(n)takes 1,000 ≤ n ≤ 10,000 (never 0 = unlimited, never below Odoo’s export batch of 1,000) and is refused when aboveprefetch_chunk. The bound is in rows, not bytes: the 1 MiB aim follows the bytes of the window before, so a window that follows narrow rows can hold up toprefetch_chunk(at most 10,000) wide ones; the worst case is that row count times the widest row. - The window is lent. It is valid until the next
nextcall. Keep values you need by copying them out; a clone of the batch stays valid too (the stream then makes new buffers for the next window, counted bybuffers_renewed). Writing to records inside the loop is fine: the writes are flushed before the next window (see “Writes inside the loop”). Creating a new (in-memory) record inside the loop is refused, because the window is dropped from the cache and a new record cannot be. A call tonextdropped before it finished (a cancelled task, a timeout) while itsFETCHwas in flight leaves the cursor’s position unknown: the stream stops and the next call says so. - Several streams. Streams of one transaction may be read in turns (two exports, a stream
inside another’s loop); each equals
read_rowsof its records. A transaction holds at most 32 open cursors (Transaction::set_cursor_limitchanges it for that transaction object); one more stream is refused with aProgrammingerror naming the setting. The cursor nameserp_c1,erp_c2, … are reserved: raw SQL must not declare cursors with theerp_cprefix. - Closing. A stream that is finished, closed (
close) or dropped asks the transaction to close its cursor; theCLOSEgoes out with the transaction’s next statement (no round trip of its own), and nothing is sent when the transaction ends first. A stream belongs to its transaction: using it with another one, after a commit, rollback or lost connection, or after a rollback to a savepoint it was declared under is aProgrammingerror. Streams are refused inside an onchange. - The transaction stays open between windows. Between two
FETCHes the transaction is idle but open, and holds its snapshot: PostgreSQL’sidle_in_transaction_session_timeout(if the server sets one) ends a stream whose consumer is slower than it; the snapshot holds backVACUUM(dead rows of every table stay until the transaction ends: bloat on a busy database); on a hot standby, a long stream can be cancelled by a replication conflict (max_standby_streaming_delay). Keep the work per window short and the transaction no longer than the stream; long exports belong in the export service (planned). query_eachruns raw SQL likeTransaction::query(prepared, counted, no access rules, the read-only guard applies) and lends each row as anSqlRow(len,column_name,column_type_name,try_getinto anSqlValuetype: integers, floats,bool, text, bytes, JSON,Decimal,Date,DateTime, each also as anOption). The memory of a large answer is one received batch, whatever the row count. An error returned by the closure stops the rows; the transaction goes on.
Working with recordsets in memory
Section titled “Working with recordsets in memory”Recordsets are immutable collections of record ids sharing an environment and a prefetch set.
Typed (RecordSet<M>) and dynamic (Records) recordsets offer the same operations as Odoo’s
recordsets; a RecordSet<M> also gives access to every Records method.
# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;# #[model(name = "library.shelf", description = "Shelf")]# pub struct Shelf {# #[field(char)]# pub name: Option<Arc<str>>,# }# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(integer)]# pub copies: i32,# #[field(many2one, comodel = "library.shelf")]# pub shelf_id: Many2one<Shelf>,# }# async fn example(mut tx: Transaction, user_id: i64) -> Result<()> {
// 1. Browsing (no query):let book_model = tx.env().model::<Book>()?;let books = book_model.browse([1, 2, 3])?;let one = books.browse([1])?;let single = one.ensure_one()?; // `Programming` error unless exactly one recordassert_eq!(books.len(), 3);assert_eq!(books.ids(), vec![1, 2, 3]);
// 2. Python-style indexing and slicing:let first = books.at(0)?; // id 1let last = books.at(-1)?; // id 3 (negative index from the end)let slice = books.slice(Some(0), Some(2), 1)?; // ids 1 and 2let reversed = books.slice(None, None, -1)?; // ids 3, 2, 1
// 3. Set operations (order and prefetch preserved):let more_books = book_model.browse([3, 4])?;let combined = books.concat(&more_books)?; // [1, 2, 3, 3, 4] (duplicates kept)let united = books.union(&more_books)?; // [1, 2, 3, 4] (de-duplicated)let common = books.intersection(&more_books)?; // [3]let diff = books.difference(&more_books)?; // [1, 2]assert!(books.contains(&first)?);assert!(diff.is_subset(&books)?);
// 4. Other environments (same ids):let sudo_books = books.sudo(true); // superuser mode: no access checkslet user_books = books.with_user(user_id); // another user's rights (who may switch: below)let ctx_books = books.with_context([("tz", Value::from("UTC")), ("active_test", Value::Bool(false))]);
// 5. Filtering, mapping, sorting and grouping on field values:let in_stock = books.filtered(&mut tx, Book::COPIES, |c| *c > 0).await?; // one column readlet named = books.as_records().filtered_path(&mut tx, "name").await?; // truthy namelet shelved = books.as_records().filtered_path(&mut tx, "shelf_id.name").await?; // through a many2onelet shelves = books.as_records().mapped_path(&mut tx, "shelf_id").await?; // Mapped::Records(union)let by_shelf = books.as_records().grouped_records(&mut tx, "shelf_id").await?; // recordset keyslet few = books.filtered_domain(&mut tx, &Domain::field("copies")?.lt(3)).await?;let titles = books.mapped(&mut tx, Book::NAME).await?; // Vec<Option<Arc<str>>>let ordered = books.sorted(&mut tx, Some("copies desc, name"), false).await?; // None: model orderlet by_copies = books.grouped(&mut tx, Book::COPIES).await?; // Vec<(i32, RecordSet<Book>)>let still_there = books.exists(&mut tx).await?;books.lock_for_update(&mut tx, false).await?; // Lock error (409) if takenlet mine = books.try_lock_for_update(&mut tx, false, Some(10)).await?; // skips locked rows
// 6. Closures that need no database access:let nonempty = books.filtered_by(|b| !b.is_empty());let by_id = books.sorted_by_key(|b| b.ids(), false);# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Set operations:
concat(&other)(+): both recordsets in order, duplicates kept (SPEC-RSET-016).union(&other)(|): union in first-occurrence order, de-duplicated (SPEC-RSET-017).intersection(&other)(&): ids of self that are in other, de-duplicated, in self’s order (SPEC-RSET-018).difference(&other)(-): ids of self that are not in other, self’s duplicates kept (SPEC-RSET-018).concat_all(sets)/union_all(sets): the same over an iterable of recordsets (SPEC-RSET-020).is_subset(&other)(<=) /is_strict_subset(&other)(<) (SPEC-RSET-013).- Operands of different models are an error (
SPEC-RSET-019).
- Environments (each returns the same ids on a new environment; the transaction’s cache is
shared):
records.sudo(flag): superuser mode on or off, same user id. Turning it on removes thedefault_*keys from the context (SPEC-ENV-004).records.with_user(uid): another user; superuser mode only whenuidis the superuser (SPEC-ENV-005). Who may switch is decided on the principal of the environment you call it on (ADR 0164 A4,SPEC-PRIN-029): theSystemprincipal switches to anyone, any principal to its own user, and another user only when it holds the capabilityprincipal.impersonate(base maps it to Settings administrators); otherwise the first use of the new environment (a read, a write, a model check, a scoped block, a job enqueue, a capability question) fails withAccess“user A may not act as user B: with_user needs the capability ‘principal.impersonate’”. A switch to the superuser id from any principal butSystemis always refused (“only the system principal may act as the superuser …”), also fromsudo(true); the refused environment stays the caller’s own user and never reportssu(). To ask whether another user is in a group, calltx.user_has_group(&env, user, "module.group")instead of switching; to open a transaction or an environment for a caller, useorm.begin_caller(user)/orm.env_caller(user, context)(orBeginOptions::caller,PrincipalHint::caller), which refuse the superuser id.records.with_context(pairs): the context updated with(key, Value)pairs (tz,lang,active_test,default_*…) (SPEC-ENV-006).records.with_env(env): the same ids on a given environment.records.with_prefetch(ids): another prefetch set (None: the recordset’s own ids) (SPEC-ENV-028).
- Results keep the input’s order and duplicates and share its prefetch set, so a field read through one result (or one group) is loaded for all of them. Each operation reads a field once for the whole recordset: at most one query per field group when the values are not cached, none when they are. Write loops over recordsets with these operations instead of reading records one by one.
filtered_domainevaluates the domain on the values in memory with the same rules assearch(NULLs,0/''treated as “not set”, negations):search(D)andsearch([]).filtered_domain(D)agree. It also works on non-stored computed fields anddisplay_name, and follows relational conditions (any, paths, x2manyin,child_of): the targets are filtered in memory on the comodel, once for all records;any!andbypass_search_accessfields look at the targets as superuser. Text follows theCcollation of ERPForAll databases: code-point order, andilikefolds ASCII letters only (Édoes not matchéunlessOrmConfig::unaccentis on).sortedtakes the same order syntax assearchand places NULLs the same way (last ascending, first descending, unlessnulls first/nulls last). It is stable, also withreverse. Like Odoo’s in-memory sort it differs fromsearchin three ways: selections sort by key text, not declaration order; NULL integers/floats/amounts count as 0; a many2one is ordered by its comodel’s order read with your rights. Text compares by code point (theCcollation of Odoo databases).- Closures that need no database access have
_byvariants:filtered_by,sorted_by_key,grouped_by. To filter or sort on field values, use the field forms above. exists()always asks the database (one query per batch of ids); it ignores record rules andactiveand never touches the cache. New records always exist.- Locks use
SKIP LOCKED: they never wait.lock_for_updatefails with aLockerror when any row is held by another transaction or deleted (rows locked before the error stay locked until the transaction ends);try_lock_for_updatereturns what it could lock, in recordset order, at mostlimitrecords (new records count as locked and come first).allow_referencing = truetakes the weakerFOR NO KEY UPDATElock, which still lets others insert rows pointing at these records.
Extending a model you do not own
Section titled “Extending a model you do not own”In an addon that depends on library:
# mod library {# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book", addon = "library")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(integer, default = 1)]# pub copies: i32,# }# }# erp_sdk::addon!(name = "library_isbn", depends = ["library"]);# use erp_sdk::prelude::*;# use library::Book;#[extend(Book)]pub struct BookIsbn { #[field(char, size = 13)] pub isbn: Option<Arc<str>>, // redefining a field merges attributes: this one becomes required with a new default #[field(integer, required, default = 2)] pub copies: i32,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON, &library::ADDON]).check()?;# Ok(())# }The new field handles are constants of the extension type with the extended model as their model:
BookIsbn::ISBN: Field<Book, Option<Arc<str>>>.
The extended model may live in another addon crate: depend on that crate and list its addon in
depends. See Extending other addons, data-only models and custom fields,
which also covers models declared in models/*.toml and custom x_ fields.
Models whose columns only their owner adds
Section titled “Models whose columns only their owner adds”A model can protect its table: with owner_only_stored_fields on the declaration that creates it,
only that addon (the owner) and the co-owner addons it names may add a column to the model or change
the storage, type, relation or generated expression of one (ADR 0166 decision 7). Integrity code that
compares or guards the table’s columns can then rely on them. The policy is native only: model files,
WebAssembly descriptions and overlays cannot set it, and an extension cannot set, replace or widen it.
A co-owner must be a known addon (installed, or linked into the build) and, when installed, depend on
the owner; one that is linked but not installed has no effect. #[extend] refuses the attribute.
# mod ledger {# erp_sdk::addon!(name = "ledger");# use erp_sdk::prelude::*;#[model( name = "ledger.entry", description = "Entry", addon = "ledger", owner_only_stored_fields = ["ledger_audit"])]pub struct Entry { #[field(char)] pub name: Option<Arc<str>>,}# }# erp_sdk::addon!(name = "ledger_audit", depends = ["ledger"]);# use erp_sdk::prelude::*;# use ledger::Entry;// in `ledger_audit`, the named co-owner: a new column is admitted#[extend(Entry)]pub struct EntryAudit { #[field(char)] pub audit_ref: Option<Arc<str>>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON, &ledger::ADDON]).check()?;# Ok(())# }Any other addon still extends the model with fields that have no column of their own: nonstored
computed or related fields, VIRTUAL generated fields (ADR 0062), one2many fields, and many2many fields
on a relation table of its own; it keeps its data in a companion model of its own. A stored column
from it (ordinary, stored computed or related, STORED generated, translated, row_version) is refused
with Programming, naming the addon, the model and field, the owner and the declaration (with its
source file and line when it has them), in this form:
addon 'audit_x' cannot add or change stored field 'ledger.entry.note'; owner is 'ledger'; declared by model definition 'ledger.entry' of addon 'audit_x'The same holds when the column arrives through a mixin that addon
adds or extends, through its model files, or as a custom x_ field (dropped and reported under
DropBroken). store = true alone is not the test: a VIRTUAL generated field has it and stores
nothing. A relation table of the model belongs to whoever created it; another field naming that table
needs the same owner group. Another model cannot take the protected model’s table or one of its relation
tables with table = "…", and a many2many cannot name it as its relation, unless the declaring addon is
in the owner group.
Extending a table that already holds many rows
Section titled “Extending a table that already holds many rows”Adding an indexed field, a many2one, a stored computed field or making a field required changes the table of a model that may already hold millions of rows. Schema sync keeps the install transaction short on such tables (ADR 0009 §2): when the table has more rows than the host’s threshold (100,000 by default), the work that would scan it runs after the install commits, as post-commit steps:
| Your change | In the install transaction | After the commit |
|---|---|---|
#[field(..., index)], a many2one (indexed by default), indexes/unique_indexes | nothing | CREATE INDEX CONCURRENTLY |
| a many2one (foreign key) | the key, added NOT VALID (new writes are checked) | VALIDATE CONSTRAINT |
a field becomes required without a default | the not-null constraint, added NOT VALID | VALIDATE CONSTRAINT |
a field becomes required with a default | nothing | NULLs filled with the default in batches, then the constraint added and validated |
a new stored computed field (compute = …, store) | the column | the computation for every existing record, in batches |
On smaller tables everything runs in the install transaction, as in Odoo, and a new stored computed
field is computed for every existing record before the install commits. Until a step has run, its
index is missing (a unique_indexes entry does not reject duplicates yet) and records not reached
by a backfill read an empty value for the new field. Write a computation that does not depend on
the order in which records are computed, since the batches follow record ids. A step does not keep
your users waiting: when it would wait for a lock while holding readers or writers up, it gives up
after a short wait (10 seconds by default), and the next schema sync plans the unfinished work again.
Methods and overrides
Section titled “Methods and overrides”The addon that owns the model defines a method:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# }#[methods(Book)]impl Book { #[method] async fn label(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<String> { let name = this.ensure_one()?.get(tx, Book::NAME).await?; Ok(name.as_deref().unwrap_or_default().to_owned()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Another addon overrides it, and callers use the generated BookMethods trait:
# mod library {# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book", addon = "library")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# }# #[methods(Book, addon = "library")]# impl Book {# #[method]# async fn label(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<String> {# let name = this.ensure_one()?.get(tx, Book::NAME).await?;# Ok(name.as_deref().unwrap_or_default().to_owned())# }# }# }# erp_sdk::addon!(name = "library_isbn", depends = ["library"]);# use erp_sdk::prelude::*;# use library::{Book, BookMethods};# #[extend(Book)]# pub struct BookIsbn {}#[methods(Book)]impl BookIsbn { #[method(override)] async fn label(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<String> { let base: String = sup.call(tx, this.as_records(), ()).await?; Ok(format!("{base} (ISBN)")) }}
# async fn example(mut tx: Transaction, book: RecordSet<Book>) -> Result<()> {let label = book.label(&mut tx).await?; // runs BookIsbn's override, which calls Book's# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON, &library::ADDON]).check()?;# Ok(())# }-
#[method]introduces a method;#[method(override)]overrides it and receivessup: Superas its last parameter (super()in Odoo). Arguments aftertxmust be owned types. -
The newest addon in load order runs first;
sup.callreaches the previous one. -
#[methods(Book)] impl Bookgenerates a traitBookMethodsfor typed calls (books.label(&mut tx).await?), available on recordsets ofBookand of models inheriting it. -
A method defined by an addon you do not depend on can still be called by name:
this.call::<(), i64>(tx, "bar", ()).await?. -
createandwriteare overridable the same way:createtakesVec<RawVals>(one entry per record to create) and returnsRecords;writetakesRawVals. Overrides receive whole recordsets and value lists: never assume a single record. -
copy,copy_data,name_create,action_archiveandaction_unarchiveare overridable model methods through the same dispatch chain:copytakesdefault: Option<ValueMap>and returnsRecords(the newly created duplicate records);copy_datatakesdefault: Option<ValueMap>and returnsVec<Option<ValueMap>>(field mappings ready forcreate);name_createtakesname: Stringand returns(i64, Arc<str>)(the id and display name of the created record; requires_rec_name);action_archiveandaction_unarchivetake no arguments and return()(writingactive = Falseoractive = Trueon active or inactive records; requires anactivefield).
Copy traversal has fixed limits of 16 nested one2many levels and 10,000 distinct records; exceeding them returns a validation error. Group-restricted copyable fields require read access and otherwise refuse the copy. Stored translations are not yet copied as translation maps. The override below gives copied books a naming convention while respecting an explicit name. Archive methods can be called directly; an override is unnecessary unless the addon adds behavior.
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# use erp_sdk::ValueMap;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(boolean, default = true)]# pub active: bool,# }#[methods(Book)]impl Book {#[method(override)]async fn copy(this: &RecordSet<Book>,tx: &mut Transaction,default: Option<ValueMap>,sup: Super,) -> Result<Records> {let mut d = default.unwrap_or_default();if !d.contains_key("name") {let orig = this.get(tx, Book::NAME).await?;if let Some(name) = orig {d.insert("name".into(), Value::str(format!("{name} (custom copy)")));}}sup.call(tx, this.as_records(), (Some(d),)).await}}# async fn example(mut tx: Transaction, book: RecordSet<Book>) -> Result<()> {# let copied = book.copy(&mut tx, None).await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# } -
Of the recordset operations, only
exists(no arguments, returnsRecords) andfiltered_domain(takes aDomain, returnsRecords) can be overridden, as Odoo addons do (for example to answerexistsfrom a cached id set, or to rewrite a condition before callingsup).filtered,mapped,sorted,grouped, the set operators andensure_oneare final.
These are reported at startup with the file and line of the implementations involved:
- two implementations of one method with different signatures;
- an override with no definition below it;
- two plain
#[method]definitions in one chain (the later one must be#[method(override)]); - a
#[methods(Model)]block in an addon that has no#[model]/#[extend]of that model; - one addon implementing a method twice.
Declaration and override order
Section titled “Declaration and override order”The order in which declarations of a model are applied (field attribute merges, method chains) is:
- addon load order: dependency depth, then addon name (identical after install, upgrade and restart, ADR 0009 §3);
- inside one addon: source file path, then line.
Link-time registration has no order of its own, so an addon that declares one model in several files gets the file-path order, not Odoo’s import order; keep each model’s declarations of one addon in one file when their order matters.
Notify the ORM after external SQL
Section titled “Notify the ORM after external SQL”Trusted native code that changes a model’s stored scalar columns with SQL must notify the
ORM about the affected records and fields. This includes columns maintained by a database
trigger. Settle pending ORM work before the SQL, then call modified_external:
# use erp_sdk::prelude::*;# erp_sdk::addon!(name = "library");# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(integer)]# pub copies: i32,# }# async fn example(mut tx: Transaction) -> Result<()> {let books = tx.env().model::<Book>()?;let book = books.create(&mut tx, vec![books.vals().set(Book::COPIES, 2)]).await?;tx.flush().await?; // settle ORM work before SQL, never after it to resolve a conflictlet id = book.ids()[0];tx.execute("UPDATE library_book SET copies = copies + 1 WHERE id = $1", &[&id]).await?;book.modified_external(&mut tx, &["copies"]).await?;let copies = book.get(&mut tx, Book::COPIES).await?;assert_eq!(copies, 3);# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }The notification drops the named source values from cache and runs the same dependency walk as an ORM write. Stored computed dependents become pending; non-stored dependents lose their cached values in every context, including dependents reached through unchanged relations. Normal reads and commit settle the computed values. The call itself neither flushes nor writes; relation traversal may issue SELECTs. It also advances the affected model’s stream generation, so an already-open cursor cannot put an earlier value back in cache.
This method performs no access authorization and grants no read or write right. The SQL writer must authorize its operation, identify all affected rows and columns, and record any required source audit or business events. Notification creates no source audit or event record. Normal later dependent recomputation retains its existing provenance requirements. An error after partial notification leaves the transaction rollback-only; rollback before continuing.
Only physical stored scalar columns owned by the recordset’s model are admitted. Unknown fields, delegated projections, non-stored fields and x2many fields fail by name. Relationship source columns are not supported yet: changing a parent link requires information about its previous owner. Notification still follows dependencies through links that did not change. Draft records and notified fields with dirty values or pending computations are refused; settle them before running external SQL. Resolve any principal switch before that SQL too: notification validates provenance without a flushing resolution step. Read-only generated-input callbacks also refuse notification. Catching that refusal does not let the callback finish successfully.
The method is final and native-only; it has no RPC, script or WASM route. Duplicate names/ids
are coalesced, and empty admitted input does nothing. Field names are validated even when the
recordset is empty. invalidate_records remains a flushing cache-invalidation operation;
it does not replace dependency notification after an external change.
Computed fields
Section titled “Computed fields”A computed field names its compute method; the method lives in a #[methods] block and declares
what it depends on:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.shelf", description = "Shelf")]# pub struct Shelf {# #[field(char)]# pub name: Option<Arc<str>>,# }#[model(name = "library.book", description = "Book")]pub struct Book { #[field(char)] pub title: Option<Arc<str>>, #[field(integer)] pub pages: i32, #[field(many2one, comodel = "library.shelf")] pub shelf_id: Many2one<Shelf>, /// stored: persisted, recomputed when `pages` changes #[field(float, compute = "_compute_weight", store)] pub weight: f64, /// not stored: computed when read, dropped from the cache when `title` changes #[field(char, compute = "_compute_label", inverse = "_inverse_label")] pub label: Option<Arc<str>>, /// related field: follows a relation path (as superuser by default) #[field(char, related = "shelf_id.name")] pub shelf_name: Option<Arc<str>>, /// writable related field: writing it writes the shelf's name #[field(char, related = "shelf_id.name", readonly = false)] pub editable_shelf_name: Option<Arc<str>>,}
#[methods(Book)]impl Book { #[compute(depends = ["pages"])] fn _compute_weight(batch: &mut Batch<'_, Book>) -> Result<()> { for i in batch.indices() { let pages = batch.get(i, Book::PAGES)?; batch.set(i, Book::WEIGHT, f64::from(pages) * 2.5)?; } Ok(()) }
#[compute(depends = ["title"])] fn _compute_label(batch: &mut Batch<'_, Book>) -> Result<()> { for i in batch.indices() { let title = batch.get(i, Book::TITLE)?; batch.set(i, Book::LABEL, format!("«{}»", title.as_deref().unwrap_or("")))?; } Ok(()) }
#[method] async fn _inverse_label(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<()> { for book in this.iter() { let label = book.get(tx, Book::LABEL).await?; let title: Option<Arc<str>> = label .as_deref() .map(|s| Arc::from(s.trim_matches('«').trim_matches('»'))); book.set(tx, Book::TITLE, title).await?; } Ok(()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Sync computes (plain
fn) run once per batch of records over values the ORM loaded first. They may read only theirdepends, the fields listed inreads = [...](read without triggering a recompute) and the fields computed by the same method; anything else is an error.batch.set_all(field, value)assigns every record. - Async computes (
async fn) are for computes that search, aggregate or create records. They receive the whole batch as a recordset and assign throughout:They also run once per batch, never per record.# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub title: Option<Arc<str>>,# #[field(char, compute = "_compute_summary")]# pub summary: Option<Arc<str>>,# }# #[methods(Book)]# impl Book {#[compute(depends = ["title"])]async fn _compute_summary(this: &RecordSet<Book>,tx: &mut Transaction,out: &mut Assign<'_, Book>,) -> Result<()> {// one query for the whole batch, not one per recordlet total = this.search_count(tx, &Domain::TRUE, None).await?;let titles = this.mapped(tx, Book::TITLE).await?;for (i, title) in titles.iter().enumerate() {out.set(i, Book::SUMMARY, format!("{} (1 of {total})", title.as_deref().unwrap_or("")))?;}Ok(())}# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# } - Several fields may share one compute method (they must all be stored or all non-stored).
dependslists fields of the record, or paths through relational fields ("line_ids.price_subtotal","partner_id.country_id.code"). A sync compute reads the values its paths reach withbatch.value_of(Field, id)(orvalues_offor several ids); the ORM loads them for the whole batch first, one query per step at most:Every prefix of a path is a dependency: changing a line’s price, moving a line to another order (both orders) or creating a line marks the order. A record’s x2many reads like the record would see it (archived lines left out). Reading a field that no path reaches is an error, as for the record’s own fields;# erp_sdk::addon!(name = "sale");# use erp_sdk::prelude::*;# #[model(name = "sale.order", description = "Order")]# pub struct Order {# #[field(one2many, comodel = "sale.order.line", inverse_name = "order_id")]# pub line_ids: X2many<Line>,# #[field(float, compute = "_compute_amount_total", store)]# pub amount_total: f64,# }# #[model(name = "sale.order.line", description = "Order Line")]# pub struct Line {# #[field(many2one, comodel = "sale.order", required, ondelete = "cascade")]# pub order_id: Many2one<Order>,# #[field(float)]# pub price_subtotal: f64,# }# #[methods(Order)]# impl Order {#[compute(depends = ["line_ids.price_subtotal"])]fn _compute_amount_total(batch: &mut Batch<'_, Order>) -> Result<()> {for i in batch.indices() {let lines = batch.get(i, Order::LINE_IDS)?; // X2many<Line>let total: f64 = batch.values_of(Line::PRICE_SUBTOTAL, lines.ids())?.iter().sum();batch.set(i, Order::AMOUNT_TOTAL, total)?;}Ok(())}# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }reads = [...]takes paths too.- A field that depends on itself through a relation (
"parent_id.display_name") is recursive: it is computed level by level, parents first, and a whole hierarchy settles in one flush. - Changes on regular models never mark fields of transient models (a wizard’s path stops where it enters a regular model).
- Marking dependents through relations reads the relation from the cache when it can (the inverse field of a one2many, a mirror many2many), otherwise one query per relation step, for all the changed records at once; nothing is read when every dependent behind a step is non-stored and not cached.
- Override a compute in another addon with
#[compute(override, depends = [...])]and a last parametersup: ComputeSuper, sync or async (an async compute receives the async variant,AsyncComputeSuper); callsup.call(batch)?(sync) orsup.call(tx, this.as_records(), out).await?(async) for the inherited value. The dependencies of every implementation add up. Adepends = [...]on the field itself replaces them:# mod library {# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book", addon = "library")]# pub struct Book {# #[field(char)]# pub title: Option<Arc<str>>,# #[field(integer)]# pub pages: i32,# #[field(float, compute = "_compute_weight", store)]# pub weight: f64,# #[field(char, compute = "_compute_summary")]# pub summary: Option<Arc<str>>,# }# #[methods(Book, addon = "library")]# impl Book {# #[compute(depends = ["pages"])]# fn _compute_weight(batch: &mut Batch<'_, Book>) -> Result<()> {# for i in batch.indices() {# let pages = batch.get(i, Book::PAGES)?;# batch.set(i, Book::WEIGHT, f64::from(pages) * 2.5)?;# }# Ok(())# }# #[compute(depends = ["title"])]# async fn _compute_summary(# this: &RecordSet<Book>,# tx: &mut Transaction,# out: &mut Assign<'_, Book>,# ) -> Result<()> {# let titles = this.mapped(tx, Book::TITLE).await?;# for (i, title) in titles.iter().enumerate() {# out.set(i, Book::SUMMARY, title.clone())?;# }# Ok(())# }# }# }# erp_sdk::addon!(name = "library_isbn", depends = ["library"]);# use erp_sdk::prelude::*;# use library::Book;# #[extend(Book)]# pub struct BookIsbn {}#[methods(Book)]impl BookIsbn {#[compute(override, depends = ["pages"])]fn _compute_weight(batch: &mut Batch<'_, Book>, sup: ComputeSuper) -> Result<()> {sup.call(batch)?;for i in batch.indices() {let w: f64 = batch.get(i, Book::WEIGHT)?;batch.set(i, Book::WEIGHT, w + 0.1)?;}Ok(())}#[compute(override, depends = ["title"])]async fn _compute_summary(this: &RecordSet<Book>,tx: &mut Transaction,out: &mut Assign<'_, Book>,sup: ComputeSuper,) -> Result<()> {sup.call(tx, this.as_records(), out).await?;// then adjust or complete the inherited values with `out.set(...)`Ok(())}}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON, &library::ADDON]).check()?;# Ok(())# } - Field options:
store,readonly = false(a written value is kept until a dependency changes),inverse = "_method"(an async#[method]with no arguments that writes the dependencies back),compute_sudo,depends_context = ["key", "uid", ...](non-stored values cached per context),related = "partner_id.country_id.code"(a path, or a field of the same record; computed as superuser by default, writable withreadonly = false: writing it writes the target record, when both records are database records or both are new). Non-stored related fields are searchable (partner_name = 'x'searchespartner_id.name; a condition matching empty values also matches records without a partner). - Sensitive display-name inputs can use
Env::label_reader()to obtain the original consumer of an internally elevated label read, or the current environment for an ordinary read. Check permissions and read those inputs through this environment. Declaredepends_context = ["label_reader", ...]to separate cached values by its principal binding, policy snapshot, resolution/groups and validated companies. This reserved key is derived by the engine; a context dictionary cannot impersonate a different reader. It does not replace ordinary data dependencies or authorization checks (ADR 0195). - Stored computes are computed before the
INSERTofcreate(one statement per batch of records), unless the field was given and is editable. Through relations, only paths of many2one fields qualify (partner_id.name: the partners are read for the whole batch); a dependency through an x2many (line_ids.price) is computed after the lines exist, at the next flush or read. Async stored computes are computed at the next flush or read. The full rules, and whatprecompute = falseandprecompute = truemean, are in Stored computes at create. - Writing a value equal to the cached one triggers nothing. Recomputation happens lazily: when the
field is read, or at flush (before commit, before savepoints, or
tx.flush_fields(...)). - A flush that keeps finding new work (computes creating records that need computing, and so on)
fails after
OrmConfig::max_flush_roundsrounds instead of committing a half-computed state. - When a compute does not assign a stored field, the record keeps its current value (as in Odoo), an in-memory record the value it holds (a form’s value); only a record with no value at all gets an empty one. A non-stored, readonly field must be assigned for every record: otherwise reading it is an error.
- Computations triggered by a flush run in the transaction’s environment (
tx.env()), not in the environment that changed the dependencies; rows written only by such a recompute get that environment’s user aswrite_uid. Computes triggered by a read run in the reader’s environment.compute_sudofields always compute as superuser, keeping the uid. - Dependencies may include
display_name; it follows the model’s rec-name field. precompute = falseon a stored computed field keeps it out of theINSERT; a compute that reads (or depends on) a field computed after theINSERTis computed after it too.
Stored computes at create
Section titled “Stored computes at create”A stored computed or related field is written by the INSERT of create, not by an UPDATE
after it, whenever its inputs are known when the row is inserted. No declaration is needed: this
is the default (ADR 0053). Odoo does it only for fields declared precompute=True and writes
every other stored compute of a new row a second time at the flush.
Known at the INSERT are the row’s own fields (given or defaulted), the stored computes of
the row that are themselves computed before the INSERT, and fields reached through many2one
fields only (partner_id.country_id.code: the partners and countries exist; they are read once for
the whole batch, nothing when they are cached).
Computed after the INSERT (at the next flush or read, one UPDATE per batch) are:
- async computes (they may query);
- computes that read
display_name; - computes with a dependency through a one2many or a many2many (
line_ids.price_subtotal: the lines of a new record are created after it); - fields declared
precompute = false; - every field that reads one of those. The fields of one compute method decide together: if one
of them is computed after the
INSERT, all of them are.
At create, a readonly precomputed field ignores a given or default value and is always computed; an editable one keeps a given or default value, and giving one editable field of a compute method leaves the method’s other fields empty (as in Odoo).
Inverses and related writes in the same create. A field computed before the INSERT without a
declaration is recomputed at the flush when an inverse method or an editable related field given
in the same create changes one of its inputs, so the stored value is the one Odoo computes at the
flush; only that case costs an UPDATE. A field declared precompute = true keeps the value it
was given before the INSERT for the rest of the create, as in Odoo.
precompute = false opts out: the field is computed after the INSERT, together with everything
that reads it. It is rarely needed; use it when the value must be computed on the stored row, for
example by an async compute that queries it.
precompute = true is an assertion, not a switch. It does two things: the value computed before
the INSERT is kept for the rest of the create (inverses and related writes do not recompute it,
as in Odoo), and the ORM refuses to build (ErrorKind::Programming) when the graph cannot honour
it, naming the field and the first input that blocks it. Declare it where you rely on the value
being in the INSERT, for example a field that a record rule on create reads: a later change
that moves the field after the INSERT (a new dependency through a one2many, say) then fails the
build instead of passing unnoticed. It is not needed for a field to be precomputed:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;#[model(name = "library.author", description = "Author")]pub struct Author { #[field(char)] pub country_code: Option<Arc<str>>,}
#[model(name = "library.book", description = "Book")]pub struct Book { #[field(integer)] pub pages: i32, #[field(many2one, comodel = "library.author", required)] pub author_id: Many2one<Author>, /// in the INSERT without any declaration #[field(float, compute = "_compute_weight", store)] pub weight: f64, /// asserted (a create rule reads it): through a many2one, its input is known at the INSERT #[field(char, related = "author_id.country_code", store, precompute)] pub origin: Option<Arc<str>>, /// computed after the INSERT, at the next flush or read #[field(char, compute = "_compute_label", store, precompute = false)] pub label: Option<Arc<str>>,}
#[methods(Book)]impl Book { #[compute(depends = ["pages"])] fn _compute_weight(batch: &mut Batch<'_, Book>) -> Result<()> { for i in batch.indices() { let pages = batch.get(i, Book::PAGES)?; batch.set(i, Book::WEIGHT, f64::from(pages) * 2.5)?; } Ok(()) }
#[compute(depends = ["pages"])] fn _compute_label(batch: &mut Batch<'_, Book>) -> Result<()> { for i in batch.indices() { let pages = batch.get(i, Book::PAGES)?; batch.set(i, Book::LABEL, format!("{pages} pages"))?; } Ok(()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Declaring precompute on a field that reads label, or on a total over line_ids, fails at build
with a one-line error that names the field, says it cannot be computed before the INSERT, names the
dependency it reads (here line_ids.price through the one2many library.book.line_ids, whose lines are
created after the INSERT) and says that precompute over one2many lines is not supported yet.
Odoo only warns there and turns precompute off, so the field is silently written twice; when
moving such a field from Odoo, drop the declaration (or the dependency that blocks it).
Separately from any declaration, a required stored compute that is computed after the
INSERT and not given would fail on the column’s NOT NULL. create refuses the call before
sending anything, with the same ErrorKind::Validation and text as that violation plus the reason
(one line):
The database refused the change: Missing required field 'Code' (code) for model 'Book'(library.book): it is computed after the INSERT because it is declared precompute = falseErrors that poison a transaction
Section titled “Errors that poison a transaction”- A
Validationerror raised bycreate,write, a recompute or a flush (a constraint, a value the converter rejects, a database constraint) leaves the transaction unable to commit:commit()returns that error untilrollback(). A savepoint whose block failed is rolled back with its errors, and the transaction can commit again. - Cancelling an ORM future half-way (dropping it, a
select!branch losing, a timeout) also poisons the transaction: every later call fails untilrollback().
Constraints
Section titled “Constraints”# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(integer)]# pub pages: i32,# }#[methods(Book)]impl Book { #[constrains("pages")] async fn _check_pages(this: &RecordSet<Book>, tx: &mut Transaction) -> Result<()> { for book in this.iter() { if book.get(tx, Book::PAGES).await? < 0 { return Err(Error::validation("A book cannot have a negative number of pages")); } } Ok(()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }Constraints run as superuser, once per create/write call on the whole recordset, and after a
stored computed field they name is recomputed. In-memory records (new_record) never run them.
Relational fields
Section titled “Relational fields”# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.item", description = "Item")]# pub struct Item {# #[field(char)]# pub name: Option<Arc<str>>,# }# #[model(name = "library.tag", description = "Tag")]# pub struct Tag {# #[field(char)]# pub name: Option<Arc<str>>,# }#[model(name = "library.shelf", description = "Shelf")]pub struct Shelf { #[field(char)] pub name: Option<Arc<str>>, #[field(one2many, comodel = "library.book", inverse_name = "shelf_id")] pub book_ids: X2many<Book>, // typed by its comodel #[field(many2many, comodel = "library.tag")] // table library_shelf_library_tag_rel pub tag_ids: Vec<RecId>, // untyped ids}
/// Delegation inheritance: every field of `library.item` is also a field of `Book`#[model(name = "library.book", description = "Book", inherits = [("library.item", "item_id")])]pub struct Book { #[field(many2one, comodel = "library.item", required, ondelete = "cascade")] pub item_id: Many2one<Item>, #[field(many2one, comodel = "library.shelf", ondelete = "set null")] pub shelf_id: Many2one<Shelf>, #[field(char)] pub title: Option<Arc<str>>,}
# async fn example(# mut tx: Transaction,# shelf: RecordSet<Shelf>,# dune: RecId,# stray: RecId,# worn_out: RecId,# ) -> Result<()> {// Add a new book, rename one, take a book from another shelf, delete a worn-out one:shelf.write(&mut tx, Vals::<Shelf>::new().commands(Shelf::BOOK_IDS, [ Cmd::create(Vals::<Book>::new().set(Book::TITLE, "Rust in Action")), Cmd::update(dune, Vals::<Book>::new().set(Book::TITLE, "Dune (2nd ed.)")), Cmd::link(stray), Cmd::delete(worn_out),])).await?;
// Keep exactly these books on the shelf:shelf.write(&mut tx, Vals::<Shelf>::new().commands(Shelf::BOOK_IDS, [Cmd::set([dune, stray])])).await?;
// Following a typed relation gives a typed recordset:let books: RecordSet<Book> = shelf.related(&mut tx, Shelf::BOOK_IDS).await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Declare relational fields with
Many2one<C>/X2many<C>to carry the comodel in the type:shelf.related(&mut tx, Shelf::BOOK_IDS)then returns aRecordSet<Book>, andvals.commands(Shelf::BOOK_IDS, [Cmd::create(Vals::<Book>::new().set(Book::TITLE, "x"))])only acceptsBookvalues (anything else does not compile).Option<RecId>/Vec<RecId>remain available, with untypedCommands. On the dynamic surfacerecords.related(&mut tx, "book_ids")returns aRecords,records.assign(&mut tx, "shelf_id", &shelf)writes one, andreadreturns many2one values as[id, display_name](read_with(.., Load::Raw)gives the bare id); a written many2one list must be exactly[id, name or False].
Relational command protocol
Section titled “Relational command protocol”| Operation | Typed Cmd | Dynamic Command | Python triple (code, id, vals) | Effect |
|---|---|---|---|---|
| Create | Cmd::create(vals) | Command::Create(raw_vals) | (0, 0, vals) | Creates a comodel record and links it |
| Update | Cmd::update(id, vals) | Command::Update(id, raw_vals) | (1, id, vals) | Writes values on the record (does not link it) |
| Delete | Cmd::delete(id) | Command::Delete(id) | (2, id, 0) | Deletes the record and so removes the link |
| Unlink | Cmd::unlink(id) | Command::Unlink(id) | (3, id, 0) | Removes the link (one2many: deletes the line when its many2one is ondelete = "cascade", else empties the many2one) |
| Link | Cmd::link(id) | Command::Link(id) | (4, id, 0) | Links an existing record |
| Clear | Cmd::clear() | Command::Clear | (5, 0, 0) | Removes all links |
| Set | Cmd::set(ids) | Command::Set(ids) | (6, 0, ids) | Replaces all links with the given ids |
- x2many fields are written with commands, as in Odoo:
create(vals),update(id, vals),delete(id),unlink(id),link(id),clear(),set(ids), or as Odoo’s[(0, 0, {...})]triples inwrite_values(exactly three elements;SETtakes a list of ids). A plain id list written to an x2many field meansset. Commands in acreaterun after the record exists; updates, unlinks and links are batched per record, many2many pairs of a batch are written in one statement. - Fail-loud ownership (ADR 0014 F3):
update,deleteandunlinkon a one2many only accept the record’s own lines (aValidationerror otherwise; Odoo would modify any record). - One2many full-delete guard (
SPEC-REL-050): on a one2many, once aCREATEorLINKwas seen in the command list (and always increate),CLEARis ignored andSETonly links, so lines created or linked in the same list are never wiped. Many2many commands have no such guard. - New records in memory: New (in-memory) records named by
link/seton a database record are created (or, with an origin, linked and updated), soorder.assign(&mut tx, "line_ids", &lines_with_new_ones)saves them. Commands on new records only change the cache (see below). Commands on a non-stored x2many apply to its current value in the cache; its inverse method then saves it. - A one2many may also be the inverse of a
many2one_reference(res_model+res_id): only the rows naming the owner’s model belong to it, and lines created through it get the model name. An integer inverse is refused when the registry is built. - A
referencevalue must name a model the field declares and a record that exists (aMissingerror otherwise; Odoo stores an empty value). - Ids of a multi-row
createascend in input order. When all rows give the same fields (the usual case), each batch of rows is oneINSERT … RETURNING; rows giving different fields first reserve their ids (one extra statement). ondeleteof a many2one isset nullby default (cascade/restrictavailable; a required field must say which).unlinkdeletes cascaded rows in the database and only forgets cached values that point at the deleted records; other cached values stay valid. Stored computed fields depending on a many2one that a deletion empties, or on a one2many/many2many that loses records, are recomputed.- An error raised by
create,writeorunlinkafter it changed data (rows inserted, parents written, lines created) makescommit()refuse until you roll back or the savepoint it ran in is rolled back. inherits = [("library.item", "item_id")]gives the model every field oflibrary.item: creating a record creates its parent, writing a delegated field writes the parent, and the child’s constraints on delegated fields are checked after the parent is written.- With
check_company_auto,createandwritecheck thecheck_companyfields: their targets must belong to no company or to the record’s company, else a user error lists the conflicts. - Differences from Odoo in the SQL (the rows are the same): a negated condition on a many2one path
(
partner_id.name != 'x') compiles toNOT EXISTS (…)instead ofIS NULL OR … NOT IN (…), and without a parent storechild_of/parent_ofbecome a recursive sub-query of the same statement (id IN (WITH RECURSIVE …)) instead of one query per level.
Hierarchies: parent store
Section titled “Hierarchies: parent store”# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;#[model(name = "library.category", description = "Category", parent_store = true)]pub struct Category { #[field(char)] pub name: Option<Arc<str>>, #[field(many2one, comodel = "library.category", ondelete = "cascade")] pub parent_id: Many2one<Category>, #[field(char, index)] pub parent_path: Option<Arc<str>>,}
# async fn example(mut tx: Transaction, parent_cat_id: i64, sub_cat_id: i64) -> Result<()> {let categories = tx.env().model::<Category>()?;// the category and everything below itlet subtree = categories .search(&mut tx, &Domain::field("parent_id")?.child_of(parent_cat_id)) .await?;// the category and everything above itlet ancestors = categories .search(&mut tx, &Domain::field("parent_id")?.parent_of(sub_cat_id)) .await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }parent_store = trueneeds a many2one to the model itself (parent_name, defaultparent_id) and an indexedparent_pathchar field; otherwise the registry does not build.- The ORM keeps
parent_path("1/4/9/", the ids from the root) up to date in SQL, at once: one extra statement aftercreate, one per new parent when records move. Values given forparent_pathare ignored. Moving a record under itself or one of its descendants is aUserError, raised before anything is written. child_ofandparent_ofon the parent field use the paths (parent_path =like '1/4/%'), in SQL and in memory.- Adding
parent_storeto a model whose table has rows fills every path at the next schema update.
In-memory records and savepoints
Section titled “In-memory records and savepoints”# #![recursion_limit = "256"]# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# #[model(name = "library.shelf", description = "Shelf")]# pub struct Shelf {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(one2many, comodel = "library.book", inverse_name = "shelf_id")]# pub book_ids: X2many<Book>,# }# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub title: Option<Arc<str>>,# #[field(integer)]# pub pages: i32,# #[field(many2one, comodel = "library.shelf")]# pub shelf_id: Many2one<Shelf>,# }# async fn example(mut tx: Transaction, book: RecordSet<Book>) -> Result<()> {let books = tx.env().model::<Book>()?;
// An in-memory record: never written to the tablelet draft = books .new_record(&mut tx, Vals::<Book>::new().set(Book::TITLE, "Draft Volume")) .await?;// Assignments change the in-memory record only:draft.set(&mut tx, Book::PAGES, 120).await?;
// A shelf form with a new line, turned back into commands for a database record:let shelves = tx.env().model::<Shelf>()?;let form = shelves .new_record( &mut tx, Vals::<Shelf>::new().commands( Shelf::BOOK_IDS, [Cmd::create(Vals::<Book>::new().set(Book::TITLE, "New"))], ), ) .await?;let commands: Vec<Command> = form.as_records().x2many_commands(&mut tx, "book_ids").await?;
// Work on database records inside a savepoint:tx.savepoint(async |tx| { book.set(tx, Book::PAGES, 200).await?; // returning Err here rolls the database back to the savepoint // and empties the transaction's record cache Ok(())}).await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }model.new_record(&mut tx, vals).awaitandmodel.new_with(&mut tx, vals, origin, reference).awaitbuild records that are never written; their computed fields compute on read, stored fields come from the origin, other fields from their defaults.- A new record’s x2many holds new records: with an origin, the origin’s lines as new records of
those origins (
line.new_with(.., origin = line)is the same record), so the value’sorigin()is the origin’s value; a many2one may point at a database record or at a new record. Reading these for several new records reads the origins once. - x2many commands on new records only change the cache:
createmakes a new line,updatechanges a line’s values,delete/unlinkdrop the line from the value (nothing is deleted),link/setadd database records as new records of those origins. The lines’ inverse fields follow (a one2many line’s many2one points at the new record). Database records never see new records in their cached values. record.x2many_commands(&mut tx, "line_ids")turns a value back into commands for a database record (Odoo’sconvert_to_write):setof the database lines (origins included), thencreatefor each new line without origin andupdatewith the changed values for each new line that differs from its origin; the inverse field is left out.tx.savepoint(async |tx| { … }).awaitflushes, runs the block in a database savepoint and releases it; when the block fails, the database rolls back to the savepoint and the transaction’s cache is emptied, so later reads see the database again.
Grouped reads
Section titled “Grouped reads”# erp_sdk::addon!(name = "library");use erp_sdk::prelude::*;use erp_sdk::ReadGroupingSets;# #[model(name = "library.shelf", description = "Shelf")]# pub struct Shelf {# #[field(char)]# pub name: Option<Arc<str>>,# }# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(integer)]# pub pages: i32,# #[field(selection, selection = [("draft", "Draft"), ("done", "Done")])]# pub state: Option<Arc<str>>,# #[field(many2one, comodel = "library.shelf")]# pub shelf_id: Many2one<Shelf>,# }# async fn example(mut tx: Transaction) -> Result<()> {
let books = tx.env().records("library.book")?;let groups = books ._read_group( &mut tx, ReadGroup::new(Domain::field("state")?.eq("done")) .groupby(["shelf_id", "create_date:month"]) .aggregates(["pages:sum", "__count"]) .order("pages:sum desc") .limit(10), ) .await?;for row in groups.rows() { // [shelf, month start, sum of pages, count]; the shelf is a one-record recordset, // or an empty one for the "no shelf" group let shelf: Option<&Records> = row[0].as_records();}let tuples = books.read_group(&mut tx, ReadGroup::new(Domain::TRUE).groupby(["state"])).await?;
// GROUPING SETS: several groupings in a single SQL statementlet sets = [vec!["shelf_id", "state"], vec!["shelf_id"], vec![]];let per_grouping = books ._read_grouping_sets( &mut tx, ReadGroupingSets::new(Domain::field("state")?.eq("done"), sets) .aggregates(["pages:sum", "__count"]), ) .await?;for groups in per_grouping { for row in groups.rows() { // [group values..., aggregates...] }}# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Group-by specs: a field,
date_field:granularity(hour,day,week,month,quarter,year, or a number part:year_number,quarter_number,month_number,iso_week_number,day_of_year,day_of_month,day_of_week,hour_number,minute_number,second_number), or a many2one pathpartner_id.country_id[:granularity]. Aggregates:__count,field:sum|avg|min|max|count|count_distinct|bool_and|bool_or|array_agg| array_agg_distinct|recordset.havingtakes domain-like items over aggregate specs. - Group count and pagination:
ReadGroup::new(domain).limit(10).offset(20).count_groups(true)also counts all groups, beforelimit/offset, in the same SQL statement (COUNT(*) OVER ());groups.group_count()then returnsSome(total). - Group values:
groups.rows()returns rows ofGroupValuecells:Null(a NULL item of anarray_agglist),False(an empty group value, or an aggregate without values),Bool,Int,Float,Decimal(exact, fornumericcolumns and their sums),Str,Date,DateTime,Json,Records(a relational group value: one record or empty; also arecordsetaggregate) andList(anarray_agglist). - Datetimes are bucketed in the context timezone (
tz); weeks start on Sunday until languages arrive (M3). Selection groups follow the declaration order; a boolean groups NULL withFalse. Without an order, groups are sorted by the group-by values (many2one by id); with an explicit order, a many2one term follows the comodel’s own order. - Everything is one SQL statement, the search predicate included: record rules restrict the grouped rows, the many2many relation joined for a many2many group-by, and a many2one path’s comodel (hidden targets fall into the empty group). Pending writes of the fields involved are flushed first; a domain known to be empty runs nothing.
_read_groupand_read_grouping_setsare overridable (#[method(override)] async fn _read_group(this, tx, args: ReadGroup, sup: Super) -> Result<Groups>); every caller, the web client’s included, goes through them.read_groupis final and returns ids instead of recordsets._read_grouping_sets(ReadGroupingSets::new(domain, [vec!["a", "b"], vec!["a"], vec![]]))computes several groupings in one statement (GROUPING SETS).numericsums stay exact decimals;sum_currencyneeds currency rates and is refused until M3.
The web client’s methods
Section titled “The web client’s methods”The always-installed web addon puts the web client’s model methods on base: web_read,
web_search_read, web_name_search, web_save, web_save_multi, web_resequence,
web_unlink, formatted_read_group, formatted_read_grouping_sets, web_read_group,
read_progress_bar, search_panel_select_range, search_panel_select_multi_range, onchange and onchange_batch. They take Odoo’s arguments (a
specification {field: {fields, context, limit, order}} instead of a field list) and return
Odoo’s shapes. Override them per model like any method:
# erp_sdk::addon!(name = "library");# use erp_sdk::prelude::*;# use erp_sdk::ValueMap;# #[model(name = "library.book", description = "Book")]# pub struct Book {# #[field(char)]# pub name: Option<Arc<str>>,# #[field(integer)]# pub pages: i32,# }#[methods(Book)]impl Book { #[method(override)] async fn web_read( this: &RecordSet<Book>, tx: &mut Transaction, spec: erp_sdk::web::Spec, sup: Super, ) -> Result<Vec<Value>> { let rows: Vec<Value> = sup.call(tx, this.as_records(), (spec,)).await?; // adjust the rows sent to the client here Ok(rows) }}
# async fn example(mut tx: Transaction, books: RecordSet<Book>) -> Result<()> {// Calling a web method with keyword arguments (the JSON-2 body as dynamic values):let map = |pairs: Vec<(&str, Value)>| { Value::Map(Arc::new(pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect::<ValueMap>()))};let kwargs = map(vec![( "specification", map(vec![("name", map(vec![])), ("pages", map(vec![]))]),)]);let result: Value = books.as_records().web_call(&mut tx, "web_read", &kwargs).await?;# Ok(())# }# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }records.web_call(&mut tx, "web_search_read", &kwargs)runs a method with keyword arguments given as dynamic values (the JSON-2 body): unknown or malformed arguments, unknown fields in a specification and lossy values areValidationerrors (422).web_read_groupreads the records of every opened group in one statement and takes the length of a limited level from the grouped statement itself: a kanban with ten open columns costs a few statements, not one per column.web_save_multiwrites records sharing the same values together, and per-record values are flushed in oneUPDATEper field set.web_unlinkraises aUserErrorwith Odoo’sUnlinkBlockedErrorcontext (Error::context()) when arestrictreference blocks the deletion, directly or through a cascade; nothing is deleted and no table or constraint name reaches the client.- Ordering grouped lists by a numeric field orders by its sum (Odoo’s default
aggregator). search_panel_select_rangeandsearch_panel_select_multi_rangecompute range and filter categories/tags for the web search panel, supporting hierarchical categories, counter badges via grouped counts, and custom domains. Omitlimit, or sendfalseor0, for an unlimited display range. A positive limit reaching the display boundary returns{"error_msg": "Too many items to display."}; counters remain complete. Hierarchical category reads apply the limit to comodel records before retaining only closed parent chains. Usehierarchize=falsefor a flat category list;comodel_domainrestricts visible choices. Selection filters ignoregroup_byand return no group keys. For many2many filters,group_domainis a map from JSON-encoded group IDs to domains: integer ID 7 uses key"7", an unset group uses"false", and a string group ID uses its full JSON string encoding (including quotes and escapes). Keys are parsed as JSON scalars and canonicalized: escaped Unicode and literal UTF-8 keys for the same group ID are equivalent. Missing entries and{}add no restriction; malformed maps, keys or domains raise typed validation errors. For many2one filters,group_domainis instead a domain applied to counters. Relationalgroup_byaccepts many2one, selection and other valid scalar fields; compound and binary group values raise an explicit typed error. Counter execution uses one grouped statement per field, including custom per-group predicates; it does not count each choice separately. The returnedvaluesuseValue::Rowsinternally, with a shared column layout, while JSON callers still receive an array of choice objects. Relational choices are filtered through comodelsearch_withand read withread_rows, preserving comodel visibility and display labels.- Not yet:
group_expandandfill_temporal(M4), other fieldaggregators (M4), pending attachments inweb_save(M3).
Onchange methods
Section titled “Onchange methods”# erp_sdk::addon!(name = "sale");# use erp_sdk::prelude::*;# #[model(name = "res.partner", description = "Contact")]# pub struct Partner {# #[field(char)]# pub name: Option<Arc<str>>,# }# #[model(name = "sale.order", description = "Order")]# pub struct Order {# #[field(many2one, comodel = "res.partner")]# pub partner_id: Many2one<Partner>,# #[field(text)]# pub note: Option<Arc<str>>,# }#[methods(Order)]impl Order { #[onchange("partner_id")] async fn _onchange_partner(this: &RecordSet<Order>, tx: &mut Transaction) -> Result<OnchangeResult> { let partner = this.as_records().related(tx, "partner_id").await?; if partner.is_empty() { return Ok(OnchangeResult::warning("No customer", "Pick a customer first.")); } this.set(tx, Order::NOTE, "Customer set").await?; Ok(OnchangeResult::none()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- An
#[onchange]method runs on the in-memory record of the form when one of its fields changes; it assigns fields withset/writeand may return values and a warning. The whole onchange is isolated (ADR 0017 §2): nothing it writes, even to database records, persists, and the transaction’s cache is left as it was before the call. An onchange that only reads costs no extra statement; the first statement that would change data opens a savepoint that is always rolled back. A database error on a read inside an onchange aborts the transaction like anywhere else (roll back). ASELECTthat calls a function which writes is not recognised as a change: do not call such functions from an onchange. Methods of every addon run in method-name order, each at most once per pass; passes repeat while fields of the form keep changing (unless the context setsrecursive_onchangesto false). - The record starts from the edited record’s values (computed ones included), so only the dependents of what changed are recomputed. The response contains only what differs from the form, x2many fields as command lists.
- Return values and warnings:
OnchangeResult::none(): nothing besides the assignments made withset/write.OnchangeResult::warning(title, message): a warning the client shows in a dialog.OnchangeWarning::with_options(class_name, sticky)validates optional notification presentation (ADR 0123). Class text is at most 512 UTF-8 bytes, eight distinct CSS identifier tokens of at most 64 bytes, separated only by ASCII spaces. Tokens match[A-Za-z_][A-Za-z0-9_-]*; malformed/duplicate values return Validation. The wire spelling isclassName;stickyis optional boolean. A single warning preserves these options, including explicit empty class text or sticky false. Complete normalized warnings deduplicate; several distinct warnings combine in method order into the existing dialog, without notification-only options. The default dialog ignores notification presentation..value(field, value): also assignfield(Odoo’s{'value': …}).idis ignored; a name that is not a field of the model is aProgrammingerror (Odoo ignores it).
- Calling onchange: the web client calls
records.web_call(&mut tx, "onchange", &kwargs); Rust code can callrecords.onchange(&mut tx, values, field_names, spec)directly.
Onchange on delegated (_inherits) fields
Section titled “Onchange on delegated (_inherits) fields”# erp_sdk::addon!(name = "account");# use erp_sdk::prelude::*;#[model(name = "account.move", description = "Entry")]pub struct Move { #[field(integer)] pub copies: i32, #[field(one2many, comodel = "account.payment", inverse_name = "move_id")] pub payment_ids: X2many<Payment>, /// sees the amounts of unsaved payments in a form #[field(integer, compute = "_compute_total")] pub total: i32,}
#[methods(Move)]impl Move { #[compute(depends = ["payment_ids.amount"])] fn _compute_total(batch: &mut Batch<'_, Move>) -> Result<()> { for i in batch.indices() { let payments = batch.get(i, Move::PAYMENT_IDS)?; let mut total: i32 = 0; for amount in batch.values_of(Payment::AMOUNT, payments.ids())? { total = total .checked_add(amount) .ok_or_else(|| Error::validation("the total of the payments overflows"))?; } batch.set(i, Move::TOTAL, total)?; } Ok(()) }}
/// A payment is a move: `copies` and `total` are fields of `Payment` too#[model(name = "account.payment", description = "Payment", inherits = [("account.move", "move_id")])]pub struct Payment { #[field(many2one, comodel = "account.move", required, ondelete = "cascade")] pub move_id: Many2one<Move>, #[field(integer)] pub amount: i32,}
#[methods(Payment)]impl Payment { #[onchange("amount")] async fn _onchange_amount(this: &RecordSet<Payment>, tx: &mut Transaction) -> Result<OnchangeResult> { // a delegated field: assigned on the form's in-memory move, never in the database this.as_records().set_value(tx, "copies", Value::Int(2)).await?; Ok(OnchangeResult::none()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Delegated fields work in onchange like the model’s own: the in-memory record gets an in-memory
parent (the edited record’s parent, or a new one), the form’s values and first-call defaults of
delegated fields go to it, and the parent’s computed fields follow. A payment form changing
amountgets the move’s recomputedtotalback, unsaved amount included; changing a field the move’s computed fields depend on returns those fields too. An onchange method may assign a delegated field (set_valueabove): it is written on the in-memory parent only. - In a one2many whose inverse is the delegate (
payment_idsof a move), a line’s delegated values go to the form’s record. Every in-memory line of a one2many points at the form’s record (as in Odoo), so a line’s computed fields see the form’s values; a line or record moved to another parent leaves the old one, so the old parent’s aggregates no longer count it. The cost does not grow with the number of lines: their parents are read together. - A delegate pointing at a record that does not exist, or that the user may not read, is a
Missing/Accesserror. A many2one value given as a map is read as the record itsidnames (its other keys are not applied); withoutidit is aValidationerror (Odoo builds an in-memory record from the map; seedocs/design/m1-onchg.md). - Outside onchange, a new record takes values of delegated fields only when its delegate is a new
record:
newwith delegated values, or a write on a new record whose delegate is empty or a database record, is aProgrammingerror (Odoo writes them on a new parent). So is a write of delegated values on database records that sets a new record as delegate, or that empties the delegate. - Not yet:
change_defaultwithir.default(M3).
Many2many lines in onchange
Section titled “Many2many lines in onchange”# erp_sdk::addon!(name = "blog");# use erp_sdk::prelude::*;#[model(name = "blog.post", description = "Post")]pub struct Post { #[field(char)] pub name: Option<Arc<str>>, #[field( many2many, comodel = "blog.tag", relation = "blog_post_tag_rel", column1 = "post_id", column2 = "tag_id" )] pub tag_ids: X2many<Tag>,}
/// `post_ids` is the mirror of `blog.post.tag_ids`: the same table, the columns swapped#[model(name = "blog.tag", description = "Tag")]pub struct Tag { #[field(char)] pub name: Option<Arc<str>>, #[field( many2many, comodel = "blog.post", relation = "blog_post_tag_rel", column1 = "tag_id", column2 = "post_id" )] pub post_ids: X2many<Post>, /// in a post's form, a tag of the form counts the unsaved post too #[field(integer, compute = "_compute_post_count")] pub post_count: i32,}
#[methods(Tag)]impl Tag { #[compute(depends = ["post_ids"])] fn _compute_post_count(batch: &mut Batch<'_, Tag>) -> Result<()> { for i in batch.indices() { let posts = batch.get(i, Tag::POST_IDS)?; let count = i32::try_from(posts.len()) .map_err(|_| Error::validation("too many posts to count"))?; batch.set(i, Tag::POST_COUNT, count)?; } Ok(()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- Every line of a many2many in a form lists the form’s in-memory record in the comodel’s mirror
many2many (the field on the same table with the columns swapped), as in Odoo: a tag created in
a post’s form has
post_count1, and a computed field of the post overtag_ids.post_idscounts the post on every tag. An edited post is listed once on the tags it already has. It costs no statement per line. - Tags linked from the database keep the stored values of the fields the form shows for them
(Odoo copies them before building the form’s record), so a
post_countin the tag list shows the stored count for them; their mirror lists the post all the same. - A tag the form removes still lists the post in its mirror until the onchange ends (as in Odoo; it is not part of the response). Nothing outlives the onchange.
- A delegated many2many (
_inherits) lists the form’s in-memory parent on its lines the same way, also for changed values, where Odoo lists it only on lines whose mirror was already read (docs/design/m1-onchg-m2m.md, candidate divergence D6 of the GRP spec).
x2many values inside lines
Section titled “x2many values inside lines”# erp_sdk::addon!(name = "sale");# use erp_sdk::prelude::*;# #[model(name = "account.tax", description = "Tax")]# pub struct Tax {# #[field(char)]# pub name: Option<Arc<str>>,# }#[model(name = "sale.order", description = "Order")]pub struct Order { #[field(one2many, comodel = "sale.order.line", inverse_name = "order_id")] pub line_ids: Vec<RecId>, #[field( many2many, comodel = "account.tax", relation = "sale_order_tax_rel", column1 = "order_id", column2 = "tax_id" )] pub tax_ids: Vec<RecId>,}
#[model(name = "sale.order.line", description = "Order line")]pub struct OrderLine { #[field(many2one, comodel = "sale.order", ondelete = "cascade")] pub order_id: Option<RecId>, #[field( many2many, comodel = "account.tax", relation = "sale_order_line_tax_rel", column1 = "line_id", column2 = "tax_id" )] pub tax_ids: Vec<RecId>,}
#[methods(Order)]impl Order { /// The order's taxes are added to every line's taxes. #[onchange("tax_ids")] async fn _onchange_taxes(this: &RecordSet<Order>, tx: &mut Transaction) -> Result<OnchangeResult> { let taxes = this.as_records().related(tx, "tax_ids").await?; let lines = this.as_records().related(tx, "line_ids").await?; for line in lines.iter() { let all = line.related(tx, "tax_ids").await?.union(&taxes)?; line.assign(tx, "tax_ids", &all).await?; } Ok(OnchangeResult::none()) }}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }- The values of a line command may hold the line’s own x2many values, command lists again, at
any depth:
[0, "virtual_7", {"tax_ids": [[4, 3, 0]]}]. They apply like the form’s own values, on the line’s current value (a saved line starts from its stored lines, a new line from none); the new lines of a one2many inside a line point at that in-memory line, so computed fields over any level (an order total over the lines’ sub-lines) see them. - With the lines’ x2many fields in the specification (
{"line_ids": {"fields": {"tax_ids": {"fields": {"name": {}}}}}}), their changes come back as nested command lists inside the line’s command: the method above returns[1, line, {"tax_ids": [[4, tax, {"id": tax, "name": …}]]}]for every line. A saved line linked into the form (LINK) comes back with its stored values and anUPDATEwhose nested commands compare its lines with the stored ones. - A line’s value of a delegated x2many field goes to the line’s in-memory parent, like its other delegated values.
- Limits: command lists nested deeper than 16 levels, or more than 100,000 line commands in one
call (all levels together, a
SETcounting its ids), areValidationerrors.
Named caches across processes
Section titled “Named caches across processes”A named cache (tx.ormcache(name, key, compute), tx.invalidate_ormcache(name)) is shared by the
transactions of one process. When the server runs with cross-process signals (set up by the
server, not by addons), an invalidation is also seen by every other process serving the database:
- Committing a transaction that called
invalidate_ormcache(name)records a change ofcache:<name>in the same transaction. Other processes clear that cache before their next transaction runs; no notification is sent for caches, the start of every transaction reads the change. - A value your method computes is published at commit only if no other process invalidated the cache after your transaction started. Otherwise it is dropped (it may come from data that is already out of date) and the next call computes it again. Nothing to do in addon code: compute from the transaction you are given.
- Cache names are 1 to 64 characters of
[a-z0-9_.]; committing an invalidation of a cache with any other name fails with aProgrammingerror.
Partitioned leaf models
Section titled “Partitioned leaf models”Append-mostly tables (an outbox, an audit trail, job history, logs) grow by millions of rows a day and are
cleaned up by age. Declare them partitioned: the rows live in one table per hour, day, week or month,
the ORM creates the coming partitions ahead of time, and old rows go away by dropping whole partitions
(constant time, no DELETE, no vacuum debt). Odoo has no partitioning; the rules below are ERPForAll’s
(ADR 0040 D6, docs/design/m3-ormx.md §7).
# erp_sdk::addon!(name = "audit_trail");use erp_sdk::prelude::*;
/// One table per day of `create_date`, 7 days created ahead, 30 days kept.#[model( name = "audit.event", description = "Audit Event", partition = partition(interval = "day", premake = 7, retain = 30))]pub struct AuditEvent { #[field(json)] pub payload: Option<erp_sdk::serde_json::Value>,}
/// One table per month of `recorded_at`, which the server fills; every partition is kept.#[model( name = "audit.entry", description = "Audit Entry", partition = partition(by = "recorded_at", interval = "month", premake = 2, retain = "all"))]pub struct AuditEntry { #[field(datetime, required, server_set)] pub recorded_at: Option<DateTime>, #[field(char)] pub what: Option<Arc<str>>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }partition(...) takes interval ("hour", "day", "week" from Monday, or "month", all in UTC),
premake (intervals created after the current one, 1 to 1000; at least 2 for "hour", because partition
upkeep may run up to one hour apart), retain (intervals kept before the current
one, 1 to 1000, or "all") and, optionally, by. None of them has a default.
The partition key is always server time. It is create_date unless by names another field, which must
be a stored, required datetime field declared server_set. The ORM fills a server_set field at insert with
the transaction timestamp, exactly as it fills create_date; the field is readonly in fields_get, never
copied, and a value for it in create, write or a data file fails with Programming
'audit.entry.recorded_at' is set by the server and cannot be written. The same error answers a value for
create_date on a partitioned model (Odoo drops it silently on other models and still does for
write_date; a partitioned model refuses it, whichever column is its key). So no caller can steer a row into
a partition, and a row never moves between partitions. server_set is allowed on any stored datetime field without a compute, related path or
default, partitioned model or not.
Only leaf models can be partitioned. The table’s primary key is (id, key): id alone is not unique
across partitions, so nothing may reference the model. The registry refuses, when it is built:
- a many2one (an
_inheritsdelegate is one) or a many2many pointing to the model, and a many2many on the model itself:model 'audit.event' is partitioned, so no field may reference it; 'sale.order.event_id' does; partitionon an#[extend]: only the declaration that creates the model decides (partitioning of 'audit.event' can only be declared by its owner (audit_trail)), and a model inheriting a partitioned one under a new name is not partitioned;- the access engine’s policy tables (
ir.access,res.groups,res.users, …: ADR 0035 D4), abstract and transient models, a fill factor, a table name longer than 51 bytes (partition names append_pand up to 10 digits), and a key that is not server time; partitioninmodels/*.toml: partitioning is declared by native addons only;- a business key (
keys = [key(...)], the arbiter ofupsert): a unique constraint of a partitioned table must contain the partition key, which the server sets on every insert, so no row could ever match it (business key '_k' of partitioned model 'audit.event' cannot be an upsert key: ...; rows of a partitioned model are inserted with create, not upserted), andupserton a partitioned model is aProgrammingerror too; - an exclusion or a
WITHOUT OVERLAPSkey that does not compare the partition key with=(exclusion '_no_overlap' of partitioned model 'audit.slot' must include the partition key 'recorded_at'): list it inequal(or the key’sfields).
Soft references (res_model/res_id, reference fields) and a one2many listing the model’s rows from
another model are fine.
Schema sync creates the table PARTITION BY RANGE (<key>) with the partitions of the declared window,
named <table>_p<YYYYMMDDHH> (hour), <table>_p<YYYYMMDD> (day, week) or <table>_p<YYYYMM> (month), each
covering [start, next start). There is never a default partition. An existing partitioned table that
matches the declaration (range on the key, a timestamp key column, primary key (id, key), every partition
named and bounded for the interval, no default partition) is adopted as it is, whoever created it: a
module that wrote its own partition DDL in this convention moves to the declaration without a rewrite. A
table whose partitioning would change (regular to partitioned, back, or a different interval) is created
again when it was never written, and refused when it has rows:
table 'audit_event' has rows; changing its partitioning is not supported (ADR 0040 D6; business tables: M5 partitioning ADR).
Upkeep keeps the window. Until the job scheduler runs it for you, call it yourself, from a loop that runs once per interval for example; each call runs on the owner pool (the request role has no DDL right), outside any request transaction:
# use erp_sdk::{Horizon, KeepAfter, Orm, Result};# async fn upkeep(orm: &Orm, owner: &erp_testkit::deadpool_postgres::Pool) -> Result<()> {// create what is missing up to `premake` intervals ahead (cheap when nothing is missing)let report = orm.ensure_partitions(owner, "audit.event", Horizon::Declared).await?;for entry in report.entries() { println!("{} {}: {}", entry.model(), entry.partition(), entry.action());}// detach (concurrently: writers keep inserting) and drop what is older than `retain`let retired = orm.retire_partitions(owner, "audit.event", KeepAfter::Declared).await?;retired.into_result()?; // a failed step becomes an error listing it# Ok(())# }# fn main() {}ensure_partitionsfirst finishes any detach an interruption left pending, then creates every missing partition of the window; it is safe to call from several processes at once (a partition created meanwhile is reportedexisted).retire_partitionsmarks each old partition, detaches it withDETACH PARTITION … CONCURRENTLYand drops it; a table an interrupted retirement left behind is dropped by the next call.maintain_partitions(owner, now)does both for every partitioned model.- The native server calls generic upkeep at startup and periodically with the current installed
registry and an owner pool. Addons only declare their partition policy; they do not register
an upkeep job.
base.partition_upkeep_interval_secsis a database-wide Technical parameter (default 3600 seconds, allowed 60 through 3600). Closed audit/outbox event-table upkeep is separate. This timer is independent of ordinary queue enablement; queue-based execution history for it is not available yet. - The returned
PartitionReportlists every partitioncreated,existed,finalized,detached,droppedorfailedwith the database’s reason; a failed step never stops the others, and nothing is skipped silently. It is#[must_use]: checkis_complete()or callinto_result(). - Every lock wait of the upkeep is bounded by
OrmConfig::partition_lock_timeout(5 s by default, 100 ms to 1 h); a concurrent detach that waits longer for older transactions gives up and leaves the partition pending, and the next call finishes it. - Removing a retired partition takes
ACCESS EXCLUSIVEon the tables its foreign keys point to (thecreate_uidandwrite_uidkeys point tores_users), and readers of those tables queue behind a waiting removal. The removal therefore gives up after 300 ms (PARTITION_SHORT_LOCK_TIMEOUT, not the longerpartition_lock_timeout): the table stays detached and marked, the report lists it asdrop deferred(drops_deferred(), not a failure; also logged as atracingwarning) and the nextretire_partitionsormaintain_partitionsremoves it. Attaching a new partition, detaching a retired one and finishing a pending detach takeSHARE ROW EXCLUSIVEon those tables, which queues their writers (a login updatingres_users) behind a waiting statement; they run under the same 300 ms. A wait that is cut is afailedentry whosePartitionEntry::is_lock_timeout()is true (SQLSTATE55P03, error kindLock): not a fault, the next run repeats it (a cut detach leaves the partition attached, or pending, which the next run finishes; the markererp:retiredis taken back from a partition that stayed attached). - The 300 ms bound also cuts the wait of a detach or finalize for older transactions (it is database-wide:
any transaction open longer than that, in any session, counts). With a long transaction around, a detach
stays pending run after run and old partitions are not retired. Watch
partition_health:PartitionWindow::pending_detaches()counts the detaches left pending andoldest_pending_end()gives the end of the oldest such partition’s range; a count above 0 over several runs means look for a long-running or prepared transaction. - A failed entry carries its structure, not only text:
PartitionEntry::step(),reason(),sqlstate()anderror_kind(). A scheduler retriesis_lock_timeout()entries quietly and raises the others. ensure_partitions(…, Horizon::Through(t))withtbefore the interval holding the current time is aProgrammingerror. A step that finds its lock held by another upkeep fails with aLockerror naming the table.maintain_partitions(owner, now)places the window and the retention cutoff bynow, one clock; the database’s clock only guards (a cutoff after it is refused, so a clock running ahead cannot retire live partitions). Pass the database’s time, or your own when it is within an interval of it.- A partition whose bounds are not a pair of timestamps cannot be compared with the cutoff: every
retirement lists it as
faileduntil someone detaches it by hand. - Upkeep bumps no cross-process generation: attaching or detaching a partition changes no result shape, and PostgreSQL re-plans the statements that read the table, in every process.
When upkeep falls behind, inserts fail loudly instead of landing in a catch-all partition:
no partition of 'audit.event' accepts create_date = 2026-10-19 10:00:00.123456: partition upkeep has not created it yet (window: 7 days; see the health check) (Database, SQLSTATE 23514).
Orm::partition_health(pool) reports, per partitioned model, how many consecutive intervals from the current
one have a partition; fewer than 2 is short. It also counts the partitions it cannot place in time
(PartitionWindow::unreadable_bounds(): a MINVALUE, MAXVALUE or infinity bound, a default partition);
anything above 0 wants a look. A model whose table is missing or not partitioned in the database is a
Database error, not a window of 0.
A partitioned table that already holds rows follows the large-table rule of schema sync
(SchemaSyncOptions::large_table_rows). PostgreSQL refuses CREATE INDEX CONCURRENTLY on a partitioned
parent, so an index on a large partitioned table becomes one SchemaStep
(SchemaStepKind::CreatePartitionedIndex): CREATE INDEX ... ON ONLY the parent (a catalog entry, invalid
for now), one CREATE INDEX CONCURRENTLY per partition, and ALTER INDEX ... ATTACH PARTITION, after which
the parent index is valid. A step that stopped half-way continues with the partitions that have no index
attached yet (a parent index left by another declaration, or without a comment to tell, is dropped with the
partition indexes attached to it and built again). Each partition’s build holds the table’s partition upkeep
lock, so a retirement cannot detach it meanwhile; a run that cannot take the lock within the step’s lock
timeout fails with a Lock error and resumes at the next sync. A UNIQUE or PRIMARY KEY constraint object
has no online form
(ADD CONSTRAINT ... USING INDEX is refused on a partitioned table), so the install fails before any DDL
naming the constraint, the table and the threshold; declare a unique index (it must include the key)
instead. An exclusion is refused like on any large table.
Reads and writes need nothing special: create, read, search, write and unlink work as on any model,
with the same statement counts (a read by id probes each partition’s primary key index; the retention keeps
their number bounded).
Search-panel many2many group_domain maps accept at most 64 entries per call; larger maps fail
with Validation. This input-shape bound does not limit returned choices or truncate counters.
For example, construct typed panel options and pass them to a model recordset:
use erp_orm::{Records, SearchPanelSelectMultiRange, SearchPanelSelectRange, Transaction};use erp_fields::{Result, Value};
async fn panel_values(tx: &mut Transaction, model: &Records) -> Result<(Value, Value)> { let mut category = SearchPanelSelectRange::new("category_id"); category.enable_counters = true; let mut tags = SearchPanelSelectMultiRange::new("tag_ids"); tags.enable_counters = true; tags.group_by = Some("category_id".to_owned()); let categories = model.search_panel_select_range(tx, category).await?; let filters = model.search_panel_select_multi_range(tx, tags).await?; Ok((categories, filters))}Bounded native selection providers
Section titled “Bounded native selection providers”A native selection_method uses #[selection] inside #[methods]. Its second
parameter is &mut SelectionContext, and it returns Result<()>. Emit each pair
through the checked sink, or read an authorized stored-text catalog:
erp_sdk::addon!(name = "selection_guide");use erp_sdk::prelude::*;use erp_sdk::{SelectionContext, SelectionLimits};
#[model(name = "selection_guide.catalog", description = "Choice catalog")]pub struct Catalog { #[field(char)] pub code: Option<Arc<str>>, #[field(text)] pub label: Option<Arc<str>>, #[field(boolean, default = true)] pub active: bool,}
#[model(name = "selection_guide.item", description = "Item")]pub struct Item { #[field(selection, selection_method = "_choices")] pub choice: Option<Arc<str>>, #[field(selection, selection_method = "_priority")] pub priority: Option<Arc<str>>,}
#[methods(Item)]impl Item { #[selection] async fn _choices(_this: &RecordSet<Item>, ctx: &mut SelectionContext<'_>) -> Result<()> { ctx.catalog("selection_guide.catalog", &Domain::TRUE, "code", "label", "code").await }
#[selection] async fn _priority(_this: &RecordSet<Item>, ctx: &mut SelectionContext<'_>) -> Result<()> { ctx.emit("normal", "Normal")?; ctx.emit("high", "High") }}
# fn main() -> erp_sdk::Result<()> {let limits = SelectionLimits::new(100, 16_384, 4, 512)?;let config = erp_sdk::OrmConfig { selection_limits: limits, ..Default::default() };# let _ = config;# Ok(())# }Use #[selection(override)] and a final sup: erp_sdk::SelectionSuper for an
inherited provider; sup.call(ctx, this.as_records()).await reaches the next native
implementation. Ordinary #[method] signatures are refused before execution.
Provider names can remain owned registry strings; no 'static conversion is needed.
emit checks duplicate keys and admission before copying. One metadata operation,
including sibling fields and ctx.resolve(model, field) re-entry, shares at most
4096 pairs, 1 MiB owned UTF-8 key/label bytes, depth 16 and 8192 work units. Limits
are positive and can only tighten. Pair emission, catalog rows, provider entries,
catalog domain/value nodes (including policy predicates) and explicit ctx.charge(work) each consume work. Charge native calculations
before performing them or copying their results. A caught failure still refuses
the outer metadata operation. Empty catalogs are valid; duplicate keys and NULL keys or
labels are errors. Static selections and callable field-value conversion keep
their existing behavior: a callable catalog is not a generic membership constraint.
catalog retains the caller’s model/field/record rights, company and active context,
and database snapshot. It supports stored text projections and direct stored scalar
domains/orders with literal or principal-parameter operands. Custom nodes, opaque
SQL/query operands and nested domain values refuse before optimization. Relational
traversal, hierarchy/access operators and nonstored
projection fields refuse; they do not trigger arbitrary computed callbacks. Pending
writes are prepared before capability entry. SQL limits candidates and suppresses
oversized strings before the driver receives them. There is no cross-transaction
catalog cache.
The capability exposes environment inspection, emit, catalog, resolve and
charge. It exposes no mutable transaction, raw SQL, create/write/unlink, flush,
commit-hook registration or transaction control. Native Rust is trusted executable
code: cooperative charging does not sandbox arbitrary CPU, allocation, files or
network access. Untrusted executable providers require a separate script/Wasm
budget; #[selection] is currently native-only.
Search domains for nonstored fields
Section titled “Search domains for nonstored fields”A nonstored compute can declare search_method and a synchronous
#[search_method] provider. The provider receives a validated operator/value
request and a read-only context, and returns a bounded domain instead of
loading and filtering records. The ordinary addon MRO supports an explicit
FieldSearchSuper continuation. ADR 0086 is accepted in substance and remains
Proposed until the designated lead merges it. See search-method contracts and examples.
Outbox checkpoint limitations during schema upgrade
Section titled “Outbox checkpoint limitations during schema upgrade”Stored-compute backfills that can change eventful physical fields are not supported
yet. Schema planning refuses them before applying planned DDL or backfill writes,
including a non-eventful source whose computed dependencies reach an eventful model.
A previously queued backfill is checked against the current registry on resume.
The error says that capture of the stored-compute backfill is not available yet. No request
identity is substituted for a system upgrade origin. Keep affected addons from
opting into events until this system-origin boundary and the lead’s other pre-opt-in
follow-ups are delivered. Fresh creation of a table without a backfill is separate.
An existing table that holds no row is admitted: the new column is added, nothing is
backfilled and no event is written, because there is no record to report. A table
whose rows were deleted but not yet vacuumed away is still refused, because the check
after the column is added looks at the table’s physical size; a VACUUM of the table normally gives those pages
back (it skips that step when it cannot take the lock), after which the sync is admitted.
An eventful model may have at most 128 fields with a column of its own table (id not
counted), because one event lists at most 128 changed field names. A model above that
limit, including one an extension makes eventful or one a custom field pushes over it,
is refused when the registry is built, with an error naming the model, the addon that
opted it in, the count and the limit. Whether wide models such as journal entries get a
larger bound is an open lead decision.
Frozen ABI1 generic guest create/write calls are subject to the same native-field refusal as direct guest CRUD, even when the called model has only native methods. Host/RPC calls to entirely native chains still accept the native scalar types. When a WASM override is present in a create/write chain, explicit native-field writes are refused for every caller before native hooks or lossy argument conversion. Ordinary neighboring fields remain usable; no whole-model activation ban applies.
See also: Tracked fields (tracking = true | <sequence> and the change capture).
Read-audit model declarations
Section titled “Read-audit model declarations”audit_reads = true selects successful RPC reads of the invoked model for independent auditing
(ADR 0167 D4). Use it on native models or extensions, ModelDecl::audit_reads(true),
ModelDef::audit_reads(true), data-only model TOML, or described WASM model arguments.
The default is false. Composition ORs every declaration in the model’s MRO: a false extension
cannot disable a true declaration. Abstract mixins contribute to concrete descendants, and
transient models may opt in. Delegation alone does not transfer the flag. A registry rebuild
recomputes it from the currently loaded declarations.
A selected read remains READ ONLY. Its result is buffered until an independent read_ok attempt
commits; audit failure withholds the result with erp.audit_unavailable and does not rerun the
successful method. Operator policy can widen selection, and request context cannot disable it.
This flag does not grant read access or admit additional principal kinds to RPC.
Column collation
Section titled “Column collation”A stored Char or Text field can select byte ordering explicitly:
use erp_sdk::prelude::*;erp_sdk::addon!(name = "collation_example", depends = ["base"]);#[model(name = "collation_example.item")]pub struct Item { #[field(char, collation = "C")] pub code: Option<String>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }The closed choices are "C" and "default". Omission inherits an earlier declaration;
otherwise it uses the database default. An extending addon can select collation = "default"
to reset an inherited C. Native FieldDecl::collation and owned FieldDef::collation use the
same names; data-only model fields accept a string collation property. Unknown names and
nontext, translated, company-dependent or nonstored storage are refused at registration.
Locale and ICU collations are not available.
C compares bytes in the database encoding. In UTF-8 this agrees with code-point ordering, not natural-language order. It does not normalize Unicode or make equality case-insensitive. PostgreSQL case conversion and character classification also use collation; selecting C is not a promise of Unicode case folding. Ordinary column indexes inherit the column’s collation.
Schema sync compares catalog identities, including when the database itself defaults to C. Changing an ordinary stored column’s choice runs transactional DDL and can rebuild indexes; use a maintenance window when the normal schema admission requires one. It preserves existing varchar width when a narrower declaration would otherwise be ignored. Dependent database objects can refuse an alteration, and the operation must then roll back. Existing generated outputs require explicit migration for collation changes; fresh outputs support the declaration. A view’s explicitly declared output collation must match its installed output. Only the owning addon and admitted co-owners can change a protected stored field’s collation.
For an existing generated output without an explicit collation declaration, its recorded installed provenance remains authoritative, including a trusted owner migration. An explicit declaration is checked against that identity before automatic sync; catalog-only drift still refuses.