Skip to content

fix: remove error handling for *-to-many in createPropertyPath - #11119

Merged
gioboa merged 9 commits into
typeorm:masterfrom
ThbltLmr:fix-cannot-query-across-many-to-many-in-queryBuilder
Jan 16, 2026
Merged

gioboa merged 9 commits into
typeorm:masterfrom
ThbltLmr:fix-cannot-query-across-many-to-many-in-queryBuilder

Conversation

@ThbltLmr

@ThbltLmr ThbltLmr commented Nov 4, 2024 •

Copy link
Copy Markdown
Contributor

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 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:

const users = await getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.posts", "posts")
    .where("posts.validatedAt IS NULL")
    .getMany();

But this will not:

const users = await getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.posts", "posts")
    .where({ posts: { validatedAt: IsNull() } })
    .getMany();

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

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

@ThbltLmr
ThbltLmr force-pushed the fix-cannot-query-across-many-to-many-in-queryBuilder branch 8 times, most recently from c9e74ff to 4c0c7a5 Compare November 5, 2024 12:52
@ThbltLmr
ThbltLmr marked this pull request as ready for review November 5, 2024 13:39

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your help @ThbltLmr
May I ask you to solve the conflicts please?

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 2, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to a66b7f0

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add validation for joined relations

Re-introduce validation to ensure one-to-many and many-to-many relations are
properly joined before being used in a query condition.

src/query-builder/QueryBuilder.ts [1414-1416]

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

Medium
  • More

Previous suggestions

✅ Suggestions up to commit 464097d
CategorySuggestion                                                                                                                                    Impact
General
✅ Handle driver-specific parameter placeholders
Suggestion 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.

test/functional/query-builder/select/query-builder-select.test.ts [311-328]

 const [sql, params] = connection
     .createQueryBuilder(Post, "post")
     .select("post.id")
     .leftJoin("post.tags", "tags_join")
     .where({
         tags: {
             name: "Foo",
         },
     })
     .getQueryAndParameters()
+
+let where = 'WHERE "tags_join"."name" = ?'
+if (DriverUtils.isPostgresFamily(connection.driver)) {
+    where = 'WHERE "tags_join"."name" = $1'
+}
+
 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" = ?',
+        where,
 )
 
 expect(params).to.eql(["Foo"])

[Suggestion processed]

Suggestion importance[1-10]: 8

__

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 syntax
Suggestion 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.

test/functional/query-builder/select/query-builder-select.test.ts [189-196]

 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.

Medium
✅ Suggestions up to commit 5892fe0
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Fix incorrect MySQL parameter placeholder
Suggestion 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.

code diff:

+                enabledDrivers: ["sqlite"],
             })),
     )
     beforeEach(() => reloadTestingDatabases(connections))
@@ -186,17 +187,10 @@
                             })
                             .getQueryAndParameters()
 
-                        const sqlVariable = DriverUtils.isPostgresFamily(
-                            connection.driver,
-                        )
-                            ? "$1"
-                            : DriverUtils.isMySQLFamily(connection.driver)
-                              ? "@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 "category_join"."name" = ?',

Correct the MySQL parameter placeholder in the test from @0 to ? to align with
the correct syntax and prevent test failures on MySQL drivers.

test/functional/query-builder/select/query-builder-select.test.ts [189-195]

 const sqlVariable = DriverUtils.isPostgresFamily(
     connection.driver,
 )
     ? "$1"
-    : DriverUtils.isMySQLFamily(connection.driver)
-      ? "@0"
-      : "?"
+    : "?"
Suggestion importance[1-10]: 7

__

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.

Medium
Suggestions up to commit c4bc5c3
CategorySuggestion                                                                                                                                    Impact
Possible issue
✅ Handle driver-specific parameter placeholders
Suggestion 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 ?.

test/functional/query-builder/select/query-builder-select.test.ts [320-325]

+const sqlVariable = DriverUtils.isPostgresFamily(
+    connection.driver,
+)
+    ? "$1"
+    : "?"
 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" = ?',
+        `WHERE "tags_join"."name" = ${sqlVariable}`,
 )
Suggestion importance[1-10]: 7

__

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 placeholder
Suggestion 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.

code diff:

+                enabledDrivers: ["sqlite"],
             })),
     )
     beforeEach(() => reloadTestingDatabases(connections))
@@ -186,17 +187,10 @@
                             })
                             .getQueryAndParameters()
 
-                        const sqlVariable = DriverUtils.isPostgresFamily(
-                            connection.driver,
-                        )
-                            ? "$1"
-                            : DriverUtils.isMySQLFamily(connection.driver)
-                              ? "@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 "category_join"."name" = ?',

Correct the MySQL parameter placeholder in the test from @0 to ? to ensure the
test passes for MySQL drivers.

test/functional/query-builder/select/query-builder-select.test.ts [189-195]

 const sqlVariable = DriverUtils.isPostgresFamily(
     connection.driver,
 )
     ? "$1"
-    : DriverUtils.isMySQLFamily(connection.driver)
-      ? "@0"
-      : "?"
+    : "?"
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the parameter placeholder @0 for MySQL is incorrect; it should be ?, thus fixing a bug in the test case.

Low
Suggestions up to commit b4cce84
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle database-specific parameter placeholders

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.

test/functional/query-builder/select/query-builder-select.test.ts [313-318]

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

test/functional/query-builder/select/query-builder-select.test.ts [265-269]

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

Medium
Suggestions up to commit 1304185
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate relation joins before querying

Re-introduce validation to ensure one-to-many and many-to-many relations are
properly joined before being used in a query condition.

src/query-builder/QueryBuilder.ts [1414-1416]

+// 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.

Medium

@ThbltLmr
ThbltLmr force-pushed the fix-cannot-query-across-many-to-many-in-queryBuilder branch from d431890 to 3308656 Compare December 2, 2025 08:33
@pkg-pr-new

pkg-pr-new Bot commented Dec 2, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11119
    

commit: a66b7f0

@coveralls

coveralls commented Dec 2, 2025 •

Copy link
Copy Markdown

Coverage Status

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.

@ThbltLmr
ThbltLmr force-pushed the fix-cannot-query-across-many-to-many-in-queryBuilder branch from 4159c5e to f1d448b Compare December 11, 2025 17:08
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This PR added that check. 👀
The big question is: why do we need it? cc @imnotjames

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 15, 2026 •

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

(Review updated until commit a66b7f0)

🐞 Bugs (0) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider

Great, No Issues Found!

Qodo reviewed your code and found no material issues that require review

Grey Divider


Previous review results

Results up to commit 464097d


🐞 Bugs (1) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider
Remediation Recommended
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()

correctness

Code

test/functional/query-builder/select/query-builder-select.test.ts[637]

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

src/driver/DriverUtils.ts[32-34]
src/query-builder/SelectQueryBuilder.ts[2230-2231]
test/functional/query-builder/select/query-builder-select.test.ts[622]

Agent Prompt
## 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


Grey Divider
Results up to commit 5892fe0


🐞 Bugs (1) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider
Action Required
✅ 1. Missing Driver-Specific Parameter Handling in Tests 🐞 Bug
Suggestion 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

correctness

Code

test/functional/query-builder/select/query-builder-select.test.ts[R320-325]

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

test/functional/query-builder/select/query-builder-select.test.ts[22-22]
test/functional/query-builder/select/query-builder-select.test.ts[320-325]
test/functional/query-builder/select/query-builder-select.test.ts[189-195]

Agent Prompt
## 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


Grey Divider
Results up to commit b4cce84


🐞 Bugs (2) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider
Remediation Recommended
1. Validation removal degrades error messaging 🐞 Bug
Description
• 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

observability

Code

src/query-builder/QueryBuilder.ts[L1414-1421]

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

src/query-builder/QueryBuilder.ts[1308-1322]
src/query-builder/QueryBuilder.ts[1384-1442]

Agent Prompt
## 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



Advisory Comments
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

correctness

Code

test/functional/query-builder/select/query-builder-select.test.ts[R255-272]

+                        const [sql, params] = connection
+                            .createQueryBuilder(Category, "category")
+                            .select("category.id")
+                            .leftJoin("category.posts", "posts")
+                            .where({
+                                posts: {
+                                    id: 10,
+                                },
+                            })
+                            .getQueryAndParameters()
+                        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',
+                        )
+
+                        expect(params).to.eql([])
                    }),
Evidence
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.

test/functional/query-builder/select/query-builder-select.test.ts[255-272]
test/functional/query-builder/select/entity/Category.ts[22-23]
test/functional/query-builder/select/entity/Post.ts[40-42]

Agent Prompt
## 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


Grey Divider
Qodo Logo

OSA413
OSA413 previously requested changes Jan 16, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit c4bc5c3

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 5892fe0

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 464097d

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit a66b7f0

@gioboa gioboa left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM 👏 Simple change, if it's going to create issues, we can revert it easily.
Thanks @ThbltLmr 🥳

@ThbltLmr

Copy link
Copy Markdown
Contributor Author

Thanks for the fixes @gioboa!

@alumni

alumni commented Jan 16, 2026 •

Copy link
Copy Markdown
Collaborator

The previous behavior looks intentional, I'm trying to understand why we have it.

Later edit 1: introduced in #7805

@gioboa
gioboa merged commit 9792beb into typeorm:master Jan 16, 2026
67 of 71 checks passed
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

6 participants