Skip to content

Commit 36da18a

Browse files
evgenovalovevgenovalov
andauthored
perf(orm): use EXISTS instead of COUNT subquery for to-one relation filters (#2579)
Co-authored-by: evgenovalov <evgenii@flowlity.com>
1 parent 44a6f9e commit 36da18a

2 files changed

Lines changed: 140 additions & 30 deletions

File tree

‎packages/orm/src/client/crud/dialects/base-dialect.ts‎

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -355,61 +355,48 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> {
355355
field,
356356
joinAlias,
357357
);
358-
const filterResultField = tmpAlias(`${field}$flt`);
359-
360-
const joinSelect = this.eb
358+
const baseJoin = this.eb
361359
.selectFrom(`${fieldDef.type} as ${joinAlias}`)
360+
.select(this.eb.lit(1).as('_'))
362361
.where(() =>
363362
this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), '=', this.eb.ref(right)))),
364-
)
365-
.select(() => this.eb.fn.count(this.eb.lit(1)).as(filterResultField));
363+
);
364+
365+
const existsSelect = (extraFilter?: () => Expression<SqlBool>) => {
366+
const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
367+
return this.buildExistsExpression(q);
368+
};
366369

367370
const conditions: Expression<SqlBool>[] = [];
368371

369372
if ('is' in payload || 'isNot' in payload) {
370373
if ('is' in payload) {
371374
if (payload.is === null) {
372375
// check if not found
373-
conditions.push(this.eb(joinSelect, '=', 0));
376+
conditions.push(this.eb.not(existsSelect()));
374377
} else {
375-
// check if found
376-
conditions.push(
377-
this.eb(
378-
joinSelect.where(() => this.buildFilter(fieldDef.type, joinAlias, payload.is)),
379-
'>',
380-
0,
381-
),
382-
);
378+
// check if found that matches the filter
379+
conditions.push(existsSelect(() => this.buildFilter(fieldDef.type, joinAlias, payload.is)));
383380
}
384381
}
385382

386383
if ('isNot' in payload) {
387384
if (payload.isNot === null) {
388385
// check if found
389-
conditions.push(this.eb(joinSelect, '>', 0));
386+
conditions.push(existsSelect());
390387
} else {
391388
conditions.push(
392389
this.or(
393-
// is null
394-
this.eb(joinSelect, '=', 0),
395-
// found one that matches the filter
396-
this.eb(
397-
joinSelect.where(() => this.buildFilter(fieldDef.type, joinAlias, payload.isNot)),
398-
'=',
399-
0,
400-
),
390+
// no related row
391+
this.eb.not(existsSelect()),
392+
// related row exists but doesn't match the filter
393+
this.eb.not(existsSelect(() => this.buildFilter(fieldDef.type, joinAlias, payload.isNot))),
401394
),
402395
);
403396
}
404397
}
405398
} else {
406-
conditions.push(
407-
this.eb(
408-
joinSelect.where(() => this.buildFilter(fieldDef.type, joinAlias, payload)),
409-
'>',
410-
0,
411-
),
412-
);
399+
conditions.push(existsSelect(() => this.buildFilter(fieldDef.type, joinAlias, payload)));
413400
}
414401

415402
return this.and(...conditions);
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { createTestClient } from '@zenstackhq/testtools';
2+
import { describe, expect, it } from 'vitest';
3+
4+
// https://github.com/zenstackhq/zenstack/issues/2578
5+
// Sibling of issue 2440, covering the to-one (non-array) relation filter path:
6+
// `buildToOneRelationFilter` used to emit `(select count(1) ...) > 0` which
7+
// PostgreSQL can't convert to a semi-join; it now emits `EXISTS (...)`.
8+
describe('Regression for issue 2578', () => {
9+
const schema = `
10+
model Post {
11+
id Int @id @default(autoincrement())
12+
title String
13+
value Int
14+
userId Int?
15+
user User? @relation(fields: [userId], references: [id])
16+
}
17+
18+
model User {
19+
id Int @id @default(autoincrement())
20+
name String
21+
posts Post[]
22+
}
23+
`;
24+
25+
it('to-one relation filter with field predicate returns matching children', async () => {
26+
const db = await createTestClient(schema);
27+
28+
const userA = await db.user.create({ data: { name: 'A' } });
29+
const userB = await db.user.create({ data: { name: 'B' } });
30+
31+
const p1 = await db.post.create({ data: { title: 'p1', value: 1, userId: userA.id } });
32+
const p2 = await db.post.create({ data: { title: 'p2', value: 2, userId: userB.id } });
33+
const p3 = await db.post.create({ data: { title: 'p3', value: 3, userId: null } });
34+
35+
// `user: { name: 'A' }` is a to-one relation filter
36+
const result = await db.post.findMany({
37+
where: { user: { name: 'A' } },
38+
orderBy: { id: 'asc' },
39+
});
40+
expect(result).toHaveLength(1);
41+
expect(result[0].id).toBe(p1.id);
42+
43+
// posts with no user should not match a user filter
44+
const result2 = await db.post.findMany({
45+
where: { user: { name: 'C' } },
46+
orderBy: { id: 'asc' },
47+
});
48+
expect(result2).toHaveLength(0);
49+
50+
// keep references live so the test intent is readable
51+
expect([p1.id, p2.id, p3.id].length).toBe(3);
52+
});
53+
54+
it('`is` with field predicate matches the related row', async () => {
55+
const db = await createTestClient(schema);
56+
57+
const userA = await db.user.create({ data: { name: 'A' } });
58+
const userB = await db.user.create({ data: { name: 'B' } });
59+
const p1 = await db.post.create({ data: { title: 'p1', value: 1, userId: userA.id } });
60+
const p2 = await db.post.create({ data: { title: 'p2', value: 2, userId: userB.id } });
61+
await db.post.create({ data: { title: 'p3', value: 3, userId: null } });
62+
63+
const result = await db.post.findMany({
64+
where: { user: { is: { name: 'B' } } },
65+
orderBy: { id: 'asc' },
66+
});
67+
expect(result).toHaveLength(1);
68+
expect(result[0].id).toBe(p2.id);
69+
70+
// sanity: other rows are still reachable
71+
expect(p1.id).toBeDefined();
72+
});
73+
74+
it('`is: null` matches rows with no related record', async () => {
75+
const db = await createTestClient(schema);
76+
77+
const userA = await db.user.create({ data: { name: 'A' } });
78+
await db.post.create({ data: { title: 'p1', value: 1, userId: userA.id } });
79+
const p2 = await db.post.create({ data: { title: 'p2', value: 2, userId: null } });
80+
81+
const result = await db.post.findMany({
82+
where: { user: { is: null } },
83+
orderBy: { id: 'asc' },
84+
});
85+
expect(result).toHaveLength(1);
86+
expect(result[0].id).toBe(p2.id);
87+
});
88+
89+
it('`isNot: null` matches rows with a related record', async () => {
90+
const db = await createTestClient(schema);
91+
92+
const userA = await db.user.create({ data: { name: 'A' } });
93+
const p1 = await db.post.create({ data: { title: 'p1', value: 1, userId: userA.id } });
94+
await db.post.create({ data: { title: 'p2', value: 2, userId: null } });
95+
96+
const result = await db.post.findMany({
97+
where: { user: { isNot: null } },
98+
orderBy: { id: 'asc' },
99+
});
100+
expect(result).toHaveLength(1);
101+
expect(result[0].id).toBe(p1.id);
102+
});
103+
104+
it('`isNot` with field predicate matches rows where the related record does not satisfy the filter or has no related record', async () => {
105+
const db = await createTestClient(schema);
106+
107+
const userA = await db.user.create({ data: { name: 'A' } });
108+
const userB = await db.user.create({ data: { name: 'B' } });
109+
const p1 = await db.post.create({ data: { title: 'p1', value: 1, userId: userA.id } });
110+
const p2 = await db.post.create({ data: { title: 'p2', value: 2, userId: userB.id } });
111+
const p3 = await db.post.create({ data: { title: 'p3', value: 3, userId: null } });
112+
113+
// posts whose related user is NOT named 'A' (includes the no-user case)
114+
const result = await db.post.findMany({
115+
where: { user: { isNot: { name: 'A' } } },
116+
orderBy: { id: 'asc' },
117+
});
118+
const ids = result.map((p: any) => p.id);
119+
expect(ids).toContain(p2.id);
120+
expect(ids).toContain(p3.id);
121+
expect(ids).not.toContain(p1.id);
122+
});
123+
});

0 commit comments

Comments
 (0)