Sequences: names, period keys and wait modes
Status: implemented. The design is in ADR 0048 D2.2/D2.8 and
docs/design/m3-base-a-seq-widen.md; the behaviour is specified in docs/specs/base/sequence-widen.md
(SPEC-SEQ-001..014).
ir.sequence draws numbers from a counter row (H21). An addon that keeps its own counter, such as the
accounting chain table of the accounting numbering service, still needs two things H21 knows: how to render a document name such as
INV/2026/00001, and which period a date belongs to, so the counter restarts at the right time. The
erp_sdk::sequence module gives both as pure functions: no transaction, no database access.
Declaring a pattern and rendering names
Section titled “Declaring a pattern and rendering names”use erp_sdk::Date;use erp_sdk::sequence::{SequencePattern, SequenceReset};
fn main() -> erp_sdk::Result<()> { let invoices = SequencePattern::builder(SequenceReset::Year) .prefix("INV/") .padding(5) .build()?; let date = Date::from_ymd(2026, 3, 12).expect("valid date"); assert_eq!(invoices.render(1, date, None)?, "INV/2026/00001"); // numbers wider than the padding widen; they never wrap assert_eq!(invoices.render(123_456, date, None)?, "INV/2026/123456"); // the reset period: the counter of the 2026 chain is separate from 2027's assert_eq!(invoices.period_key(date, None)?.as_str(), "2026"); Ok(())}The five reset rules are Odoo’s: Never, Year, Month, YearRange (fiscal year, 15-16) and
YearRangeMonth (15-16/03). Their period keys are never, 2026, 2026-07, 2025-26 and 2025-26-07.
Parts you do not set take Odoo’s starting formats: four-digit years for Year and Month, two-digit years for
the fiscal rules, / before the counter, - between the two fiscal years. Change them with year_digits,
date_separator, month_separator and number_separator. build() refuses a pattern whose names would be
misread later, for example a Never pattern with the prefix INV/2026/, which Odoo’s grammar reads back as a
yearly sequence. It also refuses padding above 64, more than 128 bytes of fixed text, line breaks, and digits in a
separator or the suffix. Each error names the part that is wrong.
Fiscal years
Section titled “Fiscal years”The fiscal rules need the company’s fiscal year that contains the date. You compute it (Odoo:
res.company.compute_fiscalyear_dates) and pass it in. There is no default, because a guessed fiscal year
silently gives the wrong number:
use erp_sdk::Date;use erp_sdk::sequence::{FiscalYear, SequencePattern, SequenceReset};
fn main() -> erp_sdk::Result<()> { let d = |y, m, day| Date::from_ymd(y, m, day).expect("valid date"); let bills = SequencePattern::builder(SequenceReset::YearRangeMonth) .prefix("BILL/") .padding(4) .build()?; // a fiscal year that ends on 15 April splits April into two periods let fy24 = FiscalYear::new(d(2023, 4, 16), d(2024, 4, 15))?; let fy25 = FiscalYear::new(d(2024, 4, 16), d(2025, 4, 15))?; assert_eq!(bills.render(1, d(2024, 4, 10), Some(&fy24))?, "BILL/23-24/04/0001"); assert_eq!(bills.render(1, d(2024, 4, 17), Some(&fy25))?, "BILL/24-25/04/0001"); // without a fiscal year the call fails and names what is missing assert!(bills.render(1, d(2024, 4, 17), None).is_err()); Ok(())}A calendar fiscal year renders the same year twice (26-26), as Odoo does.
Reading a pattern from an existing name
Section titled “Reading a pattern from an existing name”Imports and hand-typed names arrive without a declared pattern. SequencePattern::infer_from_name reads the
pattern and reset rule the way Odoo’s sequence.mixin does. It is tested against more than 700 names whose
expected values come from Odoo’s own code:
use erp_sdk::sequence::{SequencePattern, SequenceReset};
fn main() -> erp_sdk::Result<()> { let p = SequencePattern::infer_from_name("MISC/15-16/01/0001")?; assert_eq!((p.reset(), p.prefix(), p.padding()), (SequenceReset::YearRangeMonth, "MISC/", 4)); // a store code is not a year and month let p = SequencePattern::infer_from_name("SHOP/0510/00042")?; assert_eq!((p.reset(), p.prefix()), (SequenceReset::Never, "SHOP/0510/")); // a name without digits keeps its text as the prefix let p = SequencePattern::infer_from_name("INV/ABC/")?; assert_eq!((p.reset(), p.prefix(), p.padding()), (SequenceReset::Never, "INV/ABC/", 0)); Ok(())}Names longer than 256 bytes are refused. Only ASCII 0-9 count as digits.
Gapless sequences: the wait mode
Section titled “Gapless sequences: the wait mode”A gapless ir.sequence (implementation = 'no_gap') locks its row for each draw. Its wait_mode field decides
what happens when another transaction holds the row:
wait_mode | Lock | When the row is held |
|---|---|---|
nowait (default, Odoo) | FOR UPDATE NOWAIT | the draw fails at once: Lock, SQLSTATE 55P03, not retried |
lock_timeout | FOR UPDATE | the draw waits, at most the unit of work’s lock_timeout (10 s by default) |
In lock_timeout mode, when the holder commits, the waiting draw fails with Concurrency/40001. This is how
PostgreSQL reports it at REPEATABLE READ, because the row changed after the waiter’s snapshot. Orm::run then
runs your unit of work again, and the new attempt draws the next number. Keep such draws inside Orm::run and
near the end of the unit, so a retry repeats little work. If the limit runs out first, the error is Lock/55P03
with Condition::LockTimeout, and its message names the sequence. Match on the condition, not on the SQLSTATE.
The wait mode does not apply to standard sequences, which take no row lock. An unknown stored value is an error;
the draw never falls back to nowait.
Standard sequences on a server that may not create database objects
Section titled “Standard sequences on a server that may not create database objects”A standard sequence creates, changes and removes a PostgreSQL sequence object with its record. When the server’s
database role may not do that while it runs (as on a deployment, where only installs and upgrades create
objects), the database refuses the statement for missing privilege. That refusal is a UserError, not a database
error: it says the server cannot create (change, remove) database sequences while it runs and that the “No gap”
implementation works. Every other database error of these statements passes unchanged. Only code meets this
refusal: users, the administrator included, may read sequences but not create, change or remove them, so their
request is refused by access first. Numbering an addon creates
at run time should therefore be gapless (implementation = 'no_gap', usually wait_mode = 'lock_timeout');
numbering created by an install or upgrade may stay standard. Inventory does this for operation types
(the Inventory topology guide, “Numbering made while the server runs”).
Drawing a number
Section titled “Drawing a number”A document that takes its number from an ir.sequence record (a sales order, a purchase order, a transfer) draws
it with one of two calls of erp_sdk::sequence, inside the transaction that saves the document:
| Call | Draws from |
|---|---|
draw_by_code(tx, env, code, company, date) | the sequence with code of company; when that company has none, the shared one (no company) |
draw_by_id(tx, env, sequence_id, date) | the sequence record sequence_id, for a document that stores its sequence in a many2one |
use erp_sdk::sequence::{draw_by_code, draw_by_id};use erp_sdk::{CompanyId, Date, Env, Result, Transaction};
/// The name of a new order of `company`, dated `date`.async fn order_name( tx: &mut Transaction, env: &Env, company: CompanyId, date: Date,) -> Result<String> { draw_by_code(tx, env, "sale.order", company, Some(date)).await}
/// The name of a new transfer of an operation type whose sequence is record `sequence_id`.async fn transfer_name(tx: &mut Transaction, env: &Env, sequence_id: i64) -> Result<String> { draw_by_id(tx, env, sequence_id, None).await}
fn main() { let _ = (order_name, transfer_name);}- Who may draw. The caller’s environment needs read access on
ir.sequence; internal users (base.group_user) have it, as in Odoo. Write access is not needed: the counter and a new date range are written by the framework. Without read access the call fails withAccess. In superuser mode the check passes. - Company. Pass the document’s company (
CompanyId::new(id)?from itscompany_id). Its own record wins over the shared one. A company the environment may not use is refused withAccess.draw_by_iddraws a shared record for everyone and a company’s record only when that company is one of the selected companies of the environment, as a read of the record would decide; otherwiseAccess“The sequence 42 belongs to a company that is not one of the selected companies.” Superuser mode draws whatever the company. (Odoo has no company rule onir.sequenceand draws by id whatever the company.) - Date.
Nonetakes the context’sir_sequence_date, else today. A sequence withuse_date_rangethat has no range for the date gets one for that year, between its neighbours, as Odoo creates it. - Refusals. No sequence for the code, neither the company’s nor a shared one:
UserError“No sequence with the code ‘sale.order’ exists for company 3 or for all companies.” A missing record:UserError“The sequence 42 does not exist.” Neither call returns an empty string or a placeholder, so a document is never saved without its number. (Odoo’snext_by_codereturnsFalsehere;erp_orm::sequence::next_by_codekeeps that answer asNonefor parity, thedraw_*calls refuse.) - Concurrency. Two transactions never receive the same number. A
standardsequence draws from a PostgreSQL sequence without a row lock: the numbers of transactions that roll back are lost, so the series has gaps. Ano_gapsequence locks its row (or its date range) until the transaction ends, so drawers take turns as described in the wait mode:nowaitrefuses the second drawer at once,lock_timeoutmakes it wait andOrm::runretries it. Draw near the end of the unit of work.
There is no client route to draw a number: numbers are drawn by model code (the order’s create), never by an RPC
call from the web client.