Repository navigation
feat(core): Convert query.js to typescript. Implemented Caching, Pooling, and other optimizations. - #18051
Conversation
…or actual code. COPILOT DOESNT UNDERSTAND PERFORMANCE
|
Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughReplaces 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
Pull Request Overview
This PR performs a major refactoring of the query processing pipeline in Sequelize:
- Migrates
packages/core/src/abstract-dialect/query.jsfrom JavaScript to TypeScript (query.ts) - Replaces the
dottielibrary dependency with a custom high-performanceundot.tsmodule 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) |
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
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 wheni >= 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()anddeletein a loop, which is relatively slow:Object.keys()allocates an array, anddeletetriggers property map transitions in V8. For performance-critical pooling code, consider:
- Simplest: Just return
{}and rely on GC (may be faster than clearing if pools are small)- Fastest for many properties: Track keys during use and clear only those, or use a
Mapinstead of plain objectsExample 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
📒 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.
…here isnt much of a hit to performance doing it. also, we appease the clanker gods.
There was a problem hiding this comment.
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
📒 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.tspackages/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.tspackages/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
getUniqueKeyAttributesand 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
processedResultsinstead ofnull, 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
left a comment
There was a problem hiding this comment.
I'll do a proper review tomorrow (hopefully), but I also took a quick scan through the changes which resulted in these comments
Co-authored-by: Rik Smale <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
packages/core/src/abstract-dialect/query.ts (3)
122-145: Consider PascalCase for type name.The type
metaEntryuses camelCase, but TypeScript convention prefers PascalCase for type names (e.g.,MetaEntry). This would improve consistency with other type definitions in the file likeHashEntry,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
logWarningsmethod 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 topExistsForRowreads 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
📒 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
acquireValuesObjectandreleaseValuesObjectis 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
getHashfunction properly prioritizes primary keys, then unique keys, then unique indexes. Thebreakstatement at Line 680 correctly ensures only the first unique index is used, matching the logic ingetUniqueKeyAttributes.
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 offormatErrorbased onrawErrorsis 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
handleInsertQuerymethod 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
processedResultsinstead 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
_logQuerymethod 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:
- Builds metadata once on the first row (lines 1360-1420)
- Uses hash-based deduplication to avoid duplicate containers (lines 1424-1430)
- Employs object pooling to reduce GC pressure (lines 1432-1434)
- 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.
names are protected via bracketing syntax, so that doesnt matter either.
WikiRik
left a comment
There was a problem hiding this comment.
Additional suggestions for the eslint-disable. Haven't done the review of the actual changes yet
Co-authored-by: Rik Smale <[email protected]>
Co-authored-by: Rik Smale <[email protected]>
|
@SippieCup I'm coming back to this now. I think unit tests for the Apart from that I think I still need to do in depth review of the new query.ts code |
|
Ah right. I'll add those this week. enjoy the holidays! |
…eneration to ensure correct type gets generated.
|
@SippieCup fyi I've updated the PR to include the Oracle PR that we've merged today |
There was a problem hiding this comment.
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
📒 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.
|
lgtm! |
WikiRik
left a comment
There was a problem hiding this comment.
PR Review: Convert query.js to TypeScript with optimizations
Overview
This is a substantial and well-crafted PR that accomplishes several important goals:
- TypeScript conversion: Full migration from
query.js+query.d.tstoquery.tswith proper typing - Performance optimizations: Significant improvements to hydration performance through caching and pooling
- Dependency removal: Replaces
dottiedependency with customundot.tsutility - 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
_groupJoinDataalgorithm 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)
-
Type naming:
metaEntryshould beMetaEntryper TypeScript conventions (PascalCase for types) -
Comment cleanup: Line 1484 has "// Removed unused assignment to topExistsForRow" which reads more like a commit message than documentation
-
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!
|
The above comment was by AI. It didn't find anything major and I think it looks fine as well |
Pull Request Checklist
Description of Changes
Notes:
Obviously I converted query.js to typescript, which is awesome. Except I really took the easy way out, lotta
| undefinedthat 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.tswhich 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
New Features
Bug Fixes
Tests
✏️ Tip: You can customize this high-level summary in your review settings.