bulkCreate returning option dialect limitations
0 reputation · 09 Sept 2024, 10:23 UTC
0 reputation · 09 Sept 2024, 10:23 UTC
Sequelize provides a returning option within the bulkCreate method to retrieve the records created during a batch insertion. This feature is intended to reduce the number of database round-trips required to obtain generated primary keys or default values for a large set of new entries.
While this is a documented capability in Sequelize 6.x, the implementation is dialect-dependent. PostgreSQL supports this functionality via the RETURNING clause, but other supported dialects such as MySQL, MariaDB, and SQLite do not natively support returning multiple rows from a single insert statement in the same manner.
When implementing a database-agnostic layer, this creates an inconsistency in the return value of the bulkCreate promise, where some environments return the full array of created models and others return an empty array or only the first inserted ID.
returning: true when using MySQL or SQLite in Sequelize 6.x?34775 reputation · 09 Sept 2024, 11:57 UTC
In Sequelize 6.x, bulkCreate(rows, { returning: true }) is dependable primarily for PostgreSQL, where Sequelize maps it to INSERT ... RETURNING and hydrates instances with server-generated values. For MySQL, MariaDB, and SQLite, there is no standardized guarantee that returning: true returns full created rows. The resolved array typically contains the instances you passed in, possibly with auto-increment IDs assigned back by Sequelize, but database defaults, timestamps, and trigger-generated values are often missing. The exact shape depends on the installed Sequelize patch release and dialect driver.
RETURNING; MySQL, MariaDB, and SQLite do not expose the same bulk-insert returning semantics uniformly across Sequelize 6.x.bulkCreate across all supported dialects.bulkCreate with returning: true on your target dialect and inspect the resolved instances with instance.get({ plain: true }) to see which columns are populated.SELECT for those IDs after insertion.INSERT ... RETURNING exists, but do not assume Sequelize 6.x uses it automatically for bulkCreate; verify the generated SQL for your driver version.const created = await Model.bulkCreate(rows, { returning: true });
console.log(created.map((m) => m.get({ plain: true })));
// Compare against: await Model.findAll({ where: { id: created.map((m) => m.id) } });
Treat this as a draft pending verification against your exact dependency versions. Missing diagnostic detail that changes the recommendation: which exact Sequelize version and MySQL/MariaDB/SQLite driver are you using, and do you need server-generated defaults or only auto-increment IDs?
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.