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: remove error handling for *-to-many in createPropertyPath - #11119
I have encountered the following behaviour when using a QueryBuilder.
Querying across a one-to-many or many-to-many while providing strings as arguments in the where method works, but when providing an object, an error Cannot query across ${relation.relationType} for property ${path} is thrown.
For example, assuming there is a one-to-many relationship between user and post, the following code will work:
+if (+ relation.relationType === "one-to-many" ||+ relation.relationType === "many-to-many"+) {+ // Verify that the relation has been properly joined before allowing queries+ const aliasExists = this.expressionMap.aliases.some(+ alias => alias.name === key+ );+ if (!aliasExists) {+ throw new Error(+ `Cannot query across ${relation.relationType} for property ${path}. Ensure the relation is properly joined.`,+ )+ }+}+
// For any other case, if the `entity[key]` contains all of the primary keys we can do a
// lookup via these. We don't need to look up via any other values 'cause these are
// the unique primary keys.
[To ensure code accuracy, apply this suggestion manually]
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies that completely removing the validation is risky. It proposes a more nuanced check to ensure a relation is joined before being used in a where clause, which prevents a class of bugs that the PR would otherwise introduce, significantly improving the change's robustness.
✅ Handle driver-specific parameter placeholdersSuggestion Impact:The commit implemented the same concept as the suggestion but in a different location and with a slightly different approach. Instead of using a ternary expression to assign sqlVariable, the commit uses if-else statements to assign a 'where' variable. The implementation addresses the same issue of handling driver-specific parameter placeholders in tests, though it appears to be applied to a different test case (category_join instead of tags_join).
code diff:
- const sqlVariable = DriverUtils.isPostgresFamily(- connection.driver,- )- ? "$1"- : DriverUtils.isMySQLFamily(connection.driver)- ? "@0"- : "?"+ let where = 'WHERE "category_join"."name" = ?'+ if (DriverUtils.isPostgresFamily(connection.driver)) {+ where = 'WHERE "category_join"."name" = $1'+ } else if (+ DriverUtils.isMySQLFamily(connection.driver)+ ) {+ where = 'WHERE "category_join"."name" = @0'+ }
expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "category" "category_join" ON "category_join"."id"="post"."categoryId" ' +
- `WHERE "category_join"."name" = ${sqlVariable}`,+ where,
Add driver-specific logic to handle different parameter placeholders (?, $1, etc.) in the many-to-many test case to ensure it passes across all supported databases.
Why: The suggestion correctly points out that a new test case hardcodes the ? parameter placeholder, which will fail on other databases like PostgreSQL, and proposes a fix consistent with other tests in the file.
Medium
Possible issue
✅ Fix MySQL parameter placeholder syntaxSuggestion Impact:The suggestion was implemented, but with a different approach. Instead of just removing the MySQL else-if block as suggested, the commit removed the entire conditional logic for all database families and hardcoded the '?' placeholder. Additionally, the test was restricted to only run on SQLite driver (line 5), which makes the database-specific parameter placeholder logic unnecessary.
code diff:
+ enabledDrivers: ["sqlite"],
})),
)
beforeEach(() => reloadTestingDatabases(connections))
@@ -186,18 +187,10 @@
})
.getQueryAndParameters()
- let where = 'WHERE "category_join"."name" = ?'- if (DriverUtils.isPostgresFamily(connection.driver)) {- where = 'WHERE "category_join"."name" = $1'- } else if (- DriverUtils.isMySQLFamily(connection.driver)- ) {- where = 'WHERE "category_join"."name" = @0'- }
expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "category" "category_join" ON "category_join"."id"="post"."categoryId" ' +
- where,+ 'WHERE "category_join"."name" = ?',
Correct the MySQL parameter placeholder in the test from @0 to ? by removing the incorrect else if block for the MySQL family.
let where = 'WHERE "category_join"."name" = ?'
if (DriverUtils.isPostgresFamily(connection.driver)) {
where = 'WHERE "category_join"."name" = $1'
-} else if (- DriverUtils.isMySQLFamily(connection.driver)-) {- where = 'WHERE "category_join"."name" = @0'
}
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a bug in the new test code where an incorrect parameter placeholder (@0) is used for MySQL, which would cause the test to fail.
✅ Fix incorrect MySQL parameter placeholderSuggestion Impact:The suggestion was implemented, but with a different approach. Instead of just fixing the MySQL placeholder, the commit removed the entire conditional logic for different database drivers and hardcoded the placeholder to '?'. Additionally, the test was restricted to only run on SQLite by adding 'enabledDrivers: ["sqlite"]' on line 5. This achieves the same goal of preventing test failures but through a more restrictive approach.
Why: The suggestion correctly identifies that the parameter placeholder for MySQL should be ? instead of @0, which is used by MSSQL. This change prevents future test failures when running against a MySQL database.
✅ Handle driver-specific parameter placeholdersSuggestion Impact:The commit implemented the same concept as the suggestion but in a different location and with a slightly different approach. Instead of using a ternary expression to assign sqlVariable, the commit uses if-else statements to assign a 'where' variable. The implementation addresses the same issue of handling driver-specific parameter placeholders in tests, though it appears to be applied to a different test case (category_join instead of tags_join).
code diff:
- const sqlVariable = DriverUtils.isPostgresFamily(- connection.driver,- )- ? "$1"- : DriverUtils.isMySQLFamily(connection.driver)- ? "@0"- : "?"+ let where = 'WHERE "category_join"."name" = ?'+ if (DriverUtils.isPostgresFamily(connection.driver)) {+ where = 'WHERE "category_join"."name" = $1'+ } else if (+ DriverUtils.isMySQLFamily(connection.driver)+ ) {+ where = 'WHERE "category_join"."name" = @0'+ }
expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "category" "category_join" ON "category_join"."id"="post"."categoryId" ' +
- `WHERE "category_join"."name" = ${sqlVariable}`,+ where,
Use a dynamic sqlVariable for the parameter placeholder in the many-to-many test to ensure it works across different database drivers, not just those using ?.
Why: The suggestion correctly points out an inconsistency in the test suite where a hardcoded ? placeholder is used, which would cause failures on PostgreSQL, and proposes a fix to make the test driver-agnostic.
Medium
✅ Fix incorrect MySQL parameter placeholderSuggestion Impact:The suggestion was implemented, but with a different approach. Instead of just fixing the MySQL placeholder, the commit removed the entire conditional logic for different database drivers and hardcoded the placeholder to '?'. Additionally, the test was restricted to only run on SQLite by adding 'enabledDrivers: ["sqlite"]' on line 5. This achieves the same goal of preventing test failures but through a more restrictive approach.
Replace hardcoded double quotes and ? parameter placeholders in the SQL assertion with database-agnostic helpers to ensure tests run correctly across all supported database drivers.
+const quote = connection.driver.escape.bind(connection.driver)+const param = DriverUtils.buildParameterExpression(connection.driver, 0)
expect(sql).to.equal(
- 'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +- 'LEFT JOIN "post_tags_tag" "post_tags_join" ON "post_tags_join"."postId"="post"."id" ' +- 'LEFT JOIN "tag" "tags_join" ON "tags_join"."id"="post_tags_join"."tagId" ' +- 'WHERE "tags_join"."name" = ?',+ `SELECT ${quote('post')}.${quote('id')} AS ${quote('post_id')} FROM ${quote('post')} ${quote('post')} ` ++ `LEFT JOIN ${quote('post_tags_tag')} ${quote('post_tags_join')} ON ${quote('post_tags_join')}.${quote('postId')}=${quote('post')}.${quote('id')} ` ++ `LEFT JOIN ${quote('tag')} ${quote('tags_join')} ON ${quote('tags_join')}.${quote('id')}=${quote('post_tags_join')}.${quote('tagId')} ` ++ `WHERE ${quote('tags_join')}.${quote('name')} = ${param}`,
)
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly points out that hardcoded SQL quotes and parameter placeholders will break tests on different databases, which is a key change in the PR. The proposed fix is correct and necessary for robust, cross-database testing.
Medium
Use database-agnostic identifier quoting
Replace hardcoded double quotes in the SQL string assertion with a dynamic quoting mechanism using connection.driver.escape to ensure test compatibility across different database drivers.
+const quote = connection.driver.escape.bind(connection.driver)
expect(sql).to.equal(
- 'SELECT "category"."id" AS "category_id" FROM "category" "category" ' +- 'LEFT JOIN "post" "posts" ON "posts"."categoryId"="category"."id" ' +- 'WHERE "posts"."id" = 10',+ `SELECT ${quote('category')}.${quote('id')} AS ${quote('category_id')} FROM ${quote('category')} ${quote('category')} ` ++ `LEFT JOIN ${quote('post')} ${quote('posts')} ON ${quote('posts')}.${quote('categoryId')}=${quote('category')}.${quote('id')} ` ++ `WHERE ${quote('posts')}.${quote('id')} = 10`,
)
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that hardcoded SQL identifier quotes will cause test failures on different database systems, and the proposed fix using connection.driver.escape is the standard and correct way to ensure database-agnostic tests.
+// Validate that one-to-many and many-to-many relations are properly joined+if (+ (relation.relationType === "one-to-many" ||+ relation.relationType === "many-to-many") &&+ !this.expressionMap.joinAttributes.some(join => join.relationPropertyPath === path)+) {+ throw new Error(+ `Cannot query across ${relation.relationType} for property ${path} without a proper join`,+ )+}+
// For any other case, if the `entity[key]` contains all of the primary keys we can do a
// lookup via these. We don't need to look up via any other values 'cause these are
// the unique primary keys.
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that completely removing the validation is risky. It proposes a more nuanced check to ensure a join exists for one-to-many or many-to-many relations before querying, which improves the robustness of the feature and prevents potential user errors.
coverage: 80.939% (+0.004%) from 80.935%
when pulling a66b7f0 on ThbltLmr:fix-cannot-query-across-many-to-many-in-queryBuilder
into 42ce630 on typeorm:master.
1. Inconsistent driver type checking pattern 🐞 Bug
Description
• The PR changes driver type check from DriverUtils.isMySQLFamily() to direct type comparison
connection.driver.options.type !== "mysql"
• This creates inconsistency: isMySQLFamily() checks for both 'mysql' and 'mariadb', while the new
check only excludes 'mysql'
• The test will now run on MariaDB when it previously wouldn't, potentially causing unexpected
behavior
• This is inconsistent with line 622 in the same file which still uses DriverUtils.isMySQLFamily()
+ if (connection.driver.options.type !== "mysql") {
Evidence
The implementation code shows that USE INDEX feature uses DriverUtils.isMySQLFamily() which
includes both MySQL and MariaDB. The test change creates a mismatch where the test will run on
MariaDB but the actual implementation supports it, making the test skip logic incorrect.
## Issue Description
The test uses an inconsistent driver type check that doesn't match the pattern used throughout the codebase and doesn't align with the actual implementation behavior.
## Issue Context
The USE INDEX feature is implemented to work with both MySQL and MariaDB (via DriverUtils.isMySQLFamily), but the test skip logic only checks for 'mysql', causing it to run on MariaDB when it should.
## Fix Focus Areas
- test/functional/query-builder/select/query-builder-select.test.ts[637-637]
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
✅ 1. Missing Driver-Specific Parameter Handling in Tests 🐞 BugSuggestion Impact:The commit directly implements the suggested fix by adding driver-specific parameter handling to the many-to-one test case (lines 6-13 and 119-126 in the diff). The code uses DriverUtils to check the driver type and sets the appropriate WHERE clause with the correct parameter placeholder format for each database driver, exactly as suggested.
code diff:
+ let where = 'WHERE "category_join"."name" = ?'+ if (DriverUtils.isPostgresFamily(connection.driver)) {+ where = 'WHERE "category_join"."name" = $1'+ } else if (+ DriverUtils.isMySQLFamily(connection.driver)+ ) {+ where = 'WHERE "category_join"."name" = @0'+ }
expect(sql).to.equal(
'SELECT "post"."id" AS "post_id" FROM "post" "post" ' +
'LEFT JOIN "category" "category_join" ON "category_join"."id"="post"."categoryId" ' +
- 'WHERE "category_join"."name" = ?',+ where,
Description
• The test file removes the SQLite-only restriction (line 22), allowing tests to run on all database
drivers
• The many-to-many test at lines 320-325 uses hardcoded '?' placeholder, which is SQLite-specific
• PostgreSQL uses '$1' format and MySQL uses '@0' format for parameter placeholders
• Only the many-to-one test (lines 189-195) correctly implements driver-specific parameter handling
using DriverUtils
• This inconsistency will cause test failures when running on PostgreSQL or MySQL databases
+ expect(sql).to.equal(+ 'SELECT "post"."id" AS "post_id" FROM "post" "post" ' ++ 'LEFT JOIN "post_tags_tag" "post_tags_join" ON "post_tags_join"."postId"="post"."id" ' ++ 'LEFT JOIN "tag" "tags_join" ON "tags_join"."id"="post_tags_join"."tagId" ' ++ 'WHERE "tags_join"."name" = ?',+ )
Evidence
The test at lines 320-325 expects a hardcoded '?' parameter placeholder, but this is only valid for
SQLite. The many-to-one test at lines 189-195 demonstrates the correct approach by using DriverUtils
to determine the appropriate placeholder format for each driver. Since line 22 removes the
'enabledDrivers: ["sqlite"]' restriction, these tests will now run on all drivers and fail on
non-SQLite databases.
## Issue Description
The many-to-many test case expects a hardcoded '?' parameter placeholder in the SQL query, but this is only valid for SQLite. Since the test now runs on all database drivers (SQLite, PostgreSQL, MySQL), it needs to handle driver-specific parameter placeholder formats.
## Issue Context
Different database drivers use different parameter placeholder formats:
- SQLite: '?'
- PostgreSQL: '$1', '$2', etc.
- MySQL: '@0', '@1', etc.
The many-to-one test already implements the correct pattern using DriverUtils.
## Fix Focus Areas
- test/functional/query-builder/select/query-builder-select.test.ts[310-329]
- test/functional/query-builder/select/query-builder-select.test.ts[189-195] (reference implementation)
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
• The removed validation (lines 1414-1421) provided explicit error messages when developers
attempted to query one-to-many or many-to-many relations without proper joins
• After removal, the code still fails but with a less specific error from
findColumnsForPropertyPath: "Cannot find alias for relation"
• This degrades developer experience by making it harder to understand what went wrong and how to
fix it
• The validation was positioned strategically after handling *-to-one relations and before fallback
logic, catching a common mistake early
- if (- relation.relationType === "one-to-many" ||- relation.relationType === "many-to-many"- ) {- throw new Error(- `Cannot query across ${relation.relationType} for property ${path}`,- )- }
Evidence
The removed validation check provided clear error messages for a specific scenario. The code flow
shows that without this validation, the error still occurs but at a different location with less
context. The createPropertyPath method (lines 1384-1441) processes relations in where clauses, and
the removed validation was positioned to catch collection relations early. When a relation is used
without a join, findColumnsForPropertyPath (lines 1308-1322) throws a generic error instead.
## Issue Description
The validation that provided clear error messages for querying collection relations without joins was removed, degrading developer experience. Errors still occur but with less helpful messages.
## Issue Context
When developers use one-to-many or many-to-many relations in where clauses without explicit joins, they now get a generic "Cannot find alias for relation" error instead of a specific message explaining the issue.
## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1384-1442] - Consider restoring the validation or adding better error context
- src/query-builder/QueryBuilder.ts[1308-1322] - Enhance error message in findColumnsForPropertyPath to detect and explain collection relation issues
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
2. Tests verify SQL generation only 🐞 Bug
Description
• Modified tests (lines 255-272, 278-295, 303-322, 327-346) verify that SQL is generated correctly
but don't test actual query execution or results
• Tests still require explicit leftJoin calls before using relations in where clauses
• This means the validation removal doesn't enable new functionality - developers must still join
relations explicitly
• Tests changed from expecting errors to expecting specific SQL output, but the practical usage
pattern remains unchanged
The test modifications show that the validation removal allows SQL generation for properly-joined
collection relations, but the tests don't verify execution. All test cases still use leftJoin before
the where clause, indicating that the underlying requirement hasn't changed - only the error
behavior.
## Issue Description
Tests only verify SQL generation for collection relations in where clauses, but don't test actual query execution or validate results match expected behavior.
## Issue Context
The modified tests verify that getQueryAndParameters() produces correct SQL, but don't execute queries against a database or verify the returned data is correct. This leaves a gap in test coverage for the actual runtime behavior.
## Fix Focus Areas
- test/functional/query-builder/select/query-builder-select.test.ts[255-272] - Add execution tests that insert test data and verify query results
- test/functional/query-builder/select/query-builder-select.test.ts[278-295] - Add execution tests for FindOperator cases
- test/functional/query-builder/select/query-builder-select.test.ts[303-346] - Add execution tests for many-to-many scenarios
ⓘ 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
Hi!
I have encountered the following behaviour when using a QueryBuilder.
Querying across a one-to-many or many-to-many while providing strings as arguments in the
wheremethod works, but when providing an object, an errorCannot query across ${relation.relationType} for property ${path}is thrown.For example, assuming there is a one-to-many relationship between
userandpost, the following code will work:But this will not:
I tried simply removing the error handling in
QueryBuilder.ts, and the SQL generated by both examples is the same, and works as I would expect it to.If this error is actually still needed, feel free to close the PR
Pull-Request Checklist
masterbranchnpm run formatto apply prettier formattingnpm run testpasses with this changeFixes #0000