Migrations
Graphile Worker RS stores its database objects in a PostgreSQL schema and tracks
the installed schema revision in a migrations table inside that schema. The
graphile_worker_migrations crate owns this setup and exposes the migration
runner used to install or update the schema.
The public entry point is graphile_worker_migrations::migrate(database, schema).
It accepts a database connection/executor value that can be converted into the
crate database type, plus the schema name to manage.
use graphile_worker_migrations::migrate;
migrate(&database, "graphile_worker").await?;
What migrate does
On each run, the migration runner reads:
- the PostgreSQL
server_version_num - the latest row in
<schema>.migrations - the latest row in
<schema>.migrationsmarked as a breaking migration
If <schema>.migrations does not exist, the runner installs the base schema
tracking objects first:
create schema if not exists graphile_worker;
create table if not exists graphile_worker.migrations (
id int primary key,
ts timestamptz default now() not null,
breaking boolean not null default false
);
After that, it runs every packaged migration whose number is greater than the
latest recorded migration id. Each migration runs in its own database
transaction. The runner inserts the revision and its breaking flag before
executing the migration SQL in that transaction, allowing concurrent migrators
to detect an already claimed revision. It queues a worker:migrate notification
after executing the SQL. PostgreSQL delivers the notification on commit.
Running migrate again after the schema is current is expected to be harmless:
the runner sees the latest recorded revision and skips already-applied
migrations.
Packaged revisions
Migration SQL is bundled in the graphile_worker_migrations crate under
src/sql. At runtime the crate loads those files into the
GRAPHILE_WORKER_MIGRATIONS registry in revision order.
The current package contains revisions 1 through 22. The revisions marked as
breaking in the registry are:
1, 3, 11, 13, 14, 16
The runner supports taking over from an existing Graphile Worker schema as long
as the migrations table accurately records the already-applied revision. For
example, if revision 1 is already present, migrate starts at revision 2.
When an older migration table has only revision IDs and timestamps, the runner
adds the breaking flag and backfills it for known revisions before applying
pending SQL.
Startup guidance
Run migrations before starting workers that enqueue, poll, or execute jobs:
use graphile_worker_migrations::migrate;
async fn boot(database: &Database) -> Result<(), Box<dyn std::error::Error>> {
migrate(database, "graphile_worker").await?;
// Start worker processes only after the schema is installed and current.
Ok(())
}
This is especially important around breaking revisions. The runner refuses to continue if the database has a newer breaking migration than the currently running package supports. For example, a database whose migrations table records a future breaking revision cannot safely be used by an older worker binary.
If the database records a future non-breaking revision, the runner logs a warning and continues. That warning means the database schema is newer than the current package knows about, so all running Graphile Worker RS versions should be checked for compatibility.
Breaking migrations while workers are running
Continuous workers check their own schema after a breaking-migration
notification. They also check on startup and periodically on normal polling
ticks, including with notifications disabled. When the table confirms a
breaking revision beyond the worker's supported revision, the worker stops
claiming jobs, drains or returns work using its configured shutdown policy,
and returns WorkerRuntimeError::IncompatibleSchema.
The live check bounds PostgreSQL statement execution to one second and the whole check, including pool acquisition, to two seconds. An unavailable status read logs a warning and job dispatch continues.
Stop existing workers before applying a breaking migration. Detection happens after the migration commits, so an older worker's completion or return SQL may already be incompatible.
PostgreSQL version check
The migration package requires PostgreSQL 12 or newer. It checks
current_setting('server_version_num') and returns an incompatible-version error
for versions below 120000.
On a fresh schema install, the PostgreSQL version is checked before creating the schema and migrations table. On existing schemas, the version reported while reading migration state is checked before pending migrations are applied.
Locked jobs during migration 11
Migration 11 has a specific guard for locked jobs. If PostgreSQL returns SQL
state 22012 while applying that migration, the runner returns
MigrateError::LockedJobInMigration11.
Before applying a package version that still needs to run migration 11, stop
workers cleanly and make sure jobs and queues are not left locked. Then rerun
migrate.
Custom schemas
The schema argument controls where the Graphile Worker objects are installed:
migrate(&database, "my_worker_schema").await?;
Packaged migration SQL uses the :GRAPHILE_WORKER_SCHEMA placeholder
internally. The migration executor replaces that placeholder with the escaped
schema name before executing each SQL statement.
Separate Migration and Worker Roles
A deployment can use a schema-owning migration role and a more restricted worker
role. Apply migrations with the owner first, then start workers against the
current revision. The worker needs USAGE on the selected schema, table access
for queue operations, sequence access for inserts, and execution privileges on
the schema's functions. The migration ledger must also be readable.
Privileges must cover newly created objects after upgrades (including recovery tables when recovery is enabled); use appropriate default privileges for the role that creates those objects. A restricted worker cannot install a missing schema or apply a pending migration. Provision and validate the grants on an isolated database before rolling out this arrangement.
Migration callbacks
Install a MigrationHooks registry with WorkerOptions::migration_hooks
to run callbacks during worker initialization, or pass it to
WorkerUtils::migrate_with_hooks for a standalone migration. The
graphile_worker_migrations::migrate_with_hooks function also accepts a
Database and schema directly.
use graphile_worker::{DbParams, MigrationHooks, MigrationPhase, WorkerOptions};
let hooks = MigrationHooks::new().on_event(|event| {
Box::pin(async move {
if matches!(event.phase, MigrationPhase::BeforeMigrate) {
event.executor
.execute("set lock_timeout = '10s'", DbParams::new())
.await?;
}
Ok(())
})
});
let worker = WorkerOptions::default()
.database_url(&database_url)
.migration_hooks(hooks)
.init()
.await?;
Bootstrap callbacks surround creation or repair of the migration ledger.
Migrate callbacks run on every compatible migration invocation, including
when no revisions are pending. A failed revision triggers RevisionFailed
after PostgreSQL acknowledges rollback. Each callback receives the schema,
server version, single-session SQL executor and a typed scratchpad scoped
to the invocation. The migrator controls transaction boundaries. Statements
issued by callbacks run in autocommit unless they are part of a single
database statement with its own transactional effects.
Use a direct connection or a pool that preserves a PostgreSQL session for
the entire call. The built-in drivers discard this connection at the end
of the call or on cancellation so settings, locks and temporary tables cannot
leak into application work. Custom drivers need to implement
DatabaseDriver::acquire_session to support callbacks. Callback errors stop
migration, after any earlier committed revisions.