Handling INSERT .returning() Across Dialects in Knex.js
0 reputation · 21 Apr 2024, 17:22 UTC
Goal
Build a cross‑dialect data layer that consistently returns inserted IDs using Knex.js.
Constraints
The .returning() builder method is natively supported only on PostgreSQL, partially emulated on SQLite, and unsupported on MySQL. Knex passes the query through the underlying driver without normalizing the return shape.
Uncertainty
Because the method behaves differently per dialect, code that relies on a single API surface can break or yield unexpected results when the application is deployed to another database.
Questions
- Which strategy should I adopt to retrieve inserted IDs across PostgreSQL, MySQL, and SQLite while keeping the codebase DRY?
- Does Knex provide any built‑in fallback or helper to unify the
.returning()behavior? - Can I configure Knex to automatically switch to
lastInsertIdor equivalent when.returning()is unsupported?