Skip to content
Source
Sign inSign up
TanStack/db

perf(electric-db-collection): compile array-column membership to @> (GIN-eligible) #1583

Closedviktor89(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/1583/headopened

Showing 3 changed files with 91 additions and 2 deletions.

x
0 of 3 viewed, 3 left
5 additions and 0 deletions.changeset/array-column-containment.mdAdded
View file
@@ -0,0 +1,5 @@
+---
+"@tanstack/electric-db-collection": patch
+---
+​
+Compile array-column membership (`inArray(value, arrayColumn)`) to `arrayColumn @> ARRAY[value]` instead of `value = ANY(arrayColumn)`. The two are equivalent, but only the containment form can use a GIN index, letting Postgres index-seek rather than scan. Membership in a literal value list (`inArray(column, [a, b])`) is unchanged and still compiles to `= ANY`.
18 additions and 2 deletionspackages/electric-db-collection/src/sql-compiler.tsModified
View file
@@ -356,8 +356,24 @@
​
- // Special case for = ANY operator which needs parentheses around the array parameter
if (name === `in`) {
+ // `value = ANY(arrayColumn)` and `arrayColumn @> ARRAY[value]` are
+ // equivalent, but only containment can use a GIN index. Emit @> when the
+ // array operand is a column; keep = ANY for a literal value list.
+ if (args[1]?.type === `ref`) {
+ // @> wraps a single scalar into ARRAY[...]; an array-valued left
+ // operand would nest into ARRAY[<array>] and silently change the
+ // membership semantics, so reject it.
+ const valueArg = args[0]
+ if (valueArg && valueArg.type === `val` && Array.isArray(valueArg.value)) {
+ throw new Error(
+ `Cannot use an array value as the left operand of 'in' against an ` +