Skip to content

Schema, sync and migrations ​

postgrelize creates and changes tables in two ways, both compatible with Sequelize v6: sync() derives the schema from model definitions, and QueryInterface runs explicit DDL for migrations (umzug, sequelize-cli style migration files).

sync ​

sequelize.sync() creates missing tables, enum types, indexes and foreign keys for all defined models; Model.sync() does it for one model. Indexes come from the indexes model option and from unique attribute options:

ts
const Device = sequelize.define(
  'Device',
  {
    serial: { type: DataTypes.TEXT, unique: { name: 'devices_serial', nullsNotDistinct: true } },
    vendor: DataTypes.TEXT,
    model: DataTypes.TEXT,
  },
  {
    indexes: [
      { fields: ['vendor', 'model'], unique: true, nullsNotDistinct: true },
      { fields: ['model'], where: { vendor: null } },
    ],
  },
);
await sequelize.sync();

sync options:

OptionEffect
(none)CREATE TABLE IF NOT EXISTS; existing tables are left as they are.
force: trueDrops and recreates the tables. Data is lost.
alter: trueCompares each table with the model and adds, changes or drops columns, enum values and constraints. alter: { drop: false } keeps columns that are not in the model.
match: /_test$/Throws unless the database name matches the pattern (a safety net for force).
schemaCreates the tables in this PostgreSQL schema.
ts
sequelize.define(
  'Device',
  {
    serial: { type: DataTypes.TEXT, unique: { name: 'devices_serial', nullsNotDistinct: true } },
    vendor: DataTypes.TEXT,
    model: DataTypes.TEXT,
    firmware: { type: DataTypes.TEXT, allowNull: false, defaultValue: '1.0' },
  },
  { indexes: [{ fields: ['vendor', 'model'], unique: true, nullsNotDistinct: true }] },
);
await sequelize.sync({ alter: true });

sync({ alter: true }) is convenient during development; for production, prefer migrations that you review. sequelize.drop() and Model.drop() drop the tables (cascade and schema options as in v6).

PostgreSQL index and constraint options ​

Index options are the v6 ones (name, fields, unique, using, operator, where, concurrently) plus:

  • postgrelize extension nullsNotDistinct: true → UNIQUE NULLS NOT DISTINCT: NULL values count as equal, so only one row may have NULL in the key. Also accepted in the attribute option unique: { nullsNotDistinct: true }.
  • include: ['col'] → covering index (INCLUDE (...)).
  • ifNotExists: true → CREATE INDEX IF NOT EXISTS.

Foreign keys accept deferrable: Deferrable.INITIALLY_DEFERRED (or INITIALLY_IMMEDIATE, NOT) in references, so the constraint is checked at commit.

Migrations with QueryInterface ​

sequelize.getQueryInterface() returns a QueryInterface with the v6 methods. A migration is a pair of up / down functions receiving it, as with umzug or sequelize-cli:

ts
export const up = async (queryInterface: QueryInterface): Promise<void> => {
  await queryInterface.createTable('accounts', {
    id: { type: DataTypes.BIGINT, primaryKey: true, autoIncrement: true },
    email: { type: DataTypes.TEXT, allowNull: false, unique: true },
    plan: { type: DataTypes.ENUM('free', 'pro'), allowNull: false, defaultValue: 'free' },
    created_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
  });
  await queryInterface.createTable('sessions', {
    id: { type: DataTypes.UUID, primaryKey: true },
    account_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: { model: 'accounts', key: 'id', deferrable: Deferrable.INITIALLY_DEFERRED },
      onDelete: 'CASCADE',
    },
  });
  await queryInterface.addIndex('sessions', ['account_id']);
  await queryInterface.addColumn('accounts', 'note', { type: DataTypes.TEXT });
};

export const down = async (queryInterface: QueryInterface): Promise<void> => {
  await queryInterface.dropTable('sessions');
  await queryInterface.dropTable('accounts');
  await queryInterface.dropEnum('enum_accounts_plan');
};
ts
const queryInterface = sequelize.getQueryInterface();
await up(queryInterface);
const tables = await queryInterface.showAllTables();
const accounts = await queryInterface.describeTable('accounts');
await down(queryInterface);

Available methods:

  • tables: createTable, dropTable, dropAllTables, renameTable, tableExists, showAllTables, describeTable
  • columns: addColumn, removeColumn, changeColumn, renameColumn
  • indexes and constraints: addIndex, removeIndex, showIndex, addConstraint, removeConstraint, showConstraint, getForeignKeyReferencesForTable, getForeignKeysForTables
  • databases and helpers: createDatabase, dropDatabase, databaseVersion, assertTableHasColumn, quoteIdentifier, quoteIdentifiers
  • schemas and enums: createSchema, dropSchema, showAllSchemas, dropEnum, dropAllEnums
  • extensions, sequences, views, row-level security, functions and triggers: createExtension, createSequence, nextval, createView, createMaterializedView, refreshMaterializedView, createFunction, createTrigger, createPolicy and their drop / alter / rename counterparts (see Schema objects)
  • data: bulkInsert, bulkUpdate, bulkDelete

All methods take a transaction option, so a migration can run in one transaction. Table names may be strings or { tableName, schema } objects.

Differences from Sequelize v6 ​

  • describeTable, showAllTables and tableExists look in current_schema() (the first schema of search_path) when no schema is given; v6 always uses public.
  • showIndex, showConstraint and getForeignKeysForTables filter by schema like describeTable (v6 looks up the table name in every schema, and breaks for { tableName, schema } in getForeignKeysForTables). showConstraint(table, name) returns only that constraint; v6 ignores the name on PostgreSQL. quoteIdentifier doubles embedded " where v6 strips them.
  • describeTable returns literal defaults unquoted (it's, not 'it''s'::text).
  • sync({ alter: true }) keeps the sequence of non-key autoIncrement columns and does not duplicate foreign keys when tables live in a non-default schema.
  • sync({ schema }) / drop({ schema }) only touch that schema, even if tables with the same name exist elsewhere.
  • Foreign-key cycles are created after all tables exist.

The details and issue links are on Sequelize issues fixed.

API reference ​

Released under the MIT License.