Extending other addons, data-only models and custom fields
Status: implemented. Native extension across crates, models/*.toml of data-only addons and custom x_
models and fields reach the registry and the database schema. Installing a data-only addon (module
state, data records) is covered by the module lifecycle; turning ir.model/ir.model.fields rows into an
overlay comes with the work that adds those models (ADR 0026).
Every example here is taken from code that builds and runs in CI:
crates/erp-test-models/addons/test_ext_* (native crates),
crates/erp-modules/tests/fixtures/test_data_only (data-only addon) and the tests
crates/erp-test-models/tests/cross_addon.rs, crates/erp-registry/tests/overlay.rs,
crates/erp-modules/tests/model_files.rs.
For an overview of how Odoo concepts map to ERPForAll and a complete worked example, see Odoo compatibility.
Extending a model from another addon crate
Section titled “Extending a model from another addon crate”Your addon is its own crate. It depends on the crate of the addon it extends, and its manifest and
addon!() name that addon:
[dependencies]erp-sdk = { workspace = true }erp-addon-test_ext_a = { workspace = true }name = "Test Ext B"depends = ["base", "test_ext_a"]use erp_addon_test_ext_a::Book;use erp_sdk::prelude::*;
erp_sdk::addon!(name = "test_ext_b", depends = ["test_ext_a"]);
#[extend(Book)]pub struct BookPages { #[field(integer)] pub pages: i32, #[field(char, string = "ISBN")] pub isbn: Option<Arc<str>>,}
#[methods(Book)]impl BookPages { #[method(override)] async fn describe(this: &RecordSet<Book>, tx: &mut Transaction, sup: Super) -> Result<String> { let pages = this.get(tx, BookPages::PAGES).await?; Ok(format!("{}, {pages} pages", sup.call(tx, this.as_records(), ()).await?)) }}- Inside your crate,
#[extend]and#[methods]need noaddon = "...": they belong to the addon your crate root declares withaddon!(). test_ext_adoes not knowtest_ext_b. Any number of addons extend the same model and the same method;test_ext_cdoes it too, independently oftest_ext_b.- Overrides run newest first in load order (dependency depth, then name): with
a,bandcinstalled,describeruns C, then B throughsup, then A, and returns"book Dune, 412 pages [3/5]". - Field handles of your extension (
BookPages::PAGES: Field<Book, i32>) work onBookrecordsets and inVals<Book>, like the defining addon’s own. - Linking a crate does not install its addon. Only addons in the database’s addon set contribute
fields, columns and overrides. A handle of a linked addon that is not installed fails with
Programming: Invalid field 'rating' on 'test_ext.book'.
Adding selection values and ondelete policies
Section titled “Adding selection values and ondelete policies”When an extension adds values to an existing selection field (via selection_add), each added value can declare an ondelete policy that specifies what happens to records holding that value when the extending addon is uninstalled (SPEC-FIELD-034, SPEC-FIELD-035, SPEC-DATA-029):
use erp_registry::decl::{FieldDecl, SelectionOnDeleteDecl};
FieldDecl::selection_add_ondelete( "state", &[("archived", Some("Archived"))], &[("archived", SelectionOnDeleteDecl::Cascade)],)Native #[field] declarations can bind the existing cleanup metadata directly, for example
#[field(selection, selection_add = [("archived", "Archived")], ondelete = [("archived", "set default")])].
The attribute accepts set null, cascade and set default; required selections must choose a
non-null policy, and set default requires a declared default. Unknown policies and duplicate
cleanup keys are compile errors. The lower-level registry API below also supports explicit
replacement values and callbacks. This native attribute binding does not add selection support
to the WASI descriptor loader, which continues to refuse unsupported selection declarations.
The supported ondelete policies are:
"set null"(SelectionOnDeleteDecl::SetNull): Resets the selection field toNULL/Falseon affected records (the default when no policy is specified). If the selection field is markedrequired,"set null"is rejected at setup with aProgrammingerror (Odoo parity:fields_selection.py:151)."cascade"(SelectionOnDeleteDecl::Cascade): Deletes records holding this selection value via ORMunlink(withforce_delete=true), executing unlink hooks and cleaning up external IDs."set default"(SelectionOnDeleteDecl::SetDefault): Resets affected records to the field’s default value. Setup fails loudly if the field defines no default."set <value>"(SelectionOnDeleteDecl::SetValue("val")): Resets affected records to<value>. Setup fails loudly if<value>is not an existing valid option in the field’s final selection.- Callable / Callback (
SelectionOnDeleteDecl::Callback("callback_name")): Dispatches to an async callback registered onOrmBuilder::selection_callback/Transaction::call_selection_callback(name, ids). Setup fails loudly if the callback name is empty or duplicate.
Uninstall behavior and failure safety
Section titled “Uninstall behavior and failure safety”- Multi-addon preservation: If multiple addons add the same selection value, records are only purged when the last addon providing that value is uninstalled. If another installed addon retains the value, records remain untouched.
- Savepoint isolation and SQL fallback (
safe_write): Selection updates are attempted via the ORM inside a savepoint so model write overrides can execute. If an override raises an error, the savepoint rolls back cleanly and a direct parameterized SQL update (UPDATE ... WHERE id = ANY($1)) is performed. This guarantees that customwriteoverrides cannot block module uninstallation. - Company-dependent selections: Company-dependent selection fields stored as JSONB dictionaries are cleaned across all company keys using batch SQL.
Data-only addons: models/*.toml
Section titled “Data-only addons: models/*.toml”An addon without Rust (a folder with manifest.toml, data files and models/*.toml) declares and
extends models in TOML. The result is the same registry metadata as #[model]/#[extend].
[[model]]name = "test_data_only.tag"description = "Tag"order = "sequence, name"
[[model.field]]name = "name"type = "char"string = "Tag Name"required = true
[[model.field]]name = "sequence"type = "integer"default = 10
[[model.field]]name = "color"type = "selection"selection = [["red", "Red"], ["green", "Green"]]default = "red"[[model]]extend = "res.users"
[[model.field]]name = "tag_id"type = "many2one"comodel = "test_data_only.tag"ondelete = "set null"
[[model.field]]name = "tag_name"type = "char"related = "tag_id.name"Model keys
Section titled “Model keys”| Key | Meaning |
|---|---|
name | a new model (_name) |
extend | extend an existing model in place (_inherit of itself); exactly one of name/extend |
inherit | parent models: prototype inheritance for a new model, extra mixins for an extension |
description, order, rec_name | _description, _order, _rec_name |
table | _table (new models only) |
transient, abstract | the model class of a new model (default: regular). Leave them out on extend: the extension takes the kind of the model it extends (abstract and transient models included); if you state one, it must match |
field | the fields, as [[model.field]] tables |
Field keys
Section titled “Field keys”Every field has name and type. type is one of boolean, integer, float, monetary, char,
text, html, selection, date, datetime, json, many2one, one2many, many2many.
| Key | Types | Meaning |
|---|---|---|
string, help, required, readonly, store, copy, groups | all | as in Odoo |
index | all | true, false, or "btree", "btree_not_null", "trigram" |
default | all | a static value that fits the type: boolean for boolean, integer for integer, number for float/monetary (finite), string for char/text/html/selection/date/datetime; relational and json fields take none. false fits every type: on a field that is not boolean it is Odoo’s “no value” (default=False) |
related | all | a related path; the only computed field allowed here |
size | char | at least 1 (leave it out for no limit; Odoo reads size=0 as no limit) |
digits | float | [precision, scale], scale at most 1000 |
currency_field | monetary | |
selection, selection_add | selection | [[value, label], …]; selection_add also takes [value] to position an existing value |
comodel | relational | required |
inverse | one2many | required |
relation, column1, column2 | many2many | all three or none |
ondelete | many2one, many2many, selection | many2one/many2many: "set null", "restrict", "cascade"; selection: "set null", "cascade", "set default", "set <val>" |
domain, context, check_company | relational | domain in JSON list syntax, context a JSON object |
- Field names are free: TOML fields are declared fields, so they need no
x_prefix. - Unknown keys, values of the wrong type and keys that do not apply to the field type are errors
naming the file and line, e.g.
Model file 'models/test.toml:7': unknown fieldwidget, expected one ofname, …. computeanddependsare refused: in a model file a computed field isrelated.referenceandmany2one_referencefields belong in a native addon.- Files are read in file-name order (prefix them
10_,20_to control it); inside an addon, declarations apply in file, then line order. - Only regular
*.tomlfiles may sit inmodels/; anything else (other files, directories, symlinks) is an error. - Limits: 1 MiB per file, 256 files and 16 MiB per addon, 1000 models per file and 10 000 per addon, 1600 fields per model, 64 parents, 4096 selection entries, names up to 128 bytes, texts up to 16 KiB. Files must be UTF-8.
Loading them (platform code)
Section titled “Loading them (platform code)”use erp_modules::{addon_descriptor, read_manifest_from_dir, read_model_files, ModuleName};use erp_registry::{Overlay, RegistryBuilder};
let name = ModuleName::new("test_data_only")?;let manifest = read_manifest_from_dir(&dir, &name)?.expect("manifest.toml");let addon = addon_descriptor(&manifest)?; // &'static AddonDescriptorlet mut overlay = Overlay::new();overlay.add_addon_defs(read_model_files(&dir, &name)?)?;let registry = RegistryBuilder::new([addon]).overlay(&overlay).build()?;Custom x_ models and fields
Section titled “Custom x_ models and fields”Custom models and fields (Odoo’s ir.model and ir.model.fields with state = 'manual') belong to
one database. They are applied through an Overlay, after every addon:
use erp_registry::{FieldDef, KindDef, ManualModel, Overlay};
let mut overlay = Overlay::new();overlay.add_manual_model(ManualModel::new("x_bananas").description("Bananas"))?;overlay.add_manual_field("x_bananas", FieldDef::new("x_name", KindDef::Char { size: None }).string("Name"))?;overlay.add_manual_field("res.partner", FieldDef::new("x_foo", KindDef::Char { size: None }))?;- Names follow Odoo’s rules, checked when added: models start with
x_and use[a-z0-9_.]; fields start withx_and are PostgreSQL names of at most 63 bytes; each model and each(model, field)pair is unique. The messages are Odoo’s (The model name must start with 'x_'.,Custom fields must have a name that starts with 'x_'!, …) followed by what was refused. - A custom field on a delegation parent (
_inherits) shows up on every child, at any depth, with its column only on the parent. - A custom model whose only name field is
x_nameuses it as_rec_name(itsdisplay_name); anx_activefield archives its records. - Custom fields only add: one may not redefine a field an addon declares. A custom model needs a
table of its own (
x_a.bandx_a_bcannot both exist). - A static default must fit the field type, as in model files.
- A required custom field needs a default when its model’s table already has rows (or, when an
optional field becomes required, while its column holds empty values). Without one the schema
update stops with
cannot update the schema: required field 'test_rel.unit.x_code' has no default and table "test_rel_unit" has rows; …and nothing changes. Odoo only logs a warning there. - A custom field on a model that does not exist, or pointing at a comodel that does not exist, makes
the registry build fail with the model or field named, unless the database is loaded with
ManualFieldPolicy::DropBroken(next section). - A custom related field is checked when the registry is built: every step of the path must exist
(fields of
_inheritsparents included), the steps before the last must be many2one, one2many or many2many fields, and the target must have the field’s type (Type of related field res.partner.x_name_len (integer) is inconsistent with res.partner.name (char)).
Broken custom fields after an addon upgrade
Section titled “Broken custom fields after an addon upgrade”Custom fields live in the database, addons change under them. After an upgrade a custom field can
be broken: a newer addon version declares a field with the same name, the model the field extends is
gone, its comodel is gone, or its related path no longer resolves. By default (Strict) the registry
build fails, naming the field. A server loading a database after an upgrade can choose to leave such
fields out instead, as Odoo does, and gets them back as a typed report:
use erp_registry::{Databases, DropReason, ManualFieldPolicy, RegistryCache};
let dbs = Databases::new(RegistryCache::new());let registry = dbs.load_with("db_a", &addons, overlay, ManualFieldPolicy::DropBroken)?;for dropped in registry.dropped_fields() { // e.g. res.partner.x_code: DeclaredByAddon { addons: ["sale"] } report(dropped.model(), dropped.field(), dropped.reason(), dropped.error());}- Only custom fields are dropped, and only for a reason of their own (
DropReason):DeclaredByAddon(the addon field wins, as in Odoo),UnknownModel,UnknownComodel,Related(path or type),Refused(any other check of that field: one2many inverse, many2one or many2many rules, parameters such as a monetary field without a currency field).error()is the error a strict build gives for that field. - Fields that depend on a dropped one go too: a related field through a dropped many2one, a
one2many whose inverse was dropped, the inherited copies on
_inheritschildren. - Everything else still fails the build: addon declarations, custom models, the same custom field
declared twice (in two overlays, or on a model and on a model inheriting it under a new name),
broken or not, and quotas (
ResourceExhausted). - Nothing is logged instead of reported: read
dropped_fields()and show it (health check, admin notice). The columns of dropped fields are never deleted: they stay in the database, with their data, until the field is fixed or deleted by an administrator. - The policy is kept for the database:
set_overlaybuilds with it too, so a database with a broken field can still change its other custom fields. Only the fields dropped already carry over: an overlay change that would drop any other custom field (a new broken field, or a field the change breaks, e.g. by removing its comodel) is refused with that field’s strict error, before the schema is touched:
// db loaded with DropBroken; res.users.x_old_tag_id is dropped alreadylet mut changed = dbs.overlay("db_a").expect("loaded");changed.add_manual_field("res.users", FieldDef::new("x_new_id", KindDef::Many2one { comodel: "x_new_nowhere".into(), ondelete: None,}))?;let err = dbs.set_overlay("db_a", changed, sync).await.unwrap_err();assert_eq!(err.message(), "Field res.users.x_new_id refers to unknown model 'x_new_nowhere'");RegistryBuilder::manual_fields(ManualFieldPolicy::DropBroken)does the same for a registry built directly (tests, tools).
One registry per addon set and overlay
Section titled “One registry per addon set and overlay”RegistryCache shares one immutable registry between databases with the same installed addons
(names and dependencies) and the same overlay; Databases keeps the registry of each database.
Another database never sees your custom fields.
use erp_orm::{Orm, StaticPolicy};use erp_registry::{Databases, Overlay, RegistryCache};
let dbs = Databases::new(RegistryCache::new());let a = dbs.load("db_a", &addons, Overlay::new())?; // server start: schema already matcheslet b = dbs.load("db_b", &addons, Overlay::new())?; // same Arc as `a`
// custom fields changed: sync the schema with the new registry, then swaplet a2 = dbs .set_overlay("db_a", overlay, |registry| async move { let orm = Orm::builder(registry, pool).policy(policy).build()?; let report = orm.sync_schema().await?; // committed before it returns show(report.kept_comments()); // usually empty, see SchemaStepReport Ok(()) }) .await?; // on any error db_a keeps `a`dbs.cache().drop_unused(); // free registries nobody holdsset_overlayis the only way to install a changed overlay: the new columns exist before any request sees the registry that uses them.loadon a loaded database with a different overlay is refused (database 'db_a' is loaded with another overlay; change it with Databases::set_overlay, …). Oneset_overlayruns at a time per database: a second call while one is applying is refused before it builds anything (an overlay is being applied to database 'db_a' already; wait for it to finish and apply this one again, kindConcurrency). If aloadreplaced the registry while yours synchronized the schema, yours fails with aConcurrencyerror too (the schema was already changed): apply your overlay again.set_overlayis not cancel-safe: run it in its own spawned task (tokio::spawn), never inside a request future that a client disconnect or timeout can drop. Between the committed schema change and the swap, requests still on the old registry can fail; M3 makes the swap live across workers.- Registries come only through
Databases, which charges each database’s own intern quota. Databases::set_overlayis async and not cancel-safe: run it in its owntokio::spawned task, never inside a request future that can be dropped. Composing a registry is CPU work, so build the overlay value itself (and call the synchronousDatabases::load) fromtokio::task::spawn_blocking, not on a runtime worker thread.- Schema updates run with
lock_timeoutat most 10 s andstatement_timeoutat most 5 min (each statement), set before the update waits for anything (a transaction’s lower values are kept, e.g. a module operation’s): a busy table, or another schema update of the same database running longer than the lock timeout (another schema synchronization of this database is running; gave up waiting for it after 10s …, kindLock; the message names the value in force), makes the update fail instead of blocking every request behind it. Try again later. If the commit itself fails because the connection dropped, the outcome is unknown: run the update again.
Runtime definitions are interned for the life of the process (ADR 0026 §2): editing custom fields
many times grows memory a little each time (one chunk of at most 32 fields per edit). Each database
has its own quota (InternAccount, 32 MiB by default, Databases::set_account lowers it before the
first load); a refused change charges nothing. A database over it gets the runtime model declarations of this database use more than … bytes (its intern quota); … (kind ResourceExhausted) while other databases are unaffected.
The process intern budget bounds the whole process: INTERN_BUDGET_BYTES (256 MiB) by default, room
for 8 databases at their full quota. A server with more databases raises it at start:
// each database's full quota on top of the default, for 40 databaseserp_registry::set_intern_budget(erp_registry::intern_budget_for(40)?)?;Over the budget, a definition is refused with runtime model declarations use more than … bytes in this process (its intern budget); … (kind ResourceExhausted). Overlay equality depends on order (it is the field order): load custom models and
fields in ir.model/ir.model.fields id order so equal databases share a registry.