Skip to content
ERPForAll DocsDevelopment

    Keys, upsert and row versions

    Status: implemented (ADR 0040 “ORM primitives for scale” D1–D3, design note docs/design/m3-ormx.md (docs/design/m3-ormx.md, not part of the published documentation) §3–§4, spec docs/specs/orm/orm-scale.md (docs/specs/orm/orm-scale.md, not part of the published documentation) SPEC-ORMX-001..015). Odoo has none of these: a stock balance there is a row lock plus a merge job, and a stale edit silently overwrites. Every Rust block below is compiled as a doctest of erp-test-models (as in Models, fields and method overrides). Model declarations run a composition check; the async call examples are compiled but their bodies are not executed by that setup. Lines starting with # are hidden setup.

    A business key is a named UNIQUE NULLS NOT DISTINCT constraint over columns of the model’s own table. A NULL part is a value (“no lot”), so two quants without a lot for the same product and location conflict:

    # erp_sdk::addon!(name = "stock");
    use erp_sdk::prelude::*;
    #[model(name = "stock.location", description = "Location")]
    pub struct Location {
    #[field(char, required)]
    pub name: Option<Arc<str>>,
    }
    #[model(
    name = "stock.quant",
    description = "Quant",
    row_version = true,
    keys = [key(
    name = "_quant_key",
    fields = ["product_ref", "location_id", "lot_ref"],
    message = "A quant already exists for this product, location and lot."
    )]
    )]
    pub struct Quant {
    #[field(char, required)]
    pub product_ref: Option<Arc<str>>,
    #[field(many2one, comodel = "stock.location", required)]
    pub location_id: Option<RecId>,
    #[field(char)]
    pub lot_ref: Option<Arc<str>>,
    #[field(float, digits = 0)]
    pub quantity: Decimal,
    #[field(float, digits = 0)]
    pub reserved_quantity: Decimal,
    #[field(datetime)]
    pub in_date: Option<DateTime>,
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    Stock quantity examples use unrounded exact decimals (digits = 0), as required by stock addon admission.

    • The key also becomes an associated constant, Quant::QUANT_KEY (the name without its leading _, upper-cased), for Upsert::on.
    • Schema sync creates it as ALTER TABLE stock_quant ADD CONSTRAINT stock_quant_quant_key UNIQUE NULLS NOT DISTINCT (product_ref, location_id, lot_ref) (the table-object naming rule) and keeps the definition as the constraint’s comment; a changed declaration re-creates it.
    • On an existing table with more rows than SchemaSyncOptions::large_table_rows (100,000 by default), a new key puts nothing in the install transaction (the ADD CONSTRAINT would hold ACCESS EXCLUSIVE on the table while it builds the unique index). Two steps run after the commit, in order: key_index.<constraint> (CREATE UNIQUE INDEX CONCURRENTLY, writes go on) and key_constraint.<constraint> (ADD CONSTRAINT ... UNIQUE USING INDEX, a short lock, no scan). Until both have run, an upsert naming the key fails with Database “business key ‘<name>’ of ‘<model>’ is not usable yet: its post-commit steps have not completed (pending or failed; …)”. If rows already duplicate the key, step 1 fails with Validation “cannot add key ‘<name>’ to ‘<model>’: existing records conflict, e.g. (<id>, <id>)” (up to 20 pairs of ids), cleans up its invalid index and leaves the table as it was; fix the rows and sync again.
    • A key whose declaration changes on such a table is refused before any DDL (UserError): there is no online replacement that keeps the old key enforced and arbitrating correctly while the new one builds. Drop the old constraint in a window you choose and sync again; the new key is then built by the two steps.
    • A row that duplicates the key fails with Validation and The database refused the change: <message>, from create, write and raw SQL alike.
    • nulls_distinct = true gives a plain UNIQUE (rows with NULL parts never conflict). Such a key still enforces uniqueness, but it cannot arbitrate an upsert.
    • Key fields are stored columns of the model’s own table: not inherited through _inherits, not x2many, not id or row_version, not a float without digits (inexact) and not JSON. The registry refuses anything else when it is built, naming the key and the field.
    • An addon adds a key to a model it does not own with #[extend(Model, keys = [...])]; a later declaration of the same name replaces the key.

    records.upsert(tx, Upsert::on(KEY)...) inserts the rows whose key is new and updates the others in one statement per batch (1,000 distinct keys per statement, OrmConfig::insert_batch), and returns one entry per input row, in input order:

    # erp_sdk::addon!(name = "stock");
    # use erp_sdk::prelude::*;
    # #[model(name = "stock.location", description = "Location")]
    # pub struct Location {
    # #[field(char, required)]
    # pub name: Option<Arc<str>>,
    # }
    # #[model(name = "stock.quant", description = "Quant", row_version = true,
    # keys = [key(name = "_quant_key", fields = ["product_ref", "location_id", "lot_ref"],
    # message = "A quant already exists for this product, location and lot.")])]
    # pub struct Quant {
    # #[field(char, required)]
    # pub product_ref: Option<Arc<str>>,
    # #[field(many2one, comodel = "stock.location", required)]
    # pub location_id: Option<RecId>,
    # #[field(char)]
    # pub lot_ref: Option<Arc<str>>,
    # #[field(float, digits = 0)]
    # pub quantity: Decimal,
    # #[field(float, digits = 0)]
    # pub reserved_quantity: Decimal,
    # #[field(datetime)]
    # pub in_date: Option<DateTime>,
    # }
    # async fn example(mut tx: Transaction, stock: RecId, now: DateTime) -> Result<()> {
    let quants = tx.env().model::<Quant>()?;
    let row = |product: &str, quantity: Decimal| {
    quants
    .vals()
    .set(Quant::PRODUCT_REF, product)
    .set(Quant::LOCATION_ID, stock)
    .set(Quant::LOT_REF, None::<Arc<str>>)
    .set(Quant::QUANTITY, quantity)
    .set(Quant::RESERVED_QUANTITY, Decimal::ZERO)
    .set(Quant::IN_DATE, now)
    };
    let out = quants
    .upsert(
    &mut tx,
    Upsert::on(Quant::QUANT_KEY)
    .rows([row("P1", Decimal::from(5)), row("P2", Decimal::from(-2))])
    .update([Quant::IN_DATE]) // overwrite when it differs
    .accumulate(Quant::QUANTITY) // existing + row value
    .accumulate_floor(Quant::RESERVED_QUANTITY, Decimal::ZERO), // GREATEST(0, existing + value)
    )
    .await?;
    for row in out.rows() {
    let (_id, _outcome, _before): (RecId, UpsertOutcome, Option<i64>) =
    (row.id(), row.outcome(), row.previous_version());
    }
    let _records: &RecordSet<Quant> = out.records(); // the distinct upserted records
    # Ok(())
    # }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    What the call does:

    • Outcomes. Inserted for a new key, Updated when an update field differs or an accumulate delta is not zero, Unchanged otherwise (the row is not written: no new tuple, no version bump, write_date untouched). previous_version() is None for inserted rows and for models without row versions; for an unchanged row it is its current version. Without update and accumulate the call is get-or-create.
    • Every row sets every key field (a NULL part counts as set), every update field and every accumulate field (a delta, never NULL). Key fields cannot be updated on conflict.
    • Duplicates in one call are merged before the statement, as sequential calls would end: update fields take the last row’s value, accumulate fields are summed with checked arithmetic, every other field keeps the first row’s value. accumulate_floor cannot merge duplicates (its floor applies per call): split such rows over calls.
    • Accumulation adds to the existing value (a NULL counts as 0). A sum out of the column’s range fails with Validation naming the field (… the new value of 'Count' (count) on 'Quant' is out of range). accumulate_floor stores GREATEST(floor, existing + value) on updates; a new row whose value is below the floor fails the call (nothing can be committed).
    • Defaults. Static field defaults fill the fields a row leaves out (inserted rows only). A field whose default is computed — a default function, a sequence, a default_<field> context key — must be given explicitly: the statement would evaluate it before it knows which rows are new, and a sequence would lose numbers on updated rows. Required stored computed fields must be given too. default_get overrides do not run.
    • Concurrency. Two transactions that upsert the same new key both succeed: the second waits for the first, fails with a serialization failure under REPEATABLE READ and Orm::run retries it, so accumulate ends at the sum and no duplicate row exists.
    • What runs afterwards. The cache holds the written values; stored computes of inserted rows and dependents of updated fields recompute at the next flush; #[constrains] methods run for the written fields; write hooks get the old values. create and write overrides do not run: that is the contract of declaring a key. Logic that must see every change overrides upsert itself, which is a dispatched method:
    # erp_sdk::addon!(name = "stock");
    # use erp_sdk::prelude::*;
    # #[model(name = "stock.location", description = "Location")]
    # pub struct Location {
    # #[field(char, required)]
    # pub name: Option<Arc<str>>,
    # }
    # #[model(name = "stock.quant", description = "Quant",
    # keys = [key(name = "_quant_key", fields = ["product_ref", "location_id"], message = "Duplicate")])]
    # pub struct Quant {
    # #[field(char, required)]
    # pub product_ref: Option<Arc<str>>,
    # #[field(many2one, comodel = "stock.location", required)]
    # pub location_id: Option<RecId>,
    # #[field(float, digits = 0)]
    # pub quantity: Decimal,
    # }
    #[extend(Quant)]
    pub struct QuantAudit {
    #[field(integer)]
    pub upserts: i32,
    }
    #[methods(Quant)]
    impl QuantAudit {
    #[method(override)]
    async fn upsert(
    this: &RecordSet<Quant>,
    tx: &mut Transaction,
    call: UpsertCall,
    sup: Super,
    ) -> Result<UpsertResult> {
    // before: `call.rows()`, `call.update()`, `call.accumulate()`; `call.rows_mut()` to adjust
    let result = sup.call(tx, this.as_records(), (call,)).await?;
    // after: one entry per input row
    let touched = this.as_records().browse_ids(result.distinct_ids());
    touched.write(tx, RawVals::new().set_cell("upserts", Cell::Int(1))).await?;
    Ok(result)
    }
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }
    • Access follows the create and write checks of ADR 0035, through the same engine entry points: both model-level checks (an API key scoped read_only is refused here); the write rule over the existing rows of the batch’s keys in one SELECT before the statement (no statement when no rule restricts); the create rule on the inserted rows in one SELECT after it. A denied row fails the whole call with the engine’s record-level text; after the statement the transaction cannot commit. A denied existing row the caller may not read is never named: the call fails with the key’s own message (The database refused the change: A quant already exists for this product, location and lot.), as a create of that key would; the Access error is raised only for rows the caller can read. An upsert on a policy table (ir.access, groups) is a policy write: pending writes are flushed first and the transaction rebuilds its policy before its next decision. A read-only transaction refuses the call. A field outside the caller’s write mask is not checked yet.
    • Every row the upsert matches must be readable by the caller, including for get-or-create and an accumulate of 0, because the result reports ids, versions and values; otherwise the call fails with the key’s own message and no id. Rows with one key are merged: update takes the last row’s value, accumulate sums, any other field keeps the first row’s value (a field only a later duplicate gives is dropped for a new key). The access pre-check also denies a row the upsert would leave unchanged. Make the leading key column required: a nullable leading column cannot use the key’s index in the upsert’s joins. While expect_versions expectations are pending for the model the upsert is refused.
    • Server-set fields cannot be given: id, create_uid, create_date, write_uid, write_date (on models with log access), row_version and parent_path in a row, in update or in accumulate are a Programming error such as 'stock.quant.create_date' is set by the server and cannot be written. (Odoo’s create drops such values silently; the upsert refuses them.)
    • Not supported: models with _parent_store, x2many values in rows, fields inherited through _inherits, keys declared nulls_distinct (each is a Programming error naming the reason).
    • Untyped surface. Overrides and dynamic callers use UpsertCall (UpsertCall::new("_quant_key").with_rows(..).with_update([..]).with_accumulate(..)) with Records::upsert; Records::upsert_values(tx, key, rows, update, accumulate) takes rows as {field: value} maps (Luau, data files). JSON-2 exposure is separate.

    Statements (ceilings, ADR 0007): 0 for an empty batch; 1 per batch without a restricting rule; +1 for a restricting write rule, +1 for a restricting create rule (a refusal adds the engine’s evidence statements); then the model’s normal recompute flush.

    row_version = true (on the model or on an extension; it cannot be turned off later) is opt-in: a model that does not declare it has no column and no trigger, because the trigger costs about +10 % of a statement’s executor time (docs/bench/ormx-row-version.md). It adds an int8 NOT NULL field row_version, readonly and not copied. Every UPDATE of the row bumps it by exactly one: the ORM’s flush, recompute and upsert statements set row_version + 1 themselves, and a BEFORE UPDATE trigger that schema sync creates (<table>__row_version) bumps it for any other SQL — raw SQL, migrations — and corrects an explicit value. Read it like write_date, through the Base::ROW_VERSION handle or read:

    # erp_sdk::addon!(name = "stock");
    # use erp_sdk::prelude::*;
    # #[model(name = "stock.note", description = "Note", row_version = true)]
    # pub struct StockNote {
    # #[field(char)]
    # pub body: Option<Arc<str>>,
    # }
    # async fn example(mut tx: Transaction, id: i64, version_the_client_read: i64) -> Result<()> {
    let note = tx.env().model::<StockNote>()?.browse([id])?;
    let _version: i64 = note.get(&mut tx, Base::ROW_VERSION).await?;
    // optimistic concurrency: fail instead of overwriting a change someone else made meanwhile
    let record = note.rec_ids()[0];
    note.expect_versions(&mut tx, [(record, version_the_client_read)]).await?;
    note.set(&mut tx, StockNote::BODY, "edited").await?;
    tx.flush().await?; // ErrorKind::Conflict when the stored version moved
    # Ok(())
    # }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }
    • expect_versions sends nothing: the next flush UPDATE that writes the record also requires row_version = <expected> (0 extra statements when it matches). When it does not, one SELECT tells the two cases apart: a stale record fails with ErrorKind::Conflict (Record 'Note' (stock.note) 7 was changed by someone else since you read it (version 2, now 3). Reload it and apply your change again.), a deleted one with Missing.
    • Conflict answers JSON-2 with status 409 and the name erp.conflict. It is never retried by Orm::run (a retry cannot make the edit current); a concurrent change that commits while the transaction is open first surfaces as a serialization failure, the retry then reports the Conflict.
    • An expectation is consumed by the first flush that writes the record; later flushes in the same transaction already hold the row lock and do not check again.
    • A caller value for row_version — in create, write, an upsert row or an import — is a Programming error: 'stock.note.row_version' is set by the server and cannot be written.
    • expect_versions on a model without versions is a Programming error ('<model>' has no row version (declare row_version = true)).

    A WriteHook registered on the ORM (OrmBuilder::write_hook, HarnessBuilder::write_hook in tests) receives the old and new values of the fields it names for every row a flush UPDATE or an upsert update writes, from that statement’s own RETURNING (no extra statement); models nobody hooks keep the plain UPDATE. Tracking and the outbox are built on it:

    use erp_sdk::{BoxFuture, Result, Transaction, WriteBatch, WriteHook};
    fn track_quantity<'a>(_tx: &'a mut Transaction, batch: &'a WriteBatch) -> BoxFuture<'a, Result<()>> {
    Box::pin(async move {
    for row in batch.rows() {
    // one (old, new) pair per field of batch.fields(), for record row.id()
    for (old, new) in row.values() {
    assert_ne!(old, new, "record {} was written", row.id());
    }
    }
    Ok(())
    })
    }
    const TRACK: WriteHook = WriteHook::new("stock.quant", &["quantity"], track_quantity);
    # fn main() { std::hint::black_box(TRACK); }