Skip to content
ERPForAll DocsDevelopment

    Exclusion constraints and range fields

    Status: implemented. ERPForAll only: Odoo checks overlapping periods in Python after the write (hr.version._check_dates), so two concurrent transactions can both pass, or takes a row lock (resource.calendar.attendance). Here the database enforces the rule.

    Every Rust example in this guide is compiled and run as a doctest of erp-test-models (cargo test --doc): the declarations go through the registry and ORM checks a server runs at startup. Lines starting with # are hidden setup.

    An exclusion says: no two records whose equal fields are equal may have overlapping periods. The period is two stored date or two stored datetime fields, period = ("from", "to"), with bounds:

    • bounds = "[)": the start is included, the end is not, so a booking that ends at 11:00 and one that starts at 11:00 do not overlap (the usual choice for datetimes);
    • bounds = "[]": both ends are included, so two stays that share a day overlap (the usual choice for whole days).

    bounds has no default. A NULL end is unbounded: a booking without a stop is open-ended and overlaps every later booking of the same resource. A filter (a constant domain) limits the rule to the records it matches, here the ones that are not cancelled.

    A NULL in an equal column never conflicts (PostgreSQL treats NULLs as distinct), so two records without a resource may overlap. Make the field required, or add a filter such as [('resource_id', '!=', False)] to state that records without one are outside the rule on purpose.

    # erp_sdk::addon!(name = "booking");
    use erp_sdk::prelude::*;
    #[model(name = "booking.resource", description = "Resource")]
    pub struct Resource {
    #[field(char, required)]
    pub name: Option<Arc<str>>,
    }
    #[model(
    name = "booking.booking",
    description = "Booking",
    exclusions = [exclude(
    name = "_no_double_booking",
    equal = ["resource_id"],
    period = ("start", "stop"),
    bounds = "[)",
    filter = "[('state', '!=', 'cancel')]",
    message = "This resource is already booked for an overlapping period."
    )]
    )]
    pub struct Booking {
    #[field(many2one, comodel = "booking.resource", required)]
    pub resource_id: Option<RecId>,
    #[field(datetime)]
    pub start: Option<DateTime>,
    #[field(datetime)]
    pub stop: Option<DateTime>,
    #[field(
    selection,
    selection = [("confirmed", "Confirmed"), ("cancel", "Cancelled")],
    default = "confirmed",
    required
    )]
    pub state: Option<Arc<str>>,
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    What the user sees when a booking overlaps another one — in the same transaction or in a concurrent one that committed first — is a validation error with the declared message:

    The database refused the change: This resource is already booked for an overlapping period.

    The server’s DETAIL (the other row’s key values) is never shown: it can name a record the user may not read.

    Empty and inverted periods would overlap nothing and slip past the rule, so they are refused too. create, and write when the other end of the period is already in the transaction, refuse them before any statement; schema sync also adds a CHECK (named <constraint>_period_check) that refuses them in the database, for raw SQL and for writes whose other end was not loaded. Both give the same message, naming the fields’ labels and the model’s description:

    The database refused the change: 'Start' must be before 'Stop' on 'Booking'

    ('Arrival' must not be after 'Departure' for [] periods, where a period of one day is valid.)

    The period check applies to every row, whatever the exclusion’s filter says: an inverted period is always invalid, even on a record the rule leaves out (for example a cancelled booking).

    EXCLUDE USING gist ("resource_id" WITH =, tsrange("start", "stop", '[)') WITH &&) WHERE (...) (daterange for date periods), with the canonical definition in the constraint’s comment, plus the period CHECK. A changed declaration is dropped and re-created on the next sync; an unchanged one is left alone. Equality inside a GiST index needs the btree_gist extension: schema sync installs it (CREATE EXTENSION IF NOT EXISTS btree_gist, a trusted extension the owner role may create) in the same transaction, before the constraint. When the server does not have it, or the role may not create it, the install fails and names the model, the extension and the object.

    Tables above large_table_rows: erp db build-object

    Section titled “Tables above large_table_rows: erp db build-object”

    Building the GiST index takes ACCESS EXCLUSIVE on the table for the whole build and has no online form. When the table already holds more than large_table_rows rows, the install or upgrade therefore refuses to add (or change) an exclusion or a WITHOUT OVERLAPS key and says so:

    cannot add exclusion '_no_double_booking' to 'booking.booking' during the install: table 'booking_booking' has more than 1000 rows and an exclusion constraint has no online build. Run `erp db build-object -d <db> --model booking.booking --object _no_double_booking` in a maintenance window (it holds ACCESS EXCLUSIVE on the table for the build), then retry the install

    Run the command in a window you chose, then retry the install; it finds the object present and does nothing for it:

    Terminal window
    DATABASE_URL="postgres://erp@db.internal/postgres" \
    erp db build-object -d prod --model booking.booking --object _no_double_booking --lock-timeout 60
    • --object is the declared name (_no_double_booking), --lock-timeout the seconds to wait for a lock (1 to 3600, default 30; 0 and larger values are refused at argument parsing). While the build waits for its ACCESS EXCLUSIVE lock, new readers and writers of the table queue behind it: choose a short timeout. --build-timeout (60 to 86400, default six hours, longer than the lock timeout) stops a statement that runs too long.
    • It runs as the role in DATABASE_URL (the owner role), takes the schema lock that schema sync takes, and in one transaction creates btree_gist when needed, adds the period CHECK and the constraint and stores the canonical definition in the comment. Reads and writes of the table wait while it runs. It does not put a running server into maintenance mode.
    • Rows that already break the rule fail it with cannot add exclusion '<name>' to '<model>': existing records conflict, e.g. (<id>, <id>), ... (up to 20 id pairs); nothing is left behind. Fix the rows and run it again. A lock that is not granted within the timeout fails it with a message naming the table and the timeout.
    • An object that is already there with the canonical definition is left alone (the report says so), so running it twice is safe.
    • The registry is composed from the addons linked into the erp binary; from Rust, Orm::build_object(model, object, &BuildObjectOptions) does the same work and returns a BuildObjectReport.

    A filter is a domain in list syntax over the model’s own stored scalar, selection, boolean and many2one fields, with =, !=, in, not in (False meaning “not set”) and &, |, !. Its values are literals: no paths (partner_id.country_id), no uid, no context, no ref, no arithmetic. It means exactly what the same domain means in a search, NULL rules included. A filter outside these rules fails the ORM’s startup:

    exclusion '_no_double_booking' on 'booking.booking': filter [('resource_id', '=', uid)]: only literal values are allowed, found the name 'uid'

    Exclusions compose by name like the other table objects: an addon adds one with #[extend], and a later declaration with the same name replaces an earlier one. A model file (models/*.toml) or an overlay never replaces an object a Rust declaration made: the registry refuses the build naming both sources, so choose another name.

    # mod booking {
    # erp_sdk::addon!(name = "booking");
    # use erp_sdk::prelude::*;
    # #[model(name = "booking.booking", description = "Booking", addon = "booking")]
    # pub struct Booking {
    # #[field(integer, required)]
    # pub room: i32,
    # #[field(date)]
    # pub arrival: Option<Date>,
    # #[field(date)]
    # pub departure: Option<Date>,
    # }
    # }
    # erp_sdk::addon!(name = "booking_rooms", depends = ["booking"]);
    use erp_sdk::prelude::*;
    use booking::Booking;
    #[extend(
    Booking,
    exclusions = [exclude(
    name = "_one_guest_per_room",
    equal = ["room"],
    period = ("arrival", "departure"),
    bounds = "[]",
    message = "This room is already taken on one of these days."
    )]
    )]
    pub struct BookingRooms;
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON, &booking::ADDON]).check()?;
    # Ok(())
    # }

    date_range and datetime_range store a period in one column (daterange, tsrange). The Rust types are Option<DateRange> and Option<DatetimeRange>; a Range has a lower and an upper end, each optional (None is unbounded), read with the field’s bounds, which every range field declares. A [] date range is stored by PostgreSQL as [lower, upper + 1 day) and read back as declared.

    A key(..., without_overlaps = "<range field>") is PostgreSQL 18’s temporal key: UNIQUE (fields..., range WITHOUT OVERLAPS), here one rate per product for any date. It is a rule, not an upsert key.

    # erp_sdk::addon!(name = "pricing");
    use erp_sdk::prelude::*;
    #[model(name = "pricing.product", description = "Product")]
    pub struct Product {
    #[field(char, required)]
    pub name: Option<Arc<str>>,
    }
    #[model(
    name = "pricing.rate",
    description = "Rate",
    keys = [key(
    name = "_rate_key",
    fields = ["product_id"],
    without_overlaps = "validity",
    message = "A product has one rate for any date."
    )]
    )]
    pub struct Rate {
    #[field(many2one, comodel = "pricing.product", required)]
    pub product_id: Option<RecId>,
    #[field(date_range, bounds = "[)", string = "Validity")]
    pub validity: Option<DateRange>,
    #[field(float)]
    pub amount: f64,
    }
    # async fn example(mut tx: Transaction, product: RecId) -> Result<()> {
    let jan = Date::from_ymd(2026, 1, 1).expect("a date");
    let rates = tx.env().model::<Rate>()?;
    // open-ended: from January on
    let rate = rates
    .create(
    &mut tx,
    vec![
    Vals::new()
    .set(Rate::PRODUCT_ID, product)
    .set(Rate::VALIDITY, DateRange::new(Some(jan), None))
    .set(Rate::AMOUNT, 9.5),
    ],
    )
    .await?;
    let validity: Option<DateRange> = rate.get(&mut tx, Rate::VALIDITY).await?;
    // the rates valid on a day, and those overlapping a period (`false`: unbounded)
    let on_day = rates
    .search(&mut tx, &Domain::field("validity")?.contains("2026-03-01"))
    .await?;
    let from_march = rates
    .search(&mut tx, &Domain::field("validity")?.overlaps("2026-03-01", false))
    .await?;
    # let _ = (validity, on_day, from_march);
    # Ok(())
    # }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    On the dynamic surface (JSON-2, Luau, data files, read), a range is [lower, upper] with false for an unbounded end: ["2026-01-01", false]. Writing anything else (a string, a list of three) is a validation error that names the field and the expected shape. An empty or inverted range is refused with the field’s label:

    The database refused the change: 'Validity' (pricing.rate.validity) is an empty range: its lower end must be before its upper end

    Domains on range fields: overlaps takes a range [lower, upper] (with the field’s bounds), contains a date or datetime, and = False / != False test whether the field is set. Other operators are refused, and so is grouping by a range field. In-memory filtering (filtered_domain) gives the same answers as the database.

    A native addon can still write raw SQL table objects (constraints = [("_name", "EXCLUDE ...", "message")], the Odoo port path). Schema sync does not read raw SQL to guess what it needs: state it with extensions = [...] ("btree_gist", "pg_trgm" or "unaccent"), and schema sync installs them first.

    # erp_sdk::addon!(name = "legacy_booking");
    use erp_sdk::prelude::*;
    #[model(
    name = "legacy.booking",
    description = "Legacy booking",
    extensions = ["btree_gist"],
    constraints = [(
    "_no_overlap",
    "EXCLUDE USING gist (room WITH =, tsrange(start, stop) WITH &&)",
    "This room is already booked."
    )]
    )]
    pub struct LegacyBooking {
    #[field(integer)]
    pub room: i32,
    #[field(datetime)]
    pub start: Option<DateTime>,
    #[field(datetime)]
    pub stop: Option<DateTime>,
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    Data-only addons declare the same typed objects: they name fields, never SQL, so a database-stored package can use them. Unknown keys and raw SQL are errors naming the file and line.

    [[model]]
    extend = "booking.booking"
    [[model.exclude]]
    name = "_no_double_booking"
    equal = ["resource_id"]
    period = { from = "start", to = "stop", bounds = "[)" }
    filter = "[('state', '!=', 'cancel')]"
    message = "This resource is already booked for an overlapping period."
    [[model]]
    name = "pricing.season"
    description = "Season"
    [[model.field]]
    name = "product_id"
    type = "many2one"
    comodel = "pricing.product"
    required = true
    [[model.field]]
    name = "dates"
    type = "date_range"
    bounds = "[]"
    [[model.key]]
    name = "_one_season"
    fields = ["product_id"]
    without_overlaps = "dates"
    message = "Seasons of a product may not overlap."

    Partitioning is declared by native addons only, and business keys without without_overlaps (the keys an upsert uses) are planned.

    A range field without bounds:

    # erp_sdk::addon!(name = "broken_rate");
    # use erp_sdk::prelude::*;
    #[model(name = "broken.rate")]
    pub struct Rate {
    #[field(date_range)]
    pub validity: Option<DateRange>,
    }
    # fn main() {}

    An exclusion without bounds:

    # erp_sdk::addon!(name = "broken_booking");
    # use erp_sdk::prelude::*;
    #[model(
    name = "broken.booking",
    exclusions = [exclude(name = "_x", period = ("start", "stop"), message = "taken")]
    )]
    pub struct Booking {
    #[field(datetime)]
    pub start: Option<DateTime>,
    #[field(datetime)]
    pub stop: Option<DateTime>,
    }
    # fn main() {}

    Registry errors (at startup) name the object, the model and the reason: a field that does not exist or is not stored, a field type = cannot compare (JSON, x2many), period fields of different types, a field listed twice, an empty message, a without_overlaps key on a field that is not a range or without any other field.