You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: disable global order for aggregate functions - #11925
This pull request addresses an issue where an incorrect SQL query is generated when using aggregate functions on the entity repository, such as repo.max().
-- BeforeSELECTMAX("Post"."counter") AS"MAX"FROM"post""Post"ORDER BY"Post"."counter"-- QueryFailedError: Use GROUP BY "Post"."counter"-- AfterSELECTMAX("Post"."counter") AS"MAX"FROM"post""Post"
Note: When using an aggregate function on a single column, the ORDER BY clause is redundant.
Pull-Request Checklist
Code is up-to-date with the master branch
This pull request links relevant issues as Fixes #11213
There are new or updated tests validating the change (tests/**.test.ts)
Documentation has been updated to reflect this change (docs/docs/**.md) (N/A)
This pull request addresses an issue where an incorrect SQL query is generated when using aggregate functions on the entity repository, such as repo.max().
-- BeforeSELECTMAX("Post"."counter") AS"MAX"FROM"post""Post"ORDER BY"Post"."counter"-- QueryFailedError: Use GROUP BY "Post"."counter"-- AfterSELECTMAX("Post"."counter") AS"MAX"FROM"post""Post"
Note: When using an aggregate function on a single column, the ORDER BY clause is redundant.
Pull-Request Checklist
Code is up-to-date with the master branch
This pull request links relevant issues as Fixes #11213
There are new or updated tests validating the change (tests/**.test.ts)
Documentation has been updated to reflect this change (docs/docs/**.md)
PR Type
Bug fix, Tests
Description
Disable global ORDER BY clause for aggregate functions
Add setOption("disable-global-order") to aggregate query builder
Update Post entity test fixture with orderBy configuration
Prevents QueryFailedError when using aggregate functions like max()
Diagram Walkthrough
flowchart LR
A["Aggregate Function Query"] -->|setOption disable-global-order| B["Query Builder"]
B -->|generates SQL| C["SELECT without ORDER BY"]
C -->|executes successfully| D["Result"]
Loading
File Walkthrough
Relevant files
Bug fix
EntityManager.ts
Add disable-global-order option to aggregate queries
src/entity-manager/EntityManager.ts
Added .setOption("disable-global-order") to aggregate function query builder
Prevents redundant ORDER BY clause in aggregate queries
Resolves QueryFailedError when using aggregate functions on repositories
Move the .setOption("disable-global-order") call to before qb.setFindOptions({ where }) to ensure the entity-level orderBy is not applied to the aggregate query.
const qb = this.createQueryBuilder(entityClass, metadata.name)
+qb.setOption("disable-global-order")
qb.setFindOptions({ where })
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly points out a potential logic error where the disable-global-order option is set too late, making the PR's fix potentially ineffective.
Medium
Clear ordering on aggregate queries
Add a .orderBy() call without arguments before .select() to explicitly clear any ordering clauses from the query builder for the aggregate query.
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 6
__
Why: The suggestion offers a valid alternative to fix the issue by explicitly clearing any ordering with .orderBy(), which is a more direct approach than relying on an option.
Reorder the query builder methods by placing the .setOption() call before the .select() call to improve code readability and adhere to common conventions.
Why: The suggestion proposes a stylistic change to reorder query builder methods for better readability, which is a valid but low-impact improvement as it does not affect functionality.
Replace the setOption call, which uses a string literal, with a more type-safe alternative like a dedicated method or a constant to avoid potential typos and improve code clarity.
Why: The suggestion correctly identifies the use of a "magic string" and proposes a more robust and maintainable approach, which is a valid code quality improvement.
Replace the magic string "disable-global-order" in setOption with a more robust solution like a dedicated method or a constant to improve type safety and prevent typos.
Why: The suggestion correctly identifies the use of a 'magic string' which is a code smell, but the proposed improved_code uses a disableGlobalOrder() method that does not exist on the SelectQueryBuilder, making the specific improvement invalid.
Reorder the query builder calls by moving .setOption("disable-global-order") before the .select() method call for improved code structure and readability.
Why: The suggestion correctly points out that for better code structure and readability, configuration methods like setOption should precede action methods like select in a query builder chain, even if it doesn't affect functionality.
Replace parseFloat with Number() and add a check using Number.isSafeInteger to prevent potential precision loss for large aggregate values, throwing an error if the number is unsafe.
const result = await qb
.select(
`${fnName}(${this.connection.driver.escape(
alias,
)}.${this.connection.driver.escape(column.databaseName)})`,
fnName,
)
.setOption("disable-global-order")
.getRawOne()
-return result[fnName] === null ? null : parseFloat(result[fnName])+if (!result || result[fnName] === null) {+ return null+}++const num = Number(result[fnName])++if (Number.isInteger(num) && !Number.isSafeInteger(num)) {+ throw new TypeORMError(+ `Precision loss in ${fnName} calculation. The result ${result[fnName]} is larger than Number.MAX_SAFE_INTEGER.`,+ )+}++return num+
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a potential silent data corruption issue due to precision loss when parseFloat is used on large numbers from aggregate functions. The proposed fix to check for safe integers and throw an error is a robust way to prevent incorrect results.
1. repository.maximum() ordering change undocumented 📘 Rule violation✧ Quality⭐ New
Description
Aggregate methods now disable entity/global orderBy, changing generated SQL for users relying on
entity orderBy. Documentation for repository aggregate methods and @Entity({ orderBy }) does not
mention this behavior, so users may be surprised by the change.
Compliance ID 2 requires docs updates for user-facing behavior changes. The PR explicitly changes
SQL generation for aggregate methods by disabling global ordering, but the repository API docs list
aggregate methods without clarifying that orderBy is ignored, and the decorator docs describe
orderBy broadly without noting aggregates are excluded.
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue description
Repository aggregate methods (e.g., `maximum`, `minimum`, `sum`, `average`) now ignore entity/global `orderBy` by disabling global ordering, which is a user-visible SQL generation change. Docs should explicitly state that aggregate methods do not apply `orderBy` (including `@Entity({ orderBy })`).
## Issue Context
The PR fixes issue #11213 by removing redundant/incorrect `ORDER BY` from aggregate queries via `.setOption("disable-global-order")`. Current docs describe aggregate methods but do not mention ordering behavior, and `@Entity({ orderBy })` docs describe default ordering broadly.
## Fix Focus Areas
- docs/docs/working-with-entity-manager/6-repository-api.md[336-358]
- docs/docs/help/3-decorator-reference.md[17-25]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
2. Missing issue reference in test 📘 Rule violation✓ Correctness
Description
• The PR fixes issue #11213 but the test file does not include a comment referencing this issue. •
Per compliance rule 3, issue fixes should include an issue reference in the test comment when
applicable. • This makes it harder to trace the test back to the original issue for future
maintenance.
The PR description states 'Closes #11213' and the test was modified to add orderBy configuration to
verify the fix works. However, there is no comment in the test file referencing issue #11213. The
compliance rule states that 'issue fixes add or update tests in test/functional, with an issue
reference in the test comment when applicable.' Since this is an issue fix with a test update, a
comment reference would help trace the test to the original issue.
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue description
The test file is missing a comment that references issue #11213, which this PR fixes. Adding this reference helps with traceability and future maintenance.
## Issue Context
The PR fixes issue #11213 where aggregate functions incorrectly generated SQL with ORDER BY clauses. The test was updated to add `orderBy` configuration to the Post entity to verify that aggregate functions now properly disable the global order.
## Fix Focus Areas
- test/functional/repository/aggregate-methods/entity/Post.ts[5-5]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
ⓘ The new review experience is currently in Beta. Learn more
1. Missing issue reference in test 📘 Rule violation✧ Quality
Description
• The PR fixes issue #11213 but the test file does not include a comment referencing this issue.
• Per compliance rule 3, issue fixes should include an issue reference in the test comment when
applicable.
• This makes it harder to trace the test back to the original issue for future maintenance.
The PR description states 'Closes #11213' and the test was modified to add orderBy configuration to
verify the fix works. However, there is no comment in the test file referencing issue #11213. The
compliance rule states that 'issue fixes add or update tests in test/functional, with an issue
reference in the test comment when applicable.' Since this is an issue fix with a test update, a
comment reference would help trace the test to the original issue.
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
## Issue description
The test file is missing a comment that references issue #11213, which this PR fixes. Adding this reference helps with traceability and future maintenance.
## Issue Context
The PR fixes issue #11213 where aggregate functions incorrectly generated SQL with ORDER BY clauses. The test was updated to add `orderBy` configuration to the Post entity to verify that aggregate functions now properly disable the global order.
## Fix Focus Areas
- test/functional/repository/aggregate-methods/entity/Post.ts[5-5]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description of Change
This pull request addresses an issue where an incorrect SQL query is generated when using aggregate functions on the entity repository, such as
repo.max().Closes #11213
Note: When using an aggregate function on a single column, the ORDER BY clause is redundant.
Pull-Request Checklist
masterbranchFixes #11213tests/**.test.ts)docs/docs/**.md) (N/A)