@prisma-next/sql-lane 0.3.0-dev.4 → 0.3.0-dev.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,304 @@
1
+ import type { PlanMeta } from '@prisma-next/contract/types';
2
+ import type { Expression } from '@prisma-next/sql-relational-core/ast';
3
+ import { compact } from '@prisma-next/sql-relational-core/ast';
4
+ import type { AnyExpressionSource } from '@prisma-next/sql-relational-core/types';
5
+ import {
6
+ collectColumnRefs,
7
+ isColumnBuilder,
8
+ isExpressionBuilder,
9
+ isOperationExpr,
10
+ } from '@prisma-next/sql-relational-core/utils/guards';
11
+ import type { MetaBuildArgs } from '../types/internal';
12
+ import { assertColumnBuilder } from '../utils/assertions';
13
+ import { errorMissingColumnForAlias } from '../utils/errors';
14
+
15
+ /**
16
+ * Extracts column references from an ExpressionSource (ColumnBuilder or ExpressionBuilder).
17
+ */
18
+ function collectRefsFromExpressionSource(
19
+ source: AnyExpressionSource,
20
+ refsColumns: Map<string, { table: string; column: string }>,
21
+ ): void {
22
+ if (isExpressionBuilder(source)) {
23
+ // ExpressionBuilder has an OperationExpr - collect all column refs
24
+ const allRefs = collectColumnRefs(source.expr);
25
+ for (const ref of allRefs) {
26
+ refsColumns.set(`${ref.table}.${ref.column}`, {
27
+ table: ref.table,
28
+ column: ref.column,
29
+ });
30
+ }
31
+ } else if (isColumnBuilder(source)) {
32
+ // ColumnBuilder - use table and column directly
33
+ const col = source as unknown as { table: string; column: string };
34
+ refsColumns.set(`${col.table}.${col.column}`, {
35
+ table: col.table,
36
+ column: col.column,
37
+ });
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Extracts column references from an Expression (AST node).
43
+ */
44
+ function collectRefsFromExpression(
45
+ expr: Expression,
46
+ refsColumns: Map<string, { table: string; column: string }>,
47
+ ): void {
48
+ if (isOperationExpr(expr)) {
49
+ const allRefs = collectColumnRefs(expr);
50
+ for (const ref of allRefs) {
51
+ refsColumns.set(`${ref.table}.${ref.column}`, {
52
+ table: ref.table,
53
+ column: ref.column,
54
+ });
55
+ }
56
+ } else if (expr.kind === 'col') {
57
+ refsColumns.set(`${expr.table}.${expr.column}`, {
58
+ table: expr.table,
59
+ column: expr.column,
60
+ });
61
+ }
62
+ }
63
+
64
+ export function buildMeta(args: MetaBuildArgs): PlanMeta {
65
+ const refsColumns = new Map<string, { table: string; column: string }>();
66
+ const refsTables = new Set<string>([args.table.name]);
67
+
68
+ for (const column of args.projection.columns) {
69
+ collectRefsFromExpressionSource(column, refsColumns);
70
+ }
71
+
72
+ if (args.joins) {
73
+ for (const join of args.joins) {
74
+ refsTables.add(join.table.name);
75
+ const onLeft = assertColumnBuilder(join.on.left, 'join ON left');
76
+ const onRight = assertColumnBuilder(join.on.right, 'join ON right');
77
+ refsColumns.set(`${onLeft.table}.${onLeft.column}`, {
78
+ table: onLeft.table,
79
+ column: onLeft.column,
80
+ });
81
+ refsColumns.set(`${onRight.table}.${onRight.column}`, {
82
+ table: onRight.table,
83
+ column: onRight.column,
84
+ });
85
+ }
86
+ }
87
+
88
+ if (args.includes) {
89
+ for (const include of args.includes) {
90
+ refsTables.add(include.table.name);
91
+ // Add ON condition columns
92
+ // JoinOnPredicate.left and .right are always ColumnBuilder
93
+ const leftCol = assertColumnBuilder(include.on.left, 'include ON left');
94
+ const rightCol = assertColumnBuilder(include.on.right, 'include ON right');
95
+ refsColumns.set(`${leftCol.table}.${leftCol.column}`, {
96
+ table: leftCol.table,
97
+ column: leftCol.column,
98
+ });
99
+ refsColumns.set(`${rightCol.table}.${rightCol.column}`, {
100
+ table: rightCol.table,
101
+ column: rightCol.column,
102
+ });
103
+ // Add child projection columns
104
+ for (const column of include.childProjection.columns) {
105
+ const col = assertColumnBuilder(column, 'include child projection column');
106
+
107
+ refsColumns.set(`${col.table}.${col.column}`, {
108
+ table: col.table,
109
+ column: col.column,
110
+ });
111
+ }
112
+ // Add child WHERE columns if present
113
+ if (include.childWhere) {
114
+ // Handle UnaryBuilder (e.g., NullCheckBuilder) - it only has 'expr' property
115
+ if (include.childWhere.kind === 'nullCheck') {
116
+ const expr: Expression = include.childWhere.expr;
117
+ collectRefsFromExpression(expr, refsColumns);
118
+ } else {
119
+ // BinaryBuilder - has 'left' and 'right' properties
120
+ // childWhere.left is Expression (already converted at builder creation time)
121
+ collectRefsFromExpression(include.childWhere.left, refsColumns);
122
+ // Handle right side of child WHERE clause - can be ParamPlaceholder or ExpressionSource
123
+ const childWhereRight = include.childWhere.right;
124
+ if (isColumnBuilder(childWhereRight) || isExpressionBuilder(childWhereRight)) {
125
+ collectRefsFromExpressionSource(childWhereRight, refsColumns);
126
+ }
127
+ }
128
+ }
129
+ // Add child ORDER BY columns if present
130
+ if (include.childOrderBy) {
131
+ // childOrderBy.expr is Expression (already converted at builder creation time)
132
+ collectRefsFromExpression(include.childOrderBy.expr, refsColumns);
133
+ }
134
+ }
135
+ }
136
+
137
+ if (args.where) {
138
+ // Handle UnaryBuilder (e.g., NullCheckBuilder) - it only has 'expr' property
139
+ if (args.where.kind === 'nullCheck') {
140
+ const expr: Expression = args.where.expr;
141
+ collectRefsFromExpression(expr, refsColumns);
142
+ } else {
143
+ // BinaryBuilder - has 'left' and 'right' properties
144
+ // args.where.left is Expression (already converted at builder creation time)
145
+ const leftExpr: Expression = args.where.left;
146
+ if (isOperationExpr(leftExpr)) {
147
+ const allRefs = collectColumnRefs(leftExpr);
148
+ for (const ref of allRefs) {
149
+ refsColumns.set(`${ref.table}.${ref.column}`, {
150
+ table: ref.table,
151
+ column: ref.column,
152
+ });
153
+ }
154
+ } else {
155
+ // leftExpr is ColumnRef
156
+ refsColumns.set(`${leftExpr.table}.${leftExpr.column}`, {
157
+ table: leftExpr.table,
158
+ column: leftExpr.column,
159
+ });
160
+ }
161
+
162
+ // Handle right side of WHERE clause - can be ParamPlaceholder or AnyExpressionSource
163
+ const whereRight = args.where.right;
164
+ if (isColumnBuilder(whereRight) || isExpressionBuilder(whereRight)) {
165
+ collectRefsFromExpressionSource(whereRight, refsColumns);
166
+ }
167
+ }
168
+ }
169
+
170
+ if (args.orderBy) {
171
+ // args.orderBy.expr is Expression (already converted at builder creation time)
172
+ const orderByExpr: Expression = args.orderBy.expr;
173
+ if (isOperationExpr(orderByExpr)) {
174
+ const allRefs = collectColumnRefs(orderByExpr);
175
+ for (const ref of allRefs) {
176
+ refsColumns.set(`${ref.table}.${ref.column}`, {
177
+ table: ref.table,
178
+ column: ref.column,
179
+ });
180
+ }
181
+ } else {
182
+ // orderByExpr is ColumnRef
183
+ refsColumns.set(`${orderByExpr.table}.${orderByExpr.column}`, {
184
+ table: orderByExpr.table,
185
+ column: orderByExpr.column,
186
+ });
187
+ }
188
+ }
189
+
190
+ // Build projection map - mark include aliases with special marker
191
+ const includeAliases = new Set(args.includes?.map((inc) => inc.alias) ?? []);
192
+ const projectionMap = Object.fromEntries(
193
+ args.projection.aliases.map((alias, index) => {
194
+ if (includeAliases.has(alias)) {
195
+ // Mark include alias with special marker
196
+ return [alias, `include:${alias}`];
197
+ }
198
+ const column = args.projection.columns[index];
199
+ if (!column) {
200
+ // Null column means this is an include placeholder, but alias doesn't match includes
201
+ // This shouldn't happen if projection building is correct, but handle gracefully
202
+ errorMissingColumnForAlias(alias, index);
203
+ }
204
+ // Check if column is an ExpressionBuilder (operation result)
205
+ if (isExpressionBuilder(column)) {
206
+ return [alias, `operation:${column.expr.method}`];
207
+ }
208
+ // column is ColumnBuilder
209
+ const col = column as unknown as { table?: string; column?: string };
210
+ if (!col.table || !col.column) {
211
+ // This is a placeholder column for an include - skip it
212
+ return [alias, `include:${alias}`];
213
+ }
214
+
215
+ return [alias, `${col.table}.${col.column}`];
216
+ }),
217
+ );
218
+
219
+ // Build projectionTypes mapping: alias → column type ID
220
+ // Skip include aliases - they don't have column types
221
+ const projectionTypes: Record<string, string> = {};
222
+ for (let i = 0; i < args.projection.aliases.length; i++) {
223
+ const alias = args.projection.aliases[i];
224
+ if (!alias || includeAliases.has(alias)) {
225
+ continue;
226
+ }
227
+ const column = args.projection.columns[i];
228
+ if (!column) {
229
+ continue;
230
+ }
231
+ if (isExpressionBuilder(column)) {
232
+ const operationExpr = column.expr;
233
+ if (operationExpr.returns.kind === 'typeId') {
234
+ projectionTypes[alias] = operationExpr.returns.type;
235
+ } else if (operationExpr.returns.kind === 'builtin') {
236
+ projectionTypes[alias] = operationExpr.returns.type;
237
+ }
238
+ } else {
239
+ // column is ColumnBuilder
240
+ const col = column as unknown as { columnMeta?: { codecId: string } };
241
+ const columnMeta = col.columnMeta;
242
+ const codecId = columnMeta?.codecId;
243
+ if (codecId) {
244
+ projectionTypes[alias] = codecId;
245
+ }
246
+ }
247
+ }
248
+
249
+ // Build codec assignments from column types
250
+ // Skip include aliases - they don't need codec entries
251
+ const projectionCodecs: Record<string, string> = {};
252
+ for (let i = 0; i < args.projection.aliases.length; i++) {
253
+ const alias = args.projection.aliases[i];
254
+ if (!alias || includeAliases.has(alias)) {
255
+ continue;
256
+ }
257
+ const column = args.projection.columns[i];
258
+ if (!column) {
259
+ continue;
260
+ }
261
+ if (isExpressionBuilder(column)) {
262
+ const operationExpr = column.expr;
263
+ if (operationExpr.returns.kind === 'typeId') {
264
+ projectionCodecs[alias] = operationExpr.returns.type;
265
+ }
266
+ } else {
267
+ // Use columnMeta.codecId directly as typeId (already canonicalized)
268
+ // column is ColumnBuilder
269
+ const col = column as unknown as { columnMeta?: { codecId: string } };
270
+ const columnMeta = col.columnMeta;
271
+ const codecId = columnMeta?.codecId;
272
+ if (codecId) {
273
+ projectionCodecs[alias] = codecId;
274
+ }
275
+ }
276
+ }
277
+
278
+ // Merge projection and parameter codecs
279
+ const allCodecs: Record<string, string> = {
280
+ ...projectionCodecs,
281
+ ...(args.paramCodecs ? args.paramCodecs : {}),
282
+ };
283
+
284
+ return Object.freeze(
285
+ compact({
286
+ target: args.contract.target,
287
+ targetFamily: args.contract.targetFamily,
288
+ storageHash: args.contract.storageHash,
289
+ lane: 'dsl',
290
+ refs: {
291
+ tables: Array.from(refsTables),
292
+ columns: Array.from(refsColumns.values()),
293
+ },
294
+ projection: projectionMap,
295
+ projectionTypes: Object.keys(projectionTypes).length > 0 ? projectionTypes : undefined,
296
+ annotations:
297
+ Object.keys(allCodecs).length > 0
298
+ ? Object.freeze({ codecs: Object.freeze(allCodecs) })
299
+ : undefined,
300
+ paramDescriptors: args.paramDescriptors,
301
+ profileHash: args.contract.profileHash,
302
+ }) as PlanMeta,
303
+ );
304
+ }
@@ -0,0 +1,184 @@
1
+ import type { ParamDescriptor } from '@prisma-next/contract/types';
2
+ import type { SqlContract, SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';
3
+ import type {
4
+ Expression,
5
+ NullCheckExpr,
6
+ ParamRef,
7
+ WhereExpr,
8
+ } from '@prisma-next/sql-relational-core/ast';
9
+ import {
10
+ createBinaryExpr,
11
+ createNullCheckExpr,
12
+ createParamRef,
13
+ } from '@prisma-next/sql-relational-core/ast';
14
+ import type {
15
+ BinaryBuilder,
16
+ NullCheckBuilder,
17
+ ParamPlaceholder,
18
+ UnaryBuilder,
19
+ } from '@prisma-next/sql-relational-core/types';
20
+ import {
21
+ isColumnBuilder,
22
+ isExpressionBuilder,
23
+ isParamPlaceholder,
24
+ } from '@prisma-next/sql-relational-core/utils/guards';
25
+ import {
26
+ errorFailedToBuildWhereClause,
27
+ errorMissingParameter,
28
+ errorUnknownColumn,
29
+ errorUnknownTable,
30
+ } from '../utils/errors';
31
+
32
+ export interface BuildWhereExprResult {
33
+ expr: WhereExpr;
34
+ codecId: string | undefined;
35
+ paramName: string;
36
+ }
37
+
38
+ /**
39
+ * Type guard to check if a builder is a NullCheckBuilder (unary).
40
+ */
41
+ function isNullCheckBuilder(builder: BinaryBuilder | UnaryBuilder): builder is NullCheckBuilder {
42
+ return builder.kind === 'nullCheck';
43
+ }
44
+
45
+ /**
46
+ * Builds a NullCheckExpr from a NullCheckBuilder.
47
+ */
48
+ function buildNullCheckExpr(
49
+ contract: SqlContract<SqlStorage>,
50
+ where: NullCheckBuilder,
51
+ ): NullCheckExpr {
52
+ const expr = where.expr;
53
+
54
+ // Validate column exists in contract if it's a ColumnRef
55
+ if (expr.kind === 'col') {
56
+ const { table, column } = expr;
57
+ const contractTable = contract.storage.tables[table];
58
+ if (!contractTable) {
59
+ errorUnknownTable(table);
60
+ }
61
+
62
+ const columnMeta: StorageColumn | undefined = contractTable.columns[column];
63
+ if (!columnMeta) {
64
+ errorUnknownColumn(column, table);
65
+ }
66
+ }
67
+
68
+ return createNullCheckExpr(expr, where.isNull);
69
+ }
70
+
71
+ export function buildWhereExpr(
72
+ contract: SqlContract<SqlStorage>,
73
+ where: BinaryBuilder | UnaryBuilder,
74
+ paramsMap: Record<string, unknown>,
75
+ descriptors: ParamDescriptor[],
76
+ values: unknown[],
77
+ ): BuildWhereExprResult {
78
+ // Handle NullCheckBuilder (unary expression)
79
+ if (isNullCheckBuilder(where)) {
80
+ return {
81
+ expr: buildNullCheckExpr(contract, where),
82
+ codecId: undefined,
83
+ paramName: '',
84
+ };
85
+ }
86
+
87
+ // Handle BinaryBuilder (binary expression)
88
+ let leftExpr: Expression;
89
+ let codecId: string | undefined;
90
+ let rightExpr: Expression | ParamRef;
91
+ let paramName: string;
92
+
93
+ // Validate where.left is a valid Expression (col or operation)
94
+ const validExpressionKinds = ['col', 'operation'];
95
+ if (
96
+ !where.left ||
97
+ typeof where.left !== 'object' ||
98
+ !validExpressionKinds.includes((where.left as { kind?: string }).kind ?? '')
99
+ ) {
100
+ errorFailedToBuildWhereClause();
101
+ }
102
+
103
+ // where.left is an Expression (already converted at builder creation time)
104
+ // It could be a ColumnRef or OperationExpr
105
+ leftExpr = where.left;
106
+
107
+ // If the left expression is a column reference, extract codecId for param descriptors
108
+ if (leftExpr.kind === 'col') {
109
+ const { table, column } = leftExpr;
110
+ const contractTable = contract.storage.tables[table];
111
+ if (!contractTable) {
112
+ errorUnknownTable(table);
113
+ }
114
+
115
+ const columnMeta: StorageColumn | undefined = contractTable.columns[column];
116
+ if (!columnMeta) {
117
+ errorUnknownColumn(column, table);
118
+ }
119
+
120
+ codecId = columnMeta.codecId;
121
+ }
122
+
123
+ // Handle where.right - can be ParamPlaceholder or ExpressionSource
124
+ if (isParamPlaceholder(where.right)) {
125
+ // Handle param placeholder (existing logic)
126
+ const placeholder: ParamPlaceholder = where.right;
127
+ paramName = placeholder.name;
128
+
129
+ if (!Object.hasOwn(paramsMap, paramName)) {
130
+ errorMissingParameter(paramName);
131
+ }
132
+
133
+ const value = paramsMap[paramName];
134
+ const index = values.push(value);
135
+
136
+ // Construct descriptor directly from validated StorageColumn if left is a column
137
+ if (leftExpr.kind === 'col') {
138
+ const { table, column } = leftExpr;
139
+ const contractTable = contract.storage.tables[table];
140
+ const columnMeta = contractTable?.columns[column];
141
+ if (columnMeta) {
142
+ descriptors.push({
143
+ name: paramName,
144
+ source: 'dsl',
145
+ refs: { table, column },
146
+ nullable: columnMeta.nullable,
147
+ codecId: columnMeta.codecId,
148
+ nativeType: columnMeta.nativeType,
149
+ });
150
+ }
151
+ }
152
+
153
+ rightExpr = createParamRef(index, paramName);
154
+ } else if (isColumnBuilder(where.right) || isExpressionBuilder(where.right)) {
155
+ // Handle ExpressionSource (ColumnBuilder or ExpressionBuilder) on the right
156
+ rightExpr = where.right.toExpr();
157
+
158
+ // Validate column exists in contract if it's a ColumnRef
159
+ if (rightExpr.kind === 'col') {
160
+ const { table, column } = rightExpr;
161
+ const contractTable = contract.storage.tables[table];
162
+ if (!contractTable) {
163
+ errorUnknownTable(table);
164
+ }
165
+
166
+ const columnMeta: StorageColumn | undefined = contractTable.columns[column];
167
+ if (!columnMeta) {
168
+ errorUnknownColumn(column, table);
169
+ }
170
+ }
171
+
172
+ // Use a placeholder paramName for expression references (not used for params)
173
+ paramName = '';
174
+ } else {
175
+ // where.right is neither ParamPlaceholder nor ExpressionSource - invalid state
176
+ errorFailedToBuildWhereClause();
177
+ }
178
+
179
+ return {
180
+ expr: createBinaryExpr(where.op, leftExpr, rightExpr),
181
+ codecId,
182
+ paramName,
183
+ };
184
+ }
@@ -0,0 +1,117 @@
1
+ import type { TableRef } from '@prisma-next/sql-relational-core/ast';
2
+ import type { AnyExpressionSource, NestedProjection } from '@prisma-next/sql-relational-core/types';
3
+ import { isExpressionSource } from '@prisma-next/sql-relational-core/utils/guards';
4
+ import type { ProjectionInput } from '../types/internal';
5
+ import {
6
+ errorAliasCollision,
7
+ errorAliasPathEmpty,
8
+ errorIncludeAliasNotFound,
9
+ errorInvalidProjectionKey,
10
+ errorInvalidProjectionValue,
11
+ errorProjectionEmpty,
12
+ } from '../utils/errors';
13
+ import type { IncludeState, ProjectionState } from '../utils/state';
14
+
15
+ export function generateAlias(path: string[]): string {
16
+ if (path.length === 0) {
17
+ errorAliasPathEmpty();
18
+ }
19
+ return path.join('_');
20
+ }
21
+
22
+ export class AliasTracker {
23
+ private readonly aliases = new Set<string>();
24
+ private readonly aliasToPath = new Map<string, string[]>();
25
+
26
+ register(path: string[]): string {
27
+ const alias = generateAlias(path);
28
+ if (this.aliases.has(alias)) {
29
+ const existingPath = this.aliasToPath.get(alias);
30
+ errorAliasCollision(path, alias, existingPath);
31
+ }
32
+ this.aliases.add(alias);
33
+ this.aliasToPath.set(alias, path);
34
+ return alias;
35
+ }
36
+
37
+ getPath(alias: string): string[] | undefined {
38
+ return this.aliasToPath.get(alias);
39
+ }
40
+
41
+ has(alias: string): boolean {
42
+ return this.aliases.has(alias);
43
+ }
44
+ }
45
+
46
+ export function flattenProjection(
47
+ projection: NestedProjection,
48
+ tracker: AliasTracker,
49
+ currentPath: string[] = [],
50
+ ): { aliases: string[]; columns: AnyExpressionSource[] } {
51
+ const aliases: string[] = [];
52
+ const columns: AnyExpressionSource[] = [];
53
+
54
+ for (const [key, value] of Object.entries(projection)) {
55
+ const path = [...currentPath, key];
56
+
57
+ if (isExpressionSource(value)) {
58
+ const alias = tracker.register(path);
59
+ aliases.push(alias);
60
+ columns.push(value);
61
+ } else if (typeof value === 'object' && value !== null) {
62
+ const nested = flattenProjection(value, tracker, path);
63
+ aliases.push(...nested.aliases);
64
+ columns.push(...nested.columns);
65
+ } else {
66
+ errorInvalidProjectionValue(path);
67
+ }
68
+ }
69
+
70
+ return { aliases, columns };
71
+ }
72
+
73
+ export function buildProjectionState(
74
+ _table: TableRef,
75
+ projection: ProjectionInput,
76
+ includes?: ReadonlyArray<IncludeState>,
77
+ ): ProjectionState {
78
+ const tracker = new AliasTracker();
79
+ const aliases: string[] = [];
80
+ const columns: AnyExpressionSource[] = [];
81
+
82
+ for (const [key, value] of Object.entries(projection)) {
83
+ if (value === true) {
84
+ // Boolean true means this is an include reference
85
+ const matchingInclude = includes?.find((inc) => inc.alias === key);
86
+ if (!matchingInclude) {
87
+ errorIncludeAliasNotFound(key);
88
+ }
89
+ // For include references, we track the alias but use a placeholder object
90
+ // The actual handling happens in AST building where we create includeRef
91
+ aliases.push(key);
92
+ columns.push({
93
+ kind: 'column',
94
+ table: matchingInclude.table.name,
95
+ column: '',
96
+ columnMeta: { nativeType: 'jsonb', codecId: 'core/json@1', nullable: true },
97
+ toExpr: () => ({ kind: 'col', table: matchingInclude.table.name, column: '' }),
98
+ } as AnyExpressionSource);
99
+ } else if (isExpressionSource(value)) {
100
+ const alias = tracker.register([key]);
101
+ aliases.push(alias);
102
+ columns.push(value);
103
+ } else if (typeof value === 'object' && value !== null) {
104
+ const nested = flattenProjection(value as NestedProjection, tracker, [key]);
105
+ aliases.push(...nested.aliases);
106
+ columns.push(...nested.columns);
107
+ } else {
108
+ errorInvalidProjectionKey(key);
109
+ }
110
+ }
111
+
112
+ if (aliases.length === 0) {
113
+ errorProjectionEmpty();
114
+ }
115
+
116
+ return { aliases, columns };
117
+ }