Skip to content
ERPForAll DocsDevelopment

    Migrations: upgrading an addon's data and schema

    Migrations: upgrading an addon’s data and schema

    Section titled “Migrations: upgrading an addon’s data and schema”

    Status: implemented. The design is in ADR 0009 §5 and §7 and docs/design/m2-s5.md; the behaviour is specified in docs/specs/modules/module-system.md (SPEC-MOD-036..039).

    When an installed addon is upgraded to a newer version, its migrations run inside the upgrade’s transaction (ADR 0009 §2): a failing migration aborts the whole upgrade and nothing of it is kept. A migration is either a Rust function marked #[erp_sdk::migration] or a .sql file under migrations/<version>/. Odoo’s migrations/<version>/<stage>-*.py modules with a migrate(cr, version) function do not exist here; the rules for selecting and ordering them are the same.

    An upgrade from the installed version I to the manifest’s version T runs:

    • every migration of a version V with I < V <= T;
    • every migration of version 0.0.0, on any upgrade where I < T.

    A fresh install runs no migration, and neither does a reinit (an upgrade that reloads the addon in init mode). Versions are compared in their semver form (ADR 0009 §5): 1.1 and 20.0.1.1 are both 1.1.0, 1.1.2 is 1.1.2. So if the installed version is 1.0.0 and the manifest now says 1.3, the migrations of 1.1, 20.0.1.2 and 1.3 run, 1.0 and 1.4 do not.

    StageRunsVersion order
    prebefore the addon’s schema is updated and its data files are loaded: its new tables and columns do not exist yet, use SQL0.0.0 first, then ascending
    postafter the addon’s schema update and data files, on the updated registryascending, then 0.0.0 last
    endafter every addon of the operation was loaded (upgraded addons in load order)ascending, then 0.0.0 last

    Within one version and stage, the Rust and SQL migrations run together, ordered by name (a Rust migration’s name defaults to its function name). Each migration receives the previously installed version in its semver form (1.0.0, not Odoo’s '20.0.1.0').

    When one operation upgrades several addons (base with yours, for example) and your addon has a pre migration selected in it, the schema update of an addon that comes earlier in the operation does not change a table your addon creates or adds a column, index or table constraint to. That table is updated at the step of the last addon of the operation that adds to it and has a selected pre migration, after that addon’s pre migrations ran. So your pre migration sees the table as the installed versions left it, and can add and fill a new required column; the schema update then makes it required. Without a selected pre migration nothing waits: the table is updated at the earlier addon’s step, as on any upgrade.

    While a table waits, every change of it waits, the new columns of the earlier addon’s version included: in that operation, the earlier addon’s data files and post migrations cannot write a column its new version adds to such a table.

    erp_sdk::addon!(name = "library", depends = ["base"]);
    use erp_sdk::migrations::SemverVersion;
    use erp_sdk::{BoxFuture, Result, Transaction};
    /// Fill the new `isbn` column from the old `code` (version 1.1, after the schema update).
    #[erp_sdk::migration(addon = "library", version = "1.1", stage = post)]
    async fn fill_isbn(tx: &mut Transaction, _from: &SemverVersion) -> Result<()> {
    tx.execute("UPDATE library_book SET isbn = code WHERE isbn IS NULL", &[])
    .await?;
    Ok(())
    }
    /// Runs on every upgrade (version 0.0.0), after all addons were loaded; `from` says which
    /// version the database had.
    #[erp_sdk::migration(addon = "library", version = "0.0.0", stage = end)]
    async fn recount(tx: &mut Transaction, from: &SemverVersion) -> Result<()> {
    if *from < SemverVersion::new(1, 1, 0) {
    tx.batch("REFRESH MATERIALIZED VIEW library_book_counts").await?;
    }
    Ok(())
    }
    /// A plain function must already have the `MigrationFn` type; `name` sets the name that orders
    /// it among the steps of the same version and stage.
    #[erp_sdk::migration(addon = "library", version = "1.1", stage = pre, name = "pre-rename")]
    fn rename_code<'a>(tx: &'a mut Transaction, _from: &'a SemverVersion) -> BoxFuture<'a, Result<()>> {
    Box::pin(async move {
    tx.batch("ALTER TABLE library_book RENAME COLUMN ref TO code").await
    })
    }
    fn main() {}

    The attribute takes addon, version and stage (pre, post or end, written in lower case, bare or as a string) and an optional name. The build of the addon fails, on the offending token, for a missing, unknown, repeated or empty argument, an unknown stage, a method, a function with type parameters, an unsafe function, or an async fn that does not take (&mut Transaction, &SemverVersion). When the module system starts, a version that is not a migration version (0.0.0, x.y, x.y.z or 20.0.x.y) and two migrations of one addon with the same version, stage and name are errors naming the source locations.

    Put the scripts in the addon folder, one folder per version:

    library/
    manifest.toml
    migrations/
    1.1/
    pre-rename.sql runs before the schema update
    post-fill.sql runs after the data files
    0.0.0/
    end-reindex.sql runs on every upgrade, after all addons were loaded

    A file runs when its name is <stage>-<anything>.sql; other files are ignored. Its name without the .sql extension orders it (post-fill). The text is sent as one batch of statements in the upgrade’s transaction.

    A script must not end or open that transaction. When a selected script is read, before any of it is sent, a statement that starts with BEGIN, START, COMMIT, END, ROLLBACK, ABORT, SAVEPOINT, RELEASE or PREPARE TRANSACTION refuses the upgrade with Error::MigrationSqlRefused naming the file and the statement. The same words inside strings, quoted identifiers, comments and dollar-quoted bodies are fine. A BEGIN ATOMIC function body is refused as well: write the body as a dollar-quoted string. A script that ends inside a string or comment is refused. Transaction control inside DO or a procedure fails in PostgreSQL itself (SQLSTATE 2D000). Scripts are read with standard string rules, so a script runs only while the session’s standard_conforming_strings is on (PostgreSQL’s default). Rust migrations follow the same rule: they run in the upgrade’s transaction and never commit, roll back or open one (they are not scanned; the module system detects an ended transaction after the step, when a commit can no longer be undone).

    One operation selects at most max_migration_files SQL files (all its addons together, default 4096), and one addon’s migrations/ holds at most that many version folders. A file past the count is refused before it is read (Error::MigrationFilesTooMany, Error::MigrationFoldersTooMany); the selected files’ bytes count against max_operation_data_bytes with the data files (Error::OperationDataTooLarge). A folder named tests, hidden folders and folders whose name is not a version are not read (the last ones log Invalid version for upgrade script). Only the folders the upgrade selects are read; their files follow the data-file rules (modules.md, “Data files”): regular files only, no symbolic links, one hard link, at most max_data_file_bytes, UTF-8. SQL migrations are read from an addon’s development folder; an embedded or packaged addon uses Rust migrations.

    The upgrade stops, its transaction rolls back, and the modules keep their state and installed version. The error is Error::StepFailed naming the module, the stage and the step (the SQL file’s path or the Rust function’s file:line); its source is Error::MigrationFailed with the module, version, stage and name, whose source is the function’s error or the SQL statement’s (its SQLSTATE kept):

    Module "library": post migration 'migrations/1.1/post-fill.sql' failed
    caused by: Module 'library': migration 'post-fill' (version 1.1.0, stage post) failed
    caused by: <the database error>

    An upgraded addon whose stored row has no installed version (latest_version is empty) while it has migrations is refused with Error::InvalidModuleRow: the migrations cannot be selected without it.

    Pre migrations run before schema synchronization and upgrade data files; Post migrations run afterward. If an old writable catalog becomes noupdate, protect its existing external IDs in Pre. Changing the new file’s pragma or marking old IDs in Post cannot undo values already overwritten during the upgrade. Base1.1 uses Pre for currency/language protection and Post for company representatives that require the new schema. A failure later in the operation rolls back both stages, schema and data together. Test a genuine old installation, new missing records, tenant customizations and a later injected failure, without rewinding module version markers.

    Use an explicit native pre-migration when a scalar field becomes company-dependent:

    use erp_sdk::{Result, Transaction};
    use erp_sdk::migrations::{CompanyMigrationPolicy, SemverVersion};
    #[erp_sdk::migration(addon = "library", version = "1.2", stage = pre)]
    async fn assign_legacy_cost(tx: &mut Transaction, _from: &SemverVersion) -> Result<()> {
    let policy = CompanyMigrationPolicy::row_company("company_id")?;
    tx.migrate_company_dependent("library.book", "cost", &policy).await
    }
    # fn main() {}

    Alternatively, CompanyMigrationPolicy::companies([1, 2]) explicitly assigns old values to both companies. Supply verified tenant identities, never an installer-context default. Missing ownership of a non-null value refuses; shared rows need an explicit company-set decision. The target registry must declare the field company-dependent. Version bump, pre-migration, schema/data loading and later steps share the upgrade transaction: a later failure rolls the conversion back. Repeating the helper on valid maps validates them without changing their company ownership. Populated reverse conversion requires a separate reviewed materialization migration.

    Inventory version 1.2 installs database integrity guards and backfills missing location policy rows in the same upgrade transaction. Existing policy identities, flags and audit fields are preserved. Newly backfilled rows have NULL creating/updating users and migration-time timestamps; the migration does not attribute their creation to the historical location creator. New locations copy their insertion row’s creating/updating users into the policy, retaining NULL when a SQL writer supplied none. New locations, including locations inserted through COPY, receive their policy automatically. Independent deletion of a policy is refused; deleting its location may cascade it.

    Stop nodes running an older registry before an upgrade that changes SQL objects, then restart them with the matching build after it commits. A failed migration rolls back its data, installed objects and version marker together. Restore the matching release and database backup when reverting an accepted upgrade; disabling triggers or editing SQL-object provenance is not an upgrade or rollback procedure.

    Inventory 1.6 fills each transfer’s move counters and state from its moves, and 1.7 rebuilds the transfers’ reference projection. Both fills lock the transfer and move tables, but they read the upgrade transaction’s snapshot, taken before the lock (the upgrade runs at REPEATABLE READ). A move or reference link that a node on the older registry commits during the upgrade is missing from the fill, and the triggers installed by the same upgrade only add later changes to the stored values.

    Stop every node on the older registry (or at least its ingress) before this upgrade, as for any upgrade that changes SQL objects. When that was not possible, run each fill once more after the upgrade committed, in a single READ COMMITTED transaction so the snapshot follows the lock:

    psql --single-transaction -f addons/stock/migrations/1.6/post-move-counters.sql <database>
    psql --single-transaction -f addons/stock/migrations/1.7/post-move-references.sql <database>

    Both files are safe to repeat: they set the stored values from the moves and write only rows that differ, so a second run on a complete fill changes nothing.

    Exercise an upgrade through the module lifecycle against a disposable database, with existing rows and the relevant old schema restored. Assert the old state before upgrading: changing only an installed version can leave the new defaults, constraints or triggers in place and hide a missing migration. Check preserved record identities and administrator choices, newly filled values, named constraint refusals, and a second upgrade that preserves the resulting data.

    The CLI’s stock integration tests use this approach for the 1.0.0 shape: missing location policies, nullable reservation lead times, and absent security data and SQL guards. They compare the upgraded security data with a fresh install, and test the shipped policy SQL in a non-UTC session so audit timestamps cannot accidentally use local wall time. A reconstructed fixture retains unrelated current metadata; compatibility with an older executable needs a separate previous-binary rehearsal.