Company-dependent fields
A company-dependent field keeps one value per company. The same record reads one value in company A and another in company B; a company without a value of its own reads the default configured for it. Odoo calls these fields properties. The design is ADR 0163.
Status: the generic ORM support is delivered (storage, create, read and write, defaults, search,
ordering, grouping, drafts and onchange, deletion of referenced records, migration of existing
scalar columns). The operations under What is refused return a named error.
Fields in use today: property_account_position_id on contacts (account), property_stock_customer
and property_stock_supplier on contacts and property_warehouse_id on users (stock). The product
cost is not company-dependent yet; its adoption is separate work.
Do not enable the flag on an existing scalar business field without the migration under Existing data.
Declaring a field
Section titled “Declaring a field”Add company_dependent = true to the field. The Rust type stays the scalar type:
#[extend(ResPartner, addon = "stock", check_company_auto = true)]pub(crate) struct StockPartner { /// Destination used when shipping goods to this contact in the active company. #[field( many2one, comodel = "stock.location", company_dependent = true, check_company = true, string = "Customer location" )] pub property_stock_customer: Option<RecId>,}Reading and writing use the ordinary record API. Every value is the value of the environment’s current company. The public API never accepts or returns the map of all companies.
A field cannot be both translated and company-dependent.
Values and fallbacks
Section titled “Values and fallbacks”- A write stores the value for the current company only. The other companies’ values stay.
- A company without a stored value reads the fallback: the
ir.defaultvalue of that field for the company, or the global one. Defaults are looked up by model and company, not by record. - An explicit null on a nullable field is a value: it suppresses a non-null fallback.
- Writing a value equal to the company’s fallback removes that company’s stored value. A record without any stored value has SQL NULL in the column.
- Boolean and numeric nulls follow their normal conversion (false, zero).
- A required company-dependent field is checked on its effective value. The column stays nullable.
- HTML policy, precision and monetary rounding apply to the scalar before it is stored.
- Exact numbers (a Float with digits, Monetary) are stored as decimal text and never pass through a binary float.
Reads of an existing record use the fallback a superuser would see for the caller’s company. This
grants the caller no access to the record or the field. Ordinary creation defaults (default_get)
keep their usual precedence and the caller’s identity.
Fallbacks are read in the caller’s transaction and kept for that transaction only; they are never
shared between transactions, so an older snapshot never receives a newer fallback. A change of an
ir.default row through the ORM clears them and the computed fields that depend on the company
context; a pending default write is flushed before the lookup.
The fallbacks of a model for a company are read once per transaction and reused by every later create, read, write and query. The first use sends the default lookup, plus one existence statement per target model when a many2one fallback names a record. They are read again after any of these in the same transaction:
- a change of
ir.default,ir.model.fieldsordecimal.precisionrecords through the ORM, or through their_defaultfunctions; - records created or deleted in a model that a many2one fallback points to;
- a statement that names the table it writes (
INSERT INTO …,UPDATE …,DELETE FROM …,MERGE INTO …) when that table holds defaults or a fallback’s target, including rows a database cascade removes; and any rawTRUNCATE,COPY,CALL,DO, DDL orTransaction::batch; Transaction::invalidate_all,invalidate_modelof the target model without a field list, a rollback to a savepoint.
An operation that is already running keeps the fallbacks it started with; the next read, write, create or query reads them again.
Raw SQL the ORM cannot read this way owns its invalidation: after a raw data-changing WITH
(WITH … INSERT, WITH … UPDATE, WITH … DELETE), a SELECT that calls a writing function, or a
trigger that changes ir_default or a fallback’s target table, call
tx.invalidate_ormcache("ir.default") (defaults changed), tx.invalidate_model(<target>, None) (target
rows changed) or tx.invalidate_all().
Without a current company
Section titled “Without a current company”A System environment without a current company can create a record when every company-dependent
field stays unset after the creation defaults. The columns stay SQL NULL and no company is inferred.
A supplied value, including null, false or zero, and a context, field or overridden creation default
that supplies one, needs a validated company; otherwise the call returns Validation with
company-dependent fields require a current company. Reading or writing such a field needs a
current company too.
Support matrix
Section titled “Support matrix”“tested” means at least one test in the binaries listed under Tests exercises that kind in that column. “untested” means composition admits it and no test in those binaries covers it. No cell is a performance statement.
| Field kind | Create, read, write | Search, order, group | Drafts and onchange | Migration helper |
|---|---|---|---|---|
| Char | tested | search, order and group key tested | tested | tested |
| Text | tested | untested | untested | tested |
| Html | tested | untested | tested | tested |
| Boolean | tested | search tested | read from an origin tested | tested |
| Integer | tested | search and sum tested | tested | tested |
| BigInt | untested | untested | untested | untested |
| Float | tested | search tested | untested | tested |
| Float with digits (exact) | tested | sum tested | untested | tested |
| Monetary | tested | equality search and sum tested | untested | tested |
| Selection | tested | search and order tested | untested | tested |
| Date | tested | search tested | untested | tested |
| Datetime | tested | search tested | untested | tested |
| Many2one | tested | search, path, hierarchy and group key tested | tested | tested |
Every other field kind, and a field that is not stored, computed, related, generated, tracked or has an inverse, is refused when the registry is composed.
What is refused
Section titled “What is refused”Each of these returns an error whose text names the follow-up work that will add it. None is silently ignored.
| Operation | Error kind |
|---|---|
| A declaration outside the matrix (other kinds; computed, inverse, related, generated or tracked company-dependent fields) | Programming |
| Upsert on a model that has a company-dependent field | Programming |
| A write hook registered on a company-dependent field | Programming |
A compute that reads a company-dependent field and is stored, or does not depend on the company context | Programming |
| A native selection catalog expression over a company-dependent field | Programming |
| Keyset pagination ordered by a company-dependent field (use offset pagination) | Programming |
| A company-dependent many2one of a draft that points at an unsaved record | Validation |
A non-stored compute that reads a company-dependent field and declares the company context
dependency is supported. A stored output is refused because it would keep the value of whichever
company computed it last.
One further limit is open: the company-setting adapters of SPEC-FIELD-084 (a company field kept in
step with a company-dependent default) are not built. A restrict reference written while its
target is being deleted is covered, see
A write and a deletion at the same time.
Flush, rollback and concurrent writers
Section titled “Flush, rollback and concurrent writers”A flush sends only the changed companies’ entries, and the database merges them into the stored map in one statement. A mutation keeps the company and the environment it was made in; flushing through another environment does not move it to that environment’s company. Changing the origin flushes the earlier pending mutation before the new one is staged. A rollback (of the transaction or of a savepoint) discards the pending entries and their baselines.
Two transactions that write the same row conflict, also when they write for different companies:
the row is one row. The later one fails with kind Concurrency and SQLSTATE 40001, the
database’s serialization failure. Nothing of it is stored. Retry the complete
transaction; after the retry both companies’ values are stored. Orm::run and
Orm::run_with_options do this: they roll back, discard the cache and run the unit of work again in
a new transaction, within a bounded number of attempts. Code that opens a transaction by hand
retries by hand. Writers of different rows do not conflict.
Nothing here uses a process-local lock, so the rule is the same on one node and on several.
Drafts and onchange
Section titled “Drafts and onchange”New records (Transaction::new_record, the records of a form’s onchange) support company-dependent
fields. A draft keeps a company map in its cache, like a stored record, and nothing of it reaches the
database:
- An explicit value, or a field default, is the environment’s company value. Another company reads its own fallback.
- A draft without value or origin reads the company fallback (the
ir.defaultvalue for that company). A firstonchangecall returns it as the default, the same valuedefault_getgives. - A draft with an origin (an edit form) reads the origin’s value in every company. Writing on the draft, also from an onchange method, changes the writing environment’s company only, in the cache.
- Switching the environment’s company on a draft is allowed: the read projects that company’s entry.
- A non-stored compute over the field that depends on the
companycontext recomputes in the draft when the value changes. Onchange values have the same wire shape asweb_readof a stored record. - Saving goes through
createorwrite, which store the caller’s company value only. Write commands of draft lines (x2many_commands) carry that scalar, never a map. - A draft’s read is checked on its origin like a read of the stored record: an origin the reader may not read refuses with the same Access error.
- A company-dependent many2one cannot point at an unsaved record (Validation): a map stores database ids only.
Reading the company-dependent fields of a draft from its origin uses the stored record’s prefetch read; the test prints both statement counts.
Deleting a referenced record
Section titled “Deleting a referenced record”A company-dependent many2one is a reference inside a JSON map, not a foreign key, so the ORM runs the referential action itself when it unlinks the target. This happens for every caller, not only an elevated one, and it looks at the rows of all companies whatever the caller may see.
- Every refusal is decided first, then every cleanup runs; a refused deletion changes nothing.
- A
restrictfield with a reference stored for any company refuses the deletion. The message (“You cannot delete a record used by a company-dependent field”) names neither the holder nor the company, because the caller may not be allowed to see either. - A fallback set in
ir.defaultfor a company-dependent many2one to the record refuses it too, naming the field. An ordinary many2one default does not block: it is discarded with the record. Theforce_deletecontext key skips both refusals and the references are then cleared, but only for an elevated environment (the module loader’s purge). Any other caller’sforce_deleteis ignored and the refusals apply, and the RPC layer refuses the key from clients outright (Odoo honours it from any context; this is deliberate). - Every other reference is set to null in its map. The other companies’ entries stay.
cascadeon a company-dependent field behaves as set null: the holder row is never deleted. - Fields that depend on a cleared reference recompute on the next read, and cached maps are dropped.
- A target removed by a database cascade (its parent was deleted) does not run these checks, as in Odoo. References to it read as empty from then on.
A reference whose target no longer exists reads as empty (an empty recordset, False, None), and
a search for an empty value finds it. It never falls back to the default: a missing override means
“no value”, not “use the default”. The same holds when the default itself names a missing record.
A default that names a missing record is not a creation default either: default_get does not offer
it and a create does not store it, so the new record reads like every record without a value of its
own. When the missing record was a user’s own default, the company’s fallback is offered instead.
Reads do not rewrite the stored map; a dangling entry is simply not reported. A record rule
on the target does not change this; existence is checked directly in the database.
A write and a deletion at the same time
Section titled “A write and a deletion at the same time”A restrict field also holds when one transaction stores a reference while another deletes the
target (SPEC-CRUD-068; Odoo checks without a lock, BUG-147). Nothing is declared for it: the ORM
does the work for every company-dependent many2one with ondelete = "restrict".
- Storing a reference (create or write) locks the target row the way a foreign key does and records
the reference in two ORM tables,
erp_company_ref_guardanderp_company_ref_link. This costs one extra statement per such field in eachINSERTorUPDATEbatch that changes it. Removing the value, or deleting the holder withunlink, removes the recorded reference. - Deleting the target locks it first, so it waits for a write in flight. When a reference was
committed after the deletion’s snapshot, the deletion fails with a
Concurrencyerror (SQLSTATE40001).Orm::runand the RPC layer retry that error; the retry sees the reference and returns the usual refusal. Code that opens a transaction by hand handlesConcurrencyas for any other statement. - A write that waits for a deletion which then commits fails with
Concurrencytoo. Its retry stores the id of a record that no longer exists, unless the code reads the target first; that is allowed for any id and reads as empty (above). - The first reference a record ever gets creates its guard row. A second transaction that stores
a reference to the same record, and whose snapshot is older than that first commit, fails once
with
Concurrencyand succeeds on its retry. Later references to the record do not conflict with each other. - Limits:
set nullandcascadefields are not guarded; a reference stored there while its target is being deleted reads as empty, as after the cleanup. A map written with SQL outside the ORM has no link row, so only the scan protects it. A target removed by a database cascade runs none of this (above). A default inir.defaultcommitted while the record is being deleted is not seen by that deletion. Link rows of holders that a database cascade removed stay until their target is deleted; they change no result.
Search, order and grouping
Section titled “Search, order and grouping”Search and count evaluate the current company’s effective scalar value. Ordering, group keys, aggregates and HAVING use the same expression and logical SQL type. Missing company keys inherit prepared defaults, while explicit JSON null suppresses them. A missing row on an optional relation join stays absent; it does not inherit the missing model’s defaults. Relation traversal and principal user paths use the effective many2one ids, and a dangling target compares as absent. Exact values cast to PostgreSQL numeric without passing through binary floats. A query that touches only ordinary fields prepares nothing.
The ORM prepares defaults for the models the expression reads and binds company and fallback values per query component. Bound values are not stored in shared filter or order caches. Default changes, rollback and separate transaction snapshots follow the read rules above. Orders over a company-dependent field are compiled per query; ordinary orders keep the existing order memo.
Direct compiler use
Section titled “Direct compiler use”Direct erp_sql callers use company::CompanyValues with compile_where_with_company or the
context-aware order entry points. Supply normalized typed fallback cells after company authorization
and the field’s ordinary precision/HTML admission. Positive-ID validation in this pure compiler is
not authorization. Context-free compiler entry points still support ordinary fields and refuse a
referenced company-dependent field with a Programming error naming its missing prepared company
values. Constant DDL predicates also refuse them because they have no current-company context.
The context and its individual values share a 16 MiB payload admission limit. This is a resource
limit, not a measured memory cost. Values remain parameters; query text contains registry-derived
identifiers and fixed logical casts. A btree_not_null prefilter is added only when conservative
fallback evaluation proves it cannot remove matches. Unknown relation visibility or patterns omit
that prefilter. No index-performance claim is made.
Storage utilities
Section titled “Storage utilities”erp_orm::company_dependent provides pure scalar encode/decode, effective project, single-company
apply and map delta functions. They perform no database access and grant no access to another
company. Runtime callers must authorize the company, record and field and admit precision/HTML policy
before encoding. Public record values remain scalar; raw maps are an internal storage format.
Maps use positive canonical company IDs as keys. Missing keys inherit the supplied fallback; explicit JSON null suppresses it. Fallback-equal updates remove their key, and empty maps become SQL NULL. Decimal values use normalized decimal text and never pass through f64. Fractional JSON numbers are refused for Decimal storage; migrate such legacy values through exact PostgreSQL text. Dates use canonical four-digit-year date strings. Datetimes use canonical UTC strings, with a six-digit fractional suffix when microseconds are nonzero. Storage decoding rejects abbreviated or trailing date/time strings; dynamic input conversion remains the caller’s responsibility.
A map admits at most MAX_COMPANIES entries and MAX_MAP_BYTES key/scalar payload bytes, charging
64 bytes per entry in addition to key and string lengths. These are safety limits, not measured
memory-use claims. Direct scalar decoding also enforces the byte ceiling. Map mutation validates
before cloning; a delta can contain removals from the old map plus changes from the new map, so its
entry/payload upper bound is the sum of two admitted maps. Invalid map keys, nested values and wrong
scalar kinds return errors without including hidden company values.
delta returns [value] for a set (including null) and [] for removal. Pass these validated deltas
to erp_sql::version::VersionedUpdate::merge_company; translation merge_json has different null
semantics. The statement atomically patches the existing database map and has its own cache identity.
A SQL NULL patch is empty, not a request to clear every company. Company merge takes precedence if
a caller names the same column in both merge lists; callers should select exactly one operation.
Existing data
Section titled “Existing data”Do not change a populated scalar column to a company map with an implicit type cast. Its adoption must define the companies owning the old value. The installer’s current company is not a data-ownership policy.
Existing JSONB columns are not proof of compatible storage. Schema initialization validates all non-null values against the field’s map codec before applying schema changes, including on repeat initialization. Incompatible shapes, keys, scalar types or exceeded admission limits return Validation naming the field and an explicit migration requirement. Values are not included in the error. Valid maps and SQL NULL remain unchanged. An operator must migrate incompatible data with an explicit ownership policy before retrying; neither a translation marker nor the installer’s company establishes that policy.
Explicit predecessor migration
Section titled “Explicit predecessor migration”Changing an existing scalar business field requires a native pre migration in a newer addon
version. Use erp_sdk::migrations::CompanyMigrationPolicy with
tx.migrate_company_dependent(model, field, &policy). An explicit company set assigns each existing
non-null scalar to those companies; row_company("company_id") uses a stored ordinary Many2one to
res.company on the same table. Shared rows with a non-null scalar and no owner refuse. SQL NULL
stays SQL NULL. The installer’s active/allowed companies do not select owners.
The helper is trusted native migration code; it is not an RPC operation. It runs under the upgrade transaction and schema/table locks. Never commit inside a migration. Exact numeric values remain exact JSON strings; false, zero and empty text remain explicit historical overrides. Conversion does not prune values against current defaults. Existing valid maps keep their owners on repeat; explicit helper normalization changes an empty map to SQL NULL. Ordinary schema admission keeps valid maps unchanged. Invalid maps and populated reverse conversion refuse; there is no automatic conversion from a company map back to a scalar.
Operator checklist for an adoption upgrade
Section titled “Operator checklist for an adoption upgrade”- Inventory custom constraints, indexes and dependent views on the column. Known ORM scalar foreign keys are removed when a Many2one becomes a company map. Unsupported custom dependencies refuse and must be handled by a separately reviewed migration; the helper never drops their rules silently.
- Keep a backup and rehearse the version upgrade on a disposable clone.
- Run the upgrade. A lock or validation failure is an upgrade failure: the previous data and schema are kept. Resolve the cause and retry the whole upgrade from the retained predecessor.
- Coordinate runtime activation through the existing deployment procedure; the helper alone cannot make an older binary compatible with the new storage format.
Lookup costs, bytes per row and index gains of this feature are not measured. Performance acceptance is DEFERRED_PERFORMANCE until the milestone end (ADR 0065). Tests print statement counts where that helps a reader; one count is asserted.
A create on a model with a company-dependent many2one sends one statement, the INSERT, once one create
in the same transaction has warmed the caches, with or without an ir.default for the field
(SPEC-FIELD-087, asserted by tests). The first create of a transaction also sends the default lookups,
and one existence statement per target model when a fallback names a record, because fallbacks are not
shared between transactions (see Values and fallbacks).
crates/erp-test-models/tests/company_dependent_acceptance.rs: values and fallbacks per company (the whole SPEC-FIELD-075 case), product-like exact cost, partner-like relation, a real user’s company isolation, concurrent writers with retry, rollback, statements of a create.crates/erp-test-models/tests/company_dependent_create_queries.rs: one statement for a warmed create, and every way the prepared fallbacks are read again (defaults changed through the functions, the ORM or raw SQL, a target removed by raw SQL or a cascade, savepoint rollback, a second company, another transaction’s commit, a restricted read).crates/erp-test-models/tests/company_dependent_runtime.rs: create, read, write, defaults, cache, access, drafts and onchange.crates/erp-test-models/tests/company_dependent_query.rsandcrates/erp-sql/tests/company_dependent_query.rs: search, order, grouping, the direct compiler.crates/erp-test-models/tests/company_dependent_relations.rs: deletion and dangling references.crates/erp-test-models/tests/company_dependent_restrict_lock.rs: arestrictreference stored while its target is deleted.crates/erp-test-models/tests/company_dependent_schema.rs,crates/erp-test-models/tests/company_dependent_schema_migration.rsandcrates/erp-modules/tests/company_dependent_migration.rs: existing data and migration.crates/erp-orm/tests/company_dependent_codec.rsandcrates/erp-test-models/tests/company_dependent_delta_sql.rs: the codec and the merge statement.
Spec cases: SPEC-FIELD-075, 076, 085, 086, 106 to 110, SPEC-REL-015, SPEC-CRUD-035, SPEC-CRUD-068 and SPEC-COMPMIG-001 to 004. SPEC-FIELD-075, SPEC-FIELD-076, SPEC-FIELD-087, SPEC-FIELD-108, SPEC-FIELD-109 and SPEC-CRUD-035 carry a whole-case test tag; the others are covered in part. SPEC-FIELD-084 is not implemented.