Skip to content

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 ​

ts
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 ​

ts
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 / maxValue accept false for NO MINVALUE / NO MAXVALUE; numbers are number or bigint and must be whole.
  • alterSequence(name, { restartWith, increment, ... }), dropSequence(name, { ifExists, cascade }).
  • nextval(name) and setval(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.

ts
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 body is SQL you write. It is wrapped in BEGIN ... END; like v6 and is not escaped: never build it from user input. The same holds for a WHEN (...) 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]) renders EXECUTE FUNCTION f('a', 1). v6 rendered typed parameter declarations, which PostgreSQL rejects.
  • New options: dropFunction / dropTrigger accept ifExists and cascade; createTrigger accepts replace (CREATE OR REPLACE TRIGGER, PostgreSQL 14+).
  • Timing is 'before' | 'after' | 'instead_of' | 'after_constraint' (a deferrable CONSTRAINT TRIGGER); events are 'insert' | 'update' | 'delete' | 'truncate'.

Views and materialized views postgrelize extension ​

ts
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 no OR REPLACE for materialized views. concurrently needs a unique index on the view and cannot be combined with withData: false.
  • The query is 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 (freezeTableName or tableName, timestamps: false).
  • A temporary view lives only as long as its database session, which is one pooled connection: create and use it in one transaction (transaction option).

Row-level security postgrelize extension ​

ts
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 }) and disableRowLevelSecurity(table, { noForce }). force also subjects the table owner to the policies; superusers and roles with BYPASSRLS are never subject to them.
  • createPolicy(table, name, { command, kind, roles, using, withCheck }): command is 'all' (default), 'select', 'insert', 'update' or 'delete'; kind is 'permissive' (default) or 'restrictive'; roles are 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 settings option of a transaction (Sessions) and refer to it with current_setting('app.tenant_id')::int.

Unlogged and temporary tables postgrelize extension ​

ts
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 (on createTable options and on the model options used by sync) creates an UNLOGGED table: 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: true creates a TEMPORARY table 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 (pass transaction), or run with a single connection. A temporary table cannot have a schema, and it cannot be combined with unlogged.
  • Existing tables are not converted: sync({ alter: true }) does not change the persistence of a table that already exists.

API reference ​

Released under the MIT License.