Upserts and RETURNING
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.
Sequelize v6 can upsert only with fixed column lists (upsert, bulkCreate({ updateOnDuplicate })). postgrelize keeps those and adds the onConflict option, which exposes the full INSERT ... ON CONFLICT clause of PostgreSQL: any conflict target, expression updates, a WHERE condition and DO NOTHING. Model.insert() returns every written row with a flag telling whether it was inserted or updated.
The examples use this model, with a composite unique key and a partial unique index:
class Counter extends Model<InferAttributes<Counter>, InferCreationAttributes<Counter>> {
declare id: CreationOptional<number>;
declare tenant: string;
declare key: string;
declare hits: CreationOptional<number>;
declare version: CreationOptional<number>;
declare tags: CreationOptional<string[]>;
declare archived: CreationOptional<boolean>;
}
Counter.init(
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
tenant: { type: DataTypes.TEXT, allowNull: false, unique: 'counters_tenant_key' },
key: { type: DataTypes.TEXT, allowNull: false, unique: 'counters_tenant_key' },
hits: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
version: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
tags: { type: DataTypes.ARRAY(DataTypes.TEXT), allowNull: false, defaultValue: [] },
archived: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
},
{
sequelize,
tableName: 'counters',
timestamps: false,
indexes: [
{ name: 'counters_active_key', unique: true, fields: ['key'], where: { archived: false } },
],
},
);
await sequelize.sync();
await Counter.bulkCreate([
{ tenant: 't1', key: 'a', hits: 1, tags: ['x'] },
{ tenant: 't1', key: 'b', hits: 2, version: 5 },
]);Sequelize v6 upserts
These work unchanged:
const [row, created] = await Counter.upsert({ tenant: 't1', key: 'a', hits: 5 });
// row.hits === 5; created is null on PostgreSQL, as in Sequelize v6
await Counter.bulkCreate([{ tenant: 't1', key: 'b', hits: 7 }], {
updateOnDuplicate: ['hits'],
conflictAttributes: ['tenant', 'key'],
});upsert picks the conflict target from the unique keys of the given attributes (or the primary key); conflictFields sets it explicitly. As in Sequelize v6 on PostgreSQL, the second element of the result is null. bulkCreate takes updateOnDuplicate, conflictAttributes, conflictWhere (for partial indexes) and ignoreDuplicates.
onConflict postgrelize extension
onConflict is accepted by Model.insert, create, bulkCreate, upsert and insertFrom. It has two parts:
onConflict: {
target: ['tenant', 'key'], // or { constraint: 'name' }, or { columns, where } for partial indexes
action: 'nothing', // or { update: [...attributes] | { attr: value | expression }, where? }
}Expression updates and wasInserted postgrelize extension
Model.insert(rows, options) inserts one row or an array of rows and returns model instances for every row written. instance.wasInserted is true for inserted rows and false for rows updated on conflict:
const rows = await Counter.insert(
[
{ tenant: 't1', key: 'a', hits: 10 },
{ tenant: 't1', key: 'c', hits: 3 },
],
{
onConflict: {
target: ['tenant', 'key'],
action: { update: { hits: literal('"Counter"."hits" + EXCLUDED."hits"') } },
},
},
);
const report = rows.map((counter) => [counter.key, counter.hits, counter.wasInserted]);
// report: [['a', 15, false], ['c', 3, true]]Inside action.update, EXCLUDED is the proposed row and the model name is the alias of the existing row. Use excluded('attr') for a column of the proposed row, col('Counter.attr') for the existing one, and fn / literal for anything else. updatedAt is set automatically.
Conditional updates postgrelize extension
action.where adds DO UPDATE ... WHERE. Rows that fail the condition are left alone and are not returned:
const newer = await Counter.insert(
[
{ tenant: 't1', key: 'a', hits: 100, version: 2 },
{ tenant: 't1', key: 'b', hits: 100, version: 3 },
],
{
onConflict: {
target: ['tenant', 'key'],
action: {
update: ['hits', 'version'],
where: { version: { [Op.lt]: excluded('version') } },
},
},
},
);
// only 'a' is updated: 'b' already has version 5; rows that were skipped are not returnedThis is the usual pattern for "apply only newer versions" in sync jobs and event consumers.
Conflict targets postgrelize extension
target | SQL |
|---|---|
['tenant', 'key'] | ON CONFLICT ("tenant", "key") |
[fn('lower', col('email'))] | ON CONFLICT (lower("email")) — expression index |
{ columns: ['key'], where: { archived: false } } | ON CONFLICT ("key") WHERE ... — partial unique index |
{ constraint: 'counters_tenant_key' } | ON CONFLICT ON CONSTRAINT "counters_tenant_key" |
omitted (only with action: 'nothing') | ON CONFLICT DO NOTHING — any unique violation |
await Counter.bulkCreate([{ tenant: 't1', key: 'a', tags: ['y'] }], {
onConflict: {
target: { constraint: 'counters_tenant_key' },
action: { update: { tags: fn('array_cat', col('Counter.tags'), excluded('tags')) } },
},
});
const [partial] = await Counter.insert(
{ tenant: 't9', key: 'c', hits: 50 },
{
onConflict: {
target: { columns: ['key'], where: { archived: false } },
action: { update: { hits: excluded('hits') } },
},
},
);
// partial.tenant === 't1': the existing active row with key 'c' was updated
const skipped = await Counter.bulkCreate(
[
{ tenant: 't1', key: 'b' },
{ tenant: 't1', key: 'n' },
],
{ onConflict: { action: 'nothing' } },
);
// skipped: only the inserted row 'n'With action: 'nothing', skipped rows are not returned: bulkCreate and insert resolve to the inserted rows only. create with action: 'nothing' returns the unsaved instance (isNewRecord stays true) when the row was skipped.
Options are checked before any SQL runs: an unknown attribute, an update without a target, an empty update list, or onConflict combined with ignoreDuplicates / updateOnDuplicate throws an Error.
upsert with onConflict
With onConflict, upsert resolves to [instance, created] with a real boolean:
const [visit, isNew] = await Counter.upsert(
{ tenant: 't2', key: 'home', hits: 1 },
{
onConflict: {
target: ['tenant', 'key'],
action: { update: { hits: literal('"Counter"."hits" + 1') } },
},
},
);
// isNew === true on the first call, false afterwards (visit.hits is then incremented)RETURNING
PostgreSQL returns written rows with RETURNING. Besides create and save (which always read the row back), postgrelize supports:
Model.update(values, { where, returning: true })→[count, instances](as in v6);Model.destroy({ where, returning: true })→ the deleted instances instead of a count (an extension).
const [updatedCount, updated = []] = await Counter.update(
{ hits: 0 },
{ where: { key: ['a', 'b'] }, returning: true },
);
const deleted = await Counter.destroy({ where: { key: 'n' }, returning: true });
// deleted: the removed Counter instances instead of a countOld values with returningOld (PostgreSQL 18+) postgrelize extension
PostgreSQL 18 can return the row as it was before the statement (RETURNING OLD.*). With returningOld: true, every returned instance gets oldValues: the attribute values before the write, or null when the row was inserted.
const [, changed = []] = await Stock.update(
{ qty: literal('qty + 10') },
{ where: { sku: 'a' }, returning: true, returningOld: true },
);
const [stock] = changed;
// stock.get('qty') === 11, stock.oldValues === { id: 1, sku: 'a', qty: 1 }const written = await Stock.insert(
[
{ sku: 'b', qty: 5 },
{ sku: 'z', qty: 7 },
],
{
onConflict: { target: ['sku'], action: { update: { qty: excluded('qty') } } },
returningOld: true,
},
);
const previous = written.map((row) => row.oldValues?.['qty'] ?? null);
// previous: [2, null] — 'b' was updated from 2, 'z' was insertedreturningOld is accepted by Model.update (together with returning: true), Model.insert, insertFrom and merge (with returning: true). On PostgreSQL 16 and 17 it throws returningOld requires PostgreSQL 18 or newer before running the query.
API reference
Model—insert,upsert,bulkCreate,wasInserted,oldValuesOnConflictOptions,InsertOptionsexcluded