@prisma-next/sql-lane 0.3.0-pr.94.3 → 0.3.0-pr.95.2

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.
Files changed (56) hide show
  1. package/dist/chunk-72PNERR5.js +1541 -0
  2. package/dist/chunk-72PNERR5.js.map +1 -0
  3. package/dist/exports/sql.d.ts +5 -0
  4. package/dist/exports/sql.d.ts.map +1 -0
  5. package/dist/exports/sql.js +11 -0
  6. package/dist/exports/sql.js.map +1 -0
  7. package/dist/index.d.ts +5 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +11 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/raw.d.ts +11 -0
  12. package/dist/raw.d.ts.map +1 -0
  13. package/dist/sql/builder.d.ts +11 -0
  14. package/dist/sql/builder.d.ts.map +1 -0
  15. package/dist/sql/context.d.ts +5 -0
  16. package/dist/sql/context.d.ts.map +1 -0
  17. package/dist/sql/include-builder.d.ts +35 -0
  18. package/dist/sql/include-builder.d.ts.map +1 -0
  19. package/dist/sql/join-builder.d.ts +4 -0
  20. package/dist/sql/join-builder.d.ts.map +1 -0
  21. package/dist/sql/mutation-builder.d.ts +64 -0
  22. package/dist/sql/mutation-builder.d.ts.map +1 -0
  23. package/dist/sql/plan.d.ts +4 -0
  24. package/dist/sql/plan.d.ts.map +1 -0
  25. package/dist/sql/predicate-builder.d.ts +11 -0
  26. package/dist/sql/predicate-builder.d.ts.map +1 -0
  27. package/dist/sql/projection.d.ts +18 -0
  28. package/dist/sql/projection.d.ts.map +1 -0
  29. package/dist/sql/select-builder.d.ts +35 -0
  30. package/dist/sql/select-builder.d.ts.map +1 -0
  31. package/dist/types/internal.d.ts +35 -0
  32. package/dist/types/internal.d.ts.map +1 -0
  33. package/dist/types/public.d.ts +18 -0
  34. package/dist/types/public.d.ts.map +1 -0
  35. package/dist/utils/assertions.d.ts +28 -0
  36. package/dist/utils/assertions.d.ts.map +1 -0
  37. package/dist/utils/capabilities.d.ts +4 -0
  38. package/dist/utils/capabilities.d.ts.map +1 -0
  39. package/dist/utils/errors.d.ts +30 -0
  40. package/dist/utils/errors.d.ts.map +1 -0
  41. package/dist/utils/state.d.ts +30 -0
  42. package/dist/utils/state.d.ts.map +1 -0
  43. package/package.json +18 -20
  44. package/src/sql/include-builder.ts +4 -1
  45. package/src/sql/plan.ts +2 -2
  46. package/src/sql/predicate-builder.ts +2 -2
  47. package/src/sql/projection.ts +1 -1
  48. package/src/sql/select-builder.ts +1 -1
  49. package/dist/builder-7PlMfjqo.mjs +0 -1175
  50. package/dist/builder-7PlMfjqo.mjs.map +0 -1
  51. package/dist/builder-C8ExdG4j.d.mts +0 -121
  52. package/dist/builder-C8ExdG4j.d.mts.map +0 -1
  53. package/dist/exports/sql.d.mts +0 -3
  54. package/dist/exports/sql.mjs +0 -3
  55. package/dist/index.d.mts +0 -3
  56. package/dist/index.mjs +0 -3
@@ -0,0 +1,1541 @@
1
+ // src/raw.ts
2
+ import { planInvalid } from "@prisma-next/plan";
3
+ var RAW_OPTIONS_SENTINEL = /* @__PURE__ */ Symbol("rawOptions");
4
+ function createRawFactory(contract) {
5
+ const factory = ((first, ...rest) => {
6
+ if (isTemplateInvocation(first)) {
7
+ const { values, options: options2 } = splitTemplateValues(rest);
8
+ const compiled = compileTemplateToPositional(first, values);
9
+ return buildRawPlan({
10
+ contract,
11
+ sql: compiled.sql,
12
+ params: compiled.params,
13
+ paramDescriptors: compiled.paramDescriptors,
14
+ ...options2 ? { options: options2 } : {}
15
+ });
16
+ }
17
+ const text = first;
18
+ const [options] = rest;
19
+ if (!options) {
20
+ throw planInvalid("Function form requires params option");
21
+ }
22
+ if (!Array.isArray(options.params)) {
23
+ throw planInvalid("Function form params must be an array");
24
+ }
25
+ const paramDescriptors = buildSequentialDescriptors(options.params.length);
26
+ return buildRawPlan({
27
+ contract,
28
+ sql: text,
29
+ params: options.params,
30
+ paramDescriptors,
31
+ options
32
+ });
33
+ });
34
+ factory.with = (options) => {
35
+ return ((strings, ...values) => {
36
+ const compiled = compileTemplateToPositional(strings, values);
37
+ return buildRawPlan({
38
+ contract,
39
+ sql: compiled.sql,
40
+ params: compiled.params,
41
+ paramDescriptors: compiled.paramDescriptors,
42
+ options
43
+ });
44
+ });
45
+ };
46
+ return factory;
47
+ }
48
+ function compileTemplateToPositional(strings, values) {
49
+ let sql2 = "";
50
+ const params = [];
51
+ const paramDescriptors = [];
52
+ strings.forEach((part, index) => {
53
+ sql2 += part;
54
+ if (index < values.length) {
55
+ const value = values[index];
56
+ const placeholderIndex = params.push(value);
57
+ sql2 += `$${placeholderIndex}`;
58
+ paramDescriptors.push({
59
+ index: placeholderIndex,
60
+ name: `p${placeholderIndex}`,
61
+ source: "raw"
62
+ });
63
+ }
64
+ });
65
+ return {
66
+ sql: sql2,
67
+ params,
68
+ paramDescriptors
69
+ };
70
+ }
71
+ function buildRawPlan(args) {
72
+ const params = Array.from(args.params);
73
+ const descriptors = args.paramDescriptors.map(
74
+ (descriptor) => Object.freeze({ ...descriptor, source: "raw" })
75
+ );
76
+ const meta = buildRawMeta({
77
+ contract: args.contract,
78
+ paramDescriptors: descriptors,
79
+ ...args.options ? { options: args.options } : {}
80
+ });
81
+ return Object.freeze({
82
+ sql: args.sql,
83
+ params: Object.freeze(params),
84
+ meta
85
+ });
86
+ }
87
+ function buildRawMeta(args) {
88
+ const { contract, paramDescriptors, options } = args;
89
+ const meta = {
90
+ target: contract.target,
91
+ targetFamily: contract.targetFamily,
92
+ coreHash: contract.coreHash,
93
+ ...contract.profileHash !== void 0 ? { profileHash: contract.profileHash } : {},
94
+ lane: "raw",
95
+ paramDescriptors: Object.freeze([...paramDescriptors]),
96
+ ...options?.annotations ? { annotations: Object.freeze({ ...options.annotations }) } : {},
97
+ ...options?.refs ? { refs: freezeRefs(options.refs) } : {},
98
+ ...options?.projection ? { projection: Object.freeze([...options.projection]) } : {}
99
+ };
100
+ return Object.freeze(meta);
101
+ }
102
+ function freezeRefs(refs) {
103
+ return Object.freeze({
104
+ ...refs.tables ? { tables: Object.freeze([...refs.tables]) } : {},
105
+ ...refs.columns ? {
106
+ columns: Object.freeze(
107
+ refs.columns.map((col) => Object.freeze({ ...col }))
108
+ )
109
+ } : {},
110
+ ...refs.indexes ? {
111
+ indexes: Object.freeze(
112
+ refs.indexes.map(
113
+ (index) => Object.freeze({
114
+ ...index,
115
+ columns: Object.freeze([...index.columns])
116
+ })
117
+ )
118
+ )
119
+ } : {}
120
+ });
121
+ }
122
+ function buildSequentialDescriptors(count) {
123
+ return Array.from(
124
+ { length: count },
125
+ (_, idx) => Object.freeze({
126
+ index: idx + 1,
127
+ name: `p${idx + 1}`,
128
+ source: "raw"
129
+ })
130
+ );
131
+ }
132
+ function isTemplateInvocation(value) {
133
+ return Array.isArray(value) && Object.hasOwn(value, "raw");
134
+ }
135
+ function rawOptions(options) {
136
+ return Object.freeze({
137
+ [RAW_OPTIONS_SENTINEL]: true,
138
+ value: options
139
+ });
140
+ }
141
+ function splitTemplateValues(values) {
142
+ if (values.length === 0) {
143
+ return { values };
144
+ }
145
+ const last = values[values.length - 1];
146
+ if (!isOptionsSentinel(last)) {
147
+ return { values };
148
+ }
149
+ return {
150
+ values: values.slice(0, values.length - 1),
151
+ options: last.value
152
+ };
153
+ }
154
+ function isOptionsSentinel(value) {
155
+ return typeof value === "object" && value !== null && RAW_OPTIONS_SENTINEL in value;
156
+ }
157
+
158
+ // src/sql/builder.ts
159
+ import { createJoinOnBuilder as createJoinOnBuilder2 } from "@prisma-next/sql-relational-core/ast";
160
+
161
+ // src/sql/mutation-builder.ts
162
+ import {
163
+ createColumnRef,
164
+ createDeleteAst,
165
+ createInsertAst,
166
+ createParamRef as createParamRef2,
167
+ createTableRef,
168
+ createUpdateAst
169
+ } from "@prisma-next/sql-relational-core/ast";
170
+
171
+ // src/utils/errors.ts
172
+ import { planInvalid as planInvalid2 } from "@prisma-next/plan";
173
+ function errorAliasPathEmpty() {
174
+ throw planInvalid2("Alias path cannot be empty");
175
+ }
176
+ function errorAliasCollision(path, alias, existingPath) {
177
+ throw planInvalid2(
178
+ `Alias collision: path ${path.join(".")} would generate alias "${alias}" which conflicts with path ${existingPath?.join(".") ?? "unknown"}`
179
+ );
180
+ }
181
+ function errorLimitMustBeNonNegativeInteger() {
182
+ throw planInvalid2("Limit must be a non-negative integer");
183
+ }
184
+ function errorChildProjectionMustBeSpecified() {
185
+ throw planInvalid2("Child projection must be specified");
186
+ }
187
+ function errorIncludeRequiresCapabilities(target) {
188
+ throw planInvalid2(
189
+ "includeMany requires lateral and jsonAgg capabilities",
190
+ target ? { target } : void 0,
191
+ [
192
+ "Enable capabilities for your target in contract.capabilities[target]",
193
+ "For SQL includes, set both 'lateral' and 'jsonAgg' to true",
194
+ "If your database lacks lateral/json_agg, use explicit joins + group aggregates"
195
+ ],
196
+ [
197
+ "docs/Architecture Overview.md",
198
+ "docs/reference/extensions-glossary.md",
199
+ "packages/3-targets/6-adapters/postgres/README.md"
200
+ ]
201
+ );
202
+ }
203
+ function errorIncludeCapabilitiesNotTrue(target, values) {
204
+ throw planInvalid2(
205
+ "includeMany requires lateral and jsonAgg capabilities to be true",
206
+ target ? { target, values } : void 0,
207
+ [
208
+ "Set contract.capabilities[target].lateral = true and .jsonAgg = true",
209
+ "If the target does not support these, avoid includeMany and compose a two-step plan"
210
+ ],
211
+ [
212
+ "docs/Architecture Overview.md",
213
+ "docs/reference/extensions-glossary.md",
214
+ "packages/3-targets/6-adapters/postgres/README.md"
215
+ ]
216
+ );
217
+ }
218
+ function errorUnknownTable(tableName) {
219
+ throw planInvalid2(`Unknown table ${tableName}`);
220
+ }
221
+ function errorSelfJoinNotSupported() {
222
+ throw planInvalid2("Self-joins are not supported in MVP");
223
+ }
224
+ function errorChildProjectionEmpty() {
225
+ throw planInvalid2("Child projection must not be empty");
226
+ }
227
+ function errorIncludeAliasCollision(alias, type) {
228
+ throw planInvalid2(
229
+ `Alias collision: include alias "${alias}" conflicts with existing ${type} alias`
230
+ );
231
+ }
232
+ function errorMissingColumnForAlias(alias, index) {
233
+ throw planInvalid2(`Missing column for alias ${alias ?? "unknown"} at index ${index}`);
234
+ }
235
+ function errorMissingAlias(index) {
236
+ throw planInvalid2(`Missing alias at index ${index}`);
237
+ }
238
+ function errorFromMustBeCalled() {
239
+ throw planInvalid2("from() must be called before building a query");
240
+ }
241
+ function errorSelectMustBeCalled() {
242
+ throw planInvalid2("select() must be called before build()");
243
+ }
244
+ function errorMissingParameter(paramName) {
245
+ throw planInvalid2(`Missing value for parameter ${paramName}`);
246
+ }
247
+ function errorInvalidProjectionValue(path) {
248
+ throw planInvalid2(
249
+ `Invalid projection value at path ${path.join(".")}: expected ExpressionSource (ColumnBuilder or ExpressionBuilder) or nested object`
250
+ );
251
+ }
252
+ function errorIncludeAliasNotFound(alias) {
253
+ throw planInvalid2(
254
+ `Include alias "${alias}" not found. Did you call includeMany() with alias "${alias}"?`
255
+ );
256
+ }
257
+ function errorInvalidProjectionKey(key) {
258
+ throw planInvalid2(
259
+ `Invalid projection value at key "${key}": expected ColumnBuilder, boolean true (for includes), or nested object`
260
+ );
261
+ }
262
+ function errorProjectionEmpty() {
263
+ throw planInvalid2("select() requires at least one column or include");
264
+ }
265
+ function errorReturningRequiresCapability(target) {
266
+ throw planInvalid2(
267
+ "returning() requires returning capability",
268
+ target ? { target } : void 0,
269
+ [
270
+ "Enable 'returning' for your target in contract.capabilities[target]",
271
+ "PostgreSQL supports RETURNING; MySQL does not",
272
+ "If unsupported, remove returning() and fetch with a follow-up select()"
273
+ ],
274
+ [
275
+ "docs/Architecture Overview.md",
276
+ "docs/reference/extensions-glossary.md",
277
+ "packages/3-targets/6-adapters/postgres/README.md"
278
+ ]
279
+ );
280
+ }
281
+ function errorReturningCapabilityNotTrue(target, value) {
282
+ throw planInvalid2(
283
+ "returning() requires returning capability to be true",
284
+ target ? { target, value } : void 0,
285
+ [
286
+ "Set contract.capabilities[target].returning = true",
287
+ "If your database/adapter cannot support RETURNING, remove returning() and select after"
288
+ ],
289
+ [
290
+ "docs/Architecture Overview.md",
291
+ "docs/reference/extensions-glossary.md",
292
+ "packages/3-targets/6-adapters/postgres/README.md"
293
+ ]
294
+ );
295
+ }
296
+ function errorUnknownColumn(columnName, tableName) {
297
+ throw planInvalid2(`Unknown column ${columnName} in table ${tableName}`);
298
+ }
299
+ function errorWhereMustBeCalledForUpdate() {
300
+ throw planInvalid2("where() must be called before building an UPDATE query");
301
+ }
302
+ function errorFailedToBuildWhereClause() {
303
+ throw planInvalid2("Failed to build WHERE clause");
304
+ }
305
+ function errorWhereMustBeCalledForDelete() {
306
+ throw planInvalid2("where() must be called before building a DELETE query");
307
+ }
308
+
309
+ // src/utils/capabilities.ts
310
+ function checkIncludeCapabilities(contract) {
311
+ const target = contract.target;
312
+ const contractCapabilities = contract.capabilities;
313
+ const declaredTargetCapabilities = contractCapabilities?.[target];
314
+ if (!contractCapabilities || !declaredTargetCapabilities) {
315
+ errorIncludeRequiresCapabilities(target);
316
+ }
317
+ if (declaredTargetCapabilities["lateral"] !== true || declaredTargetCapabilities["jsonAgg"] !== true) {
318
+ errorIncludeCapabilitiesNotTrue(target, {
319
+ lateral: declaredTargetCapabilities["lateral"],
320
+ jsonAgg: declaredTargetCapabilities["jsonAgg"]
321
+ });
322
+ }
323
+ }
324
+ function checkReturningCapability(contract) {
325
+ const target = contract.target;
326
+ const capabilities = contract.capabilities;
327
+ if (!capabilities || !capabilities[target]) {
328
+ errorReturningRequiresCapability(target);
329
+ }
330
+ const targetCapabilities = capabilities[target];
331
+ if (targetCapabilities["returning"] !== true) {
332
+ errorReturningCapabilityNotTrue(target, targetCapabilities["returning"]);
333
+ }
334
+ }
335
+
336
+ // src/sql/plan.ts
337
+ import { compact } from "@prisma-next/sql-relational-core/ast";
338
+ import {
339
+ collectColumnRefs,
340
+ isColumnBuilder,
341
+ isExpressionBuilder,
342
+ isOperationExpr
343
+ } from "@prisma-next/sql-relational-core/utils/guards";
344
+
345
+ // src/utils/assertions.ts
346
+ import { planInvalid as planInvalid3 } from "@prisma-next/plan";
347
+ function assertColumnBuilder(col, context) {
348
+ if (typeof col === "object" && col !== null && "table" in col && "column" in col && typeof col.table === "string" && typeof col.column === "string") {
349
+ return col;
350
+ }
351
+ throw planInvalid3(`ColumnBuilder missing table/column in ${context}`);
352
+ }
353
+
354
+ // src/sql/plan.ts
355
+ function collectRefsFromExpressionSource(source, refsColumns) {
356
+ if (isExpressionBuilder(source)) {
357
+ const allRefs = collectColumnRefs(source.expr);
358
+ for (const ref of allRefs) {
359
+ refsColumns.set(`${ref.table}.${ref.column}`, {
360
+ table: ref.table,
361
+ column: ref.column
362
+ });
363
+ }
364
+ } else if (isColumnBuilder(source)) {
365
+ const col = source;
366
+ refsColumns.set(`${col.table}.${col.column}`, {
367
+ table: col.table,
368
+ column: col.column
369
+ });
370
+ }
371
+ }
372
+ function collectRefsFromExpression(expr, refsColumns) {
373
+ if (isOperationExpr(expr)) {
374
+ const allRefs = collectColumnRefs(expr);
375
+ for (const ref of allRefs) {
376
+ refsColumns.set(`${ref.table}.${ref.column}`, {
377
+ table: ref.table,
378
+ column: ref.column
379
+ });
380
+ }
381
+ } else if (expr.kind === "col") {
382
+ refsColumns.set(`${expr.table}.${expr.column}`, {
383
+ table: expr.table,
384
+ column: expr.column
385
+ });
386
+ }
387
+ }
388
+ function buildMeta(args) {
389
+ const refsColumns = /* @__PURE__ */ new Map();
390
+ const refsTables = /* @__PURE__ */ new Set([args.table.name]);
391
+ for (const column of args.projection.columns) {
392
+ collectRefsFromExpressionSource(column, refsColumns);
393
+ }
394
+ if (args.joins) {
395
+ for (const join of args.joins) {
396
+ refsTables.add(join.table.name);
397
+ const onLeft = assertColumnBuilder(join.on.left, "join ON left");
398
+ const onRight = assertColumnBuilder(join.on.right, "join ON right");
399
+ refsColumns.set(`${onLeft.table}.${onLeft.column}`, {
400
+ table: onLeft.table,
401
+ column: onLeft.column
402
+ });
403
+ refsColumns.set(`${onRight.table}.${onRight.column}`, {
404
+ table: onRight.table,
405
+ column: onRight.column
406
+ });
407
+ }
408
+ }
409
+ if (args.includes) {
410
+ for (const include of args.includes) {
411
+ refsTables.add(include.table.name);
412
+ const leftCol = assertColumnBuilder(include.on.left, "include ON left");
413
+ const rightCol = assertColumnBuilder(include.on.right, "include ON right");
414
+ refsColumns.set(`${leftCol.table}.${leftCol.column}`, {
415
+ table: leftCol.table,
416
+ column: leftCol.column
417
+ });
418
+ refsColumns.set(`${rightCol.table}.${rightCol.column}`, {
419
+ table: rightCol.table,
420
+ column: rightCol.column
421
+ });
422
+ for (const column of include.childProjection.columns) {
423
+ const col = assertColumnBuilder(column, "include child projection column");
424
+ refsColumns.set(`${col.table}.${col.column}`, {
425
+ table: col.table,
426
+ column: col.column
427
+ });
428
+ }
429
+ if (include.childWhere) {
430
+ collectRefsFromExpression(include.childWhere.left, refsColumns);
431
+ const childWhereRight = include.childWhere.right;
432
+ if (isColumnBuilder(childWhereRight) || isExpressionBuilder(childWhereRight)) {
433
+ collectRefsFromExpressionSource(childWhereRight, refsColumns);
434
+ }
435
+ }
436
+ if (include.childOrderBy) {
437
+ collectRefsFromExpression(include.childOrderBy.expr, refsColumns);
438
+ }
439
+ }
440
+ }
441
+ if (args.where) {
442
+ const leftExpr = args.where.left;
443
+ if (isOperationExpr(leftExpr)) {
444
+ const allRefs = collectColumnRefs(leftExpr);
445
+ for (const ref of allRefs) {
446
+ refsColumns.set(`${ref.table}.${ref.column}`, {
447
+ table: ref.table,
448
+ column: ref.column
449
+ });
450
+ }
451
+ } else {
452
+ refsColumns.set(`${leftExpr.table}.${leftExpr.column}`, {
453
+ table: leftExpr.table,
454
+ column: leftExpr.column
455
+ });
456
+ }
457
+ const whereRight = args.where.right;
458
+ if (isColumnBuilder(whereRight) || isExpressionBuilder(whereRight)) {
459
+ collectRefsFromExpressionSource(whereRight, refsColumns);
460
+ }
461
+ }
462
+ if (args.orderBy) {
463
+ const orderByExpr = args.orderBy.expr;
464
+ if (isOperationExpr(orderByExpr)) {
465
+ const allRefs = collectColumnRefs(orderByExpr);
466
+ for (const ref of allRefs) {
467
+ refsColumns.set(`${ref.table}.${ref.column}`, {
468
+ table: ref.table,
469
+ column: ref.column
470
+ });
471
+ }
472
+ } else {
473
+ refsColumns.set(`${orderByExpr.table}.${orderByExpr.column}`, {
474
+ table: orderByExpr.table,
475
+ column: orderByExpr.column
476
+ });
477
+ }
478
+ }
479
+ const includeAliases = new Set(args.includes?.map((inc) => inc.alias) ?? []);
480
+ const projectionMap = Object.fromEntries(
481
+ args.projection.aliases.map((alias, index) => {
482
+ if (includeAliases.has(alias)) {
483
+ return [alias, `include:${alias}`];
484
+ }
485
+ const column = args.projection.columns[index];
486
+ if (!column) {
487
+ errorMissingColumnForAlias(alias, index);
488
+ }
489
+ if (isExpressionBuilder(column)) {
490
+ return [alias, `operation:${column.expr.method}`];
491
+ }
492
+ const col = column;
493
+ if (!col.table || !col.column) {
494
+ return [alias, `include:${alias}`];
495
+ }
496
+ return [alias, `${col.table}.${col.column}`];
497
+ })
498
+ );
499
+ const projectionTypes = {};
500
+ for (let i = 0; i < args.projection.aliases.length; i++) {
501
+ const alias = args.projection.aliases[i];
502
+ if (!alias || includeAliases.has(alias)) {
503
+ continue;
504
+ }
505
+ const column = args.projection.columns[i];
506
+ if (!column) {
507
+ continue;
508
+ }
509
+ if (isExpressionBuilder(column)) {
510
+ const operationExpr = column.expr;
511
+ if (operationExpr.returns.kind === "typeId") {
512
+ projectionTypes[alias] = operationExpr.returns.type;
513
+ } else if (operationExpr.returns.kind === "builtin") {
514
+ projectionTypes[alias] = operationExpr.returns.type;
515
+ }
516
+ } else {
517
+ const col = column;
518
+ const columnMeta = col.columnMeta;
519
+ const codecId = columnMeta?.codecId;
520
+ if (codecId) {
521
+ projectionTypes[alias] = codecId;
522
+ }
523
+ }
524
+ }
525
+ const projectionCodecs = {};
526
+ for (let i = 0; i < args.projection.aliases.length; i++) {
527
+ const alias = args.projection.aliases[i];
528
+ if (!alias || includeAliases.has(alias)) {
529
+ continue;
530
+ }
531
+ const column = args.projection.columns[i];
532
+ if (!column) {
533
+ continue;
534
+ }
535
+ if (isExpressionBuilder(column)) {
536
+ const operationExpr = column.expr;
537
+ if (operationExpr.returns.kind === "typeId") {
538
+ projectionCodecs[alias] = operationExpr.returns.type;
539
+ }
540
+ } else {
541
+ const col = column;
542
+ const columnMeta = col.columnMeta;
543
+ const codecId = columnMeta?.codecId;
544
+ if (codecId) {
545
+ projectionCodecs[alias] = codecId;
546
+ }
547
+ }
548
+ }
549
+ const allCodecs = {
550
+ ...projectionCodecs,
551
+ ...args.paramCodecs ? args.paramCodecs : {}
552
+ };
553
+ return Object.freeze(
554
+ compact({
555
+ target: args.contract.target,
556
+ targetFamily: args.contract.targetFamily,
557
+ coreHash: args.contract.coreHash,
558
+ lane: "dsl",
559
+ refs: {
560
+ tables: Array.from(refsTables),
561
+ columns: Array.from(refsColumns.values())
562
+ },
563
+ projection: projectionMap,
564
+ projectionTypes: Object.keys(projectionTypes).length > 0 ? projectionTypes : void 0,
565
+ annotations: Object.keys(allCodecs).length > 0 ? Object.freeze({ codecs: Object.freeze(allCodecs) }) : void 0,
566
+ paramDescriptors: args.paramDescriptors,
567
+ profileHash: args.contract.profileHash
568
+ })
569
+ );
570
+ }
571
+
572
+ // src/sql/predicate-builder.ts
573
+ import { createBinaryExpr, createParamRef } from "@prisma-next/sql-relational-core/ast";
574
+ import {
575
+ isColumnBuilder as isColumnBuilder2,
576
+ isExpressionBuilder as isExpressionBuilder2,
577
+ isParamPlaceholder
578
+ } from "@prisma-next/sql-relational-core/utils/guards";
579
+ function buildWhereExpr(contract, where, paramsMap, descriptors, values) {
580
+ let leftExpr;
581
+ let codecId;
582
+ let rightExpr;
583
+ let paramName;
584
+ const validExpressionKinds = ["col", "operation"];
585
+ if (!where.left || typeof where.left !== "object" || !validExpressionKinds.includes(where.left.kind ?? "")) {
586
+ errorFailedToBuildWhereClause();
587
+ }
588
+ leftExpr = where.left;
589
+ if (leftExpr.kind === "col") {
590
+ const { table, column } = leftExpr;
591
+ const contractTable = contract.storage.tables[table];
592
+ if (!contractTable) {
593
+ errorUnknownTable(table);
594
+ }
595
+ const columnMeta = contractTable.columns[column];
596
+ if (!columnMeta) {
597
+ errorUnknownColumn(column, table);
598
+ }
599
+ codecId = columnMeta.codecId;
600
+ }
601
+ if (isParamPlaceholder(where.right)) {
602
+ const placeholder = where.right;
603
+ paramName = placeholder.name;
604
+ if (!Object.hasOwn(paramsMap, paramName)) {
605
+ errorMissingParameter(paramName);
606
+ }
607
+ const value = paramsMap[paramName];
608
+ const index = values.push(value);
609
+ if (leftExpr.kind === "col") {
610
+ const { table, column } = leftExpr;
611
+ const contractTable = contract.storage.tables[table];
612
+ const columnMeta = contractTable?.columns[column];
613
+ if (columnMeta) {
614
+ descriptors.push({
615
+ name: paramName,
616
+ source: "dsl",
617
+ refs: { table, column },
618
+ nullable: columnMeta.nullable,
619
+ codecId: columnMeta.codecId,
620
+ nativeType: columnMeta.nativeType
621
+ });
622
+ }
623
+ }
624
+ rightExpr = createParamRef(index, paramName);
625
+ } else if (isColumnBuilder2(where.right) || isExpressionBuilder2(where.right)) {
626
+ rightExpr = where.right.toExpr();
627
+ if (rightExpr.kind === "col") {
628
+ const { table, column } = rightExpr;
629
+ const contractTable = contract.storage.tables[table];
630
+ if (!contractTable) {
631
+ errorUnknownTable(table);
632
+ }
633
+ const columnMeta = contractTable.columns[column];
634
+ if (!columnMeta) {
635
+ errorUnknownColumn(column, table);
636
+ }
637
+ }
638
+ paramName = "";
639
+ } else {
640
+ errorFailedToBuildWhereClause();
641
+ }
642
+ return {
643
+ expr: createBinaryExpr(where.op, leftExpr, rightExpr),
644
+ codecId,
645
+ paramName
646
+ };
647
+ }
648
+
649
+ // src/sql/mutation-builder.ts
650
+ var InsertBuilderImpl = class _InsertBuilderImpl {
651
+ contract;
652
+ context;
653
+ table;
654
+ values;
655
+ returningColumns = [];
656
+ constructor(options, table, values) {
657
+ this.context = options.context;
658
+ this.contract = options.context.contract;
659
+ this.table = table;
660
+ this.values = values;
661
+ }
662
+ returning(...columns) {
663
+ checkReturningCapability(this.contract);
664
+ const builder = new _InsertBuilderImpl(
665
+ {
666
+ context: this.context
667
+ },
668
+ this.table,
669
+ this.values
670
+ );
671
+ builder.returningColumns = [...this.returningColumns, ...columns];
672
+ return builder;
673
+ }
674
+ build(options) {
675
+ const paramsMap = options?.params ?? {};
676
+ const paramDescriptors = [];
677
+ const paramValues = [];
678
+ const paramCodecs = {};
679
+ const contractTable = this.contract.storage.tables[this.table.name];
680
+ if (!contractTable) {
681
+ errorUnknownTable(this.table.name);
682
+ }
683
+ const values = {};
684
+ for (const [columnName, placeholder] of Object.entries(this.values)) {
685
+ if (!contractTable.columns[columnName]) {
686
+ errorUnknownColumn(columnName, this.table.name);
687
+ }
688
+ const paramName = placeholder.name;
689
+ if (!Object.hasOwn(paramsMap, paramName)) {
690
+ errorMissingParameter(paramName);
691
+ }
692
+ const value = paramsMap[paramName];
693
+ const index = paramValues.push(value);
694
+ const columnMeta = contractTable.columns[columnName];
695
+ const codecId = columnMeta?.codecId;
696
+ if (paramName && codecId) {
697
+ paramCodecs[paramName] = codecId;
698
+ }
699
+ paramDescriptors.push({
700
+ name: paramName,
701
+ source: "dsl",
702
+ refs: { table: this.table.name, column: columnName },
703
+ ...codecId ? { codecId } : {},
704
+ ...columnMeta?.nativeType ? { nativeType: columnMeta.nativeType } : {},
705
+ ...columnMeta?.nullable !== void 0 ? { nullable: columnMeta.nullable } : {}
706
+ });
707
+ values[columnName] = createParamRef2(index, paramName);
708
+ }
709
+ const returning = this.returningColumns.map((col) => {
710
+ const c = col;
711
+ return createColumnRef(c.table, c.column);
712
+ });
713
+ const ast = createInsertAst({
714
+ table: createTableRef(this.table.name),
715
+ values,
716
+ returning
717
+ });
718
+ const returningProjection = {
719
+ aliases: this.returningColumns.map((col) => {
720
+ const c = col;
721
+ return c.column;
722
+ }),
723
+ columns: this.returningColumns
724
+ };
725
+ const planMeta = buildMeta({
726
+ contract: this.contract,
727
+ table: this.table,
728
+ projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
729
+ paramDescriptors,
730
+ ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {}
731
+ });
732
+ const queryPlan = Object.freeze({
733
+ ast,
734
+ params: paramValues,
735
+ meta: {
736
+ ...planMeta,
737
+ lane: "dsl",
738
+ annotations: {
739
+ ...planMeta.annotations,
740
+ intent: "write",
741
+ isMutation: true
742
+ }
743
+ }
744
+ });
745
+ return queryPlan;
746
+ }
747
+ };
748
+ var UpdateBuilderImpl = class _UpdateBuilderImpl {
749
+ contract;
750
+ context;
751
+ table;
752
+ set;
753
+ wherePredicate;
754
+ returningColumns = [];
755
+ constructor(options, table, set) {
756
+ this.context = options.context;
757
+ this.contract = options.context.contract;
758
+ this.table = table;
759
+ this.set = set;
760
+ }
761
+ where(predicate) {
762
+ const builder = new _UpdateBuilderImpl(
763
+ {
764
+ context: this.context
765
+ },
766
+ this.table,
767
+ this.set
768
+ );
769
+ builder.wherePredicate = predicate;
770
+ builder.returningColumns = [...this.returningColumns];
771
+ return builder;
772
+ }
773
+ returning(...columns) {
774
+ checkReturningCapability(this.contract);
775
+ const builder = new _UpdateBuilderImpl(
776
+ {
777
+ context: this.context
778
+ },
779
+ this.table,
780
+ this.set
781
+ );
782
+ if (this.wherePredicate) {
783
+ builder.wherePredicate = this.wherePredicate;
784
+ }
785
+ builder.returningColumns = [...this.returningColumns, ...columns];
786
+ return builder;
787
+ }
788
+ build(options) {
789
+ if (!this.wherePredicate) {
790
+ errorWhereMustBeCalledForUpdate();
791
+ }
792
+ const paramsMap = options?.params ?? {};
793
+ const paramDescriptors = [];
794
+ const paramValues = [];
795
+ const paramCodecs = {};
796
+ const contractTable = this.contract.storage.tables[this.table.name];
797
+ if (!contractTable) {
798
+ errorUnknownTable(this.table.name);
799
+ }
800
+ const set = {};
801
+ for (const [columnName, placeholder] of Object.entries(this.set)) {
802
+ if (!contractTable.columns[columnName]) {
803
+ errorUnknownColumn(columnName, this.table.name);
804
+ }
805
+ const paramName = placeholder.name;
806
+ if (!Object.hasOwn(paramsMap, paramName)) {
807
+ errorMissingParameter(paramName);
808
+ }
809
+ const value = paramsMap[paramName];
810
+ const index = paramValues.push(value);
811
+ const columnMeta = contractTable.columns[columnName];
812
+ const codecId = columnMeta?.codecId;
813
+ if (paramName && codecId) {
814
+ paramCodecs[paramName] = codecId;
815
+ }
816
+ paramDescriptors.push({
817
+ name: paramName,
818
+ source: "dsl",
819
+ refs: { table: this.table.name, column: columnName },
820
+ ...codecId ? { codecId } : {},
821
+ ...columnMeta?.nativeType ? { nativeType: columnMeta.nativeType } : {},
822
+ ...columnMeta?.nullable !== void 0 ? { nullable: columnMeta.nullable } : {}
823
+ });
824
+ set[columnName] = createParamRef2(index, paramName);
825
+ }
826
+ const whereResult = buildWhereExpr(
827
+ this.contract,
828
+ this.wherePredicate,
829
+ paramsMap,
830
+ paramDescriptors,
831
+ paramValues
832
+ );
833
+ const whereExpr = whereResult.expr;
834
+ if (!whereExpr) {
835
+ errorFailedToBuildWhereClause();
836
+ }
837
+ if (whereResult.codecId && whereResult.paramName) {
838
+ paramCodecs[whereResult.paramName] = whereResult.codecId;
839
+ }
840
+ const returning = this.returningColumns.map((col) => {
841
+ const c = col;
842
+ return createColumnRef(c.table, c.column);
843
+ });
844
+ const ast = createUpdateAst({
845
+ table: createTableRef(this.table.name),
846
+ set,
847
+ where: whereExpr,
848
+ returning
849
+ });
850
+ const returningProjection = {
851
+ aliases: this.returningColumns.map((col) => {
852
+ const c = col;
853
+ return c.column;
854
+ }),
855
+ columns: this.returningColumns
856
+ };
857
+ const planMeta = buildMeta({
858
+ contract: this.contract,
859
+ table: this.table,
860
+ projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
861
+ paramDescriptors,
862
+ ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {},
863
+ where: this.wherePredicate
864
+ });
865
+ const queryPlan = Object.freeze({
866
+ ast,
867
+ params: paramValues,
868
+ meta: {
869
+ ...planMeta,
870
+ lane: "dsl",
871
+ annotations: {
872
+ ...planMeta.annotations,
873
+ intent: "write",
874
+ isMutation: true,
875
+ hasWhere: true
876
+ }
877
+ }
878
+ });
879
+ return queryPlan;
880
+ }
881
+ };
882
+ var DeleteBuilderImpl = class _DeleteBuilderImpl {
883
+ contract;
884
+ context;
885
+ table;
886
+ wherePredicate;
887
+ returningColumns = [];
888
+ constructor(options, table) {
889
+ this.context = options.context;
890
+ this.contract = options.context.contract;
891
+ this.table = table;
892
+ }
893
+ where(predicate) {
894
+ const builder = new _DeleteBuilderImpl(
895
+ {
896
+ context: this.context
897
+ },
898
+ this.table
899
+ );
900
+ builder.wherePredicate = predicate;
901
+ builder.returningColumns = [...this.returningColumns];
902
+ return builder;
903
+ }
904
+ returning(...columns) {
905
+ checkReturningCapability(this.contract);
906
+ const builder = new _DeleteBuilderImpl(
907
+ {
908
+ context: this.context
909
+ },
910
+ this.table
911
+ );
912
+ if (this.wherePredicate) {
913
+ builder.wherePredicate = this.wherePredicate;
914
+ }
915
+ builder.returningColumns = [...this.returningColumns, ...columns];
916
+ return builder;
917
+ }
918
+ build(options) {
919
+ if (!this.wherePredicate) {
920
+ errorWhereMustBeCalledForDelete();
921
+ }
922
+ const paramsMap = options?.params ?? {};
923
+ const paramDescriptors = [];
924
+ const paramValues = [];
925
+ const paramCodecs = {};
926
+ const contractTable = this.contract.storage.tables[this.table.name];
927
+ if (!contractTable) {
928
+ errorUnknownTable(this.table.name);
929
+ }
930
+ const whereResult = buildWhereExpr(
931
+ this.contract,
932
+ this.wherePredicate,
933
+ paramsMap,
934
+ paramDescriptors,
935
+ paramValues
936
+ );
937
+ const whereExpr = whereResult.expr;
938
+ if (!whereExpr) {
939
+ errorFailedToBuildWhereClause();
940
+ }
941
+ if (whereResult.codecId && whereResult.paramName) {
942
+ paramCodecs[whereResult.paramName] = whereResult.codecId;
943
+ }
944
+ const returning = this.returningColumns.map((col) => {
945
+ const c = col;
946
+ return createColumnRef(c.table, c.column);
947
+ });
948
+ const ast = createDeleteAst({
949
+ table: createTableRef(this.table.name),
950
+ where: whereExpr,
951
+ returning
952
+ });
953
+ const returningProjection = {
954
+ aliases: this.returningColumns.map((col) => {
955
+ const c = col;
956
+ return c.column;
957
+ }),
958
+ columns: this.returningColumns
959
+ };
960
+ const planMeta = buildMeta({
961
+ contract: this.contract,
962
+ table: this.table,
963
+ projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
964
+ paramDescriptors,
965
+ ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {},
966
+ where: this.wherePredicate
967
+ });
968
+ const queryPlan = Object.freeze({
969
+ ast,
970
+ params: paramValues,
971
+ meta: {
972
+ ...planMeta,
973
+ lane: "dsl",
974
+ annotations: {
975
+ ...planMeta.annotations,
976
+ intent: "write",
977
+ isMutation: true,
978
+ hasWhere: true
979
+ }
980
+ }
981
+ });
982
+ return queryPlan;
983
+ }
984
+ };
985
+
986
+ // src/sql/select-builder.ts
987
+ import {
988
+ createJoinOnBuilder,
989
+ createOrderByItem as createOrderByItem2,
990
+ createSelectAst,
991
+ createTableRef as createTableRef4
992
+ } from "@prisma-next/sql-relational-core/ast";
993
+ import { isExpressionBuilder as isExpressionBuilder3 } from "@prisma-next/sql-relational-core/utils/guards";
994
+
995
+ // src/sql/include-builder.ts
996
+ import {
997
+ createColumnRef as createColumnRef2,
998
+ createJoinOnExpr,
999
+ createOrderByItem,
1000
+ createTableRef as createTableRef2
1001
+ } from "@prisma-next/sql-relational-core/ast";
1002
+ import {
1003
+ extractBaseColumnRef,
1004
+ isOperationExpr as isOperationExpr2
1005
+ } from "@prisma-next/sql-relational-core/utils/guards";
1006
+
1007
+ // src/sql/projection.ts
1008
+ import { isExpressionSource } from "@prisma-next/sql-relational-core/utils/guards";
1009
+ function generateAlias(path) {
1010
+ if (path.length === 0) {
1011
+ errorAliasPathEmpty();
1012
+ }
1013
+ return path.join("_");
1014
+ }
1015
+ var AliasTracker = class {
1016
+ aliases = /* @__PURE__ */ new Set();
1017
+ aliasToPath = /* @__PURE__ */ new Map();
1018
+ register(path) {
1019
+ const alias = generateAlias(path);
1020
+ if (this.aliases.has(alias)) {
1021
+ const existingPath = this.aliasToPath.get(alias);
1022
+ errorAliasCollision(path, alias, existingPath);
1023
+ }
1024
+ this.aliases.add(alias);
1025
+ this.aliasToPath.set(alias, path);
1026
+ return alias;
1027
+ }
1028
+ getPath(alias) {
1029
+ return this.aliasToPath.get(alias);
1030
+ }
1031
+ has(alias) {
1032
+ return this.aliases.has(alias);
1033
+ }
1034
+ };
1035
+ function flattenProjection(projection, tracker, currentPath = []) {
1036
+ const aliases = [];
1037
+ const columns = [];
1038
+ for (const [key, value] of Object.entries(projection)) {
1039
+ const path = [...currentPath, key];
1040
+ if (isExpressionSource(value)) {
1041
+ const alias = tracker.register(path);
1042
+ aliases.push(alias);
1043
+ columns.push(value);
1044
+ } else if (typeof value === "object" && value !== null) {
1045
+ const nested = flattenProjection(value, tracker, path);
1046
+ aliases.push(...nested.aliases);
1047
+ columns.push(...nested.columns);
1048
+ } else {
1049
+ errorInvalidProjectionValue(path);
1050
+ }
1051
+ }
1052
+ return { aliases, columns };
1053
+ }
1054
+ function buildProjectionState(_table, projection, includes) {
1055
+ const tracker = new AliasTracker();
1056
+ const aliases = [];
1057
+ const columns = [];
1058
+ for (const [key, value] of Object.entries(projection)) {
1059
+ if (value === true) {
1060
+ const matchingInclude = includes?.find((inc) => inc.alias === key);
1061
+ if (!matchingInclude) {
1062
+ errorIncludeAliasNotFound(key);
1063
+ }
1064
+ aliases.push(key);
1065
+ columns.push({
1066
+ kind: "column",
1067
+ table: matchingInclude.table.name,
1068
+ column: "",
1069
+ columnMeta: { nativeType: "jsonb", codecId: "core/json@1", nullable: true },
1070
+ toExpr: () => ({ kind: "col", table: matchingInclude.table.name, column: "" })
1071
+ });
1072
+ } else if (isExpressionSource(value)) {
1073
+ const alias = tracker.register([key]);
1074
+ aliases.push(alias);
1075
+ columns.push(value);
1076
+ } else if (typeof value === "object" && value !== null) {
1077
+ const nested = flattenProjection(value, tracker, [key]);
1078
+ aliases.push(...nested.aliases);
1079
+ columns.push(...nested.columns);
1080
+ } else {
1081
+ errorInvalidProjectionKey(key);
1082
+ }
1083
+ }
1084
+ if (aliases.length === 0) {
1085
+ errorProjectionEmpty();
1086
+ }
1087
+ return { aliases, columns };
1088
+ }
1089
+
1090
+ // src/sql/include-builder.ts
1091
+ var IncludeChildBuilderImpl = class _IncludeChildBuilderImpl {
1092
+ contract;
1093
+ codecTypes;
1094
+ table;
1095
+ childProjection;
1096
+ childWhere;
1097
+ childOrderBy;
1098
+ childLimit;
1099
+ constructor(contract, codecTypes, table) {
1100
+ this.contract = contract;
1101
+ this.codecTypes = codecTypes;
1102
+ this.table = table;
1103
+ }
1104
+ select(projection) {
1105
+ const projectionState = buildProjectionState(this.table, projection);
1106
+ const builder = new _IncludeChildBuilderImpl(this.contract, this.codecTypes, this.table);
1107
+ builder.childProjection = projectionState;
1108
+ if (this.childWhere !== void 0) {
1109
+ builder.childWhere = this.childWhere;
1110
+ }
1111
+ if (this.childOrderBy !== void 0) {
1112
+ builder.childOrderBy = this.childOrderBy;
1113
+ }
1114
+ if (this.childLimit !== void 0) {
1115
+ builder.childLimit = this.childLimit;
1116
+ }
1117
+ return builder;
1118
+ }
1119
+ where(expr) {
1120
+ const builder = new _IncludeChildBuilderImpl(
1121
+ this.contract,
1122
+ this.codecTypes,
1123
+ this.table
1124
+ );
1125
+ if (this.childProjection !== void 0) {
1126
+ builder.childProjection = this.childProjection;
1127
+ }
1128
+ builder.childWhere = expr;
1129
+ if (this.childOrderBy !== void 0) {
1130
+ builder.childOrderBy = this.childOrderBy;
1131
+ }
1132
+ if (this.childLimit !== void 0) {
1133
+ builder.childLimit = this.childLimit;
1134
+ }
1135
+ return builder;
1136
+ }
1137
+ orderBy(order) {
1138
+ const builder = new _IncludeChildBuilderImpl(
1139
+ this.contract,
1140
+ this.codecTypes,
1141
+ this.table
1142
+ );
1143
+ if (this.childProjection !== void 0) {
1144
+ builder.childProjection = this.childProjection;
1145
+ }
1146
+ if (this.childWhere !== void 0) {
1147
+ builder.childWhere = this.childWhere;
1148
+ }
1149
+ builder.childOrderBy = order;
1150
+ if (this.childLimit !== void 0) {
1151
+ builder.childLimit = this.childLimit;
1152
+ }
1153
+ return builder;
1154
+ }
1155
+ limit(count) {
1156
+ if (!Number.isInteger(count) || count < 0) {
1157
+ errorLimitMustBeNonNegativeInteger();
1158
+ }
1159
+ const builder = new _IncludeChildBuilderImpl(
1160
+ this.contract,
1161
+ this.codecTypes,
1162
+ this.table
1163
+ );
1164
+ if (this.childProjection !== void 0) {
1165
+ builder.childProjection = this.childProjection;
1166
+ }
1167
+ if (this.childWhere !== void 0) {
1168
+ builder.childWhere = this.childWhere;
1169
+ }
1170
+ if (this.childOrderBy !== void 0) {
1171
+ builder.childOrderBy = this.childOrderBy;
1172
+ }
1173
+ builder.childLimit = count;
1174
+ return builder;
1175
+ }
1176
+ getState() {
1177
+ if (!this.childProjection) {
1178
+ errorChildProjectionMustBeSpecified();
1179
+ }
1180
+ const state = {
1181
+ childProjection: this.childProjection
1182
+ };
1183
+ if (this.childWhere !== void 0) {
1184
+ state.childWhere = this.childWhere;
1185
+ }
1186
+ if (this.childOrderBy !== void 0) {
1187
+ state.childOrderBy = this.childOrderBy;
1188
+ }
1189
+ if (this.childLimit !== void 0) {
1190
+ state.childLimit = this.childLimit;
1191
+ }
1192
+ return state;
1193
+ }
1194
+ };
1195
+ function buildIncludeAst(include, contract, paramsMap, paramDescriptors, paramValues) {
1196
+ const childOrderBy = include.childOrderBy ? (() => {
1197
+ const orderBy = include.childOrderBy;
1198
+ const orderExpr = orderBy.expr;
1199
+ const expr = (() => {
1200
+ if (isOperationExpr2(orderExpr)) {
1201
+ const baseCol = extractBaseColumnRef(orderExpr);
1202
+ return createColumnRef2(baseCol.table, baseCol.column);
1203
+ }
1204
+ const colBuilder = orderExpr;
1205
+ return createColumnRef2(colBuilder.table, colBuilder.column);
1206
+ })();
1207
+ return [createOrderByItem(expr, orderBy.dir)];
1208
+ })() : void 0;
1209
+ let childWhere;
1210
+ if (include.childWhere) {
1211
+ const whereResult = buildWhereExpr(
1212
+ contract,
1213
+ include.childWhere,
1214
+ paramsMap,
1215
+ paramDescriptors,
1216
+ paramValues
1217
+ );
1218
+ childWhere = whereResult.expr;
1219
+ }
1220
+ const onLeft = include.on.left;
1221
+ const onRight = include.on.right;
1222
+ const leftCol = createColumnRef2(onLeft.table, onLeft.column);
1223
+ const rightCol = createColumnRef2(onRight.table, onRight.column);
1224
+ const onExpr = createJoinOnExpr(leftCol, rightCol);
1225
+ return {
1226
+ kind: "includeMany",
1227
+ alias: include.alias,
1228
+ child: {
1229
+ table: createTableRef2(include.table.name),
1230
+ on: onExpr,
1231
+ ...childWhere ? { where: childWhere } : {},
1232
+ ...childOrderBy ? { orderBy: childOrderBy } : {},
1233
+ ...typeof include.childLimit === "number" ? { limit: include.childLimit } : {},
1234
+ project: include.childProjection.aliases.map((alias, idx) => {
1235
+ const column = include.childProjection.columns[idx];
1236
+ if (!column || !alias) {
1237
+ errorMissingColumnForAlias(alias ?? "unknown", idx);
1238
+ }
1239
+ return {
1240
+ alias,
1241
+ expr: column.toExpr()
1242
+ };
1243
+ })
1244
+ }
1245
+ };
1246
+ }
1247
+
1248
+ // src/sql/join-builder.ts
1249
+ import {
1250
+ createColumnRef as createColumnRef3,
1251
+ createJoin,
1252
+ createJoinOnExpr as createJoinOnExpr2,
1253
+ createTableRef as createTableRef3
1254
+ } from "@prisma-next/sql-relational-core/ast";
1255
+ function buildJoinAst(join) {
1256
+ const onLeft = join.on.left;
1257
+ const onRight = join.on.right;
1258
+ const leftCol = createColumnRef3(onLeft.table, onLeft.column);
1259
+ const rightCol = createColumnRef3(onRight.table, onRight.column);
1260
+ const onExpr = createJoinOnExpr2(leftCol, rightCol);
1261
+ return createJoin(join.joinType, createTableRef3(join.table.name), onExpr);
1262
+ }
1263
+
1264
+ // src/sql/select-builder.ts
1265
+ var SelectBuilderImpl = class _SelectBuilderImpl {
1266
+ contract;
1267
+ codecTypes;
1268
+ context;
1269
+ state = {};
1270
+ constructor(options, state) {
1271
+ this.context = options.context;
1272
+ this.contract = options.context.contract;
1273
+ this.codecTypes = options.context.contract.mappings.codecTypes;
1274
+ if (state) {
1275
+ this.state = state;
1276
+ }
1277
+ }
1278
+ from(table) {
1279
+ return new _SelectBuilderImpl(
1280
+ {
1281
+ context: this.context
1282
+ },
1283
+ { ...this.state, from: table }
1284
+ );
1285
+ }
1286
+ innerJoin(table, on) {
1287
+ return this._addJoin("inner", table, on);
1288
+ }
1289
+ leftJoin(table, on) {
1290
+ return this._addJoin("left", table, on);
1291
+ }
1292
+ rightJoin(table, on) {
1293
+ return this._addJoin("right", table, on);
1294
+ }
1295
+ fullJoin(table, on) {
1296
+ return this._addJoin("full", table, on);
1297
+ }
1298
+ includeMany(childTable, on, childBuilder, options) {
1299
+ checkIncludeCapabilities(this.contract);
1300
+ if (!this.contract.storage.tables[childTable.name]) {
1301
+ errorUnknownTable(childTable.name);
1302
+ }
1303
+ const joinOnBuilder = createJoinOnBuilder();
1304
+ const onPredicate = on(joinOnBuilder);
1305
+ const onLeft = onPredicate.left;
1306
+ const onRight = onPredicate.right;
1307
+ if (onLeft.table === onRight.table) {
1308
+ errorSelfJoinNotSupported();
1309
+ }
1310
+ const childBuilderImpl = new IncludeChildBuilderImpl(
1311
+ this.contract,
1312
+ this.codecTypes,
1313
+ childTable
1314
+ );
1315
+ const builtChild = childBuilder(
1316
+ childBuilderImpl
1317
+ );
1318
+ const childState = builtChild.getState();
1319
+ if (childState.childProjection.aliases.length === 0) {
1320
+ errorChildProjectionEmpty();
1321
+ }
1322
+ const alias = options?.alias ?? childTable.name;
1323
+ if (this.state.projection) {
1324
+ if (this.state.projection.aliases.includes(alias)) {
1325
+ errorIncludeAliasCollision(alias, "projection");
1326
+ }
1327
+ }
1328
+ const existingIncludes = this.state.includes ?? [];
1329
+ if (existingIncludes.some((inc) => inc.alias === alias)) {
1330
+ errorIncludeAliasCollision(alias, "include");
1331
+ }
1332
+ const includeState = {
1333
+ alias,
1334
+ table: childTable,
1335
+ on: onPredicate,
1336
+ childProjection: childState.childProjection,
1337
+ ...childState.childWhere !== void 0 ? { childWhere: childState.childWhere } : {},
1338
+ ...childState.childOrderBy !== void 0 ? { childOrderBy: childState.childOrderBy } : {},
1339
+ ...childState.childLimit !== void 0 ? { childLimit: childState.childLimit } : {}
1340
+ };
1341
+ const newIncludes = [...existingIncludes, includeState];
1342
+ return new _SelectBuilderImpl(
1343
+ {
1344
+ context: this.context
1345
+ },
1346
+ { ...this.state, includes: newIncludes }
1347
+ );
1348
+ }
1349
+ _addJoin(joinType, table, on) {
1350
+ const fromTable = this.ensureFrom();
1351
+ if (!this.contract.storage.tables[table.name]) {
1352
+ errorUnknownTable(table.name);
1353
+ }
1354
+ if (table.name === fromTable.name) {
1355
+ errorSelfJoinNotSupported();
1356
+ }
1357
+ const joinOnBuilder = createJoinOnBuilder();
1358
+ const onPredicate = on(joinOnBuilder);
1359
+ const joinState = {
1360
+ joinType,
1361
+ table,
1362
+ on: onPredicate
1363
+ };
1364
+ const existingJoins = this.state.joins ?? [];
1365
+ const newJoins = [...existingJoins, joinState];
1366
+ return new _SelectBuilderImpl(
1367
+ {
1368
+ context: this.context
1369
+ },
1370
+ { ...this.state, joins: newJoins }
1371
+ );
1372
+ }
1373
+ where(expr) {
1374
+ return new _SelectBuilderImpl(
1375
+ {
1376
+ context: this.context
1377
+ },
1378
+ { ...this.state, where: expr }
1379
+ );
1380
+ }
1381
+ select(projection) {
1382
+ const table = this.ensureFrom();
1383
+ const projectionState = buildProjectionState(table, projection, this.state.includes);
1384
+ return new _SelectBuilderImpl(
1385
+ {
1386
+ context: this.context
1387
+ },
1388
+ { ...this.state, projection: projectionState }
1389
+ );
1390
+ }
1391
+ orderBy(order) {
1392
+ return new _SelectBuilderImpl(
1393
+ {
1394
+ context: this.context
1395
+ },
1396
+ { ...this.state, orderBy: order }
1397
+ );
1398
+ }
1399
+ limit(count) {
1400
+ if (!Number.isInteger(count) || count < 0) {
1401
+ errorLimitMustBeNonNegativeInteger();
1402
+ }
1403
+ return new _SelectBuilderImpl(
1404
+ {
1405
+ context: this.context
1406
+ },
1407
+ { ...this.state, limit: count }
1408
+ );
1409
+ }
1410
+ build(options) {
1411
+ const table = this.ensureFrom();
1412
+ const projection = this.ensureProjection();
1413
+ const paramsMap = options?.params ?? {};
1414
+ const contractTable = this.contract.storage.tables[table.name];
1415
+ if (!contractTable) {
1416
+ errorUnknownTable(table.name);
1417
+ }
1418
+ const paramDescriptors = [];
1419
+ const paramValues = [];
1420
+ const paramCodecs = {};
1421
+ const whereResult = this.state.where ? buildWhereExpr(this.contract, this.state.where, paramsMap, paramDescriptors, paramValues) : void 0;
1422
+ const whereExpr = whereResult?.expr;
1423
+ if (whereResult?.codecId && whereResult.paramName) {
1424
+ paramCodecs[whereResult.paramName] = whereResult.codecId;
1425
+ }
1426
+ const orderByClause = this.state.orderBy ? (() => {
1427
+ const orderBy = this.state.orderBy;
1428
+ return [createOrderByItem2(orderBy.expr, orderBy.dir)];
1429
+ })() : void 0;
1430
+ const joins = this.state.joins?.map((join) => buildJoinAst(join));
1431
+ const includes = this.state.includes?.map(
1432
+ (include) => buildIncludeAst(include, this.contract, paramsMap, paramDescriptors, paramValues)
1433
+ );
1434
+ const projectEntries = [];
1435
+ for (let i = 0; i < projection.aliases.length; i++) {
1436
+ const alias = projection.aliases[i];
1437
+ if (!alias) {
1438
+ errorMissingAlias(i);
1439
+ }
1440
+ const column = projection.columns[i];
1441
+ const matchingInclude = this.state.includes?.find((inc) => inc.alias === alias);
1442
+ if (matchingInclude) {
1443
+ projectEntries.push({
1444
+ alias,
1445
+ expr: { kind: "includeRef", alias }
1446
+ });
1447
+ } else if (column && isExpressionBuilder3(column)) {
1448
+ projectEntries.push({
1449
+ alias,
1450
+ expr: column.expr
1451
+ });
1452
+ } else if (column) {
1453
+ const columnRef = column.toExpr();
1454
+ projectEntries.push({
1455
+ alias,
1456
+ expr: columnRef
1457
+ });
1458
+ }
1459
+ }
1460
+ const ast = createSelectAst({
1461
+ from: createTableRef4(table.name),
1462
+ joins,
1463
+ includes,
1464
+ project: projectEntries,
1465
+ where: whereExpr,
1466
+ orderBy: orderByClause,
1467
+ limit: this.state.limit
1468
+ });
1469
+ const planMeta = buildMeta({
1470
+ contract: this.contract,
1471
+ table,
1472
+ projection,
1473
+ joins: this.state.joins,
1474
+ includes: this.state.includes,
1475
+ paramDescriptors,
1476
+ paramCodecs,
1477
+ where: this.state.where,
1478
+ orderBy: this.state.orderBy
1479
+ });
1480
+ const queryPlan = Object.freeze({
1481
+ ast,
1482
+ params: paramValues,
1483
+ meta: planMeta
1484
+ });
1485
+ return queryPlan;
1486
+ }
1487
+ ensureFrom() {
1488
+ if (!this.state.from) {
1489
+ errorFromMustBeCalled();
1490
+ }
1491
+ return this.state.from;
1492
+ }
1493
+ ensureProjection() {
1494
+ if (!this.state.projection) {
1495
+ errorSelectMustBeCalled();
1496
+ }
1497
+ return this.state.projection;
1498
+ }
1499
+ };
1500
+
1501
+ // src/sql/builder.ts
1502
+ function sql(options) {
1503
+ const builder = new SelectBuilderImpl(
1504
+ options
1505
+ );
1506
+ const rawFactory = createRawFactory(options.context.contract);
1507
+ Object.defineProperty(builder, "raw", {
1508
+ value: rawFactory,
1509
+ enumerable: true,
1510
+ configurable: false
1511
+ });
1512
+ Object.defineProperty(builder, "insert", {
1513
+ value: (table, values) => {
1514
+ return new InsertBuilderImpl(options, table, values);
1515
+ },
1516
+ enumerable: true,
1517
+ configurable: false
1518
+ });
1519
+ Object.defineProperty(builder, "update", {
1520
+ value: (table, set) => {
1521
+ return new UpdateBuilderImpl(options, table, set);
1522
+ },
1523
+ enumerable: true,
1524
+ configurable: false
1525
+ });
1526
+ Object.defineProperty(builder, "delete", {
1527
+ value: (table) => {
1528
+ return new DeleteBuilderImpl(options, table);
1529
+ },
1530
+ enumerable: true,
1531
+ configurable: false
1532
+ });
1533
+ return builder;
1534
+ }
1535
+
1536
+ export {
1537
+ rawOptions,
1538
+ createJoinOnBuilder2 as createJoinOnBuilder,
1539
+ sql
1540
+ };
1541
+ //# sourceMappingURL=chunk-72PNERR5.js.map