Skip to content

test: added tests to verify jsonb operators in find options with Raw() - #11917

Merged
gioboa merged 7 commits into
typeorm:masterfrom
Cprakhar:test/find-options-raw-jsonb-operators
Jan 20, 2026
Merged

gioboa merged 7 commits into
typeorm:masterfrom
Cprakhar:test/find-options-raw-jsonb-operators

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 12, 2026 •

Copy link
Copy Markdown
Collaborator

Description of change

Added several tests to verify jsonb operators in the find() and findBy() methods using the Raw() function.

Related issue:

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

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Unused Import
The Comment entity is imported at line 26 but not added to the entities array in the main test suite setup (line 33). While it's used in the nested describe block with its own setup, this could cause confusion. Consider whether the import is needed at the top level.

Test Data Duplication
In the test at line 1204, both comment1 and comment2 have identical metadata values { likesDislikes: [300, 20] }. This makes the test less meaningful as it doesn't verify that the operator correctly filters different data. Consider using distinct values to better validate the filtering logic.

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 8e60809

CategorySuggestion                                                                                                                                    Impact
Security
Use parameterized queries for JSON values

Replace the hardcoded JSON string in the Raw query with a parameterized query to
improve security and maintainability.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [1144-1153]

 const loadedComments2 = await connection
     .getRepository(Comment)
     .find({
         where: {
             metadata: Raw(
                 (alias) =>
-                    `${alias} -> 'author' = '{"name":"Bob"}'`,
+                    `${alias} -> 'author' = :detail`,
+                {
+                    detail: JSON.stringify({ name: "Bob" }),
+                },
             ),
         },
     })
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly points out that hardcoding a JSON string in a raw query is bad practice and proposes using query parameters, which is more secure and consistent with other tests in the file.

Medium
General
Avoid variable shadowing in nested scope

Rename the connections variable in the nested describe block to avoid shadowing
the variable from the outer scope, improving code clarity.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [898-908]

 describe("raw with jsonb columns", () => {
-    let connections: DataSource[]
+    let jsonbConnections: DataSource[]
     before(
         async () =>
-            (connections = await createTestingConnections({
+            (jsonbConnections = await createTestingConnections({
                 entities: [Comment],
                 enabledDrivers: ["postgres", "cockroachdb"],
             })),
     )
-    beforeEach(() => reloadTestingDatabases(connections))
-    after(() => closeTestingConnections(connections))
+    beforeEach(() => reloadTestingDatabases(jsonbConnections))
+    after(() => closeTestingConnections(jsonbConnections))
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies variable shadowing, which is a code smell that can lead to confusion, and the proposed fix improves code clarity and maintainability.

Low
  • More

Previous suggestions

Suggestions up to commit c876674
CategorySuggestion                                                                                                                                    Impact
Security
Use parameterized queries for JSON

Replace the hardcoded JSON string in the Raw query with a parameterized query to
improve security and maintainability.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [1148-1151]

 metadata: Raw(
-    (alias) => `${alias} -> 'author' = '{"name":"Bob"}'`,
+    (alias) => `${alias} -> 'author' = :detail`,
+    {
+        detail: JSON.stringify({ name: "Bob" }),
+    },
 ),
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a hardcoded JSON string in a raw query and recommends using query parameters, which is a best practice for security and maintainability, and aligns with other tests in the same file.

Medium
Use parameterized queries for values

Replace the hardcoded string value in the Raw query with a parameterized query
to improve security and maintainability.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [1207-1210]

 metadata: Raw(
-    (alias) => `${alias} ->> 'author' = 'Bob'`,
+    (alias) => `${alias} ->> 'author' = :name`,
+    {
+        name: "Bob",
+    },
 ),
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a hardcoded string value in a raw query and recommends using query parameters, which is a best practice for security and maintainability, and aligns with other tests in the same file.

Medium
General
Use repository pattern consistently

For consistency, use repository.save() instead of connection.manager.save() to
align with how entities are fetched in the tests.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [913-924]

+const repository = connection.getRepository(Comment)
+
 const comment1 = new Comment()
 comment1.text = "Comment #1"
 comment1.metadata = {
     approved: true,
     tags: ["news", "tech"],
 }
-await connection.manager.save(comment1)
+await repository.save(comment1)
 
 const comment2 = new Comment()
 comment2.text = "Comment #2"
 comment2.metadata = { approved: false, tags: ["news"] }
-await connection.manager.save(comment2)
+await repository.save(comment2)
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies an inconsistent use of data access patterns within a test file and proposes a change that improves code consistency and maintainability.

Low
Suggestions up to commit 1df9c77
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent connection leaks in nested tests

Ensure proper test cleanup by awaiting the closeTestingConnections async
function within the after hook.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [898-908]

+// Move outside the main describe block or ensure cleanup
 describe("raw with jsonb columns", () => {
     let connections: DataSource[]
     before(
         async () =>
             (connections = await createTestingConnections({
                 entities: [Comment],
                 enabledDrivers: ["postgres", "cockroachdb"],
             })),
     )
     beforeEach(() => reloadTestingDatabases(connections))
-    after(() => closeTestingConnections(connections))
+    after(async () => {
+        await closeTestingConnections(connections)
+    })
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that closeTestingConnections is an async function that is not being awaited in the after hook, which can cause test instability. The proposed fix of using async/await is correct and improves test reliability.

Medium
Security
Use parameterized queries for JSON values

Replace a hardcoded JSON string in a raw SQL query with a parameterized query to
maintain consistency and follow best practices.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [1148-1151]

 metadata: Raw(
-    (alias) => `${alias} -> 'author' = '{"name":"Bob"}'`,
+    (alias) => `${alias} -> 'author' = :detail`,
+    {
+        detail: JSON.stringify({ name: "Bob" }),
+    },
 ),
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out an inconsistency in using raw SQL strings instead of parameterized queries, which is a good practice to follow even in tests. While there is no immediate security risk as the data is hardcoded, promoting consistency is valuable.

Low
Suggestions up to commit ea076ab
CategorySuggestion                                                                                                                                    Impact
General
Use saved entity IDs in assertions

Avoid hardcoding IDs in test assertions by using the IDs from the saved
entities, making the tests more robust.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [913-924]

 const comment1 = new Comment()
 comment1.text = "Comment #1"
 comment1.metadata = {
     approved: true,
     tags: ["news", "tech"],
 }
-await connection.manager.save(comment1)
+const savedComment1 = await connection.manager.save(comment1)
 
 const comment2 = new Comment()
 comment2.text = "Comment #2"
 comment2.metadata = { approved: false, tags: ["news"] }
-await connection.manager.save(comment2)
+const savedComment2 = await connection.manager.save(comment2)
 
+// Use savedComment1.id and savedComment2.id in assertions
+
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that hardcoding IDs in tests is a bad practice that can lead to flaky tests. Using the returned ID from the save operation makes the tests more robust and reliable.

Medium
Avoid connection variable name collision

In the nested describe block, rename the connections variable to avoid shadowing
the variable from the outer scope, which improves code clarity.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [898-908]

 describe("raw with jsonb columns", () => {
-    let connections: DataSource[]
+    let jsonbConnections: DataSource[]
     before(
         async () =>
-            (connections = await createTestingConnections({
+            (jsonbConnections = await createTestingConnections({
                 entities: [Comment],
                 enabledDrivers: ["postgres", "cockroachdb"],
             })),
     )
-    beforeEach(() => reloadTestingDatabases(connections))
-    after(() => closeTestingConnections(connections))
+    beforeEach(() => reloadTestingDatabases(jsonbConnections))
+    after(() => closeTestingConnections(jsonbConnections))
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies variable shadowing, and renaming the connections variable as proposed in the improved_code improves code clarity and maintainability, although the risk of resource leaks is low due to proper scoping.

Low
Suggestions up to commit f44ee7b
CategorySuggestion                                                                                                                                    Impact
Possible issue
Use correct JSONB operator for comparison

In the test for the #> JSONB operator, replace #> with #>>. The #> operator
extracts a jsonb value, and comparing it with a text parameter will cause a
database error, whereas #>> extracts it as text, allowing for a valid
comparison.

test/functional/repository/find-options-operators/repository-find-operators.test.ts [1183-1193]

 const loadedComments = await connection
     .getRepository(Comment)
     .findBy({
         metadata: Raw(
             (alias) =>
-                `${alias} #> '{stats, views}' = :views`,
+                `${alias} #>> '{stats, views}' = :views`,
             {
                 views: "100",
             },
         ),
     })
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a bug in the new test case where a jsonb value is compared to a text value, which would cause a PostgreSQL error. The proposed fix using the #>> operator is accurate and necessary for the test to pass.

Medium

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

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

(Review updated until commit ea076ab)

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

Grey Divider


Remediation Recommended

1. Brittle Entity Loading Pattern Reduces Extensibility 🐞 Bug
Description
• The test suite was changed from using a glob pattern to load all entities (`__dirname +
  "/entity/*{.js,.ts}") to an explicit list ([PersonAR, Post]`), excluding the newly added Comment
  entity
• This creates a maintenance burden where future entity additions require manual updates to the
  entity list, breaking the previous auto-discovery pattern
• The glob pattern was the standard approach used across the codebase (found in 30+ other test
  files), making this change inconsistent with established patterns
• If developers add new entities to the directory and expect them to be tested alongside existing
  entities, tests will silently fail to include them

reliability

Code

test/functional/repository/find-options-operators/repository-find-operators.test.ts[33]

+                entities: [PersonAR, Post],
Evidence
The change from glob pattern to explicit entity list is evident in the diff. The original code used
a glob pattern that would automatically load all entities in the directory, while the new code
explicitly lists only PersonAR and Post. This pattern is inconsistent with the rest of the codebase,
where glob patterns are the standard approach. The Comment entity, which is in the same directory,
is intentionally excluded from the parent test suite and only loaded in a nested describe block with
different database drivers.

test/functional/repository/find-options-operators/repository-find-operators.test.ts[33-33]
test/functional/repository/find-options-operators/repository-find-operators.test.ts[903-903]
test/functional/repository/delete-by-criteria/repository-delete-by-criteria.test.ts[20-20]
test/functional/repository/find-options/repository-find-options.test.ts[23-23]

Agent Prompt
## Issue Description
The test suite changed from using a glob pattern to load entities to an explicit list, which reduces extensibility and creates maintenance burden. The glob pattern was the standard approach used throughout the codebase.

## Issue Context
- The original code used `entities: [__dirname + "/entity/*{.js,.ts}"]` to automatically load all entities
- The new code uses `entities: [PersonAR, Post]` which excludes the Comment entity
- The Comment entity is only loaded in a nested describe block with postgres/cockroachdb drivers
- This pattern is inconsistent with 30+ other test files that use glob patterns

## Fix Focus Areas
- test/functional/repository/find-options-operators/repository-find-operators.test.ts[33-33]

## Recommended Approach
Restore the glob pattern for entity loading to maintain consistency and extensibility. If the Comment entity needs special handling (e.g., postgres-only), consider using driver filtering in the nested describe block instead of fragmenting the entity loading strategy.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider


Previous review results

Results up to commit f44ee7b


🐞 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

Qodo Logo

@Cprakhar
Cprakhar force-pushed the test/find-options-raw-jsonb-operators branch from f44ee7b to ea076ab Compare January 12, 2026 16:25
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit ea076ab

@coveralls

coveralls commented Jan 12, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.956% (+0.001%) from 80.955%
when pulling 8e60809 on Cprakhar:test/find-options-raw-jsonb-operators
into 8a9a376 on typeorm:master.

@Cprakhar

Copy link
Copy Markdown
Collaborator Author

@gioboa should I implement a fix like @BenjD90 wants ${alias}->>'tags' does not work and ${alias} ->>'tags' or ${alias} ->> 'tags' works.
Also in PostgreSQL its ->>'something'
Need to modify the regex in QueryBuilder.replacePropertyNamesForTheWholeQuery() method

if (replacementKeys.length > 0) {
            statement = statement.replace(
                new RegExp(
                    // Avoid a lookbehind here since it's not well supported
                    `([ =(]|^.{0})` + // any of ' =(' or start of line
                        // followed by our prefix, e.g. 'tablename.' or ''
                        `${
                            replaceAliasNamePrefixes
                                ? "(" + replaceAliasNamePrefixes + ")"
                                : ""
                        }([^ =(),]+)` + // a possible property name: sequence of anything but ' =(),' FIX: HERE
                        // terminated by ' =),' or end of line
                        `(?=[ =),]|.{0}$)`,
                    "gm",
                ),

@alumni

alumni commented Jan 13, 2026 •

Copy link
Copy Markdown
Collaborator

Hmm but this is not really testing something in TypeORM, it's testing the implementation of that operator defined in the test. Or?

Is the Raw operator replacing something in the user-defined string and is this testing that the SQL strings don't get replaced?

@Cprakhar

Cprakhar commented Jan 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Hmm but this is not really testing something in TypeORM, it's testing the implementation of that operator defined in the test. Or?

Is the Raw operator replacing something in the user-defined string and is this testing that the SQL strings don't get replaced?

Raw creates raw sql where conditions with columnAlias but it was not correctly escaped when ${alias}->>'tags', but works with space between the alias and operand ${alias} ->>'tags'

@gioboa
gioboa requested review from G0maa and alumni January 20, 2026 11:31

@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 @Cprakhar it looks awesome to me 👏

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

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


ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Previous review results

Review updated until commit 8e60809

Results up to commit c876674


🐞 Bugs (0) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider
Remediation recommended
1. Missing newline before test case 📘 Rule violation ✓ Correctness
Description
• The test case at line 1222 is missing a blank line before it, which is inconsistent with the
  file's established formatting pattern.
• All other test cases in the file have a blank line separating them from the previous test.
• This minor formatting inconsistency deviates from the project's style conventions.
Code

test/functional/repository/find-options-operators/repository-find-operators.test.ts[1222]

+        it("should work with #> (get object field as JSON) operator", () =>
Evidence
The compliance rule requires consistent naming and formatting conventions. Comparing line 1222 with
other test cases in the file (e.g., lines 63-64, 1163-1165) shows that all tests are separated by
blank lines, except this one at line 1222 which immediately follows line 1221.

Rule 1: Consistent Naming Conventions
test/functional/repository/find-options-operators/repository-find-operators.test.ts[1221-1222]
test/functional/repository/find-options-operators/repository-find-operators.test.ts[62-64]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test case at line 1222 is missing a blank line before it, which is inconsistent with the file's established formatting pattern where all test cases are separated by blank lines.

## Issue Context
This is a minor formatting issue that affects code readability and consistency with the project's style conventions.

## Fix Focus Areas
- test/functional/repository/find-options-operators/repository-find-operators.test.ts[1221-1222]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Tests added to functional, not github-issues 📘 Rule violation ✓ Correctness
Description
• The PR description mentions closing issue #11611, but the tests are added to test/functional
  instead of test/github-issues.
• According to the compliance rule, issue fixes should add tests in test/functional with an issue
  reference in comments when applicable.
• While the tests are in the correct location (test/functional), they lack a comment referencing
  issue #11611.
Code

test/functional/repository/find-options-operators/repository-find-operators.test.ts[898]

+    describe("raw with jsonb columns", () => {
Evidence
The compliance rule states that issue fixes should add or update tests in test/functional with an
issue reference in the test comment when applicable. The PR description explicitly mentions 'Close
#11611', but there is no comment in the test code referencing this issue number.

Rule 3: Prefer functional tests over per-issue tests
test/functional/repository/find-options-operators/repository-find-operators.test.ts[898-910]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The tests are correctly placed in test/functional, but they lack a comment referencing the related issue #11611 as mentioned in the PR description.

## Issue Context
The compliance rule requires issue references in test comments when applicable. The PR description explicitly mentions 'Close #11611', so a comment should be added to link the tests to this issue.

## Fix Focus Areas
- test/functional/repository/find-options-operators/repository-find-operators.test.ts[898-899]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 1df9c77


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider
Action required
✅ 1. Incorrect comment for ->> operator 📘 Rule violation ✓ Correctness
Suggestion Impact:The commit directly fixed the incorrect comment by changing 'Test -> operator' to 'Test ->> operator' on line 1182 (shown as line 15 in the diff), which matches exactly what the suggestion requested

code diff:

-                    // Test -> operator - get nested object and compare
+                    // Test ->> operator - get nested object and compare

Description
• The comment on line 1182 incorrectly states 'Test -> operator' when the test is actually for the
  ->> operator
• This is misleading and could confuse developers reading the test code
• The comment should accurately describe the operator being tested
Code

test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182]

+                    // Test -> operator - get nested object and compare
Evidence
The comment says 'Test -> operator' but the actual test code on line 1187 uses the ->> operator
(${alias} ->> 'author' = :name). This violates the compliance requirement to avoid AI-generated
noise and inconsistent style, as incorrect comments are a common sign of AI-generated code that
wasn't properly reviewed.

Rule 4: Remove AI-generated noise
test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182-1182]
test/functional/repository/find-options-operators/repository-find-operators.test.ts[1187-1187]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The comment on line 1182 incorrectly describes the operator being tested. It says 'Test -> operator' but the test actually uses the ->> operator.

## Issue Context
This is a test for JSONB operators in PostgreSQL. The -> operator returns JSON, while ->> returns text. The comment should accurately reflect which operator is being tested.

## Fix Focus Areas
- test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182-1182]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 6329d5d


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider
Action required
✅ 1. Comment on line 1182 mentions wrong operator 📘 Rule violation ✓ Correctness
Suggestion Impact:The commit directly fixed the comment by changing "Test -> operator" to "Test ->> operator" on line 1182, matching the actual operator being tested in the code

code diff:

-                    // Test -> operator - get nested object and compare
+                    // Test ->> operator - get nested object and compare

Description
• The comment on line 1182 states Test -> operator but the actual code uses the ->> operator
• This is misleading and could confuse developers reading the test
• The comment appears to be copy-pasted from the previous test without updating the operator name
Code

test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182]

+                    // Test -> operator - get nested object and compare
Evidence
The comment claims to test the -> operator, but the code on line 1187 clearly uses the ->>
operator. This violates the compliance requirement to avoid AI-generated noise, as copy-pasted
comments without proper updates are a common AI-generated pattern. The existing test file uses
simple, accurate comments like 'check operator' or 'insert some fake data', not detailed explanatory
comments.

Rule 4: Remove AI-generated noise
test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182-1187]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The comment on line 1182 incorrectly states it's testing the `->` operator when it actually tests the `->>` operator.

## Issue Context
This test is for the `->>` (get object field as text) operator, not the `->` (get object field as JSON) operator. The comment was likely copy-pasted from the previous test without updating.

## Fix Focus Areas
- test/functional/repository/find-options-operators/repository-find-operators.test.ts[1182-1182]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

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

Copy link
Copy Markdown

Persistent review updated to latest commit 1df9c77

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

Copy link
Copy Markdown

Persistent review updated to latest commit c876674

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

Copy link
Copy Markdown

Persistent review updated to latest commit 8e60809

@gioboa
gioboa merged commit ed2478a into typeorm:master Jan 20, 2026
36 checks passed
@alumni

alumni commented Jan 21, 2026 •

Copy link
Copy Markdown
Collaborator

Raw creates raw sql where conditions with columnAlias but it was not correctly escaped when ${alias}->>'tags', but works with space between the alias and operand ${alias} ->>'tags'

This confirms it's not testing anything in TypeORM 😛

@Cprakhar
Cprakhar deleted the test/find-options-raw-jsonb-operators branch January 24, 2026 20:05
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 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.

Invalid Raw() query in postgresql in jsonb fields

6 participants