Skip to content

feat(core): Convert query.js to typescript. Implemented Caching, Pooling, and other optimizations. - #18051

Merged
WikiRik merged 31 commits into
sequelize:mainfrom
SippieCup:join_optimization
Jan 23, 2026
Merged

WikiRik merged 31 commits into
sequelize:mainfrom
SippieCup:join_optimization

Conversation

@SippieCup

@SippieCup SippieCup commented Nov 8, 2025 •

Copy link
Copy Markdown
Contributor

Pull Request Checklist

  • Have you added new tests to prevent regressions? None needed. No core functionality change.
  • Did you update the typescript typings accordingly (if applicable)?
  • Does the name of your PR follow our conventions?

Description of Changes

  1. Converted query.js to be fully typed.
  2. Added caching to Hydration. Computes metadata on first row instead of every row.
  3. Refactored variable usage to avoid dangerous recasting. Should improve branch prediction.
  4. Hoisted function to allow for in-lining by compiler.
  5. Added pooling to row resolution. more predictable garbage collection.
  6. Removed Dottie dependency.

Notes:

Obviously I converted query.js to typescript, which is awesome. Except I really took the easy way out, lotta | undefined that should be resolved at a later point in a cleaner way.

More importantly (or less for maintainability... but important to me), because we know what the shape and size of the data coming out is going to be, there are a lot of optimizations that can be made within hydration. the data is at least predictable from it's own set, which is what I did here. But it can be taken a step further and cached off the model definitions at init, then reused rather than rebuilding it every query.

That said, this is by far good enough. In sufficently large enough queries (I can share privately) we can see a speedup on hydration around 60-70%. Hydration on a shallow include like foo.bar, across 5,000 rows still nets a 12% speedup. While complexity doesnt really change, the coefficent of work per row drops significantly.

I then applied the same general concepts to a simplified Dottie utlity, undot.ts which takes in the simple transforms we have and should make it a bit faster, typed, and maintainable. Dottie was pretty fast, so idk if this really makes much of a difference.

List of Breaking Changes

No breaking changes

Summary by CodeRabbit

  • Refactor

    • Core query abstraction and result processing rewritten to unify query lifecycle, parsing, logging, and join-grouping behavior.
  • New Features

    • Fast flat→nested transformer with precompilation and object pooling to accelerate reconstruction of nested query results.
  • Bug Fixes

    • Improved handling of enum array column types so generated SQL/DDL is correct.
  • Tests

    • Added unit tests for the transformer and new/updated query-generation behaviors.

✏️ Tip: You can customize this high-level summary in your review settings.

@SippieCup
SippieCup requested a review from a team as a code owner November 8, 2025 01:57
@coderabbitai

coderabbitai Bot commented Nov 8, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Replaces the removed AbstractQuery JS/typings with a TypeScript AbstractQuery implementation, adds typed options, and introduces an undot utility to transform flat dotted/bracketed keys into nested objects for result post-processing and pooling.

Changes

Cohort / File(s) Summary
Removed JS + d.ts
packages/core/src/abstract-dialect/query.d.ts, packages/core/src/abstract-dialect/query.js
Deleted the previous AbstractQuery typings and JS implementation, removing exported interfaces and the AbstractQuery class and its helpers.
New TypeScript AbstractQuery
packages/core/src/abstract-dialect/query.ts
Added a full TypeScript AbstractQuery implementation and exported interfaces (AbstractQueryOptions, AbstractQueryGroupJoinDataOptions, AbstractQueryFormatBindOptions) including lifecycle, query-type predicates, result parsing, logging, and static join-grouping logic.
New undot utility
packages/core/src/utils/undot.ts
Added tokenize/precompile/set/transform utilities and a simple object pool to convert dotted/bracketed flat keys (e.g., a.b[0].c) into nested structures at high performance.
Tests added
packages/core/test/unit/query-generator/create-table-query.test.ts, packages/core/test/unit/utils/undot.test.ts
Added PostgreSQL UUID array DDL test(s) and extensive unit tests for undot (tokenizePath, precompileKeys, setByPathArray, transformRowWithPrecompiled, pooling and edge cases).
Postgres enum array handling
packages/postgres/src/query-generator.js
Fixes enum-array detection by extracting array element subtype and using it when resolving ENUM values for ARRAY columns.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Q as AbstractQuery
    participant U as undot.ts
    participant M as Model

    Caller->>Q: handleSelectQuery(rows, options)
    Q->>Q: _parseDataArrayByType(rows, model?, includeMap?)
    alt flat->nested transform
        Q->>U: precompileKeys(keys)
        U-->>Q: precompiled map
        Q->>U: transformRowWithPrecompiled(row, pre)
        U-->>Q: nested row
    end
    Q->>M: build/map parsed values into model instances
    M-->>Q: instances
    Q-->>Caller: processed results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • sdepold
  • ephys

Poem

🐇 I hopped through lines of JS and TS,
I tokenized dots and jumped the square nests,
I stitched flat rows into nested tea trees,
Typed queries hum while pooled objects rest,
A tiny rabbit claps — well parsed and blessed!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: converting query.js to TypeScript and implementing caching/pooling optimizations as evidenced by the addition of query.ts with comprehensive query processing, the new undot.ts utility for pooling/optimization, and removal of the old query.js/query.d.ts.
Docstring Coverage ✅ Passed Docstring coverage is 95.83% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

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.

Pull Request Overview

This PR performs a major refactoring of the query processing pipeline in Sequelize:

  • Migrates packages/core/src/abstract-dialect/query.js from JavaScript to TypeScript (query.ts)
  • Replaces the dottie library dependency with a custom high-performance undot.ts module for transforming flat dotted keys into nested objects
  • Removes outdated CHANGELOG files for several packages

Reviewed Changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
packages/core/src/abstract-dialect/query.ts Complete TypeScript rewrite of the AbstractQuery class with improved type safety, performance optimizations (traditional for-loops, object pooling), and comprehensive documentation
packages/core/src/abstract-dialect/query.js Removed original JavaScript implementation
packages/core/src/abstract-dialect/query.d.ts Removed separate type definitions file (now co-located in .ts file)
packages/core/src/utils/undot.ts New high-performance module replacing dottie.js for transforming flat dotted keys to nested objects with array index support
packages/validator-js/CHANGELOG.md Removed changelog (likely auto-generated)
packages/utils/CHANGELOG.md Removed changelog (likely auto-generated)
packages/core/CHANGELOG.md Removed changelog (likely auto-generated)
CHANGELOG.md Removed root changelog (likely auto-generated)

Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved

@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.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0e8bd9 and b1a1d2d.

📒 Files selected for processing (8)
  • CHANGELOG.md (0 hunks)
  • packages/core/CHANGELOG.md (0 hunks)
  • packages/core/src/abstract-dialect/query.d.ts (0 hunks)
  • packages/core/src/abstract-dialect/query.js (0 hunks)
  • packages/core/src/abstract-dialect/query.ts (1 hunks)
  • packages/core/src/utils/undot.ts (1 hunks)
  • packages/utils/CHANGELOG.md (0 hunks)
  • packages/validator-js/CHANGELOG.md (0 hunks)
💤 Files with no reviewable changes (6)
  • packages/validator-js/CHANGELOG.md
  • packages/core/CHANGELOG.md
  • packages/core/src/abstract-dialect/query.js
  • packages/utils/CHANGELOG.md
  • packages/core/src/abstract-dialect/query.d.ts
  • CHANGELOG.md
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
🧬 Code graph analysis (1)
packages/core/src/abstract-dialect/query.ts (5)
packages/core/src/model.d.ts (3)
  • ModelStatic (3183-3183)
  • IncludeOptions (654-758)
  • BuildOptions (1013-1030)
packages/core/src/model-typescript.ts (2)
  • primaryKeyAttributes (118-120)
  • uniqueKeys (352-384)
packages/core/src/abstract-dialect/connection-manager.ts (1)
  • AbstractConnection (15-19)
packages/core/src/utils/undot.ts (5)
  • PrecompiledTransform (23-28)
  • precompileKeys (109-126)
  • transformRowWithPrecompiled (198-215)
  • tokenizePath (38-101)
  • setByPathArray (136-188)
packages/core/src/abstract-dialect/data-types.ts (1)
  • NormalizedDataType (63-63)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Lint code

@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.

Actionable comments posted: 2

♻️ Duplicate comments (1)
packages/core/src/utils/undot.ts (1)

59-91: Unclosed bracket not detected.

If a bracket is opened but never closed (e.g., "a[0"), the inner while loop exits when i >= n, and if digits were found, the function silently accepts the malformed input without throwing an error. Only empty brackets trigger the error at line 86.

Add explicit validation after the digit-reading loop:

       while (i < n) {
         const c = key.charCodeAt(i);
         if (c >= 48 && c <= 57) {
           hasDigit = true;
           num = num * 10 + (c - 48);
           i++;
           continue;
         }
 
         if (c === 93 /* ']' */) {
           i++;
           break;
         }
 
         // Non-digit inside brackets: fallback to simple behavior (treat as text)
         // For perf, this doesn't support ["complex.key"] patterns.
         throw new Error(`Unsupported bracket syntax in key: ${key}`);
       }
 
+      if (i >= n) {
+        throw new Error(`Unclosed bracket in key: ${key}`);
+      }
+
       if (!hasDigit) {
         throw new Error(`Empty or non-numeric bracket in key: ${key}`);
       }
🧹 Nitpick comments (2)
packages/core/src/utils/undot.ts (2)

1-14: Consider improving the justification comment.

The comment "disable some linting rules for performance" is vague. Consider documenting specifically why each rule is disabled (e.g., "prefer-includes has overhead vs indexOf in tight loops", "traditional for-loops avoid iterator allocation").


223-236: Consider faster object clearing strategy.

The current approach uses Object.keys() and delete in a loop, which is relatively slow: Object.keys() allocates an array, and delete triggers property map transitions in V8. For performance-critical pooling code, consider:

  1. Simplest: Just return {} and rely on GC (may be faster than clearing if pools are small)
  2. Fastest for many properties: Track keys during use and clear only those, or use a Map instead of plain objects

Example with tracked keys:

-export function acquirePooledObject(pool: Array<Record<string, unknown>>): Record<string, unknown> {
-  const obj = pool.pop();
-  if (!obj) {
-    return {};
-  }
-  // Clear previous contents
-
-  const keys = Object.keys(obj);
-  for (let i = 0; i < keys.length; i++) {
-    delete (obj as any)[keys[i]];
-  }
-
-  return obj;
-}
+export function acquirePooledObject(
+  pool: Array<{ obj: Record<string, unknown>; keys: string[] }>
+): Record<string, unknown> {
+  const entry = pool.pop();
+  if (!entry) {
+    return {};
+  }
+  // Clear only known keys
+  const { obj, keys } = entry;
+  for (let i = 0; i < keys.length; i++) {
+    delete obj[keys[i]];
+  }
+  return obj;
+}

Or simply return a new object if the pool doesn't provide significant benefit.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b1a1d2d and 6a95a32.

📒 Files selected for processing (1)
  • packages/core/src/utils/undot.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Upload install and build artifact (Node 20)
  • GitHub Check: Upload install and build artifact (Node 18)
🔇 Additional comments (2)
packages/core/src/utils/undot.ts (2)

109-126: LGTM!

The fast-path optimization for simple keys and dual indexing (array + Map) are well-designed for the performance goals.


198-215: Function depends on setByPathArray fixes.

The logic here is sound, but this function inherits the critical bug from setByPathArray. Once that's fixed, this should work correctly. The undefined-skipping behavior is appropriate for typical row transformation use cases.

Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
…here isnt much of a hit to performance doing it.

also, we appease the clanker gods.

@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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/core/src/utils/undot.ts (1)

180-193: Replace informal comment with clear technical explanation.

The edge case handling is valid (single-segment numeric paths from table aliases or unusual column names), but the comment signals uncertainty. Replace with a professional explanation.

Apply this diff:

   const leaf = path[last];
   if (typeof leaf === 'number') {
     if (!Array.isArray(obj)) {
-      // LLMs said we need this. I'm not sure, but it seems like it won't hurt. -sid
-      // Convert to array for correctness; small overhead but rare in well-formed paths
+      // Handle single-segment numeric paths (e.g., table aliases or columns named "0")
+      // When path length is 1, the traversal loop never runs and obj remains the target object
       const arr: any[] = [];
       (obj as any[]).length = 0; // drop refs (no-op if not array)
       obj = arr;

Based on learnings

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ee33cb and a3ace77.

📒 Files selected for processing (2)
  • packages/core/src/abstract-dialect/query.ts (1 hunks)
  • packages/core/src/utils/undot.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:177-177
Timestamp: 2025-11-08T03:05:56.939Z
Learning: In packages/core/src/utils/undot.ts, the defensive check "if (!Array.isArray(obj))" before numeric leaf assignment in setByPathArray is intentional to handle edge cases where table aliases or oddly-named columns produce single-segment numeric keys (e.g., "0").
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:148-188
Timestamp: 2025-11-08T03:08:35.621Z
Learning: In packages/core/src/utils/undot.ts, the setByPathArray function intentionally does not track parent references or write back replaced containers (e.g., when converting non-array to array at numeric segments). This is a deliberate performance trade-off: adding parent tracking causes ~10% performance degradation with 1 million rows. The function expects well-formed input and does not defensively handle all edge cases.
📚 Learning: 2025-11-08T03:05:56.939Z
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:177-177
Timestamp: 2025-11-08T03:05:56.939Z
Learning: In packages/core/src/utils/undot.ts, the defensive check "if (!Array.isArray(obj))" before numeric leaf assignment in setByPathArray is intentional to handle edge cases where table aliases or oddly-named columns produce single-segment numeric keys (e.g., "0").

Applied to files:

  • packages/core/src/utils/undot.ts
📚 Learning: 2025-11-08T03:08:35.621Z
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:148-188
Timestamp: 2025-11-08T03:08:35.621Z
Learning: In packages/core/src/utils/undot.ts, the setByPathArray function intentionally does not track parent references or write back replaced containers (e.g., when converting non-array to array at numeric segments). This is a deliberate performance trade-off: adding parent tracking causes ~10% performance degradation with 1 million rows. The function expects well-formed input and does not defensively handle all edge cases.

Applied to files:

  • packages/core/src/utils/undot.ts
  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js

Applied to files:

  • packages/core/src/utils/undot.ts
  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/dialect.ts : When adding a dialect feature, update packages/{dialect}/src/dialect.ts to declare feature support flags

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
🧬 Code graph analysis (1)
packages/core/src/abstract-dialect/query.ts (6)
packages/core/src/model.d.ts (2)
  • ModelStatic (3183-3183)
  • IncludeOptions (654-758)
packages/core/src/model-typescript.ts (2)
  • primaryKeyAttributes (118-120)
  • uniqueKeys (352-384)
packages/core/src/abstract-dialect/connection-manager.ts (1)
  • AbstractConnection (15-19)
packages/core/src/utils/undot.ts (5)
  • PrecompiledTransform (23-28)
  • precompileKeys (115-132)
  • transformRowWithPrecompiled (204-221)
  • tokenizePath (38-107)
  • setByPathArray (142-194)
packages/core/src/abstract-dialect/data-types.ts (1)
  • NormalizedDataType (63-63)
packages/core/src/data-types.ts (1)
  • AbstractDataType (17-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Upload install and build artifact (Node 18)
  • GitHub Check: Upload install and build artifact (Node 20)
🔇 Additional comments (7)
packages/core/src/utils/undot.ts (1)

1-14: LGTM - Performance optimizations documented.

The eslint disables are appropriate for hot-path code and the rationale is clearly documented.

packages/core/src/abstract-dialect/query.ts (6)

1-256: LGTM - Well-structured utilities and caching.

The eslint disables are documented, caching strategy is sound, and the utility functions are correctly implemented.


280-614: LGTM - Deduplication and pooling logic is sound.

The JOIN deduplication strategy using hashing and the object pooling implementation are well-designed for the performance requirements.


648-685: LGTM - Hash computation correctly prioritizes identity attributes.

The break at line 680 correctly ensures only the first unique index is used, matching the logic in getUniqueKeyAttributes and preventing incorrect hash combinations.


846-1049: LGTM - AbstractQuery core methods are well-implemented.

The constructor properly initializes state, type predicates are clear, and the insert handling safely manages auto-increment attributes.


1060-1174: LGTM - Critical null result issue resolved.

The fallback at lines 1165-1167 ensures plain SELECT queries without models return processedResults instead of null, fixing the regression from the previous implementation.


1332-1515: LGTM - JOIN grouping algorithm is well-optimized.

The extensive benchmarking justification for array pre-allocation (lines 1348-1370) demonstrates thoughtful performance work. The hash-based deduplication strategy and metadata caching on the first row are solid optimizations for the hot path.

@WikiRik WikiRik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'll do a proper review tomorrow (hopefully), but I also took a quick scan through the changes which resulted in these comments

Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved

@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.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/core/src/abstract-dialect/query.ts (3)

122-145: Consider PascalCase for type name.

The type metaEntry uses camelCase, but TypeScript convention prefers PascalCase for type names (e.g., MetaEntry). This would improve consistency with other type definitions in the file like HashEntry, IncludeMap, etc.

Apply this diff to follow TypeScript naming conventions:

-type metaEntry = {
+type MetaEntry = {

Then update all usages throughout the file (lines 280, 281, 313, 399, 436, 447, 486, 498, 725, 1344, 1436, 1439, 1442, 1463, 1466).


881-923: Consider simplifying the nested iteration logic.

The logWarnings method has deeply nested loops and conditional checks to handle various warning result formats. While functional, this could potentially be refactored to use helper functions for each warning format type to improve readability.

Example approach:

function extractMessage(warningResult: unknown): string | null {
  // Extract message from various formats
  // ...
}

However, given this handles edge cases from multiple database dialects, the defensive approach may be justified.


1484-1484: Consider removing or clarifying this comment.

The comment // Removed unused assignment to topExistsForRow reads more like a commit message than production code documentation. Consider either removing it or clarifying why the assignment was removed (e.g., // topExistsForRow is not needed after finalization).

-        // Removed unused assignment to topExistsForRow
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a3ace77 and 03d20cf.

📒 Files selected for processing (1)
  • packages/core/src/abstract-dialect/query.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:177-177
Timestamp: 2025-11-08T03:05:56.939Z
Learning: In packages/core/src/utils/undot.ts, the defensive check "if (!Array.isArray(obj))" before numeric leaf assignment in setByPathArray is intentional to handle edge cases where table aliases or oddly-named columns produce single-segment numeric keys (e.g., "0").
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:148-188
Timestamp: 2025-11-08T03:08:35.621Z
Learning: In packages/core/src/utils/undot.ts, the setByPathArray function intentionally does not track parent references or write back replaced containers (e.g., when converting non-array to array at numeric segments). This is a deliberate performance trade-off: adding parent tracking causes ~10% performance degradation with 1 million rows. The function expects well-formed input and does not defensively handle all edge cases.
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
📚 Learning: 2025-11-08T03:05:56.939Z
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:177-177
Timestamp: 2025-11-08T03:05:56.939Z
Learning: In packages/core/src/utils/undot.ts, the defensive check "if (!Array.isArray(obj))" before numeric leaf assignment in setByPathArray is intentional to handle edge cases where table aliases or oddly-named columns produce single-segment numeric keys (e.g., "0").

Applied to files:

  • packages/core/src/abstract-dialect/query.ts
🧬 Code graph analysis (1)
packages/core/src/abstract-dialect/query.ts (4)
packages/core/src/model.d.ts (3)
  • ModelStatic (3183-3183)
  • IncludeOptions (654-758)
  • BuildOptions (1013-1030)
packages/core/src/model-typescript.ts (2)
  • primaryKeyAttributes (118-120)
  • uniqueKeys (352-384)
packages/core/src/abstract-dialect/connection-manager.ts (1)
  • AbstractConnection (15-19)
packages/core/src/utils/undot.ts (5)
  • PrecompiledTransform (23-28)
  • precompileKeys (115-132)
  • transformRowWithPrecompiled (204-221)
  • tokenizePath (38-107)
  • setByPathArray (142-194)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Upload install and build artifact (Node 20)
  • GitHub Check: Upload install and build artifact (Node 18)
🔇 Additional comments (10)
packages/core/src/abstract-dialect/query.ts (10)

1-47: LGTM! Well-documented performance optimizations.

The eslint-disable for traditional for-loops is properly justified, and the WeakMap-based caching strategy for model metadata is a solid performance optimization. The comprehensive module documentation provides good context for future maintainers.


353-378: Object pooling implementation looks good.

The pooling pattern with acquireValuesObject and releaseValuesObject is a solid optimization for reducing GC pressure in high-throughput scenarios. Clearing objects by deleting keys (rather than creating new objects) is a valid approach here, especially given the PR mentions significant performance gains.


648-685: Hash generation logic is correct.

The getHash function properly prioritizes primary keys, then unique keys, then unique indexes. The break statement at Line 680 correctly ensures only the first unique index is used, matching the logic in getUniqueKeyAttributes.


789-844: LGTM! Clean public API interfaces.

The exported interfaces are well-documented and provide a clear contract for the query system. The option types are appropriately flexible while maintaining type safety.


855-879: Constructor implementation is solid.

Proper option merging with sensible defaults (plain: false, raw: false, logging: console.debug). The conditional assignment of formatError based on rawErrors is a good pattern for performance when error wrapping is disabled.


979-1021: Query type detection and handling is correct.

The type checker methods are straightforward and efficient. The handleInsertQuery method properly handles the optional nature of instances and auto-increment attributes with appropriate defensive checks.


1060-1174: SELECT query handling is comprehensive and correct.

The method properly handles all query modes (raw, nested, joined, plain) with appropriate fallbacks. The fix at lines 1165-1167 ensures that plain SELECT queries without a model return processedResults instead of null, addressing the previous review concern. The precompiled transform caching (lines 1078-1100) is an excellent optimization for repeated row structures.


1184-1257: LGTM! Type-aware parsing with proper recursion.

The parsing methods correctly handle nested includes by recursively descending into child objects and arrays. The defensive type checking in _parseDatabaseValue (lines 1248-1254) ensures robustness when attribute types are missing or unexpected.


1278-1310: Logging implementation is well-designed.

The _logQuery method returns a closure for completion logging, which is a clean pattern for measuring execution time. The separation of debug context and sequelize logging allows for different verbosity levels.


1332-1491: Complex but highly optimized JOIN grouping algorithm.

This method is the core of the performance improvements mentioned in the PR. The algorithm efficiently:

  1. Builds metadata once on the first row (lines 1360-1420)
  2. Uses hash-based deduplication to avoid duplicate containers (lines 1424-1430)
  3. Employs object pooling to reduce GC pressure (lines 1432-1434)
  4. Pre-allocates result arrays when possible (line 1349)

The complexity is justified by the reported 60-70% hydration speedup for large queries. Breaking this down into smaller functions could hurt performance by preventing inlining.

@WikiRik WikiRik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Additional suggestions for the eslint-disable. Haven't done the review of the actual changes yet

Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
Comment thread packages/core/src/utils/undot.ts Resolved
@WikiRik

WikiRik commented Dec 24, 2025

Copy link
Copy Markdown
Member

@SippieCup I'm coming back to this now. I think unit tests for the undot utils is the main thing that's holding this back from merging.

Apart from that I think I still need to do in depth review of the new query.ts code

@SippieCup

Copy link
Copy Markdown
Contributor Author

Ah right. I'll add those this week.

enjoy the holidays!

@WikiRik

WikiRik commented Jan 14, 2026

Copy link
Copy Markdown
Member

@SippieCup fyi I've updated the PR to include the Oracle PR that we've merged today

@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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/core/test/unit/query-generator/create-table-query.test.ts`:
- Around line 339-373: Update the expected SQL string in the test for
UuidArrayModel by removing the stray space before the comma after the id column:
locate the expectsql call that checks queryGenerator.createTableQuery for
UuidArrayModel and change the postgres expected value from '"id" UUID ,' to
'"id" UUID,' so the expected SQL matches the formatting used elsewhere.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd5a142 and 8fe0e5d.

📒 Files selected for processing (1)
  • packages/core/test/unit/query-generator/create-table-query.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
packages/**/test/**/*.test.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name unit tests with the .test.ts suffix

Files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
packages/**/test/**/*.test.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

packages/**/test/**/*.test.{js,ts}: Use Support.getTestDialectTeaser() for dialect-specific test descriptions
Use beforeEach/afterEach to sync with { force: true } and close Sequelize instances in tests
In tests, skip unsupported behavior with dialect.supports.featureName checks

Files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
🧠 Learnings (5)
📓 Common learnings
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations
Learnt from: SippieCup
Repo: sequelize/sequelize PR: 18051
File: packages/core/src/utils/undot.ts:177-177
Timestamp: 2025-11-08T03:05:56.951Z
Learning: In packages/core/src/utils/undot.ts, the defensive check "if (!Array.isArray(obj))" before numeric leaf assignment in setByPathArray is intentional to handle edge cases where table aliases or oddly-named columns produce single-segment numeric keys (e.g., "0").
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations

Applied to files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js

Applied to files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/test/**/*.test.{js,ts} : Use beforeEach/afterEach to sync with { force: true } and close Sequelize instances in tests

Applied to files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
Repo: sequelize/sequelize PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js

Applied to files:

  • packages/core/test/unit/query-generator/create-table-query.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Upload install and build artifact (Node 20)
  • GitHub Check: Upload install and build artifact (Node 18)
🔇 Additional comments (1)
packages/core/test/unit/query-generator/create-table-query.test.ts (1)

1-1: LGTM!

Import is necessary for the new UUID array test case.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@SippieCup

Copy link
Copy Markdown
Contributor Author

@WikiRik

lgtm!

@WikiRik WikiRik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

PR Review: Convert query.js to TypeScript with optimizations

Overview

This is a substantial and well-crafted PR that accomplishes several important goals:

  1. TypeScript conversion: Full migration from query.js + query.d.ts to query.ts with proper typing
  2. Performance optimizations: Significant improvements to hydration performance through caching and pooling
  3. Dependency removal: Replaces dottie dependency with custom undot.ts utility
  4. Bug fix: Fixes enum array column type handling in Postgres

Code Quality Assessment

Strengths:

  • Well-documented code with comprehensive JSDoc comments
  • Clear separation of concerns with extracted helper functions
  • Smart use of WeakMaps for model metadata caching
  • Object pooling pattern for reduced GC pressure
  • Comprehensive test coverage for undot.ts (534 lines of tests covering edge cases)
  • The _groupJoinData algorithm is significantly more readable than the original while maintaining performance

Performance Optimizations:

  • Metadata computed once on first row rather than per-row
  • Precompiled key transforms for raw/nested queries
  • Object pooling avoids repeated allocations in hot loops
  • Traditional for-loops with proper JIT-friendly patterns
  • Result array pre-allocation when deduplication is disabled

Minor Suggestions (non-blocking)

  1. Type naming: metaEntry should be MetaEntry per TypeScript conventions (PascalCase for types)

  2. Comment cleanup: Line 1484 has "// Removed unused assignment to topExistsForRow" which reads more like a commit message than documentation

  3. Test formatting: The expected SQL in the UUID array test has a stray space ("id" UUID , vs "id" UUID,) - may be intentional based on how attributesToSQL works

The Postgres enum array fix

The fix in packages/postgres/src/query-generator.js correctly uses attribute.type.options.type instead of attribute.type.type to get the array subtype. This is a good fix that prevents incorrect SQL generation for ENUM arrays.

Testing

  • The undot.ts tests are thorough and cover edge cases including:

    • Bracket indices and nested paths
    • Object pooling lifecycle
    • Error handling for malformed keys
  • The create-table-query test validates the enum array fix works correctly

Conclusion

This is high-quality work that improves both the codebase maintainability (TypeScript, better organization) and runtime performance (caching, pooling). The claimed 60-70% speedup on large query hydration is plausible given the algorithmic improvements.

Approving this PR. Great work @SippieCup!

@WikiRik

WikiRik commented Jan 23, 2026

Copy link
Copy Markdown
Member

The above comment was by AI. It didn't find anything major and I think it looks fine as well

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.

3 participants