Schema objects
postgrelize extensions
Sections marked postgrelize extension describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the extensions page.
QueryInterface creates more than tables: extensions, sequences, views, functions, triggers and row-level security policies. These are PostgreSQL features, so they are additions to Sequelize v6 (except createFunction and createTrigger, which v6 has too). Object names are always quoted identifiers; the few places that take SQL text are listed in Security.
Extensions postgrelize extension
await queryInterface.createExtension('pg_trgm', { ifNotExists: true });createExtension(name, { ifNotExists, schema, version, cascade }) and dropExtension(name, { ifExists, cascade }). The database role needs the privileges PostgreSQL requires for that extension.
Sequences postgrelize extension
await queryInterface.createSequence('invoice_number', { start: 1000, increment: 1 });
const first = await queryInterface.nextval('invoice_number');
await queryInterface.setval('invoice_number', 5000);
const afterSet = await queryInterface.nextval('invoice_number');
await queryInterface.alterSequence('invoice_number', { restartWith: 1, cycle: false });
await queryInterface.dropSequence('invoice_number');createSequence(name, { dataType, start, increment, minValue, maxValue, cache, cycle, ownedBy, ifNotExists }):minValue/maxValueacceptfalseforNO MINVALUE/NO MAXVALUE; numbers arenumberorbigintand must be whole.alterSequence(name, { restartWith, increment, ... }),dropSequence(name, { ifExists, cascade }).nextval(name)andsetval(name, value, isCalled = true)return the value as text, so bigint values stay exact.
Sequences of autoIncrement and identity columns are created by sync; use these methods for standalone counters.
Functions and triggers postgrelize extension
createFunction, dropFunction, renameFunction, createTrigger, dropTrigger and renameTrigger have the Sequelize v6 names and argument order, so v6 migrations run unchanged.
await queryInterface.createFunction(
'touch_post',
[],
'trigger',
'plpgsql',
'NEW."updatedAt" := now(); NEW.edits := OLD.edits + 1; RETURN NEW;',
['VOLATILE'],
{ force: true },
);
await queryInterface.createTrigger(
'posts',
'posts_touch',
'before',
['update'],
'touch_post',
[],
['FOR EACH ROW', 'WHEN (OLD.title IS DISTINCT FROM NEW.title)'],
);- The function
bodyis SQL you write. It is wrapped inBEGIN ... END;like v6 and is not escaped: never build it from user input. The same holds for aWHEN (...)clause in the trigger options. See Security. - A function name given as a string (
'touch_post','app.touch_post') is an unquoted identifier that folds to lower case, like v6. Use{ name, schema }for an exact, quoted name. - Parameter and variable names and the language are identifier words. Types (
'integer','varchar(10)','text[]','SETOF users') and keywords ('IMMUTABLE','SECURITY DEFINER','COST 10','FOR EACH ROW','DEFERRABLE') are checked against strict patterns and allowlists; anything else throws before SQL is sent. - Trigger arguments are literals:
createTrigger(table, name, 'before', ['insert'], 'f', ['a', 1])rendersEXECUTE FUNCTION f('a', 1). v6 rendered typed parameter declarations, which PostgreSQL rejects. - New options:
dropFunction/dropTriggeracceptifExistsandcascade;createTriggeracceptsreplace(CREATE OR REPLACE TRIGGER, PostgreSQL 14+). - Timing is
'before' | 'after' | 'instead_of' | 'after_constraint'(a deferrableCONSTRAINT TRIGGER); events are'insert' | 'update' | 'delete' | 'truncate'.
Views and materialized views postgrelize extension
await queryInterface.createView('edited_posts', 'SELECT id, title FROM posts WHERE edits > 0', {
replace: true,
});
await queryInterface.createMaterializedView(
'post_stats',
'SELECT 1 AS k, count(*)::int AS posts, sum(edits)::int AS edits FROM posts',
);
await sequelize.query('CREATE UNIQUE INDEX post_stats_k ON post_stats (k)');
await queryInterface.refreshMaterializedView('post_stats', { concurrently: true });createView(name, query, { replace, temporary, recursive, columns, checkOption, securityBarrier, securityInvoker }),dropView(name, { ifExists, cascade }).createMaterializedView(name, query, { ifNotExists, columns, using, withData }),refreshMaterializedView(name, { concurrently, withData }),dropMaterializedView(name, { ifExists, cascade }). PostgreSQL has noOR REPLACEfor materialized views.concurrentlyneeds a unique index on the view and cannot be combined withwithData: false.- The
queryis SQL you write. It is not escaped: never build it from user input. See Security. View and column names are quoted identifiers. - A model can read a view like a table (
freezeTableNameortableName,timestamps: false). - A
temporaryview lives only as long as its database session, which is one pooled connection: create and use it in one transaction (transactionoption).
Row-level security postgrelize extension
await queryInterface.enableRowLevelSecurity('posts', { force: true });
await queryInterface.createPolicy('posts', 'edited_only', {
command: 'select',
using: { edits: { [Op.gt]: 0 } },
});
await queryInterface.alterPolicy('posts', 'edited_only', { using: 'edits >= 0' });enableRowLevelSecurity(table, { force })anddisableRowLevelSecurity(table, { noForce }).forcealso subjects the table owner to the policies; superusers and roles withBYPASSRLSare never subject to them.createPolicy(table, name, { command, kind, roles, using, withCheck }):commandis'all'(default),'select','insert','update'or'delete';kindis'permissive'(default) or'restrictive';rolesare role names or'public','current_user','current_role','session_user'.alterPolicy(table, name, { roles, using, withCheck, rename }),dropPolicy(table, name, { ifExists, cascade }).- A string condition is SQL you write: not escaped, never build it from user input. A where object (
{ edits: { [Op.gt]: 0 } }) compiles like a partial-index condition and its values are escaped as literals. See Security. - Policies usually read a per-request setting. Set it with the
settingsoption of a transaction (Sessions) and refer to it withcurrent_setting('app.tenant_id')::int.
Unlogged and temporary tables postgrelize extension
const Cache = sequelize.define(
'Cache',
{ key: DataTypes.TEXT },
{ tableName: 'cache', unlogged: true },
);
await Cache.sync();
await sequelize.transaction(async (transaction) => {
await queryInterface.createTable(
'scratch',
{ n: DataTypes.INTEGER },
{ temporary: true, transaction },
);
await sequelize.query('INSERT INTO scratch (n) VALUES (1)', { transaction });
});unlogged: true(oncreateTableoptions and on the model options used bysync) creates anUNLOGGEDtable: writes skip the write-ahead log, so they are faster, but the table is emptied after a crash and is not replicated. Use it for caches and staging data.temporary: truecreates aTEMPORARYtable that exists only for the database session and is dropped when the connection closes. A pool hands out different connections, so create and use the table inside one transaction (passtransaction), or run with a single connection. A temporary table cannot have aschema, and it cannot be combined withunlogged.- Existing tables are not converted:
sync({ alter: true })does not change the persistence of a table that already exists.