Postgrelize: Rewriting Sequelize v6 Strictly for PostgreSQL and Proving Compatibility on Its Own Test SuiteArticle · digest for December 3
Staged still life: a bulky five-way universal adapter next to a sleek monolithic Postgrelize adapter precision-fitted for PostgreSQL.
Article4 sections≈ 9 min

Postgrelize: Rewriting Sequelize v6 Strictly for PostgreSQL and Proving Compatibility on Its Own Test Suite

When a Node.js and PostgreSQL app uses Sequelize v6, everything feels fine at first. Basic findAll calls, associations, and migrations work. Trouble starts when you need native Postgres features: ON CONFLICT with expressions, SQL MERGE, COPY bulk loads, LISTEN/NOTIFY, or advisory locks. The ORM shrugs, you drop down to raw SQL, and you instantly lose hooks, validations, Model hydration, and TypeScript types.

Why Sequelize v6's multi-database design gets in PostgreSQL's way

Sequelize tries to please five databases at once: MySQL, MariaDB, SQLite, MSSQL, and PostgreSQL. That keeps its API stuck on the lowest common denominator. Branch v6 (6.37.8, 16 runtime dependencies plus pg-hstore) is in maintenance mode, while the v7 TypeScript rewrite has stalled in alpha.

Migrating dozens of models and hooks to Drizzle, Prisma, or Kysely takes months of refactoring. Developer Andrey Kuznetsov took another route and built Postgrelize from scratch in TypeScript—a drop-in replacement that mirrors Sequelize v6's API and types while targeting PostgreSQL exclusively. Existing models run unchanged, and native Postgres features sit cleanly on top as extra options.

Official Postgrelize documentation banner — a drop-in ORM with Sequelize v6 API built exclusively for PostgreSQL (Source: tormozz48.github.io/postgrelize)

The npm package (MIT, v1.17.0 from December 2, 2026) has just two runtime dependencies (validator and inflection) plus peer pg ^8.0.0, with no pg-hstore needed. Run npm uninstall sequelize pg-hstore && npm install postgrelize pg and swap one import line:

// Before:
// import { DataTypes, Model, Op, Sequelize } from 'sequelize';

// After:
import { DataTypes, Model, Op, Sequelize } from 'postgrelize';

Models, findAll with include, scopes, hooks, validations, paranoid models, transactions, QueryInterface, and sync follow the v6 contract. TypeScript types (Model, ModelStatic, InferAttributes, association mixins) match too, and CommonJS require('postgrelize') returns the Sequelize class.

Three layers of compatibility testing

Promising drop-in compatibility is easy; proving it on real code is hard. The library was built with AI agents (Claude Opus 5.5 + Sonnet 5.5 using 10x-team skills). After a naive "make it v6-compatible" prompt, the first build threw hundreds of errors on a real project. That led to a three-tier test harness and strict AGENTS.md rules: a v6 contract, 35+ ADRs before coding, a regression test per fix, and green CI before merge.

Layer one is differential testing: the same scenario runs against both sequelize@6 and Postgrelize, comparing outputs automatically. Over 150 test files catch subtle behavioral mismatches.

Layer two is Sequelize v6's own test suite. A script clones the v6 tag, copies test/, swaps node_modules/sequelize with a proxy to the built Postgrelize package, and runs the original Mocha unit and integration tests. Known failures sit in a baseline file with reasons (bug, intentional divergence, or non-Postgres test). CI only allows the baseline to shrink; any new failure breaks the build.

There was even a real scare: v6's native tests wipe all tables, enums, and schemas in their target database, and one run dropped the backend database of a live project. The runner now lives in an isolated container and refuses to start on the main test DB port.

Layer three is TypeScript type parity. A corpus of v6-style code compiles against both libraries to catch missing types or options (exceptions live in tests/compat/type-parity/exceptions.json). Combined with 99.0% test coverage, compatibility becomes measurable.

Fixed v6 bugs and native PostgreSQL features

Along the way, the author audited 73 open Sequelize PostgreSQL issues (as of November 14, 2026) and intentionally fixed several, documenting differences in ADR-016 with regression tests. Fixes include JSON key matching in where with ,, ", and \ (#18617), jsonb Op.contains and Op.hasKey on nested paths (#5173), partial unique index predicates in upsert (#12595), sync({ alter }) dropping sequence on non-PK autoIncrement columns (#13167), and sync({ schema }) / drop({ schema }) leaking outside the target schema (#18423). Model.aggregate also blocks unvalidated SQL function names. All values go through bound parameters ($1..$n), identifiers are quoted, and sorts, casts, and operators pass an allowlist.

On top of v6, Postgrelize adds native Postgres capabilities. Counter.insert supports ON CONFLICT with expressions, conditions, and instance.wasInserted:

// Increment counter on conflict and check whether each row is new
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"') },
      },
    },
  },
);
rows.map((c) => [c.key, c.hits, c.wasInserted]);
// [['a', 15, false], ['c', 3, true]]

// Update only if incoming version is newer, avoiding read-modify-write races
await Counter.insert(incoming, {
  onConflict: {
    target: ['tenant', 'key'],
    action: {
      update: ['hits', 'version'],
      where: { version: { [Op.lt]: excluded('version') } },
    },
  },
});

"Update only if a newer version arrived" now runs in one race-free query. Conflict targets can be constraints, partial indexes, or expressions ([fn('lower', col('email'))]). On PostgreSQL 18, returningOld: true uses OLD/NEW in RETURNING (PostgreSQL 18 docs) and exposes previous row values in instance.oldValues in the same round-trip.

Next come SQL MERGE and UNNEST bulk inserts. UNNEST expands arrays into rows—sending one array parameter per column instead of one parameter per cell, bypassing Postgres's 65,535-parameter limit:

// Sync inventory: delete negative quantities, add the rest
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 },
});

// Bulk insert without hitting the 65,535 parameter limit
await Stock.bulkCreate(largeBatch, { unnest: true });

Heavy imports get streaming COPY FROM / COPY TO, while queues, multi-tenancy, and cron locks get LISTEN/NOTIFY, SET LOCAL, and advisory locks:

// Subscribe and send notifications strictly after COMMIT
const unlisten = await sequelize.listen('jobs', (msg) => {
  console.log(msg);
});
await sequelize.transaction(async (transaction) => {
  await Job.create({ name: 'export' }, { transaction });
  await sequelize.notify('jobs', 'export queued', { transaction });
});

// Transaction-scoped SET LOCAL variable — handy for RLS
await sequelize.transaction(
  { settings: { 'app.user_id': 42 } },
  async (t) => { /* queries under Row-Level Security */ },
);

// Advisory lock so cron never runs on two nodes at once
await sequelize.withAdvisoryLock('nightly-report', () => buildReport());

SET LOCAL binds a session variable to a transaction (great for Row-Level Security policies), and advisory locks prevent duplicate job runs using Postgres itself. The Postgrelize docs also cover CTE, LATERAL, DISTINCT ON, window functions, keyset pagination, JSON_TABLE, full-text search, server-side cursors, read replicas, @Table/@Column decorators, materialized views, partitioning, EXCLUDE constraints, and PostGIS (GeoJSON).

CPU benchmarks and honest limits

Benchmarks against sequelize@6 ran in the same process, alternating order each round and measuring process.cpuUsage() (GitHub Actions ubuntu-latest, Node 22, median of three runs after 1.8.3). In stub mode, pg is replaced by an in-memory stub to isolate pure ORM overhead:

Postgrelize CPU speedup vs Sequelize v6 in stub mode (v6 / postgrelize)

Heavy where clauses, model setup, and short queries benefit most—places where Sequelize's multi-dialect layer wastes cycles. build + toJSON is honestly a touch slower than the original. Against a live database, network and PostgreSQL dominate, putting end-to-end CPU gains at 1.1–2.4×. CI also enforces a performance gate: any PR slowing benchmarked cases by over 10% fails.

Caveats and differences when migrating from Sequelize v6

The repo was created on November 14, 2026, hit 1.0.0 on November 21, and as of December 3 has 1 GitHub star and over 50 releases. Requirements are strict: PostgreSQL 16–18 only (CI also tests 19) and Node.js 20+; any other dialect throws. There are intentional differences from v6: in CommonJS, HasOne/HasMany/BelongsTo/BelongsToMany are decorators (classes sit on Sequelize.HasMany); QueryInterface#queryGenerator only keeps selectQuery; omitNull is dropped from types; retry is off by default and won't retry inside transactions; pool.min and pool.evict are ignored; and SQL log spacing differs ("col" = $1 vs "col"=$1), so exact-SQL snapshot tests need updating.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 6