Skip to content

fix(find-options): allow array values in JsonContains - #12420

Merged
gioboa merged 7 commits into
typeorm:masterfrom
kyungseopk1m:fix/json-contains-array-type
May 15, 2026
Merged

gioboa merged 7 commits into
typeorm:masterfrom
kyungseopk1m:fix/json-contains-array-type

Conversation

@kyungseopk1m

Copy link
Copy Markdown
Contributor

Summary

Fixes #11800.

JsonContains constrained T to Record<...>, which forced users to pass arrays through as any even though Postgres @> accepts both object and array containment. Relax the constraint to also accept readonly arrays so jsonb columns that store arrays can be queried without the cast.

Tests

  • test/github-issues/9381/issue-9381.test.ts:115: removed the now-unnecessary as any cast on JsonContains([5, 6, 7, 8]). The case existed precisely to exercise array containment at runtime but had to be type-cast to compile.
  • test/functional/find-options/json-contains-operator/: new functional test mirroring the reporter's array-of-objects scenario.

CC @PreAgile since you mentioned wanting to take this in #11800. I did not find an open PR for this issue; happy to coordinate or defer if there is in-flight work I missed.

JsonContains constrained its generic to Record<...>, which forced
users to pass arrays through `as any` even though Postgres `@>`
accepts both object and array containment. Relax the constraint to
also accept readonly arrays so jsonb columns that store arrays can
be queried without the cast.

The existing test at test/github-issues/9381/issue-9381.test.ts:115
already exercised the array case via JsonContains([5, 6, 7, 8] as any);
the cast is no longer required and has been removed. A new functional
test under test/functional/find-options/json-contains-operator covers
the array-of-objects scenario from the original report.

Closes typeorm#11800
@kyungseopk1m
kyungseopk1m force-pushed the fix/json-contains-array-type branch from fd40de4 to 73fc3f8 Compare April 28, 2026 12:16
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. JsonContains array binds wrongly ✓ Resolved 🐞 Bug ≡ Correctness
Description
By allowing array inputs, JsonContains can now bind a JS array directly as a query parameter, but
the query builder does not JSON-serialize jsonContains values, so the driver may treat the parameter
as a SQL array instead of JSON. This can cause jsonb @> comparisons against JSON arrays (especially
arrays of objects) to return wrong results or fail parsing at runtime.
Code

src/find-options/operator/JsonContains.ts[R11-14]

export function JsonContains<
-    T extends Record<string | number | symbol, unknown>,
+    T extends Record<string | number | symbol, unknown> | readonly unknown[],
>(value: T | FindOperator<T>): FindOperator<any> {
return new FindOperator("jsonContains", value as any)
Evidence
JsonContains only creates a FindOperator and does not transform/serialize the value; QueryBuilder
later binds the operator value as-is via createParameter, and PostgresDriver parameter escaping
likewise pushes the value through unchanged. In contrast, PostgresDriver.preparePersistentValue
explicitly JSON.stringifys json/jsonb values for persistence, indicating JSON values are expected to
be serialized—this mismatch becomes more likely to break now that arrays are a first-class accepted
input.

src/find-options/operator/JsonContains.ts[11-15]
src/query-builder/QueryBuilder.ts[1529-1604]
src/query-builder/QueryBuilder.ts[1105-1109]
src/driver/postgres/PostgresDriver.ts[801-807]
src/driver/postgres/PostgresDriver.ts[1013-1056]

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

## Issue description
`JsonContains` now accepts arrays, but TypeORM binds `FindOperator.value` for `jsonContains` without JSON serialization. This can cause a JS array (and especially an array of objects) to be sent through the driver parameter pipeline in a non-JSON representation.
### Issue Context
Postgres persistence path (`preparePersistentValue`) JSON-stringifies `json`/`jsonb` values, but the where/find-operator binding path does not. With arrays newly accepted by the API, we should ensure `jsonContains` parameters are serialized as JSON prior to binding.
### Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1529-1604]
- src/driver/postgres/PostgresDriver.ts[1013-1056]
- src/query-builder/QueryBuilder.ts[1105-1109]
### Suggested approach
- In `QueryBuilder.getWherePredicateCondition`, when `parameterValue.type === "jsonContains"` and it uses a single parameter, JSON-stringify the bound value (after transformers have been applied), e.g. stringify arrays and plain objects, but avoid double-stringifying strings.
- Keep existing behavior for `multipleParameters` operators.
- Ensure functional tests cover both primitive arrays and arrays of objects (already added) and add an assertion that the generated parameter is JSON (if you have SQL/parameter inspection helpers in this repo).

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


2. JsonContains docs missing arrays 📘 Rule violation ⚙ Maintainability
Description
JsonContains now accepts array values in its public TypeScript signature, but the documentation
only shows object containment usage. This violates the requirement to update docs for user-facing
changes and can leave users unaware of the new supported input shape.
Code

src/find-options/operator/JsonContains.ts[R11-13]

export function JsonContains<
-    T extends Record<string | number | symbol, unknown>,
+    T extends Record<string | number | symbol, unknown> | readonly unknown[],
>(value: T | FindOperator<T>): FindOperator<any> {
Evidence
PR Compliance ID 2 requires documentation updates for user-facing API/usage changes. The PR changes
JsonContains to accept readonly unknown[], but the Find Options docs section for JsonContains
documents only object examples and does not mention array containment.

Rule 2: Docs updated for user-facing changes
src/find-options/operator/JsonContains.ts[11-14]
docs/docs/working-with-entity-manager/3-find-options.md[536-550]

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

## Issue description
`JsonContains` now accepts arrays (in addition to objects), but the docs only show object containment, so the user-facing change is undocumented.
## Issue Context
The public TypeScript signature was relaxed to allow `readonly unknown[]`, enabling JSONB array containment queries without casts.
## Fix Focus Areas
- src/find-options/operator/JsonContains.ts[11-14]
- docs/docs/working-with-entity-manager/3-find-options.md[536-550]

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


3. JsonContains arrays undocumented 📘 Rule violation ⚙ Maintainability
Description
The PR expands JsonContains to accept readonly arrays, which is a user-facing API/type change, but
no documentation or samples were updated to reflect the new supported usage. This can lead to users
missing the feature or misunderstanding supported inputs.
Code

src/find-options/operator/JsonContains.ts[9]

+    T extends Record<string | number | symbol, unknown> | readonly unknown[],
Evidence
PR Compliance ID 2 requires docs updates for user-facing changes; this PR changes the public
JsonContains generic constraint to allow arrays, but the docs section for JsonContains only
demonstrates object containment and is not updated in this PR.

Rule 2: Docs updated for user-facing changes
src/find-options/operator/JsonContains.ts[9-9]
docs/docs/working-with-entity-manager/3-find-options.md[536-550]

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

## Issue description
`JsonContains` now supports array values at the type level, but documentation was not updated to mention or demonstrate array containment.
## Issue Context
Docs currently show only an object-containment example for `JsonContains`, while the PR change makes array containment a supported and intended usage.
## Fix Focus Areas
- docs/docs/working-with-entity-manager/3-find-options.md[536-550]
- src/find-options/operator/JsonContains.ts[8-11]

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



Remediation recommended

4. CockroachDB test coverage missing ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new JsonContains functional test only enables Postgres, even though JsonContains is documented
as supported for PostgreSQL and CockroachDB. This can let CockroachDB regressions for array
containment ship unnoticed.
Code

test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[R14-17]

+        dataSources = await createTestingConnections({
+            __dirname,
+            enabledDrivers: ["postgres"],
+        })
Evidence
The new suite restricts enabledDrivers to only Postgres, while the documentation states JsonContains
is supported for PostgreSQL/CockroachDB and similar operator suites test both drivers.

test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[11-18]
docs/docs/working-with-entity-manager/3-find-options.md[536-550]
test/functional/find-options/array-contains-operator/array-contains-operator.test.ts[11-18]

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 new functional test for `JsonContains` only runs on Postgres, but `JsonContains` is documented as supported on both Postgres and CockroachDB.
### Issue Context
Other find-operator functional suites (e.g. `ArrayContains`) include both `postgres` and `cockroachdb` in `enabledDrivers`, which helps catch driver-specific SQL/parameterization differences.
### Fix Focus Areas
- test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[13-18]

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


5. Primitive array untested ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
JsonContains now accepts arrays, but the added functional test only validates array-of-objects
containment and the existing primitive-array test uses a column transformer that wraps the value, so
it doesn’t exercise primitive jsonb array containment end-to-end on a raw jsonb column.
Code

test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[R35-67]

+    it("should match jsonb columns by partial array containment", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                await prepareData(dataSource.manager)
+
+                const matched = await dataSource.manager.find(Item, {
+                    where: {
+                        input: JsonContains([
+                            { id: "connection_id", value: "1" },
+                        ]),
+                    },
+                    order: {
+                        id: "asc",
+                    },
+                })
+
+                matched.should.have.length(1)
+                matched[0].input.should.have.deep.members([
+                    { id: "connection_id", value: "1" },
+                    { id: "user_id", value: "42" },
+                ])
+            }),
+        ))
+
+    it("should not match when no array element is contained", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                await prepareData(dataSource.manager)
+
+                const matched = await dataSource.manager.find(Item, {
+                    where: {
+                        input: JsonContains([{ id: "missing" }]),
+                    },
Evidence
The new functional test suite asserts JsonContains against a jsonb column that stores an array of
objects, but it never stores/queries a jsonb column containing a primitive array (e.g., number[]).
The existing primitive-array JsonContains test in #9381 targets a jsonb column with a transformer
that wraps values in an object, meaning it is not a direct test of primitive-array containment on a
raw jsonb array column.

test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[35-67]
test/github-issues/9381/entity/JsonExampleEntity.ts[9-12]
test/github-issues/9381/issue-9381.test.ts[71-120]

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

## Issue description
`JsonContains` now type-accepts arrays (including primitive arrays like `number[]`), but tests only cover array-of-objects on a plain jsonb column. The existing primitive-array test (#9381) is executed through a json transformer that wraps the stored value, so it does not validate primitive-array containment on an untransformed jsonb column.
### Issue Context
To reduce regression risk for the newly-enabled type use case, add an end-to-end functional test that stores a primitive array in a `jsonb` column (no transformer) and queries it with `JsonContains([..])`.
### Fix Focus Areas
- test/functional/find-options/json-contains-operator/json-contains-operator.test.ts[11-73]
- test/functional/find-options/json-contains-operator/entity/Item.ts[1-10]
### Suggested test shape
- Add a new entity column (or a new entity) with `@Column({ type: "jsonb" }) numbers: number[]`.
- Insert rows like `[5,6,7,8]` and `[1,2]`.
- Assert `JsonContains([5,6])` matches the first and not the second, and that `JsonContains([9])` matches none.

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


Grey Divider

Qodo Logo

kyungseopk1m and others added 3 commits April 29, 2026 01:33
JsonContains now accepts arrays as well as objects, but the find-options
docs only demonstrated object containment. Add a short example showing
array containment so the docs match the supported usage.

Refs typeorm#11800
The existing functional test only exercised array-of-objects
containment, and the older issue typeorm#9381 case stores primitive arrays
through a JSON transformer that wraps the value, so neither path
covered raw jsonb columns holding a primitive array.

Add a nullable jsonb numbers column on the test entity and a new case
that stores [5, 6, 7, 8] / [1, 2] and asserts JsonContains([5, 6])
matches only the first row while JsonContains([9]) matches none.

Refs typeorm#11800
@pkg-pr-new

pkg-pr-new Bot commented May 9, 2026 •

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

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

commit: 1be5731

Allowing arrays in JsonContains exposed a binding gap: the WHERE
parameter is bound through createParameter without JSON serialization,
so pg-node converts a JS array to a Postgres array literal "{...}"
which then fails to parse on the right side of `col ::jsonb @> $1`
with `invalid input syntax for type json`. Object containment worked
only because pg-node stringifies plain objects on its own.

Stringify the value in getWherePredicateCondition when the operator
is jsonContains and the value is a non-null object or array, leaving
strings untouched so a pre-serialized JSON payload is not double
encoded.

Refs typeorm#11800
JsonContains is documented as supported on PostgreSQL and CockroachDB,
and the comparable ArrayContains/ArrayContainedBy/ArrayOverlap suites
already cover both drivers. Add cockroachdb to enabledDrivers so jsonb
@> regressions on CockroachDB are caught by the same suite.

Refs typeorm#11800
@Cprakhar
Cprakhar requested review from alumni, gioboa and smith-xyz May 10, 2026 06:01

@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 @kyungseopk1m

@PreAgile

Copy link
Copy Markdown
Contributor

@kyungseopk1m all yours — thanks for picking this up. I didn't end up getting to it, and your approach matches what I had in mind.

@gioboa
gioboa enabled auto-merge (squash) May 15, 2026 10:06
@gioboa
gioboa merged commit f5cc456 into typeorm:master May 15, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone May 15, 2026
alumni pushed a commit that referenced this pull request May 16, 2026
alumni pushed a commit that referenced this pull request May 18, 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.

JsonContains should allow arrays

4 participants