@prisma-next/sql-lane 0.3.0-pr.93.4 → 0.3.0-pr.94.1

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 (59) hide show
  1. package/dist/builder-C87NiJaP.mjs +1175 -0
  2. package/dist/builder-C87NiJaP.mjs.map +1 -0
  3. package/dist/builder-C8ExdG4j.d.mts +121 -0
  4. package/dist/builder-C8ExdG4j.d.mts.map +1 -0
  5. package/dist/exports/sql.d.mts +3 -0
  6. package/dist/exports/sql.mjs +3 -0
  7. package/dist/index.d.mts +3 -0
  8. package/dist/index.mjs +3 -0
  9. package/package.json +20 -18
  10. package/src/sql/include-builder.ts +1 -1
  11. package/src/sql/plan.ts +102 -101
  12. package/src/sql/predicate-builder.ts +41 -44
  13. package/src/sql/projection.ts +15 -10
  14. package/src/sql/select-builder.ts +16 -35
  15. package/src/types/internal.ts +2 -2
  16. package/src/utils/errors.ts +1 -1
  17. package/src/utils/state.ts +2 -4
  18. package/dist/chunk-AWSKRSFP.js +0 -1569
  19. package/dist/chunk-AWSKRSFP.js.map +0 -1
  20. package/dist/exports/sql.d.ts +0 -5
  21. package/dist/exports/sql.d.ts.map +0 -1
  22. package/dist/exports/sql.js +0 -11
  23. package/dist/exports/sql.js.map +0 -1
  24. package/dist/index.d.ts +0 -5
  25. package/dist/index.d.ts.map +0 -1
  26. package/dist/index.js +0 -11
  27. package/dist/index.js.map +0 -1
  28. package/dist/raw.d.ts +0 -11
  29. package/dist/raw.d.ts.map +0 -1
  30. package/dist/sql/builder.d.ts +0 -11
  31. package/dist/sql/builder.d.ts.map +0 -1
  32. package/dist/sql/context.d.ts +0 -5
  33. package/dist/sql/context.d.ts.map +0 -1
  34. package/dist/sql/include-builder.d.ts +0 -35
  35. package/dist/sql/include-builder.d.ts.map +0 -1
  36. package/dist/sql/join-builder.d.ts +0 -4
  37. package/dist/sql/join-builder.d.ts.map +0 -1
  38. package/dist/sql/mutation-builder.d.ts +0 -64
  39. package/dist/sql/mutation-builder.d.ts.map +0 -1
  40. package/dist/sql/plan.d.ts +0 -4
  41. package/dist/sql/plan.d.ts.map +0 -1
  42. package/dist/sql/predicate-builder.d.ts +0 -11
  43. package/dist/sql/predicate-builder.d.ts.map +0 -1
  44. package/dist/sql/projection.d.ts +0 -18
  45. package/dist/sql/projection.d.ts.map +0 -1
  46. package/dist/sql/select-builder.d.ts +0 -35
  47. package/dist/sql/select-builder.d.ts.map +0 -1
  48. package/dist/types/internal.d.ts +0 -35
  49. package/dist/types/internal.d.ts.map +0 -1
  50. package/dist/types/public.d.ts +0 -18
  51. package/dist/types/public.d.ts.map +0 -1
  52. package/dist/utils/assertions.d.ts +0 -28
  53. package/dist/utils/assertions.d.ts.map +0 -1
  54. package/dist/utils/capabilities.d.ts +0 -4
  55. package/dist/utils/capabilities.d.ts.map +0 -1
  56. package/dist/utils/errors.d.ts +0 -30
  57. package/dist/utils/errors.d.ts.map +0 -1
  58. package/dist/utils/state.d.ts +0 -30
  59. package/dist/utils/state.d.ts.map +0 -1
@@ -1,1569 +0,0 @@
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 as createColumnRef2,
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 ColumnBuilder 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
- getColumnInfo,
341
- getOperationExpr,
342
- isColumnBuilder,
343
- isOperationExpr
344
- } from "@prisma-next/sql-relational-core/utils/guards";
345
-
346
- // src/utils/assertions.ts
347
- import { planInvalid as planInvalid3 } from "@prisma-next/plan";
348
- function assertColumnBuilder(col, context) {
349
- if (typeof col === "object" && col !== null && "table" in col && "column" in col && typeof col.table === "string" && typeof col.column === "string") {
350
- return col;
351
- }
352
- throw planInvalid3(`ColumnBuilder missing table/column in ${context}`);
353
- }
354
-
355
- // src/sql/plan.ts
356
- function buildMeta(args) {
357
- const refsColumns = /* @__PURE__ */ new Map();
358
- const refsTables = /* @__PURE__ */ new Set([args.table.name]);
359
- for (const column of args.projection.columns) {
360
- if (!column) {
361
- continue;
362
- }
363
- const operationExpr = getOperationExpr(column);
364
- if (operationExpr) {
365
- const allRefs = collectColumnRefs(operationExpr);
366
- for (const ref of allRefs) {
367
- refsColumns.set(`${ref.table}.${ref.column}`, {
368
- table: ref.table,
369
- column: ref.column
370
- });
371
- }
372
- } else {
373
- refsColumns.set(`${column.table}.${column.column}`, {
374
- table: column.table,
375
- column: column.column
376
- });
377
- }
378
- }
379
- if (args.joins) {
380
- for (const join of args.joins) {
381
- refsTables.add(join.table.name);
382
- const onLeft = assertColumnBuilder(join.on.left, "join ON left");
383
- const onRight = assertColumnBuilder(join.on.right, "join ON right");
384
- refsColumns.set(`${onLeft.table}.${onLeft.column}`, {
385
- table: onLeft.table,
386
- column: onLeft.column
387
- });
388
- refsColumns.set(`${onRight.table}.${onRight.column}`, {
389
- table: onRight.table,
390
- column: onRight.column
391
- });
392
- }
393
- }
394
- if (args.includes) {
395
- for (const include of args.includes) {
396
- refsTables.add(include.table.name);
397
- const leftCol = assertColumnBuilder(include.on.left, "include ON left");
398
- const rightCol = assertColumnBuilder(include.on.right, "include ON right");
399
- refsColumns.set(`${leftCol.table}.${leftCol.column}`, {
400
- table: leftCol.table,
401
- column: leftCol.column
402
- });
403
- refsColumns.set(`${rightCol.table}.${rightCol.column}`, {
404
- table: rightCol.table,
405
- column: rightCol.column
406
- });
407
- for (const column of include.childProjection.columns) {
408
- const col = assertColumnBuilder(column, "include child projection column");
409
- refsColumns.set(`${col.table}.${col.column}`, {
410
- table: col.table,
411
- column: col.column
412
- });
413
- }
414
- if (include.childWhere) {
415
- const colInfo = getColumnInfo(include.childWhere.left);
416
- refsColumns.set(`${colInfo.table}.${colInfo.column}`, {
417
- table: colInfo.table,
418
- column: colInfo.column
419
- });
420
- const childWhereRight = include.childWhere.right;
421
- if (isColumnBuilder(childWhereRight)) {
422
- const rightColInfo = getColumnInfo(childWhereRight);
423
- refsColumns.set(`${rightColInfo.table}.${rightColInfo.column}`, {
424
- table: rightColInfo.table,
425
- column: rightColInfo.column
426
- });
427
- }
428
- }
429
- if (include.childOrderBy) {
430
- const orderBy = include.childOrderBy;
431
- if (orderBy.expr) {
432
- const colInfo = getColumnInfo(orderBy.expr);
433
- refsColumns.set(`${colInfo.table}.${colInfo.column}`, {
434
- table: colInfo.table,
435
- column: colInfo.column
436
- });
437
- }
438
- }
439
- }
440
- }
441
- if (args.where) {
442
- const whereLeft = args.where.left;
443
- if (isOperationExpr(whereLeft)) {
444
- const allRefs = collectColumnRefs(whereLeft);
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
- const operationExpr = whereLeft._operationExpr;
453
- if (operationExpr) {
454
- const allRefs = collectColumnRefs(operationExpr);
455
- for (const ref of allRefs) {
456
- refsColumns.set(`${ref.table}.${ref.column}`, {
457
- table: ref.table,
458
- column: ref.column
459
- });
460
- }
461
- } else {
462
- const colBuilder = assertColumnBuilder(whereLeft, "where clause must be a ColumnBuilder");
463
- refsColumns.set(`${colBuilder.table}.${colBuilder.column}`, {
464
- table: colBuilder.table,
465
- column: colBuilder.column
466
- });
467
- }
468
- }
469
- const whereRight = args.where.right;
470
- if (isColumnBuilder(whereRight)) {
471
- const colInfo = getColumnInfo(whereRight);
472
- refsColumns.set(`${colInfo.table}.${colInfo.column}`, {
473
- table: colInfo.table,
474
- column: colInfo.column
475
- });
476
- }
477
- }
478
- if (args.orderBy) {
479
- const orderBy = args.orderBy;
480
- const orderByExpr = orderBy.expr;
481
- if (orderByExpr) {
482
- if (isOperationExpr(orderByExpr)) {
483
- const allRefs = collectColumnRefs(orderByExpr);
484
- for (const ref of allRefs) {
485
- refsColumns.set(`${ref.table}.${ref.column}`, {
486
- table: ref.table,
487
- column: ref.column
488
- });
489
- }
490
- } else {
491
- refsColumns.set(`${orderByExpr.table}.${orderByExpr.column}`, {
492
- table: orderByExpr.table,
493
- column: orderByExpr.column
494
- });
495
- }
496
- }
497
- }
498
- const includeAliases = new Set(args.includes?.map((inc) => inc.alias) ?? []);
499
- const projectionMap = Object.fromEntries(
500
- args.projection.aliases.map((alias, index) => {
501
- if (includeAliases.has(alias)) {
502
- return [alias, `include:${alias}`];
503
- }
504
- const column = args.projection.columns[index];
505
- if (!column) {
506
- errorMissingColumnForAlias(alias, index);
507
- }
508
- const operationExpr = getOperationExpr(column);
509
- if (operationExpr) {
510
- return [alias, `operation:${operationExpr.method}`];
511
- }
512
- return [alias, `${column.table}.${column.column}`];
513
- })
514
- );
515
- const projectionTypes = {};
516
- for (let i = 0; i < args.projection.aliases.length; i++) {
517
- const alias = args.projection.aliases[i];
518
- if (!alias || includeAliases.has(alias)) {
519
- continue;
520
- }
521
- const column = args.projection.columns[i];
522
- if (!column) {
523
- continue;
524
- }
525
- const operationExpr = column._operationExpr;
526
- if (operationExpr) {
527
- if (operationExpr.returns.kind === "typeId") {
528
- projectionTypes[alias] = operationExpr.returns.type;
529
- } else if (operationExpr.returns.kind === "builtin") {
530
- projectionTypes[alias] = operationExpr.returns.type;
531
- }
532
- } else {
533
- const col = column;
534
- const columnMeta = col.columnMeta;
535
- const codecId = columnMeta?.codecId;
536
- if (codecId) {
537
- projectionTypes[alias] = codecId;
538
- }
539
- }
540
- }
541
- const projectionCodecs = {};
542
- for (let i = 0; i < args.projection.aliases.length; i++) {
543
- const alias = args.projection.aliases[i];
544
- if (!alias || includeAliases.has(alias)) {
545
- continue;
546
- }
547
- const column = args.projection.columns[i];
548
- if (!column) {
549
- continue;
550
- }
551
- const operationExpr = column._operationExpr;
552
- if (operationExpr) {
553
- if (operationExpr.returns.kind === "typeId") {
554
- projectionCodecs[alias] = operationExpr.returns.type;
555
- }
556
- } else {
557
- const col = column;
558
- const columnMeta = col.columnMeta;
559
- const codecId = columnMeta?.codecId;
560
- if (codecId) {
561
- projectionCodecs[alias] = codecId;
562
- }
563
- }
564
- }
565
- const allCodecs = {
566
- ...projectionCodecs,
567
- ...args.paramCodecs ? args.paramCodecs : {}
568
- };
569
- return Object.freeze(
570
- compact({
571
- target: args.contract.target,
572
- targetFamily: args.contract.targetFamily,
573
- coreHash: args.contract.coreHash,
574
- lane: "dsl",
575
- refs: {
576
- tables: Array.from(refsTables),
577
- columns: Array.from(refsColumns.values())
578
- },
579
- projection: projectionMap,
580
- projectionTypes: Object.keys(projectionTypes).length > 0 ? projectionTypes : void 0,
581
- annotations: Object.keys(allCodecs).length > 0 ? Object.freeze({ codecs: Object.freeze(allCodecs) }) : void 0,
582
- paramDescriptors: args.paramDescriptors,
583
- profileHash: args.contract.profileHash
584
- })
585
- );
586
- }
587
-
588
- // src/sql/predicate-builder.ts
589
- import {
590
- createBinaryExpr,
591
- createColumnRef,
592
- createParamRef
593
- } from "@prisma-next/sql-relational-core/ast";
594
- import {
595
- getColumnInfo as getColumnInfo2,
596
- getOperationExpr as getOperationExpr2,
597
- isColumnBuilder as isColumnBuilder2,
598
- isParamPlaceholder
599
- } from "@prisma-next/sql-relational-core/utils/guards";
600
- function buildWhereExpr(contract, where, paramsMap, descriptors, values) {
601
- let leftExpr;
602
- let codecId;
603
- let rightExpr;
604
- let paramName;
605
- const operationExpr = getOperationExpr2(where.left);
606
- if (operationExpr) {
607
- leftExpr = operationExpr;
608
- } else if (isColumnBuilder2(where.left)) {
609
- const { table, column } = getColumnInfo2(where.left);
610
- const contractTable = contract.storage.tables[table];
611
- if (!contractTable) {
612
- errorUnknownTable(table);
613
- }
614
- const columnMeta = contractTable.columns[column];
615
- if (!columnMeta) {
616
- errorUnknownColumn(column, table);
617
- }
618
- codecId = columnMeta.codecId;
619
- leftExpr = createColumnRef(table, column);
620
- } else {
621
- errorFailedToBuildWhereClause();
622
- }
623
- if (isParamPlaceholder(where.right)) {
624
- const placeholder = where.right;
625
- paramName = placeholder.name;
626
- if (!Object.hasOwn(paramsMap, paramName)) {
627
- errorMissingParameter(paramName);
628
- }
629
- const value = paramsMap[paramName];
630
- const index = values.push(value);
631
- if (isColumnBuilder2(where.left)) {
632
- const { table, column } = getColumnInfo2(where.left);
633
- const contractTable = contract.storage.tables[table];
634
- const columnMeta = contractTable?.columns[column];
635
- if (columnMeta) {
636
- descriptors.push({
637
- name: paramName,
638
- source: "dsl",
639
- refs: { table, column },
640
- nullable: columnMeta.nullable,
641
- codecId: columnMeta.codecId,
642
- nativeType: columnMeta.nativeType
643
- });
644
- }
645
- }
646
- rightExpr = createParamRef(index, paramName);
647
- } else if (isColumnBuilder2(where.right)) {
648
- const { table, column } = getColumnInfo2(where.right);
649
- const contractTable = contract.storage.tables[table];
650
- if (!contractTable) {
651
- errorUnknownTable(table);
652
- }
653
- const columnMeta = contractTable.columns[column];
654
- if (!columnMeta) {
655
- errorUnknownColumn(column, table);
656
- }
657
- rightExpr = createColumnRef(table, column);
658
- paramName = "";
659
- } else {
660
- errorFailedToBuildWhereClause();
661
- }
662
- return {
663
- expr: createBinaryExpr(where.op, leftExpr, rightExpr),
664
- codecId,
665
- paramName
666
- };
667
- }
668
-
669
- // src/sql/mutation-builder.ts
670
- var InsertBuilderImpl = class _InsertBuilderImpl {
671
- contract;
672
- context;
673
- table;
674
- values;
675
- returningColumns = [];
676
- constructor(options, table, values) {
677
- this.context = options.context;
678
- this.contract = options.context.contract;
679
- this.table = table;
680
- this.values = values;
681
- }
682
- returning(...columns) {
683
- checkReturningCapability(this.contract);
684
- const builder = new _InsertBuilderImpl(
685
- {
686
- context: this.context
687
- },
688
- this.table,
689
- this.values
690
- );
691
- builder.returningColumns = [...this.returningColumns, ...columns];
692
- return builder;
693
- }
694
- build(options) {
695
- const paramsMap = options?.params ?? {};
696
- const paramDescriptors = [];
697
- const paramValues = [];
698
- const paramCodecs = {};
699
- const contractTable = this.contract.storage.tables[this.table.name];
700
- if (!contractTable) {
701
- errorUnknownTable(this.table.name);
702
- }
703
- const values = {};
704
- for (const [columnName, placeholder] of Object.entries(this.values)) {
705
- if (!contractTable.columns[columnName]) {
706
- errorUnknownColumn(columnName, this.table.name);
707
- }
708
- const paramName = placeholder.name;
709
- if (!Object.hasOwn(paramsMap, paramName)) {
710
- errorMissingParameter(paramName);
711
- }
712
- const value = paramsMap[paramName];
713
- const index = paramValues.push(value);
714
- const columnMeta = contractTable.columns[columnName];
715
- const codecId = columnMeta?.codecId;
716
- if (paramName && codecId) {
717
- paramCodecs[paramName] = codecId;
718
- }
719
- paramDescriptors.push({
720
- name: paramName,
721
- source: "dsl",
722
- refs: { table: this.table.name, column: columnName },
723
- ...codecId ? { codecId } : {},
724
- ...columnMeta?.nativeType ? { nativeType: columnMeta.nativeType } : {},
725
- ...columnMeta?.nullable !== void 0 ? { nullable: columnMeta.nullable } : {}
726
- });
727
- values[columnName] = createParamRef2(index, paramName);
728
- }
729
- const returning = this.returningColumns.map((col) => {
730
- const c = col;
731
- return createColumnRef2(c.table, c.column);
732
- });
733
- const ast = createInsertAst({
734
- table: createTableRef(this.table.name),
735
- values,
736
- returning
737
- });
738
- const returningProjection = {
739
- aliases: this.returningColumns.map((col) => {
740
- const c = col;
741
- return c.column;
742
- }),
743
- columns: this.returningColumns
744
- };
745
- const planMeta = buildMeta({
746
- contract: this.contract,
747
- table: this.table,
748
- projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
749
- paramDescriptors,
750
- ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {}
751
- });
752
- const queryPlan = Object.freeze({
753
- ast,
754
- params: paramValues,
755
- meta: {
756
- ...planMeta,
757
- lane: "dsl",
758
- annotations: {
759
- ...planMeta.annotations,
760
- intent: "write",
761
- isMutation: true
762
- }
763
- }
764
- });
765
- return queryPlan;
766
- }
767
- };
768
- var UpdateBuilderImpl = class _UpdateBuilderImpl {
769
- contract;
770
- context;
771
- table;
772
- set;
773
- wherePredicate;
774
- returningColumns = [];
775
- constructor(options, table, set) {
776
- this.context = options.context;
777
- this.contract = options.context.contract;
778
- this.table = table;
779
- this.set = set;
780
- }
781
- where(predicate) {
782
- const builder = new _UpdateBuilderImpl(
783
- {
784
- context: this.context
785
- },
786
- this.table,
787
- this.set
788
- );
789
- builder.wherePredicate = predicate;
790
- builder.returningColumns = [...this.returningColumns];
791
- return builder;
792
- }
793
- returning(...columns) {
794
- checkReturningCapability(this.contract);
795
- const builder = new _UpdateBuilderImpl(
796
- {
797
- context: this.context
798
- },
799
- this.table,
800
- this.set
801
- );
802
- if (this.wherePredicate) {
803
- builder.wherePredicate = this.wherePredicate;
804
- }
805
- builder.returningColumns = [...this.returningColumns, ...columns];
806
- return builder;
807
- }
808
- build(options) {
809
- if (!this.wherePredicate) {
810
- errorWhereMustBeCalledForUpdate();
811
- }
812
- const paramsMap = options?.params ?? {};
813
- const paramDescriptors = [];
814
- const paramValues = [];
815
- const paramCodecs = {};
816
- const contractTable = this.contract.storage.tables[this.table.name];
817
- if (!contractTable) {
818
- errorUnknownTable(this.table.name);
819
- }
820
- const set = {};
821
- for (const [columnName, placeholder] of Object.entries(this.set)) {
822
- if (!contractTable.columns[columnName]) {
823
- errorUnknownColumn(columnName, this.table.name);
824
- }
825
- const paramName = placeholder.name;
826
- if (!Object.hasOwn(paramsMap, paramName)) {
827
- errorMissingParameter(paramName);
828
- }
829
- const value = paramsMap[paramName];
830
- const index = paramValues.push(value);
831
- const columnMeta = contractTable.columns[columnName];
832
- const codecId = columnMeta?.codecId;
833
- if (paramName && codecId) {
834
- paramCodecs[paramName] = codecId;
835
- }
836
- paramDescriptors.push({
837
- name: paramName,
838
- source: "dsl",
839
- refs: { table: this.table.name, column: columnName },
840
- ...codecId ? { codecId } : {},
841
- ...columnMeta?.nativeType ? { nativeType: columnMeta.nativeType } : {},
842
- ...columnMeta?.nullable !== void 0 ? { nullable: columnMeta.nullable } : {}
843
- });
844
- set[columnName] = createParamRef2(index, paramName);
845
- }
846
- const whereResult = buildWhereExpr(
847
- this.contract,
848
- this.wherePredicate,
849
- paramsMap,
850
- paramDescriptors,
851
- paramValues
852
- );
853
- const whereExpr = whereResult.expr;
854
- if (!whereExpr) {
855
- errorFailedToBuildWhereClause();
856
- }
857
- if (whereResult.codecId && whereResult.paramName) {
858
- paramCodecs[whereResult.paramName] = whereResult.codecId;
859
- }
860
- const returning = this.returningColumns.map((col) => {
861
- const c = col;
862
- return createColumnRef2(c.table, c.column);
863
- });
864
- const ast = createUpdateAst({
865
- table: createTableRef(this.table.name),
866
- set,
867
- where: whereExpr,
868
- returning
869
- });
870
- const returningProjection = {
871
- aliases: this.returningColumns.map((col) => {
872
- const c = col;
873
- return c.column;
874
- }),
875
- columns: this.returningColumns
876
- };
877
- const planMeta = buildMeta({
878
- contract: this.contract,
879
- table: this.table,
880
- projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
881
- paramDescriptors,
882
- ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {},
883
- where: this.wherePredicate
884
- });
885
- const queryPlan = Object.freeze({
886
- ast,
887
- params: paramValues,
888
- meta: {
889
- ...planMeta,
890
- lane: "dsl",
891
- annotations: {
892
- ...planMeta.annotations,
893
- intent: "write",
894
- isMutation: true,
895
- hasWhere: true
896
- }
897
- }
898
- });
899
- return queryPlan;
900
- }
901
- };
902
- var DeleteBuilderImpl = class _DeleteBuilderImpl {
903
- contract;
904
- context;
905
- table;
906
- wherePredicate;
907
- returningColumns = [];
908
- constructor(options, table) {
909
- this.context = options.context;
910
- this.contract = options.context.contract;
911
- this.table = table;
912
- }
913
- where(predicate) {
914
- const builder = new _DeleteBuilderImpl(
915
- {
916
- context: this.context
917
- },
918
- this.table
919
- );
920
- builder.wherePredicate = predicate;
921
- builder.returningColumns = [...this.returningColumns];
922
- return builder;
923
- }
924
- returning(...columns) {
925
- checkReturningCapability(this.contract);
926
- const builder = new _DeleteBuilderImpl(
927
- {
928
- context: this.context
929
- },
930
- this.table
931
- );
932
- if (this.wherePredicate) {
933
- builder.wherePredicate = this.wherePredicate;
934
- }
935
- builder.returningColumns = [...this.returningColumns, ...columns];
936
- return builder;
937
- }
938
- build(options) {
939
- if (!this.wherePredicate) {
940
- errorWhereMustBeCalledForDelete();
941
- }
942
- const paramsMap = options?.params ?? {};
943
- const paramDescriptors = [];
944
- const paramValues = [];
945
- const paramCodecs = {};
946
- const contractTable = this.contract.storage.tables[this.table.name];
947
- if (!contractTable) {
948
- errorUnknownTable(this.table.name);
949
- }
950
- const whereResult = buildWhereExpr(
951
- this.contract,
952
- this.wherePredicate,
953
- paramsMap,
954
- paramDescriptors,
955
- paramValues
956
- );
957
- const whereExpr = whereResult.expr;
958
- if (!whereExpr) {
959
- errorFailedToBuildWhereClause();
960
- }
961
- if (whereResult.codecId && whereResult.paramName) {
962
- paramCodecs[whereResult.paramName] = whereResult.codecId;
963
- }
964
- const returning = this.returningColumns.map((col) => {
965
- const c = col;
966
- return createColumnRef2(c.table, c.column);
967
- });
968
- const ast = createDeleteAst({
969
- table: createTableRef(this.table.name),
970
- where: whereExpr,
971
- returning
972
- });
973
- const returningProjection = {
974
- aliases: this.returningColumns.map((col) => {
975
- const c = col;
976
- return c.column;
977
- }),
978
- columns: this.returningColumns
979
- };
980
- const planMeta = buildMeta({
981
- contract: this.contract,
982
- table: this.table,
983
- projection: returning.length > 0 ? returningProjection : { aliases: [], columns: [] },
984
- paramDescriptors,
985
- ...Object.keys(paramCodecs).length > 0 ? { paramCodecs } : {},
986
- where: this.wherePredicate
987
- });
988
- const queryPlan = Object.freeze({
989
- ast,
990
- params: paramValues,
991
- meta: {
992
- ...planMeta,
993
- lane: "dsl",
994
- annotations: {
995
- ...planMeta.annotations,
996
- intent: "write",
997
- isMutation: true,
998
- hasWhere: true
999
- }
1000
- }
1001
- });
1002
- return queryPlan;
1003
- }
1004
- };
1005
-
1006
- // src/sql/select-builder.ts
1007
- import {
1008
- createColumnRef as createColumnRef5,
1009
- createJoinOnBuilder,
1010
- createOrderByItem as createOrderByItem2,
1011
- createSelectAst,
1012
- createTableRef as createTableRef4
1013
- } from "@prisma-next/sql-relational-core/ast";
1014
- import { getOperationExpr as getOperationExpr3 } from "@prisma-next/sql-relational-core/utils/guards";
1015
-
1016
- // src/sql/include-builder.ts
1017
- import {
1018
- createColumnRef as createColumnRef3,
1019
- createJoinOnExpr,
1020
- createOrderByItem,
1021
- createTableRef as createTableRef2
1022
- } from "@prisma-next/sql-relational-core/ast";
1023
- import {
1024
- extractBaseColumnRef,
1025
- isOperationExpr as isOperationExpr2
1026
- } from "@prisma-next/sql-relational-core/utils/guards";
1027
-
1028
- // src/sql/projection.ts
1029
- import { isColumnBuilder as isColumnBuilder3 } from "@prisma-next/sql-relational-core/utils/guards";
1030
- function generateAlias(path) {
1031
- if (path.length === 0) {
1032
- errorAliasPathEmpty();
1033
- }
1034
- return path.join("_");
1035
- }
1036
- var AliasTracker = class {
1037
- aliases = /* @__PURE__ */ new Set();
1038
- aliasToPath = /* @__PURE__ */ new Map();
1039
- register(path) {
1040
- const alias = generateAlias(path);
1041
- if (this.aliases.has(alias)) {
1042
- const existingPath = this.aliasToPath.get(alias);
1043
- errorAliasCollision(path, alias, existingPath);
1044
- }
1045
- this.aliases.add(alias);
1046
- this.aliasToPath.set(alias, path);
1047
- return alias;
1048
- }
1049
- getPath(alias) {
1050
- return this.aliasToPath.get(alias);
1051
- }
1052
- has(alias) {
1053
- return this.aliases.has(alias);
1054
- }
1055
- };
1056
- function flattenProjection(projection, tracker, currentPath = []) {
1057
- const aliases = [];
1058
- const columns = [];
1059
- for (const [key, value] of Object.entries(projection)) {
1060
- const path = [...currentPath, key];
1061
- if (isColumnBuilder3(value)) {
1062
- const alias = tracker.register(path);
1063
- aliases.push(alias);
1064
- columns.push(value);
1065
- } else if (typeof value === "object" && value !== null) {
1066
- const nested = flattenProjection(value, tracker, path);
1067
- aliases.push(...nested.aliases);
1068
- columns.push(...nested.columns);
1069
- } else {
1070
- errorInvalidProjectionValue(path);
1071
- }
1072
- }
1073
- return { aliases, columns };
1074
- }
1075
- function buildProjectionState(_table, projection, includes) {
1076
- const tracker = new AliasTracker();
1077
- const aliases = [];
1078
- const columns = [];
1079
- for (const [key, value] of Object.entries(projection)) {
1080
- if (value === true) {
1081
- const matchingInclude = includes?.find((inc) => inc.alias === key);
1082
- if (!matchingInclude) {
1083
- errorIncludeAliasNotFound(key);
1084
- }
1085
- aliases.push(key);
1086
- columns.push(null);
1087
- } else if (isColumnBuilder3(value)) {
1088
- const alias = tracker.register([key]);
1089
- aliases.push(alias);
1090
- columns.push(value);
1091
- } else if (typeof value === "object" && value !== null) {
1092
- const nested = flattenProjection(value, tracker, [key]);
1093
- aliases.push(...nested.aliases);
1094
- columns.push(...nested.columns);
1095
- } else {
1096
- errorInvalidProjectionKey(key);
1097
- }
1098
- }
1099
- if (aliases.length === 0) {
1100
- errorProjectionEmpty();
1101
- }
1102
- return { aliases, columns };
1103
- }
1104
-
1105
- // src/sql/include-builder.ts
1106
- var IncludeChildBuilderImpl = class _IncludeChildBuilderImpl {
1107
- contract;
1108
- codecTypes;
1109
- table;
1110
- childProjection;
1111
- childWhere;
1112
- childOrderBy;
1113
- childLimit;
1114
- constructor(contract, codecTypes, table) {
1115
- this.contract = contract;
1116
- this.codecTypes = codecTypes;
1117
- this.table = table;
1118
- }
1119
- select(projection) {
1120
- const projectionState = buildProjectionState(this.table, projection);
1121
- const builder = new _IncludeChildBuilderImpl(this.contract, this.codecTypes, this.table);
1122
- builder.childProjection = projectionState;
1123
- if (this.childWhere !== void 0) {
1124
- builder.childWhere = this.childWhere;
1125
- }
1126
- if (this.childOrderBy !== void 0) {
1127
- builder.childOrderBy = this.childOrderBy;
1128
- }
1129
- if (this.childLimit !== void 0) {
1130
- builder.childLimit = this.childLimit;
1131
- }
1132
- return builder;
1133
- }
1134
- where(expr) {
1135
- const builder = new _IncludeChildBuilderImpl(
1136
- this.contract,
1137
- this.codecTypes,
1138
- this.table
1139
- );
1140
- if (this.childProjection !== void 0) {
1141
- builder.childProjection = this.childProjection;
1142
- }
1143
- builder.childWhere = expr;
1144
- if (this.childOrderBy !== void 0) {
1145
- builder.childOrderBy = this.childOrderBy;
1146
- }
1147
- if (this.childLimit !== void 0) {
1148
- builder.childLimit = this.childLimit;
1149
- }
1150
- return builder;
1151
- }
1152
- orderBy(order) {
1153
- const builder = new _IncludeChildBuilderImpl(
1154
- this.contract,
1155
- this.codecTypes,
1156
- this.table
1157
- );
1158
- if (this.childProjection !== void 0) {
1159
- builder.childProjection = this.childProjection;
1160
- }
1161
- if (this.childWhere !== void 0) {
1162
- builder.childWhere = this.childWhere;
1163
- }
1164
- builder.childOrderBy = order;
1165
- if (this.childLimit !== void 0) {
1166
- builder.childLimit = this.childLimit;
1167
- }
1168
- return builder;
1169
- }
1170
- limit(count) {
1171
- if (!Number.isInteger(count) || count < 0) {
1172
- errorLimitMustBeNonNegativeInteger();
1173
- }
1174
- const builder = new _IncludeChildBuilderImpl(
1175
- this.contract,
1176
- this.codecTypes,
1177
- this.table
1178
- );
1179
- if (this.childProjection !== void 0) {
1180
- builder.childProjection = this.childProjection;
1181
- }
1182
- if (this.childWhere !== void 0) {
1183
- builder.childWhere = this.childWhere;
1184
- }
1185
- if (this.childOrderBy !== void 0) {
1186
- builder.childOrderBy = this.childOrderBy;
1187
- }
1188
- builder.childLimit = count;
1189
- return builder;
1190
- }
1191
- getState() {
1192
- if (!this.childProjection) {
1193
- errorChildProjectionMustBeSpecified();
1194
- }
1195
- const state = {
1196
- childProjection: this.childProjection
1197
- };
1198
- if (this.childWhere !== void 0) {
1199
- state.childWhere = this.childWhere;
1200
- }
1201
- if (this.childOrderBy !== void 0) {
1202
- state.childOrderBy = this.childOrderBy;
1203
- }
1204
- if (this.childLimit !== void 0) {
1205
- state.childLimit = this.childLimit;
1206
- }
1207
- return state;
1208
- }
1209
- };
1210
- function buildIncludeAst(include, contract, paramsMap, paramDescriptors, paramValues) {
1211
- const childOrderBy = include.childOrderBy ? (() => {
1212
- const orderBy = include.childOrderBy;
1213
- const orderExpr = orderBy.expr;
1214
- const expr = (() => {
1215
- if (isOperationExpr2(orderExpr)) {
1216
- const baseCol = extractBaseColumnRef(orderExpr);
1217
- return createColumnRef3(baseCol.table, baseCol.column);
1218
- }
1219
- const colBuilder = orderExpr;
1220
- return createColumnRef3(colBuilder.table, colBuilder.column);
1221
- })();
1222
- return [createOrderByItem(expr, orderBy.dir)];
1223
- })() : void 0;
1224
- let childWhere;
1225
- if (include.childWhere) {
1226
- const whereResult = buildWhereExpr(
1227
- contract,
1228
- include.childWhere,
1229
- paramsMap,
1230
- paramDescriptors,
1231
- paramValues
1232
- );
1233
- childWhere = whereResult.expr;
1234
- }
1235
- const onLeft = include.on.left;
1236
- const onRight = include.on.right;
1237
- const leftCol = createColumnRef3(onLeft.table, onLeft.column);
1238
- const rightCol = createColumnRef3(onRight.table, onRight.column);
1239
- const onExpr = createJoinOnExpr(leftCol, rightCol);
1240
- return {
1241
- kind: "includeMany",
1242
- alias: include.alias,
1243
- child: {
1244
- table: createTableRef2(include.table.name),
1245
- on: onExpr,
1246
- ...childWhere ? { where: childWhere } : {},
1247
- ...childOrderBy ? { orderBy: childOrderBy } : {},
1248
- ...typeof include.childLimit === "number" ? { limit: include.childLimit } : {},
1249
- project: include.childProjection.aliases.map((alias, idx) => {
1250
- const column = include.childProjection.columns[idx];
1251
- if (!column || !alias) {
1252
- errorMissingColumnForAlias(alias ?? "unknown", idx);
1253
- }
1254
- return {
1255
- alias,
1256
- expr: createColumnRef3(column.table, column.column)
1257
- };
1258
- })
1259
- }
1260
- };
1261
- }
1262
-
1263
- // src/sql/join-builder.ts
1264
- import {
1265
- createColumnRef as createColumnRef4,
1266
- createJoin,
1267
- createJoinOnExpr as createJoinOnExpr2,
1268
- createTableRef as createTableRef3
1269
- } from "@prisma-next/sql-relational-core/ast";
1270
- function buildJoinAst(join) {
1271
- const onLeft = join.on.left;
1272
- const onRight = join.on.right;
1273
- const leftCol = createColumnRef4(onLeft.table, onLeft.column);
1274
- const rightCol = createColumnRef4(onRight.table, onRight.column);
1275
- const onExpr = createJoinOnExpr2(leftCol, rightCol);
1276
- return createJoin(join.joinType, createTableRef3(join.table.name), onExpr);
1277
- }
1278
-
1279
- // src/sql/select-builder.ts
1280
- var SelectBuilderImpl = class _SelectBuilderImpl {
1281
- contract;
1282
- codecTypes;
1283
- context;
1284
- state = {};
1285
- constructor(options, state) {
1286
- this.context = options.context;
1287
- this.contract = options.context.contract;
1288
- this.codecTypes = options.context.contract.mappings.codecTypes;
1289
- if (state) {
1290
- this.state = state;
1291
- }
1292
- }
1293
- from(table) {
1294
- return new _SelectBuilderImpl(
1295
- {
1296
- context: this.context
1297
- },
1298
- { ...this.state, from: table }
1299
- );
1300
- }
1301
- innerJoin(table, on) {
1302
- return this._addJoin("inner", table, on);
1303
- }
1304
- leftJoin(table, on) {
1305
- return this._addJoin("left", table, on);
1306
- }
1307
- rightJoin(table, on) {
1308
- return this._addJoin("right", table, on);
1309
- }
1310
- fullJoin(table, on) {
1311
- return this._addJoin("full", table, on);
1312
- }
1313
- includeMany(childTable, on, childBuilder, options) {
1314
- checkIncludeCapabilities(this.contract);
1315
- if (!this.contract.storage.tables[childTable.name]) {
1316
- errorUnknownTable(childTable.name);
1317
- }
1318
- const joinOnBuilder = createJoinOnBuilder();
1319
- const onPredicate = on(joinOnBuilder);
1320
- const onLeft = onPredicate.left;
1321
- const onRight = onPredicate.right;
1322
- if (onLeft.table === onRight.table) {
1323
- errorSelfJoinNotSupported();
1324
- }
1325
- const childBuilderImpl = new IncludeChildBuilderImpl(
1326
- this.contract,
1327
- this.codecTypes,
1328
- childTable
1329
- );
1330
- const builtChild = childBuilder(
1331
- childBuilderImpl
1332
- );
1333
- const childState = builtChild.getState();
1334
- if (childState.childProjection.aliases.length === 0) {
1335
- errorChildProjectionEmpty();
1336
- }
1337
- const alias = options?.alias ?? childTable.name;
1338
- if (this.state.projection) {
1339
- if (this.state.projection.aliases.includes(alias)) {
1340
- errorIncludeAliasCollision(alias, "projection");
1341
- }
1342
- }
1343
- const existingIncludes = this.state.includes ?? [];
1344
- if (existingIncludes.some((inc) => inc.alias === alias)) {
1345
- errorIncludeAliasCollision(alias, "include");
1346
- }
1347
- const includeState = {
1348
- alias,
1349
- table: childTable,
1350
- on: onPredicate,
1351
- childProjection: childState.childProjection,
1352
- ...childState.childWhere !== void 0 ? { childWhere: childState.childWhere } : {},
1353
- ...childState.childOrderBy !== void 0 ? { childOrderBy: childState.childOrderBy } : {},
1354
- ...childState.childLimit !== void 0 ? { childLimit: childState.childLimit } : {}
1355
- };
1356
- const newIncludes = [...existingIncludes, includeState];
1357
- return new _SelectBuilderImpl(
1358
- {
1359
- context: this.context
1360
- },
1361
- { ...this.state, includes: newIncludes }
1362
- );
1363
- }
1364
- _addJoin(joinType, table, on) {
1365
- const fromTable = this.ensureFrom();
1366
- if (!this.contract.storage.tables[table.name]) {
1367
- errorUnknownTable(table.name);
1368
- }
1369
- if (table.name === fromTable.name) {
1370
- errorSelfJoinNotSupported();
1371
- }
1372
- const joinOnBuilder = createJoinOnBuilder();
1373
- const onPredicate = on(joinOnBuilder);
1374
- const joinState = {
1375
- joinType,
1376
- table,
1377
- on: onPredicate
1378
- };
1379
- const existingJoins = this.state.joins ?? [];
1380
- const newJoins = [...existingJoins, joinState];
1381
- return new _SelectBuilderImpl(
1382
- {
1383
- context: this.context
1384
- },
1385
- { ...this.state, joins: newJoins }
1386
- );
1387
- }
1388
- where(expr) {
1389
- return new _SelectBuilderImpl(
1390
- {
1391
- context: this.context
1392
- },
1393
- { ...this.state, where: expr }
1394
- );
1395
- }
1396
- select(projection) {
1397
- const table = this.ensureFrom();
1398
- const projectionState = buildProjectionState(table, projection, this.state.includes);
1399
- return new _SelectBuilderImpl(
1400
- {
1401
- context: this.context
1402
- },
1403
- { ...this.state, projection: projectionState }
1404
- );
1405
- }
1406
- orderBy(order) {
1407
- return new _SelectBuilderImpl(
1408
- {
1409
- context: this.context
1410
- },
1411
- { ...this.state, orderBy: order }
1412
- );
1413
- }
1414
- limit(count) {
1415
- if (!Number.isInteger(count) || count < 0) {
1416
- errorLimitMustBeNonNegativeInteger();
1417
- }
1418
- return new _SelectBuilderImpl(
1419
- {
1420
- context: this.context
1421
- },
1422
- { ...this.state, limit: count }
1423
- );
1424
- }
1425
- build(options) {
1426
- const table = this.ensureFrom();
1427
- const projection = this.ensureProjection();
1428
- const paramsMap = options?.params ?? {};
1429
- const contractTable = this.contract.storage.tables[table.name];
1430
- if (!contractTable) {
1431
- errorUnknownTable(table.name);
1432
- }
1433
- const paramDescriptors = [];
1434
- const paramValues = [];
1435
- const paramCodecs = {};
1436
- const whereResult = this.state.where ? buildWhereExpr(this.contract, this.state.where, paramsMap, paramDescriptors, paramValues) : void 0;
1437
- const whereExpr = whereResult?.expr;
1438
- if (whereResult?.codecId && whereResult.paramName) {
1439
- paramCodecs[whereResult.paramName] = whereResult.codecId;
1440
- }
1441
- const orderByClause = this.state.orderBy ? (() => {
1442
- const orderBy = this.state.orderBy;
1443
- const orderExpr = orderBy.expr;
1444
- const operationExpr = getOperationExpr3(orderExpr);
1445
- const expr = operationExpr ? operationExpr : (() => {
1446
- const colBuilder = orderExpr;
1447
- return createColumnRef5(colBuilder.table, colBuilder.column);
1448
- })();
1449
- return [createOrderByItem2(expr, orderBy.dir)];
1450
- })() : void 0;
1451
- const joins = this.state.joins?.map((join) => buildJoinAst(join));
1452
- const includes = this.state.includes?.map(
1453
- (include) => buildIncludeAst(include, this.contract, paramsMap, paramDescriptors, paramValues)
1454
- );
1455
- const projectEntries = [];
1456
- for (let i = 0; i < projection.aliases.length; i++) {
1457
- const alias = projection.aliases[i];
1458
- if (!alias) {
1459
- errorMissingAlias(i);
1460
- }
1461
- const column = projection.columns[i];
1462
- const matchingInclude = this.state.includes?.find((inc) => inc.alias === alias);
1463
- if (matchingInclude) {
1464
- projectEntries.push({
1465
- alias,
1466
- expr: { kind: "includeRef", alias }
1467
- });
1468
- } else {
1469
- if (!column) {
1470
- errorMissingColumnForAlias(alias, i);
1471
- }
1472
- const operationExpr = column._operationExpr;
1473
- if (operationExpr) {
1474
- projectEntries.push({
1475
- alias,
1476
- expr: operationExpr
1477
- });
1478
- } else {
1479
- const col = column;
1480
- assertColumnBuilder(col, "projection column");
1481
- projectEntries.push({
1482
- alias,
1483
- expr: createColumnRef5(col.table, col.column)
1484
- });
1485
- }
1486
- }
1487
- }
1488
- const ast = createSelectAst({
1489
- from: createTableRef4(table.name),
1490
- joins,
1491
- includes,
1492
- project: projectEntries,
1493
- where: whereExpr,
1494
- orderBy: orderByClause,
1495
- limit: this.state.limit
1496
- });
1497
- const planMeta = buildMeta({
1498
- contract: this.contract,
1499
- table,
1500
- projection,
1501
- joins: this.state.joins,
1502
- includes: this.state.includes,
1503
- paramDescriptors,
1504
- paramCodecs,
1505
- where: this.state.where,
1506
- orderBy: this.state.orderBy
1507
- });
1508
- const queryPlan = Object.freeze({
1509
- ast,
1510
- params: paramValues,
1511
- meta: planMeta
1512
- });
1513
- return queryPlan;
1514
- }
1515
- ensureFrom() {
1516
- if (!this.state.from) {
1517
- errorFromMustBeCalled();
1518
- }
1519
- return this.state.from;
1520
- }
1521
- ensureProjection() {
1522
- if (!this.state.projection) {
1523
- errorSelectMustBeCalled();
1524
- }
1525
- return this.state.projection;
1526
- }
1527
- };
1528
-
1529
- // src/sql/builder.ts
1530
- function sql(options) {
1531
- const builder = new SelectBuilderImpl(
1532
- options
1533
- );
1534
- const rawFactory = createRawFactory(options.context.contract);
1535
- Object.defineProperty(builder, "raw", {
1536
- value: rawFactory,
1537
- enumerable: true,
1538
- configurable: false
1539
- });
1540
- Object.defineProperty(builder, "insert", {
1541
- value: (table, values) => {
1542
- return new InsertBuilderImpl(options, table, values);
1543
- },
1544
- enumerable: true,
1545
- configurable: false
1546
- });
1547
- Object.defineProperty(builder, "update", {
1548
- value: (table, set) => {
1549
- return new UpdateBuilderImpl(options, table, set);
1550
- },
1551
- enumerable: true,
1552
- configurable: false
1553
- });
1554
- Object.defineProperty(builder, "delete", {
1555
- value: (table) => {
1556
- return new DeleteBuilderImpl(options, table);
1557
- },
1558
- enumerable: true,
1559
- configurable: false
1560
- });
1561
- return builder;
1562
- }
1563
-
1564
- export {
1565
- rawOptions,
1566
- createJoinOnBuilder2 as createJoinOnBuilder,
1567
- sql
1568
- };
1569
- //# sourceMappingURL=chunk-AWSKRSFP.js.map