Skip to content

Bulk writes and COPY ​

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.

Set-based writes avoid loading rows into Node.js and writing them back one by one. postgrelize exposes the PostgreSQL statements for this: UPDATE ... FROM, DELETE ... USING, INSERT ... SELECT, MERGE, and COPY for bulk import and export. None of them exist in Sequelize v6.

The examples use three models: Stock (sku, qty), Delivery (sku, amount) and Archive (sku, qty):

ts
const Stock = sequelize.define('Stock', {
  sku: { type: DataTypes.TEXT, allowNull: false, unique: true },
  qty: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
});
const Delivery = sequelize.define(
  'Delivery',
  { sku: DataTypes.TEXT, amount: DataTypes.INTEGER },
  { timestamps: false },
);
const Archive = sequelize.define(
  'Archive',
  { sku: DataTypes.TEXT, qty: DataTypes.INTEGER },
  { timestamps: false },
);
await sequelize.sync();
await Stock.bulkCreate([
  { sku: 'a', qty: 1 },
  { sku: 'b', qty: 2 },
  { sku: 'c', qty: 0 },
]);
await Delivery.bulkCreate([
  { sku: 'a', amount: 10 },
  { sku: 'b', amount: 20 },
]);

Large inserts with unnest postgrelize extension ​

bulkCreate sends one bound parameter per cell, and PostgreSQL accepts at most 65 535 parameters per statement. bulkCreate(rows, { unnest: true }) sends one array parameter per column instead (INSERT … SELECT * FROM unnest($1::integer[], $2::text[])), so one statement can insert hundreds of thousands of rows:

ts
// One array parameter per column: no 65535-parameter cap on the batch size.
const many = Array.from({ length: 70_000 }, (_, index) => ({ sku: `u${index}`, qty: index }));
const inserted = await Archive.bulkCreate(many, { unnest: true });

Every row must provide every column (there is no per-row DEFAULT), and ARRAY columns and the conflict options (ignoreDuplicates, updateOnDuplicate, onConflict) are not supported with unnest; those calls throw. Values, hooks, validation and returned instances behave as for the default path. For millions of rows prefer copyFrom.

UPDATE ... FROM postgrelize extension ​

The from option of Model.update joins other relations, keyed by alias. Reference their columns with col('alias.attr') in where and with literal or col in the new values:

ts
const [updated] = await Stock.update(
  { qty: literal('"Stock"."qty" + "d"."amount"') },
  { where: { sku: col('d.sku') }, from: { d: Delivery } },
);
// UPDATE "Stocks" AS "Stock" SET ... FROM "Deliveries" AS "d" WHERE "Stock"."sku" = "d"."sku"

A from value can be a model, a subquery from Model.subquery(), or a table / CTE name as a string.

DELETE ... USING postgrelize extension ​

Model.destroy takes using with the same shape:

ts
const removed = await Stock.destroy({
  where: { sku: col('a.sku') },
  using: { a: Archive },
});

INSERT ... SELECT postgrelize extension ​

Model.insertFrom(subquery, { columns }) inserts the rows a subquery produces, without a round trip through Node.js. columns lists the target attributes in the order of the subquery columns:

ts
const archived = await Archive.insertFrom(
  Stock.subquery({ attributes: ['sku', 'qty'], where: { qty: { [Op.gt]: 20 } } }),
  { columns: ['sku', 'qty'] },
);

It returns the written rows as instances (with wasInserted) and accepts onConflict, so it can upsert from another table. Fill NOT NULL timestamps in the subquery, e.g. attributes: ['sku', [literal('now()'), 'createdAt']].

MERGE postgrelize extension ​

Model.merge runs MERGE INTO ... USING ... (PostgreSQL 15+): one statement that updates, deletes or inserts depending on whether each source row matches a target row. The source is an array of plain objects (sent as a VALUES list with bound parameters) or a subquery:

ts
const merged = await Stock.merge({
  source: [
    { sku: 'a', qty: 5 },
    { sku: 'c', qty: -1 },
    { sku: 'z', qty: 7 },
  ],
  on: { sku: col('source.sku') },
  whenMatched: [
    { where: literal('"source"."qty" < 0'), delete: true },
    { update: { qty: literal('"Stock"."qty" + "source"."qty"') } },
  ],
  whenNotMatched: { insert: true },
});
// merged.rowCount === 3: 'a' updated, 'c' deleted, 'z' inserted
  • on is the join condition; the source alias is source unless you pass as.
  • whenMatched and whenNotMatched take one action or an array, evaluated in order. Each action may have a where condition.
  • Matched actions: { update: {...} }, { delete: true } or { nothing: true }. Not-matched actions: { insert: true } (copy same-named source columns), { insert: {...} } or { nothing: true }.
  • Timestamps are set automatically. Hooks and validation do not run.
  • The result is { rowCount, rows }; rows is filled only with returning: true.

With a subquery source and an explicit insert map:

ts
await Stock.merge({
  source: Delivery.subquery({ attributes: ['sku', 'amount'] }),
  as: 'd',
  on: { sku: col('d.sku') },
  whenMatched: { update: { qty: col('d.amount') } },
  whenNotMatched: { insert: { sku: col('d.sku'), qty: col('d.amount') } },
});

RETURNING and NOT MATCHED BY SOURCE (PostgreSQL 17+) postgrelize extension ​

On PostgreSQL 17, returning: true returns each written row with the action taken, and whenNotMatchedBySource handles target rows that have no source row — for example to retire items missing from a full import:

ts
const { rows } = await Stock.merge({
  source: [
    { sku: 'a', qty: 3 },
    { sku: 'n', qty: 9 },
  ],
  on: { sku: col('source.sku') },
  whenMatched: { update: { qty: col('source.qty') } },
  whenNotMatched: { insert: true },
  whenNotMatchedBySource: { update: { status: 'retired' } },
  returning: true,
});
const actions = rows.map(({ action, instance }) => `${action} ${String(instance.get('sku'))}`);
// actions (in any order): 'UPDATE a', 'INSERT n', 'UPDATE b' (b is retired)

On older servers these options throw before any SQL runs. With returningOld: true (PostgreSQL 18), each instance also has oldValues.

COPY postgrelize extension ​

COPY is the fastest way to move many rows in or out of PostgreSQL.

Import with copyFrom postgrelize extension ​

Model.copyFrom(rows, options) streams rows with COPY ... FROM STDIN. rows can be an array, an iterable or an async iterable, so you can pipe a file parser or another database cursor through it without holding everything in memory:

ts
async function* readEvents(): AsyncGenerator<{ kind: string; payload: object }> {
  for (let index = 0; index < 1000; index += 1) {
    yield { kind: index % 2 === 0 ? 'view' : 'click', payload: { index } };
  }
}
ts
const fromArray = await Event.copyFrom([
  { kind: 'signup', payload: { plan: 'pro' }, tags: ['web'] },
  { kind: 'login', payload: null, tags: null },
]);

const fromStream = await Event.copyFrom(readEvents(), { columns: ['kind', 'payload'] });
// fromArray === 2, fromStream === 1000; createdAt / updatedAt are filled in
  • columns lists the attributes to copy. It defaults to the keys of the first row of an array and is required for iterables.
  • Values are serialized like in create (JSON, arrays, dates); escaping is handled for you.
  • createdAt / updatedAt are filled when the model has timestamps.
  • No hooks, validation or defaults defined in Node.js run, and missing values are NULL (column defaults of the table do not apply to listed columns). The result is the number of copied rows.
  • With transaction, the copy is rolled back together with the transaction.

Export with copyTo postgrelize extension ​

Model.copyTo(options) runs COPY (SELECT ...) TO STDOUT and returns an async iterator of Buffer chunks. It takes the find options (attributes, where, order, include, scopes, with) and the output format:

ts
const chunks: Buffer[] = [];
for await (const chunk of Event.copyTo({
  attributes: ['id', 'kind', 'tags'],
  where: { kind: { [Op.in]: ['signup', 'login'] } },
  order: [['id', 'ASC']],
  format: 'csv',
  header: true,
})) {
  chunks.push(chunk);
}
const csv = Buffer.concat(chunks).toString('utf8');
// id,kind,tags
// 1,signup,{web}
// 2,login,
OptionDescription
format'text' (default), 'csv' or 'binary'
headerHeader line with column names (text and CSV)
delimiterSingle-character field delimiter
nullStringText written for NULL
quoteSingle-character quote (CSV)

Write the chunks straight to an HTTP response or a file stream. Stopping the iteration early is safe: the rest of the output is drained before the connection returns to the pool. Because COPY cannot take parameters, values of the query are inlined as escaped literals.

API reference ​

Released under the MIT License.