Skip to content

Constraints and indexes ​

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.

addIndex and addConstraint cover the Sequelize v6 shapes (see Schema). This page lists the PostgreSQL additions. They are new options: existing option shapes and defaults do not change.

Expression indexes postgrelize extension ​

ts
await queryInterface.addIndex('accounts', {
  name: 'accounts_lower_email',
  unique: true,
  fields: [{ expression: 'lower(email)' }],
  include: ['nick'],
});
await queryInterface.addIndex('accounts', {
  name: 'accounts_nick_search',
  fields: [
    { name: 'nick', collate: 'C', operator: 'text_pattern_ops', order: 'DESC', nulls: 'LAST' },
  ],
});
  • An index field is a column ('email', { name: 'email' }) or an expression ({ expression: 'lower(email)' }). Every field accepts order, nulls ('FIRST' / 'LAST'), collate (a quoted collation name) and operator (operator class); include adds covering columns.
  • The expression is SQL you write. It is wrapped in parentheses and is not escaped: never build it from user input. See Security.
  • A name cannot be derived from an expression, so an index with an expression field needs an explicit name.
  • Model indexes accept the same fields. An expression must be immutable (PostgreSQL rejects date_trunc on timestamptz, for example).

EXCLUDE constraints postgrelize extension ​

ts
await queryInterface.addConstraint('bookings', {
  type: 'exclude',
  name: 'bookings_no_overlap',
  using: 'gist',
  exclude: [
    { name: 'room', with: '=' },
    { name: 'period', with: '&&' },
  ],
});
  • addConstraint(table, { type: 'exclude', exclude: [{ name | expression, with }], using, where, include, deferrable }). Each element is a column or an expression with the operator it is compared with (with), and accepts collate, operator (operator class), order and nulls.
  • Scalar columns with = in a gist / spgist exclusion need the btree_gist extension (createExtension('btree_gist')).
  • The operator is checked against a pattern of operator characters (=, &&, -|-, <->); a name or expression cannot be smuggled in. Expressions are trusted SQL (see above). where is a where-object compiled like a partial-index condition; deferrable takes a Deferrable constant.
  • Without name the constraint is called <table>_<columns>_excl; with an expression element give a name.
  • A violation raises ExclusionConstraintError.

NOT VALID and VALIDATE CONSTRAINT postgrelize extension ​

ts
await queryInterface.addConstraint('products', {
  type: 'check',
  fields: ['price'],
  name: 'products_price_positive',
  where: { price: { [Op.gt]: 0 } },
  notValid: true,
});
await sequelize.query('UPDATE products SET price = 1');
await queryInterface.validateConstraint('products', 'products_price_positive');

notValid: true (check and foreign key constraints) adds the constraint without scanning existing rows, so it takes only a short lock; new and updated rows are checked at once. After cleaning the old rows, validateConstraint(table, name) scans the table without blocking writes. Using notValid with another constraint type throws.

Declarative partitioning postgrelize extension ​

ts
await queryInterface.createTable(
  'events',
  { at: DataTypes.DATE, kind: DataTypes.TEXT },
  { partitionBy: { strategy: 'range', columns: ['at'] } },
);
await queryInterface.createPartition('events', 'events_2026', {
  from: ['2026-01-01'],
  to: ['2027-01-01'],
});
await queryInterface.createPartition('events', 'events_other', { default: true });
await queryInterface.createTable('events_2027', { at: DataTypes.DATE, kind: DataTypes.TEXT });
await queryInterface.attachPartition('events', 'events_2027', {
  from: ['2027-01-01'],
  to: ['2028-01-01'],
});
await queryInterface.detachPartition('events', 'events_2026');
  • createTable(name, attributes, { partitionBy: { strategy: 'range' | 'list' | 'hash', columns } }) creates the partitioned parent. Columns are names or { name | expression, collate, operator }; an expression is trusted SQL. Primary and unique keys must include every partition column (PostgreSQL rule).
  • createPartition(parent, name, bound, { partitionBy, ifNotExists }) bounds: { in: [...] } for list, { from: [...], to: [...] } for range (PartitionBound.MINVALUE / MAXVALUE are markers, a string 'MINVALUE' is just a string), { modulus, remainder } for hash and { default: true }. Values are literals. partitionBy makes the partition itself partitioned.
  • attachPartition(parent, existingTable, bound) and detachPartition(parent, partition, { concurrently, finalize }). concurrently cannot run inside a transaction.
  • Partitions are real tables: showAllTables lists them, describeTable works on parent and partitions, and queries and models on the parent work as usual. sync does not create partitions: create them with createPartition.

PostgreSQL 18 constraints postgrelize extension ​

ts
await queryInterface.addConstraint('rooms', {
  type: 'primary key',
  name: 'rooms_pk',
  fields: ['id', 'validAt'],
  withoutOverlaps: true,
});
await queryInterface.addConstraint('stays', {
  type: 'foreign key',
  name: 'stays_room_fk',
  fields: ['roomId', 'during'],
  period: true,
  references: { table: 'rooms', field: 'id', fields: ['id', 'validAt'] },
});
ts
await queryInterface.addConstraint('stays', {
  type: 'check',
  name: 'stays_nights_positive',
  fields: ['nights'],
  where: { nights: { [Op.gt]: 0 } },
  enforced: false,
});

These options render PostgreSQL 18 syntax. Older servers reject the statement with their own syntax error; nothing is sent differently by version.

  • withoutOverlaps: true (unique and primary key): the last field is a range or multirange column and no two rows with equal other fields may overlap. Scalar columns in a temporal key need the btree_gist extension.
  • period: true (foreign key): the last field and the last referenced field are PERIOD columns; the referenced table needs a withoutOverlaps key. List the referenced columns with references.fields (references.field stays the single-column form).
  • enforced: false (check and foreign key): NOT ENFORCED records the constraint without checking it, so it documents a rule or helps the planner. It can be combined with notValid.

Released under the MIT License.