Index kinds
Status: implemented (ADR 0040 D5, design docs/design/m3-ormx.md §6). Field indexes brin and gin,
typed model-level indexes with include and a constant filter (a partial index such as WHERE state = 'open'), from native addons and from models/*.toml.
Every Rust example in this page is compiled and run as a doctest of erp-test-models (cargo test --doc, part of scripts/ci.sh), through the same registry checks a server runs at startup. Lines
starting with # are hidden setup.
Field indexes
Section titled “Field indexes”index on a field takes Odoo’s three kinds and two more:
index = | Index | For |
|---|---|---|
true, "btree" | USING btree (f) | equality, ranges, ordering (the default for many2one fields) |
"btree_not_null" | USING btree (f) WHERE f IS NOT NULL | columns that are mostly empty |
"trigram" | USING gin (f gin_trgm_ops), accent-folded like ilike when that is indexable | ilike substring search; needs the pg_trgm extension |
"brin" | USING brin (f) | date, datetime and integer fields whose values follow the insert order |
"gin" | USING gin (f jsonb_path_ops) | json fields searched by containment (@>) or JSON path (@?, @@) |
# erp_sdk::addon!(name = "events");use erp_sdk::prelude::*;
#[model(name = "event.log", description = "Event log")]pub struct EventLog { #[field(integer, index = "brin")] pub seq: i32, #[field(json, index = "gin")] pub payload: Option<erp_sdk::serde_json::Value>,}
/// The audit field `create_date` of the log gets a BRIN index too: an `#[extend]` may set `index`/// on a field it does not declare, like any other attribute.#[extend(EventLog)]pub struct EventLogDates { #[field(datetime, index = "brin")] pub create_date: Option<DateTime>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }When BRIN helps. A BRIN index stores the smallest and largest value of each block range of the table (128 pages by default), so it is thousands of times smaller than a btree and costs almost nothing to maintain. It only narrows a search when the values in each block range are close together, i.e. when the column follows the order rows are inserted in: creation dates and sequence numbers of append-mostly tables (logs, outbox, audit, posted journal items). On a column that is updated freely, or filled in random order, use a btree.
When GIN helps. jsonb_path_ops indexes the paths and values of a JSON document, so a
containment filter (payload @> '{"tag": "t42"}') reads only the matching rows. It does not serve
key-existence (?) or ordering. The domain operators that use it on json fields arrive with
properties (M4); the index can be declared now.
A kind on a field type it does not fit is refused when the registry is built (and, for #[field],
at compile time):
# erp_sdk::addon!(name = "events");# use erp_sdk::prelude::*;#[model(name = "event.code")]pub struct EventCode { // error: index = "brin" is for date, datetime, integer and bigint fields (this field is char) #[field(char, index = "brin")] pub code: Option<Arc<str>>,}# fn main() {}trigram needs the pg_trgm extension in the database (erp db create installs it). Without it the
install fails before any table is touched, naming the field: field '<model>.<field>' declares index = "trigram", which needs the PostgreSQL extension pg_trgm; it is not installed.
Changing a field’s kind (say from true to "brin") rebuilds its index under the same name at the
next schema sync; an index that already matches is left alone, so a sync that changes nothing
issues no DDL. Removing index keeps the existing index in the database, as Odoo does.
Runtime extension limits. A runtime extension (models/*.toml or overlay) can add an index to an
unindexed native field (one where no index attribute was specified in native code) or declare typed
indexes ([[model.index]]), but it cannot change or drop the index kind of a field already carrying an
index in native code, nor add an index to a field that explicitly declared index = false (which
records kind none). Likewise, a runtime extension cannot change the field type of a natively indexed
field or make it non-stored via store = false, compute, or related. Attempting to violate these
limits fails at registry build with a Programming error naming both declarations and both index kinds
(SPEC-ORMX-034).
Typed indexes on the model
Section titled “Typed indexes on the model”An index over several fields, with another access method or with covering columns, is declared on
the model with index(...) in indexes = [...], next to the raw ("_name", "(a, b)") tuples Odoo
ports use:
# erp_sdk::addon!(name = "booking");use erp_sdk::prelude::*;
#[model( name = "booking.slot", description = "Booking slot", indexes = [ // key (state, start), resource_id stored in the index: a list of a resource's open slots // by date is answered from the index alone (an index-only scan) // only open slots are indexed: a smaller index, and the planner uses it for queries that // filter on state = 'open' index( name = "_open_by_date", fields = ["state", "start"], include = ["resource_id"], filter = "[('state', '=', 'open')]" ), index(name = "_by_stop", fields = ["stop"], method = "brin"), ])]pub struct Slot { #[field(many2one, comodel = "res.users")] pub resource_id: Option<RecId>, #[field(datetime)] pub start: Option<DateTime>, #[field(datetime)] pub stop: Option<DateTime>, #[field(selection, selection = [("open", "Open"), ("cancel", "Cancelled")])] pub state: Option<Arc<str>>,}# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&ADDON]).check()?;# Ok(())# }| Parameter | Meaning |
|---|---|
name | required, starts with _; the index is <table>_<name without _> (shortened to 63 bytes like every table object) |
fields | required, the key fields in order: stored fields of the model’s own table, or id |
method | "btree" (default), "brin" (date, datetime, integer), "gin" (json, jsonb_path_ops), "gist" (scalar and range fields; needs btree_gist, which schema sync installs when the index is declared, from a model file too), "trigram" (char, text, html; needs pg_trgm) |
filter | optional constant domain in list syntax, e.g. "[('state', '=', 'open')]": only matching rows are indexed (WHERE (...)). Literal operands over the model’s own stored fields, operators =, !=, in, not in; anything else is refused when the ORM is built, naming the index and the model |
include | covering fields (stored fields or id), stored in the index but not part of its key; btree and gist only, never a key field |
At most 32 columns in all (PostgreSQL’s limit). Everything is checked when the registry is built;
the errors name the index and the model, for example index '_by_state' of 'booking.slot': method = "brin" is for date, datetime, integer and bigint fields ('state' is char).
Why include. An index-only scan answers a query from the index without visiting the table,
as long as the table’s visibility map says the pages are all visible (after a VACUUM; autovacuum
keeps it so on tables that are not rewritten constantly). include adds the columns the query
returns without making them part of the key, so the key stays small and ordered by what you
filter on.
Across addons. An addon may add typed indexes to a model it does not own, in #[extend], and
may replace one by name: the composed index is the newest declaration’s (load order), exactly like
raw table objects.
# erp_sdk::addon!(name = "booking_reports", depends = ["booking"]);# use erp_sdk::prelude::*;# #[model(name = "booking.slot", addon = "booking")]# pub struct Slot {# #[field(datetime)]# pub start: Option<DateTime>,# #[field(datetime)]# pub stop: Option<DateTime>,# #[field(char)]# pub state: Option<Arc<str>>,# }# pub static BOOKING: erp_sdk::AddonDescriptor = erp_sdk::AddonDescriptor { name: "booking", depends: &["base"], exact_only: false };#[extend(Slot, indexes = [index(name = "_by_start", fields = ["start"], method = "brin")])]pub struct SlotReportIndexes;# fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {# erp_testkit::Harness::builder([&BOOKING, &ADDON]).check()?;# Ok(())# }Schema sync creates a typed index with its definition (INDEX USING btree ("state", "start") INCLUDE ("resource_id")) as the index comment and compares that text at every sync: a changed
declaration drops and recreates the index, an unchanged one issues nothing.
An existing index of the same name without the ORM comment (or from an interrupted build) is compared
by structure (IndexStruct::is_declared):
- When the existing index matches structurally (same method, columns in order,
INCLUDEcolumns, exact PostgreSQL canonicalised filter predicate via temporary probe index, and exact trigram key expressions), only the comment is written (COMMENT ON INDEX ... IS ...), adopting the index without rebuild. The filter comparison creates a temporary probe table, so the schema-sync role needs theTEMPprivilege on the database (PostgreSQL grants it toPUBLICby default). Without it, or when the probe cannot parse the predicate on the existing table, the sync fails withcould not canonicalise index predicate ...and the server’s message; the index is left untouched. - If it differs, a native declaration replaces it (the declaration owns the name) with a warning in the log,
while a runtime declaration (
models/*.tomlor overlay) is refused loudly with aProgrammingerror to avoid silently shadowing or destroying DBA-managed objects.
In models/*.toml
Section titled “In models/*.toml”A data-only addon declares the same typed indexes, with field names only (no SQL), so a package loaded from the database may use them:
[[model]]extend = "booking.slot"
[[model.index]]name = "_by_date"fields = ["start"]method = "brin"
[[model.index]]name = "_open_by_date"fields = ["state", "start"]include = ["resource_id"]Unknown keys, an unknown method, a name without _, a name declared twice in one model, and
filter that is not a string are refused with the file and line; field checks happen when the registry is built, with
the messages above. A model file declares at most 64 indexes per model.
Large tables
Section titled “Large tables”Below large_table_rows (the schema-sync option) an index is built, or replaced when its kind, method,
include or filter changed, inside the install transaction. Above it, a new or replaced index of any
kind (field or typed) is built by a CREATE INDEX CONCURRENTLY step after the install commits, which
does not block writes while it builds: init_models_with plans the steps (SchemaSync::steps) and
sync_schema_with runs them. For a replaced index the step builds the new index concurrently under
a temporary name (<name>__swap) on nonpartitioned tables, verifies it is valid, and then swaps it into place in one short
transaction (DROP INDEX / ALTER INDEX RENAME or DROP CONSTRAINT / ADD CONSTRAINT ... UNIQUE USING INDEX):
the old index keeps enforcing until the atomic swap. Partitioned-table replacement still uses its separate drop-and-rebuild path; it does not have this guarantee. If the build fails,
the existing index remains in place untouched; run the step again once the failure is resolved.