Skip to content

feat(core,postgres): native UUIDv7 generation with fallback - #18258

Open
vineetj12 wants to merge 3 commits into
sequelize:mainfrom
vineetj12:feat/uuidv7-native
Open

vineetj12 wants to merge 3 commits into
sequelize:mainfrom
vineetj12:feat/uuidv7-native

Conversation

@vineetj12

@vineetj12 vineetj12 commented Jul 14, 2026 •

Copy link
Copy Markdown

Pull Request Checklist

  • Have you added new tests to prevent regressions?
  • If a documentation update is necessary, have you opened a PR to the documentation repository?
  • Did you update the typescript typings accordingly (if applicable)?
  • Does the description below contain a link to an existing issue (Closes #[issue]) or a description of the issue you are solving?
  • Does the name of your PR follow our conventions?

Description of Changes

Closes #18253. Related to #17832.

Adds native UUIDv7 generation support:

  • node:crypto's randomUUIDv7() is used when available (Node 26+), falling back to the uuid package's v7() otherwise. The native detection is guarded with an explicit typeof === 'function' check.
  • PostgreSQL now advertises UUIDv7 database-level generation as version-gated (minimumDatabaseVersion: '18.0.0') instead of a static boolean. On Postgres 18+, sql.uuidV7 produces a column default of uuidv7(). On Postgres <18 (or when the database version is unknown), Sequelize falls back to JavaScript-side generation instead of emitting a SQL default.

Files changed:

  • packages/core/src/expression-builders/uuid.ts — injectable native UUIDv7 detection + version-aware supportsDialect()
  • packages/core/src/abstract-dialect/dialect.ts — widened uuidV7Generation to boolean | { minimumDatabaseVersion: string }
  • packages/postgres/src/dialect.ts — declared Postgres UUIDv7 support starting at 18.0.0
  • packages/postgres/src/query-generator-typescript.internal.ts — added getUuidV7FunctionCall() returning uuidv7()
  • packages/core/test/unit/query-interface/create-table.test.ts — added Postgres 18 (uuidv7() default) and Postgres 17 (JS fallback, no default) cases
  • packages/core/test/unit/expression-builders/uuid.test.ts — new tests for native-injected and fallback UUIDv7 generation
  • .github/workflows/ci.yml — added Node 26 to the CI matrix
  • dev/postgres/latest/docker-compose.yml — bumped the latest Postgres image to 18

Notes for reviewers:

  • Per WikiRik's comment on Add native UUIDv7 support (v7 branch) #18253, the CI workflow and Postgres image changes may need to land in a separate PR first. Happy to split these out if preferred — just let me know.
  • Unit tests cover the version-gating logic against mocked database versions (PG17/PG18 in create-table.test.ts), and the native/fallback selection is covered in uuid.test.ts. I was unable to bring up a local Postgres 18 environment to run the integration path directly, so I'd appreciate confirmation from CI or a maintainer that the live uuidv7() SQL path behaves as expected against a real database.

List of Breaking Changes

None. uuidV7Generation widened from boolean to boolean | { minimumDatabaseVersion: string }, but this is an internal DialectSupports capability type, not part of the public API, and all existing dialects other than Postgres remain unaffected (default stays false).

Summary by CodeRabbit

  • New Features

    • Added UUIDv7 generation for supported PostgreSQL databases.
    • PostgreSQL 18 and later can automatically use uuidv7() for UUID defaults.
    • UUIDv7 generation now prefers native runtime support when available, with a compatible fallback.
  • Bug Fixes

    • UUIDv7 defaults are no longer applied to PostgreSQL versions that do not support them.

@vineetj12
vineetj12 requested a review from a team as a code owner July 14, 2026 08:25
@vineetj12
vineetj12 requested review from Copilot, ephys and sdepold July 14, 2026 08:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

UUIDv7 generation now probes Node.js native support with a package fallback. Dialect capability checks support minimum database versions, and PostgreSQL declares UUIDv7 support from version 18.0.0 with uuidv7() SQL generation and corresponding tests.

Changes

UUIDv7 support

Layer / File(s) Summary
Core UUIDv7 generation and capability contract
packages/core/src/abstract-dialect/dialect.ts, packages/core/src/expression-builders/uuid.ts
UUIDv7 capability configuration accepts a minimum database version, while generation uses native Node.js support when available and otherwise falls back to the uuid package.
PostgreSQL UUIDv7 integration
packages/postgres/src/dialect.ts, packages/postgres/src/query-generator-typescript.internal.ts
PostgreSQL declares UUIDv7 support for version 18.0.0 and provides the uuidv7() function call.
UUIDv7 behavior validation
packages/core/test/unit/expression-builders/uuid.test.ts, packages/core/test/unit/query-interface/create-table.test.ts
Tests cover native and fallback generation plus PostgreSQL 18 and pre-18 UUIDv7 table defaults.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Sequelize
  participant PostgresDialect
  participant QueryGenerator
  participant Database
  Sequelize->>PostgresDialect: evaluate UUIDv7 support
  PostgresDialect->>Database: retrieve database version
  Database-->>PostgresDialect: return version
  PostgresDialect->>QueryGenerator: request UUIDv7 function call
  QueryGenerator-->>Sequelize: return uuidv7()
Loading

Possibly related PRs

  • sequelize/sequelize#17832: Extends the existing UUIDv7 dialect capability with version-gated configuration and support logic.

Suggested reviewers: sdepold, ephys

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: native UUIDv7 generation with a fallback for unsupported runtimes.
Linked Issues check ✅ Passed The PR adds native UUIDv7 generation, a Sequelize fn('uuidv7') path, and PostgreSQL 18+ support as requested.
Out of Scope Changes check ✅ Passed The changes stay focused on UUIDv7 generation, dialect support, and tests, with no unrelated additions evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@WikiRik

WikiRik commented Jul 14, 2026

Copy link
Copy Markdown
Member

Thanks for opening the PR! Please split the Node 26 and postgres 18 support to two different PRs. I have time to review those today, so it shouldn't delay this PR too much

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/core/src/expression-builders/uuid.ts (1)

9-13: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Cache the native UUIDv7 function reference.

Currently, the native crypto.randomUUIDv7 property is accessed and its type is checked on every single invocation. Caching the function reference at the module level avoids this overhead, which is particularly beneficial since UUID generation can be frequently called in hot paths like bulk inserts.

♻️ Proposed refactor
-function getNativeUuidV7(): string | undefined {
-  const nativeUuidV7 = (crypto as typeof crypto & { randomUUIDv7?: unknown }).randomUUIDv7;
-
-  return typeof nativeUuidV7 === 'function' ? nativeUuidV7() : undefined;
-}
+const nativeUuidV7Fn = (crypto as typeof crypto & { randomUUIDv7?: unknown }).randomUUIDv7;
+const nativeUuidV7 = typeof nativeUuidV7Fn === 'function' ? (nativeUuidV7Fn as () => string) : undefined;
+
+function getNativeUuidV7(): string | undefined {
+  return nativeUuidV7?.();
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/expression-builders/uuid.ts` around lines 9 - 13, Cache the
validated crypto.randomUUIDv7 function reference at module scope, then update
getNativeUuidV7 to reuse that reference without rereading or rechecking the
property on each invocation. Preserve the existing undefined fallback when the
native function is unavailable.
packages/core/test/unit/expression-builders/uuid.test.ts (1)

10-15: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Test generateUuidV7 with its default argument.

The current tests verify the injection of a custom generator and the fallback behavior, but they don't exercise the zero-argument behavior where it resolves the native generator (or fallback) by default. Adding a test for the default parameter ensures that the end-to-end integration works seamlessly.

♻️ Proposed refactor
   it('uses the provided native fn when available', () => {
     const nativeUuidV7 = sinon.stub().returns('native-uuidv7');
 
     expect(generateUuidV7(nativeUuidV7)).to.equal('native-uuidv7');
     expect(nativeUuidV7.callCount).to.equal(1);
   });
+
+  it('generates a valid UUIDv7 without arguments', () => {
+    const generated = generateUuidV7();
+    expect(generated).to.match(
+      /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
+    );
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/unit/expression-builders/uuid.test.ts` around lines 10 -
15, Add a unit test alongside the existing generateUuidV7 tests that calls
generateUuidV7() without passing a native generator, and assert it returns a
valid UUID v7 result through the default native-or-fallback resolution path.
Keep the existing injected-generator and fallback tests unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/core/src/expression-builders/uuid.ts`:
- Around line 9-13: Cache the validated crypto.randomUUIDv7 function reference
at module scope, then update getNativeUuidV7 to reuse that reference without
rereading or rechecking the property on each invocation. Preserve the existing
undefined fallback when the native function is unavailable.

In `@packages/core/test/unit/expression-builders/uuid.test.ts`:
- Around line 10-15: Add a unit test alongside the existing generateUuidV7 tests
that calls generateUuidV7() without passing a native generator, and assert it
returns a valid UUID v7 result through the default native-or-fallback resolution
path. Keep the existing injected-generator and fallback tests unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e40f4435-7b0e-43d5-be52-322516502748

📥 Commits

Reviewing files that changed from the base of the PR and between ac2e892 and 4d94281.

📒 Files selected for processing (8)
  • .github/workflows/ci.yml
  • dev/postgres/latest/docker-compose.yml
  • packages/core/src/abstract-dialect/dialect.ts
  • packages/core/src/expression-builders/uuid.ts
  • packages/core/test/unit/expression-builders/uuid.test.ts
  • packages/core/test/unit/query-interface/create-table.test.ts
  • packages/postgres/src/dialect.ts
  • packages/postgres/src/query-generator-typescript.internal.ts

@vineetj12
vineetj12 force-pushed the feat/uuidv7-native branch from eb8cc61 to 01d1707 Compare July 14, 2026 12:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/core/test/unit/query-interface/create-table.test.ts (1)

97-118: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add cross-dialect test coverage for sql.uuidV7.

The test for sql.uuidV7 default values is currently gated inside the if (dialect.name === 'postgres') block. To prevent regressions and ensure that JS-side fallback generation translates into valid schema generation (i.e., emitting a column with no DEFAULT clause) across all other dialects, consider extracting this test into a cross-dialect assertion similar to the existing supports sql.uuidV4 default values test.

The postgres < 18 fallback test at line 120 should remain inside the postgres block.

♻️ Proposed refactor to test across all dialects

Move this test outside the if (dialect.name === 'postgres') block and adjust it as follows:

  it('supports sql.uuidV7 default values', async () => {
    const localSequelize =
      dialect.name === 'postgres'
        ? createSequelizeInstance({
            databaseVersion: '18.0.0',
          })
        : sequelize;

    const stub = sinon.stub(localSequelize, 'queryRaw');

    await localSequelize.queryInterface.createTable('table', {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        defaultValue: sql.uuidV7,
      },
    });

    expect(stub.callCount).to.eq(1);
    const firstCall = stub.getCall(0);
    expectsql(firstCall.args[0], {
      postgres:
        'CREATE TABLE IF NOT EXISTS "table" ("id" UUID DEFAULT uuidv7(), PRIMARY KEY ("id"));',
      'mariadb mysql':
        'CREATE TABLE IF NOT EXISTS `table` (`id` CHAR(36) BINARY, PRIMARY KEY (`id`)) ENGINE=InnoDB;',
      mssql: `IF OBJECT_ID(N'[table]', 'U') IS NULL CREATE TABLE [table] ([id] UNIQUEIDENTIFIER, PRIMARY KEY ([id]));`,
      sqlite3: 'CREATE TABLE IF NOT EXISTS `table` (`id` TEXT PRIMARY KEY);',
      snowflake: 'CREATE TABLE IF NOT EXISTS "table" ("id" VARCHAR(36), PRIMARY KEY ("id"));',
      db2: 'CREATE TABLE IF NOT EXISTS "table" ("id" CHAR(36) FOR BIT DATA NOT NULL, PRIMARY KEY ("id"));',
      ibmi: `BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE VALUE '42710' BEGIN END; CREATE TABLE "table" ("id" CHAR(36), PRIMARY KEY ("id")); END`,
      oracle: `BEGIN EXECUTE IMMEDIATE 'CREATE TABLE "table" ("id" VARCHAR2(36),PRIMARY KEY ("id"))'; EXCEPTION WHEN OTHERS THEN IF SQLCODE != -955 THEN RAISE; END IF; END;`,
    });
  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/unit/query-interface/create-table.test.ts` around lines 97
- 118, Move the sql.uuidV7 default-value test outside the postgres-only block,
following the existing cross-dialect sql.uuidV4 test pattern. Use the
postgres-specific Sequelize instance with databaseVersion 18.0.0 only for
postgres, use the shared sequelize instance for other dialects, and add expected
SQL asserting no DEFAULT clause for non-Postgres dialects. Keep the postgres <18
fallback test inside the postgres block.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/core/test/unit/query-interface/create-table.test.ts`:
- Around line 97-118: Move the sql.uuidV7 default-value test outside the
postgres-only block, following the existing cross-dialect sql.uuidV4 test
pattern. Use the postgres-specific Sequelize instance with databaseVersion
18.0.0 only for postgres, use the shared sequelize instance for other dialects,
and add expected SQL asserting no DEFAULT clause for non-Postgres dialects. Keep
the postgres <18 fallback test inside the postgres block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9fea08b5-a8ae-424b-b964-6bf5e6f5652e

📥 Commits

Reviewing files that changed from the base of the PR and between eb8cc61 and 01d1707.

📒 Files selected for processing (6)
  • packages/core/src/abstract-dialect/dialect.ts
  • packages/core/src/expression-builders/uuid.ts
  • packages/core/test/unit/expression-builders/uuid.test.ts
  • packages/core/test/unit/query-interface/create-table.test.ts
  • packages/postgres/src/dialect.ts
  • packages/postgres/src/query-generator-typescript.internal.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/core/test/unit/expression-builders/uuid.test.ts
  • packages/postgres/src/dialect.ts
  • packages/postgres/src/query-generator-typescript.internal.ts
  • packages/core/src/abstract-dialect/dialect.ts

@vineetj12
vineetj12 force-pushed the feat/uuidv7-native branch from 01d1707 to 9be67f2 Compare July 14, 2026 15:11
@vineetj12

vineetj12 commented Jul 14, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review! I've updated the PR as requested.

  • Split the Node 26 and PostgreSQL 18 support into separate PRs.
  • This PR is now focused only on the PostgreSQL native UUIDv7 support.
  • Rebasing onto the latest main has been completed.
  • All CI checks are now passing.

Please let me know if there's anything else you'd like me to adjust. Thanks!

@WikiRik

WikiRik commented Jul 14, 2026

Copy link
Copy Markdown
Member

Please open those PRs now, so I can review this with the proper changes

@vineetj12

Copy link
Copy Markdown
Author

Thanks for the review! I've split the changes as requested.

  • This PR is now focused only on the PostgreSQL native UUIDv7 support.
  • I've opened a separate PR for the Node.js runtime UUIDv7 support.
  • Both branches have been rebased onto the latest main, and the relevant tests are passing.

Please let me know if you'd like any further changes.

@WikiRik

WikiRik commented Jul 14, 2026

Copy link
Copy Markdown
Member

I think I've been unclear. Apologies for that. I meant to say that we should have three PRs;

  1. Add support for Node 26 in the CI
  2. Add support for postgres 18 in the CI
  3. This PR; which adds UUIDv7 support for Node and postgres

@vineetj12

Copy link
Copy Markdown
Author

Thanks for clarifying, @WikiRik — understood, three PRs:

  1. Node 26 CI support (separate PR)
  2. PostgreSQL 18 CI support (separate PR)
  3. This PR — UUIDv7 support for Node and PostgreSQL, no CI changes

This PR already contains the full feature (native Node.js detection via
crypto.randomUUIDv7 with fallback, plus PostgreSQL's version-gated
support). I'll close #18261 since that feature belongs here instead of
as a separate PR, and I'll open the two CI PRs separately once this one
is settled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add native UUIDv7 support (v7 branch)

4 participants