-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathquery-plan-select.ts
More file actions
481 lines (438 loc) · 14.3 KB
/
Copy pathquery-plan-select.ts
File metadata and controls
481 lines (438 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
import {
AndExpr,
type AnyExpression,
type AstRewriter,
BinaryExpr,
type BinaryOp,
ColumnRef,
DerivedTableSource,
EqColJoinOn,
JoinAst,
JsonArrayAggExpr,
JsonObjectExpr,
ListExpression,
OrderByItem,
OrExpr,
ParamRef,
ProjectionItem,
SelectAst,
SubqueryExpr,
TableSource,
} from '@prisma-next/sql-relational-core/ast';
import type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';
import { resolveColumnCodecId } from './collection-contract';
import { buildOrmQueryPlan, deriveParamsFromAst, resolveTableColumns } from './query-plan-meta';
import type { CollectionState, IncludeExpr, OrderExpr } from './types';
import { combineWhereExprs } from './where-utils';
type CursorOrderEntry = OrderExpr & {
readonly value: unknown;
};
function buildProjection(
contract: SqlContract<SqlStorage>,
tableName: string,
selectedFields: readonly string[] | undefined,
tableRef = tableName,
): ProjectionItem[] {
const columns =
selectedFields && selectedFields.length > 0
? [...selectedFields]
: resolveTableColumns(contract, tableName);
return columns.map((column) => ProjectionItem.of(column, ColumnRef.of(tableRef, column)));
}
function toOrderBy(
tableName: string,
orderBy: readonly OrderExpr[] | undefined,
): ReadonlyArray<OrderByItem> | undefined {
if (!orderBy || orderBy.length === 0) {
return undefined;
}
return orderBy.map(
(entry) => new OrderByItem(ColumnRef.of(tableName, entry.column), entry.direction),
);
}
function columnParam(
contract: SqlContract<SqlStorage>,
tableName: string,
column: string,
value: unknown,
): ParamRef {
const codecId = resolveColumnCodecId(contract, tableName, column);
return ParamRef.of(value, { name: column, ...(codecId ? { codecId } : {}) });
}
function createBoundaryExpr(
contract: SqlContract<SqlStorage>,
tableName: string,
entry: CursorOrderEntry,
): AnyExpression {
const comparator: BinaryOp = entry.direction === 'asc' ? 'gt' : 'lt';
return new BinaryExpr(
comparator,
ColumnRef.of(tableName, entry.column),
columnParam(contract, tableName, entry.column, entry.value),
);
}
function buildLexicographicCursorWhere(
contract: SqlContract<SqlStorage>,
tableName: string,
entries: readonly CursorOrderEntry[],
): AnyExpression {
const branches = entries.map((entry, index): AnyExpression => {
const branchExprs: AnyExpression[] = [];
for (const prefixEntry of entries.slice(0, index)) {
branchExprs.push(
BinaryExpr.eq(
ColumnRef.of(tableName, prefixEntry.column),
columnParam(contract, tableName, prefixEntry.column, prefixEntry.value),
),
);
}
branchExprs.push(createBoundaryExpr(contract, tableName, entry));
if (branchExprs.length === 1) {
return branchExprs[0] as AnyExpression;
}
return AndExpr.of(branchExprs);
});
if (branches.length === 1) {
return branches[0] as AnyExpression;
}
return OrExpr.of(branches);
}
function buildCursorWhere(
contract: SqlContract<SqlStorage>,
tableName: string,
orderBy: readonly OrderExpr[] | undefined,
cursor: Readonly<Record<string, unknown>> | undefined,
): AnyExpression | undefined {
if (!cursor || !orderBy || orderBy.length === 0) {
return undefined;
}
const entries: CursorOrderEntry[] = [];
for (const order of orderBy) {
const value = cursor[order.column];
if (value === undefined) {
throw new Error(`Missing cursor value for orderBy column "${order.column}"`);
}
entries.push({
...order,
value,
});
}
const firstEntry = entries[0];
if (entries.length === 1 && firstEntry !== undefined) {
return createBoundaryExpr(contract, tableName, firstEntry);
}
return buildLexicographicCursorWhere(contract, tableName, entries);
}
function createTableRefRemapper(fromTable: string, toTable: string): AstRewriter {
return {
columnRef: (col) => (col.table === fromTable ? ColumnRef.of(toTable, col.column) : col),
tableSource: (source) => {
if (source.alias === fromTable) return TableSource.named(source.name, toTable);
if (!source.alias && source.name === fromTable)
return TableSource.named(source.name, toTable);
return source;
},
eqColJoinOn: (on) =>
EqColJoinOn.of(
on.left.table === fromTable ? ColumnRef.of(toTable, on.left.column) : on.left,
on.right.table === fromTable ? ColumnRef.of(toTable, on.right.column) : on.right,
),
};
}
function buildStateWhere(
contract: SqlContract<SqlStorage>,
tableName: string,
state: CollectionState,
options?: {
readonly filterTableName?: string;
},
): AnyExpression | undefined {
const filterTableName = options?.filterTableName;
const cursorTableName = filterTableName ?? tableName;
const cursorWhere = buildCursorWhere(contract, cursorTableName, state.orderBy, state.cursor);
const remappedFilters =
filterTableName && filterTableName !== tableName
? state.filters.map((filter) =>
filter.rewrite(createTableRefRemapper(filterTableName, tableName)),
)
: state.filters;
const remappedCursorWhere =
cursorWhere && filterTableName && filterTableName !== tableName
? cursorWhere.rewrite(createTableRefRemapper(filterTableName, tableName))
: cursorWhere;
const filters = remappedCursorWhere ? [...remappedFilters, remappedCursorWhere] : remappedFilters;
return combineWhereExprs(filters);
}
function buildIncludeOrderArtifacts(
relationName: string,
childTableRef: string,
rowAlias: string,
orderBy: readonly OrderExpr[] | undefined,
): {
readonly childOrderBy: ReadonlyArray<OrderByItem> | undefined;
readonly hiddenOrderProjection: ReadonlyArray<ProjectionItem>;
readonly aggregateOrderBy: ReadonlyArray<OrderByItem> | undefined;
} {
const childOrderBy = toOrderBy(childTableRef, orderBy);
if (!childOrderBy || childOrderBy.length === 0) {
return {
childOrderBy: undefined,
hiddenOrderProjection: [],
aggregateOrderBy: undefined,
};
}
const hiddenOrderProjection = childOrderBy.map((orderItem, index) =>
ProjectionItem.of(`${relationName}__order_${index}`, orderItem.expr),
);
const aggregateOrderBy = hiddenOrderProjection.map((projection, index) => {
const orderItem = childOrderBy[index];
if (!orderItem) {
throw new Error(`Missing include order metadata at index ${index}`);
}
return new OrderByItem(ColumnRef.of(rowAlias, projection.alias), orderItem.dir);
});
return {
childOrderBy,
hiddenOrderProjection,
aggregateOrderBy,
};
}
function buildIncludeChildRowsSelect(
contract: SqlContract<SqlStorage>,
parentTableName: string,
include: IncludeExpr,
): {
readonly childRows: SelectAst;
readonly childProjection: ReadonlyArray<ProjectionItem>;
readonly rowsAlias: string;
readonly aggregateOrderBy: ReadonlyArray<OrderByItem> | undefined;
} {
const childState = include.nested;
const childTableAlias =
include.relatedTableName === parentTableName ? `${include.relationName}__child` : undefined;
const childTableRef = childTableAlias ?? include.relatedTableName;
const rowsAlias = `${include.relationName}__rows`;
const childProjection = buildProjection(
contract,
include.relatedTableName,
childState.selectedFields,
childTableRef,
);
const { childOrderBy, hiddenOrderProjection, aggregateOrderBy } = buildIncludeOrderArtifacts(
include.relationName,
childTableRef,
rowsAlias,
childState.orderBy,
);
const childWhere = buildStateWhere(contract, childTableRef, childState, {
filterTableName: include.relatedTableName,
});
const joinExpr = BinaryExpr.eq(
ColumnRef.of(childTableRef, include.fkColumn),
ColumnRef.of(parentTableName, include.parentPkColumn),
);
const whereExpr = childWhere ? AndExpr.of([joinExpr, childWhere]) : joinExpr;
let childRows = SelectAst.from(TableSource.named(include.relatedTableName, childTableAlias))
.withProjection([...childProjection, ...hiddenOrderProjection])
.withWhere(whereExpr);
if (childOrderBy) {
childRows = childRows.withOrderBy(childOrderBy);
}
if (childState.distinctOn && childState.distinctOn.length > 0) {
childRows = childRows.withDistinctOn(
childState.distinctOn.map((column) => ColumnRef.of(childTableRef, column)),
);
} else if (childState.distinct && childState.distinct.length > 0) {
childRows = childRows.withDistinct(true);
}
if (childState.limit !== undefined) {
childRows = childRows.withLimit(childState.limit);
}
if (childState.offset !== undefined) {
childRows = childRows.withOffset(childState.offset);
}
return {
childRows,
childProjection,
rowsAlias,
aggregateOrderBy,
};
}
function buildLateralIncludeArtifacts(
contract: SqlContract<SqlStorage>,
parentTableName: string,
include: IncludeExpr,
): {
readonly join: JoinAst;
readonly projection: ProjectionItem;
} {
const { childRows, childProjection, rowsAlias, aggregateOrderBy } = buildIncludeChildRowsSelect(
contract,
parentTableName,
include,
);
const lateralAlias = `${include.relationName}_lateral`;
const jsonObjectExpr = JsonObjectExpr.fromEntries(
childProjection.map((item) =>
JsonObjectExpr.entry(item.alias, ColumnRef.of(rowsAlias, item.alias)),
),
);
const aggregateQuery = SelectAst.from(DerivedTableSource.as(rowsAlias, childRows)).withProjection(
[
ProjectionItem.of(
include.relationName,
JsonArrayAggExpr.of(jsonObjectExpr, 'emptyArray', aggregateOrderBy),
),
],
);
return {
join: JoinAst.left(DerivedTableSource.as(lateralAlias, aggregateQuery), AndExpr.true(), true),
projection: ProjectionItem.of(
include.relationName,
ColumnRef.of(lateralAlias, include.relationName),
),
};
}
function buildCorrelatedIncludeProjection(
contract: SqlContract<SqlStorage>,
parentTableName: string,
include: IncludeExpr,
): {
readonly projection: ProjectionItem;
} {
const { childRows, childProjection, rowsAlias, aggregateOrderBy } = buildIncludeChildRowsSelect(
contract,
parentTableName,
include,
);
const jsonObjectExpr = JsonObjectExpr.fromEntries(
childProjection.map((item) =>
JsonObjectExpr.entry(item.alias, ColumnRef.of(rowsAlias, item.alias)),
),
);
const aggregateQuery = SelectAst.from(DerivedTableSource.as(rowsAlias, childRows)).withProjection(
[
ProjectionItem.of(
include.relationName,
JsonArrayAggExpr.of(jsonObjectExpr, 'emptyArray', aggregateOrderBy),
),
],
);
return {
projection: ProjectionItem.of(include.relationName, SubqueryExpr.of(aggregateQuery)),
};
}
function buildSelectAst(
contract: SqlContract<SqlStorage>,
tableName: string,
state: CollectionState,
options: {
readonly joins?: ReadonlyArray<JoinAst>;
readonly includeProjection?: ReadonlyArray<ProjectionItem>;
readonly where?: AnyExpression;
} = {},
): SelectAst {
const scalarProjection = buildProjection(contract, tableName, state.selectedFields);
const projection = [...scalarProjection, ...(options.includeProjection ?? [])];
const where = options.where ?? buildStateWhere(contract, tableName, state);
const orderBy = toOrderBy(tableName, state.orderBy);
let ast = SelectAst.from(TableSource.named(tableName)).withProjection(projection);
if (where) {
ast = ast.withWhere(where);
}
if (orderBy) {
ast = ast.withOrderBy(orderBy);
}
if (state.selectedFields === undefined) {
ast = ast.withSelectAllIntent({ table: tableName });
}
if (state.distinctOn && state.distinctOn.length > 0) {
ast = ast.withDistinctOn(state.distinctOn.map((column) => ColumnRef.of(tableName, column)));
} else if (state.distinct && state.distinct.length > 0) {
ast = ast.withDistinct(true);
}
if (state.limit !== undefined) {
ast = ast.withLimit(state.limit);
}
if (state.offset !== undefined) {
ast = ast.withOffset(state.offset);
}
if (options.joins && options.joins.length > 0) {
ast = ast.withJoins(options.joins);
}
return ast;
}
export function compileSelect(
contract: SqlContract<SqlStorage>,
tableName: string,
state: CollectionState,
): SqlQueryPlan<Record<string, unknown>> {
const ast = buildSelectAst(contract, tableName, {
...state,
includes: [],
});
const { params, paramDescriptors } = deriveParamsFromAst(ast);
return buildOrmQueryPlan(contract, ast, params, paramDescriptors);
}
export function compileRelationSelect(
contract: SqlContract<SqlStorage>,
relatedTableName: string,
fkColumn: string,
parentPks: readonly unknown[],
nestedState: CollectionState,
): SqlQueryPlan<Record<string, unknown>> {
const inFilter: AnyExpression = BinaryExpr.in(
ColumnRef.of(relatedTableName, fkColumn),
ListExpression.of(parentPks.map((pk) => columnParam(contract, relatedTableName, fkColumn, pk))),
);
return compileSelect(contract, relatedTableName, {
...nestedState,
includes: [],
limit: undefined,
offset: undefined,
filters: [inFilter, ...nestedState.filters],
});
}
export function compileSelectWithIncludeStrategy(
contract: SqlContract<SqlStorage>,
tableName: string,
state: CollectionState,
strategy: 'lateral' | 'correlated',
): SqlQueryPlan<Record<string, unknown>> {
if (
state.includes.some((include) => include.scalar !== undefined || include.combine !== undefined)
) {
throw new Error(
'single-query include strategy does not support scalar include selectors or combine()',
);
}
const includeJoins: JoinAst[] = [];
const includeProjection: ProjectionItem[] = [];
const topLevelWhere = buildStateWhere(contract, tableName, state);
for (const include of state.includes) {
if (strategy === 'lateral') {
const artifact = buildLateralIncludeArtifacts(contract, tableName, include);
includeJoins.push(artifact.join);
includeProjection.push(artifact.projection);
continue;
}
const artifact = buildCorrelatedIncludeProjection(contract, tableName, include);
includeProjection.push(artifact.projection);
}
const ast = buildSelectAst(
contract,
tableName,
{
...state,
includes: [],
},
{
joins: includeJoins,
includeProjection,
...(topLevelWhere ? { where: topLevelWhere } : {}),
},
);
const { params, paramDescriptors } = deriveParamsFromAst(ast);
return buildOrmQueryPlan(contract, ast, params, paramDescriptors);
}