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:
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:
| Option | Effect |
|---|---|
| (none) | CREATE TABLE IF NOT EXISTS; existing tables are left as they are. |
force: true | Drops and recreates the tables. Data is lost. |
alter: true | Compares 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). |
schema | Creates the tables in this PostgreSQL schema. |
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:NULLvalues count as equal, so only one row may haveNULLin the key. Also accepted in the attribute optionunique: { 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:
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');
};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,createPolicyand 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,showAllTablesandtableExistslook incurrent_schema()(the first schema ofsearch_path) when no schema is given; v6 always usespublic.showIndex,showConstraintandgetForeignKeysForTablesfilter by schema likedescribeTable(v6 looks up the table name in every schema, and breaks for{ tableName, schema }ingetForeignKeysForTables).showConstraint(table, name)returns only that constraint; v6 ignores the name on PostgreSQL.quoteIdentifierdoubles embedded"where v6 strips them.describeTablereturns literal defaults unquoted (it's, not'it''s'::text).sync({ alter: true })keeps the sequence of non-keyautoIncrementcolumns 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.