@prisma-next/sql-orm-lane 0.3.0-pr.93.5 → 0.3.0-pr.94.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 (76) hide show
  1. package/dist/exports/orm.d.mts +2 -0
  2. package/dist/exports/orm.mjs +3 -0
  3. package/dist/index.d.mts +42 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +3 -0
  6. package/dist/orm-BYJaTDLm.mjs +1286 -0
  7. package/dist/orm-BYJaTDLm.mjs.map +1 -0
  8. package/dist/orm-DxyXF2Wh.d.mts +89 -0
  9. package/dist/orm-DxyXF2Wh.d.mts.map +1 -0
  10. package/package.json +22 -20
  11. package/src/orm/state.ts +3 -3
  12. package/src/plan/plan-assembly.ts +95 -80
  13. package/src/relations/include-plan.ts +5 -5
  14. package/src/selection/predicates.ts +25 -41
  15. package/src/selection/projection.ts +16 -10
  16. package/src/selection/select-builder.ts +22 -24
  17. package/dist/chunk-3DNKIXXB.js +0 -1736
  18. package/dist/chunk-3DNKIXXB.js.map +0 -1
  19. package/dist/exports/orm.d.ts +0 -3
  20. package/dist/exports/orm.d.ts.map +0 -1
  21. package/dist/exports/orm.js +0 -7
  22. package/dist/exports/orm.js.map +0 -1
  23. package/dist/index.d.ts +0 -4
  24. package/dist/index.d.ts.map +0 -1
  25. package/dist/index.js +0 -9
  26. package/dist/index.js.map +0 -1
  27. package/dist/mutations/delete-builder.d.ts +0 -9
  28. package/dist/mutations/delete-builder.d.ts.map +0 -1
  29. package/dist/mutations/insert-builder.d.ts +0 -7
  30. package/dist/mutations/insert-builder.d.ts.map +0 -1
  31. package/dist/mutations/update-builder.d.ts +0 -9
  32. package/dist/mutations/update-builder.d.ts.map +0 -1
  33. package/dist/orm/builder.d.ts +0 -38
  34. package/dist/orm/builder.d.ts.map +0 -1
  35. package/dist/orm/capabilities.d.ts +0 -3
  36. package/dist/orm/capabilities.d.ts.map +0 -1
  37. package/dist/orm/context.d.ts +0 -5
  38. package/dist/orm/context.d.ts.map +0 -1
  39. package/dist/orm/state.d.ts +0 -45
  40. package/dist/orm/state.d.ts.map +0 -1
  41. package/dist/orm-include-child.d.ts +0 -35
  42. package/dist/orm-include-child.d.ts.map +0 -1
  43. package/dist/orm-relation-filter.d.ts +0 -19
  44. package/dist/orm-relation-filter.d.ts.map +0 -1
  45. package/dist/orm-types.d.ts +0 -86
  46. package/dist/orm-types.d.ts.map +0 -1
  47. package/dist/orm.d.ts +0 -5
  48. package/dist/orm.d.ts.map +0 -1
  49. package/dist/plan/lowering.d.ts +0 -2
  50. package/dist/plan/lowering.d.ts.map +0 -1
  51. package/dist/plan/plan-assembly.d.ts +0 -24
  52. package/dist/plan/plan-assembly.d.ts.map +0 -1
  53. package/dist/plan/result-typing.d.ts +0 -2
  54. package/dist/plan/result-typing.d.ts.map +0 -1
  55. package/dist/relations/include-plan.d.ts +0 -38
  56. package/dist/relations/include-plan.d.ts.map +0 -1
  57. package/dist/selection/join.d.ts +0 -3
  58. package/dist/selection/join.d.ts.map +0 -1
  59. package/dist/selection/ordering.d.ts +0 -11
  60. package/dist/selection/ordering.d.ts.map +0 -1
  61. package/dist/selection/pagination.d.ts +0 -6
  62. package/dist/selection/pagination.d.ts.map +0 -1
  63. package/dist/selection/predicates.d.ts +0 -10
  64. package/dist/selection/predicates.d.ts.map +0 -1
  65. package/dist/selection/projection.d.ts +0 -28
  66. package/dist/selection/projection.d.ts.map +0 -1
  67. package/dist/selection/select-builder.d.ts +0 -22
  68. package/dist/selection/select-builder.d.ts.map +0 -1
  69. package/dist/types/internal.d.ts +0 -4
  70. package/dist/types/internal.d.ts.map +0 -1
  71. package/dist/utils/ast.d.ts +0 -2
  72. package/dist/utils/ast.d.ts.map +0 -1
  73. package/dist/utils/errors.d.ts +0 -29
  74. package/dist/utils/errors.d.ts.map +0 -1
  75. package/dist/utils/param-descriptor.d.ts +0 -10
  76. package/dist/utils/param-descriptor.d.ts.map +0 -1
@@ -1,1736 +0,0 @@
1
- // src/orm/builder.ts
2
- import { planInvalid as planInvalid5 } from "@prisma-next/plan";
3
- import { schema as schema4 } from "@prisma-next/sql-relational-core/schema";
4
-
5
- // src/selection/predicates.ts
6
- import { augmentDescriptorWithColumnMeta } from "@prisma-next/sql-relational-core/plan";
7
- import {
8
- getColumnInfo,
9
- getColumnMeta,
10
- getOperationExpr,
11
- isColumnBuilder,
12
- isParamPlaceholder
13
- } from "@prisma-next/sql-relational-core/utils/guards";
14
-
15
- // src/utils/ast.ts
16
- import {
17
- createBinaryExpr,
18
- createColumnRef,
19
- createDeleteAst,
20
- createInsertAst,
21
- createJoinOnExpr,
22
- createOrderByItem,
23
- createParamRef,
24
- createSelectAst,
25
- createTableRef,
26
- createUpdateAst
27
- } from "@prisma-next/sql-relational-core/ast";
28
-
29
- // src/utils/errors.ts
30
- import { planInvalid } from "@prisma-next/plan";
31
- function errorModelNotFound(modelName) {
32
- throw planInvalid(`Model ${modelName} not found in mappings`);
33
- }
34
- function errorTableNotFound(tableName) {
35
- throw planInvalid(`Table ${tableName} not found in schema`);
36
- }
37
- function errorUnknownTable(tableName) {
38
- throw planInvalid(`Unknown table ${tableName}`);
39
- }
40
- function errorUnknownColumn(columnName, tableName) {
41
- throw planInvalid(`Unknown column ${columnName} in table ${tableName}`);
42
- }
43
- function errorMissingParameter(paramName) {
44
- throw planInvalid(`Missing value for parameter ${paramName}`);
45
- }
46
- function errorAliasPathEmpty() {
47
- throw planInvalid("Alias path cannot be empty");
48
- }
49
- function errorAliasCollision(path, alias, existingPath) {
50
- throw planInvalid(
51
- `Alias collision: path ${path.join(".")} would generate alias "${alias}" which conflicts with path ${existingPath?.join(".") ?? "unknown"}`
52
- );
53
- }
54
- function errorInvalidProjectionValue(path) {
55
- throw planInvalid(
56
- `Invalid projection value at path ${path.join(".")}: expected ColumnBuilder or nested object`
57
- );
58
- }
59
- function errorIncludeAliasNotFound(alias) {
60
- throw planInvalid(
61
- `Include alias "${alias}" not found. Did you call includeMany() with alias "${alias}"?`
62
- );
63
- }
64
- function errorInvalidProjectionKey(key) {
65
- throw planInvalid(
66
- `Invalid projection value at key "${key}": expected ColumnBuilder, boolean true (for includes), or nested object`
67
- );
68
- }
69
- function errorProjectionEmpty() {
70
- throw planInvalid("select() requires at least one column or include");
71
- }
72
- function errorCreateRequiresFields() {
73
- throw planInvalid("create() requires at least one field");
74
- }
75
- function errorUpdateRequiresFields() {
76
- throw planInvalid("update() requires at least one field");
77
- }
78
- function errorIncludeRequiresCapabilities() {
79
- throw planInvalid("includeMany requires lateral and jsonAgg capabilities");
80
- }
81
- function errorIncludeCapabilitiesNotTrue() {
82
- throw planInvalid("includeMany requires lateral and jsonAgg capabilities to be true");
83
- }
84
- function errorMultiColumnJoinsNotSupported() {
85
- throw planInvalid("Multi-column joins in includes are not yet supported");
86
- }
87
- function errorJoinColumnsMustBeDefined() {
88
- throw planInvalid("Join columns must be defined");
89
- }
90
- function errorColumnNotFound(columnName, tableName) {
91
- throw planInvalid(`Column ${columnName} not found in table ${tableName}`);
92
- }
93
- function errorChildProjectionMustBeSpecified() {
94
- throw planInvalid("Child projection must be specified");
95
- }
96
- function errorChildProjectionEmpty() {
97
- throw planInvalid("Child projection must not be empty after filtering boolean values");
98
- }
99
- function errorMissingAlias(index) {
100
- throw planInvalid(`Missing alias at index ${index}`);
101
- }
102
- function errorMissingColumn(alias, index) {
103
- throw planInvalid(`Missing column for alias "${alias}" at index ${index}`);
104
- }
105
- function errorInvalidColumn(alias, index) {
106
- throw planInvalid(`Invalid column for alias "${alias}" at index ${index}`);
107
- }
108
- function errorFailedToBuildWhereClause() {
109
- throw planInvalid("Failed to build WHERE clause");
110
- }
111
- function assertColumnExists(columnMeta, columnName, tableName) {
112
- if (!columnMeta) {
113
- errorUnknownColumn(columnName, tableName);
114
- }
115
- }
116
- function assertParameterExists(paramsMap, paramName) {
117
- if (!Object.hasOwn(paramsMap, paramName)) {
118
- errorMissingParameter(paramName);
119
- }
120
- return paramsMap[paramName];
121
- }
122
-
123
- // src/selection/predicates.ts
124
- function buildWhereExpr(where, contract, paramsMap, descriptors, values) {
125
- let leftExpr;
126
- let codecId;
127
- let rightExpr;
128
- let paramName;
129
- const operationExpr = getOperationExpr(where.left);
130
- if (operationExpr) {
131
- leftExpr = operationExpr;
132
- } else if (isColumnBuilder(where.left)) {
133
- const { table, column } = getColumnInfo(where.left);
134
- const contractTable = contract.storage.tables[table];
135
- if (!contractTable) {
136
- errorUnknownTable(table);
137
- }
138
- const columnMeta = contractTable.columns[column];
139
- if (columnMeta) {
140
- codecId = columnMeta.codecId;
141
- }
142
- leftExpr = createColumnRef(table, column);
143
- } else {
144
- errorFailedToBuildWhereClause();
145
- }
146
- if (isParamPlaceholder(where.right)) {
147
- const placeholder = where.right;
148
- paramName = placeholder.name;
149
- if (!Object.hasOwn(paramsMap, paramName)) {
150
- errorMissingParameter(paramName);
151
- }
152
- const value = paramsMap[paramName];
153
- const index = values.push(value);
154
- if (isColumnBuilder(where.left)) {
155
- const { table, column } = getColumnInfo(where.left);
156
- const contractTable = contract.storage.tables[table];
157
- const columnMeta = contractTable?.columns[column];
158
- const builderColumnMeta = getColumnMeta(where.left);
159
- descriptors.push({
160
- name: paramName,
161
- source: "dsl",
162
- refs: { table, column },
163
- ...typeof builderColumnMeta?.nullable === "boolean" ? { nullable: builderColumnMeta.nullable } : {}
164
- });
165
- augmentDescriptorWithColumnMeta(descriptors, columnMeta);
166
- }
167
- rightExpr = createParamRef(index, paramName);
168
- } else if (isColumnBuilder(where.right)) {
169
- const { table, column } = getColumnInfo(where.right);
170
- const contractTable = contract.storage.tables[table];
171
- if (!contractTable) {
172
- errorUnknownTable(table);
173
- }
174
- rightExpr = createColumnRef(table, column);
175
- paramName = "";
176
- } else {
177
- errorFailedToBuildWhereClause();
178
- }
179
- return {
180
- expr: createBinaryExpr(where.op, leftExpr, rightExpr),
181
- ...codecId ? { codecId } : {},
182
- paramName
183
- };
184
- }
185
-
186
- // src/mutations/delete-builder.ts
187
- function buildDeletePlan(context, modelName, where, getModelAccessor, options) {
188
- const modelAccessor = getModelAccessor();
189
- const wherePredicate = where(modelAccessor);
190
- const tableName = context.contract.mappings.modelToTable?.[modelName];
191
- if (!tableName) {
192
- errorModelNotFound(modelName);
193
- }
194
- const table = createTableRef(tableName);
195
- const paramsMap = options?.params ?? {};
196
- const paramDescriptors = [];
197
- const paramValues = [];
198
- const paramCodecs = {};
199
- const whereResult = buildWhereExpr(
200
- wherePredicate,
201
- context.contract,
202
- paramsMap,
203
- paramDescriptors,
204
- paramValues
205
- );
206
- const whereExpr = whereResult.expr;
207
- if (!whereExpr) {
208
- errorFailedToBuildWhereClause();
209
- }
210
- if (whereResult?.codecId && whereResult.paramName) {
211
- paramCodecs[whereResult.paramName] = whereResult.codecId;
212
- }
213
- const ast = createDeleteAst({
214
- table,
215
- where: whereExpr
216
- });
217
- return Object.freeze({
218
- ast,
219
- params: paramValues,
220
- meta: {
221
- target: context.contract.target,
222
- targetFamily: context.contract.targetFamily,
223
- coreHash: context.contract.coreHash,
224
- lane: "orm",
225
- refs: {
226
- tables: [tableName],
227
- columns: []
228
- },
229
- projection: {},
230
- paramDescriptors,
231
- ...Object.keys(paramCodecs).length > 0 ? {
232
- annotations: {
233
- codecs: paramCodecs,
234
- intent: "write",
235
- isMutation: true
236
- }
237
- } : {
238
- annotations: {
239
- intent: "write",
240
- isMutation: true
241
- }
242
- }
243
- }
244
- });
245
- }
246
-
247
- // src/mutations/insert-builder.ts
248
- import { param } from "@prisma-next/sql-relational-core/param";
249
-
250
- // src/utils/param-descriptor.ts
251
- function createParamDescriptor(args) {
252
- return {
253
- name: args.name,
254
- source: "dsl",
255
- refs: { table: args.table, column: args.column },
256
- ...args.codecId ? { codecId: args.codecId } : {},
257
- ...args.nativeType ? { nativeType: args.nativeType } : {},
258
- nullable: args.nullable
259
- };
260
- }
261
-
262
- // src/mutations/insert-builder.ts
263
- function convertModelFieldsToColumns(contract, modelName, fields) {
264
- const model = contract.models[modelName];
265
- if (!model || typeof model !== "object" || !("fields" in model)) {
266
- throw new Error(`Model ${modelName} does not have fields`);
267
- }
268
- const modelFields = model.fields;
269
- const result = {};
270
- for (const fieldName in fields) {
271
- if (!Object.hasOwn(fields, fieldName)) {
272
- continue;
273
- }
274
- if (!Object.hasOwn(modelFields, fieldName)) {
275
- throw new Error(`Field ${fieldName} does not exist on model ${modelName}`);
276
- }
277
- const field = modelFields[fieldName];
278
- if (!field) {
279
- continue;
280
- }
281
- const columnName = contract.mappings.fieldToColumn?.[modelName]?.[fieldName] ?? field.column ?? fieldName;
282
- result[columnName] = param(fieldName);
283
- }
284
- return result;
285
- }
286
- function buildInsertPlan(context, modelName, data, options) {
287
- if (!data || Object.keys(data).length === 0) {
288
- errorCreateRequiresFields();
289
- }
290
- const values = convertModelFieldsToColumns(context.contract, modelName, data);
291
- const tableName = context.contract.mappings.modelToTable?.[modelName];
292
- if (!tableName) {
293
- errorModelNotFound(modelName);
294
- }
295
- const table = createTableRef(tableName);
296
- const paramsMap = {
297
- ...options?.params ?? {},
298
- ...data
299
- };
300
- const paramDescriptors = [];
301
- const paramValues = [];
302
- const paramCodecs = {};
303
- const contractTable = context.contract.storage.tables[tableName];
304
- if (!contractTable) {
305
- errorUnknownTable(tableName);
306
- }
307
- const insertValues = {};
308
- for (const [columnName, placeholder] of Object.entries(values)) {
309
- const columnMeta = contractTable.columns[columnName];
310
- assertColumnExists(columnMeta, columnName, tableName);
311
- const paramName = placeholder.name;
312
- const value = assertParameterExists(paramsMap, paramName);
313
- const index = paramValues.push(value);
314
- const codecId = columnMeta.codecId;
315
- if (paramName) {
316
- paramCodecs[paramName] = codecId;
317
- }
318
- paramDescriptors.push(
319
- createParamDescriptor({
320
- name: paramName,
321
- table: tableName,
322
- column: columnName,
323
- codecId,
324
- nativeType: columnMeta.nativeType,
325
- nullable: columnMeta.nullable
326
- })
327
- );
328
- insertValues[columnName] = createParamRef(index, paramName);
329
- }
330
- const ast = createInsertAst({
331
- table,
332
- values: insertValues
333
- });
334
- return Object.freeze({
335
- ast,
336
- params: paramValues,
337
- meta: {
338
- target: context.contract.target,
339
- targetFamily: context.contract.targetFamily,
340
- coreHash: context.contract.coreHash,
341
- lane: "orm",
342
- refs: {
343
- tables: [tableName],
344
- columns: []
345
- },
346
- projection: {},
347
- paramDescriptors,
348
- ...Object.keys(paramCodecs).length > 0 ? {
349
- annotations: {
350
- codecs: paramCodecs,
351
- intent: "write",
352
- isMutation: true
353
- }
354
- } : {
355
- annotations: {
356
- intent: "write",
357
- isMutation: true
358
- }
359
- }
360
- }
361
- });
362
- }
363
-
364
- // src/mutations/update-builder.ts
365
- function buildUpdatePlan(context, modelName, where, getModelAccessor, data, options) {
366
- if (!data || Object.keys(data).length === 0) {
367
- errorUpdateRequiresFields();
368
- }
369
- const set = convertModelFieldsToColumns(context.contract, modelName, data);
370
- const modelAccessor = getModelAccessor();
371
- const wherePredicate = where(modelAccessor);
372
- const tableName = context.contract.mappings.modelToTable?.[modelName];
373
- if (!tableName) {
374
- errorModelNotFound(modelName);
375
- }
376
- const table = createTableRef(tableName);
377
- const paramsMap = {
378
- ...options?.params ?? {},
379
- ...data
380
- };
381
- const paramDescriptors = [];
382
- const paramValues = [];
383
- const paramCodecs = {};
384
- const contractTable = context.contract.storage.tables[tableName];
385
- if (!contractTable) {
386
- errorUnknownTable(tableName);
387
- }
388
- const updateSet = {};
389
- for (const [columnName, placeholder] of Object.entries(set)) {
390
- const columnMeta = contractTable.columns[columnName];
391
- assertColumnExists(columnMeta, columnName, tableName);
392
- const paramName = placeholder.name;
393
- const value = assertParameterExists(paramsMap, paramName);
394
- const index = paramValues.push(value);
395
- const codecId = columnMeta.codecId;
396
- if (paramName) {
397
- paramCodecs[paramName] = codecId;
398
- }
399
- paramDescriptors.push(
400
- createParamDescriptor({
401
- name: paramName,
402
- table: tableName,
403
- column: columnName,
404
- codecId,
405
- nativeType: columnMeta.nativeType,
406
- nullable: columnMeta.nullable
407
- })
408
- );
409
- updateSet[columnName] = createParamRef(index, paramName);
410
- }
411
- const whereResult = buildWhereExpr(
412
- wherePredicate,
413
- context.contract,
414
- paramsMap,
415
- paramDescriptors,
416
- paramValues
417
- );
418
- const whereExpr = whereResult.expr;
419
- if (!whereExpr) {
420
- errorFailedToBuildWhereClause();
421
- }
422
- if (whereResult?.codecId && whereResult.paramName) {
423
- paramCodecs[whereResult.paramName] = whereResult.codecId;
424
- }
425
- const ast = createUpdateAst({
426
- table,
427
- set: updateSet,
428
- where: whereExpr
429
- });
430
- return Object.freeze({
431
- ast,
432
- params: paramValues,
433
- meta: {
434
- target: context.contract.target,
435
- targetFamily: context.contract.targetFamily,
436
- coreHash: context.contract.coreHash,
437
- lane: "orm",
438
- refs: {
439
- tables: [tableName],
440
- columns: []
441
- },
442
- projection: {},
443
- paramDescriptors,
444
- ...Object.keys(paramCodecs).length > 0 ? {
445
- annotations: {
446
- codecs: paramCodecs,
447
- intent: "write",
448
- isMutation: true
449
- }
450
- } : {
451
- annotations: {
452
- intent: "write",
453
- isMutation: true
454
- }
455
- }
456
- }
457
- });
458
- }
459
-
460
- // src/orm-include-child.ts
461
- import { planInvalid as planInvalid2 } from "@prisma-next/plan";
462
- import { schema } from "@prisma-next/sql-relational-core/schema";
463
- var OrmIncludeChildBuilderImpl = class _OrmIncludeChildBuilderImpl {
464
- context;
465
- contract;
466
- childModelName;
467
- childWhere;
468
- childOrderBy;
469
- childLimit;
470
- childProjection = void 0;
471
- constructor(options, childModelName) {
472
- this.context = options.context;
473
- this.contract = options.context.contract;
474
- this.childModelName = childModelName;
475
- }
476
- where(fn) {
477
- const builder = new _OrmIncludeChildBuilderImpl(
478
- { context: this.context },
479
- this.childModelName
480
- );
481
- builder.childWhere = fn(this._getModelAccessor());
482
- builder.childOrderBy = this.childOrderBy;
483
- builder.childLimit = this.childLimit;
484
- builder.childProjection = this.childProjection;
485
- return builder;
486
- }
487
- orderBy(fn) {
488
- const builder = new _OrmIncludeChildBuilderImpl(
489
- { context: this.context },
490
- this.childModelName
491
- );
492
- builder.childWhere = this.childWhere;
493
- builder.childOrderBy = fn(this._getModelAccessor());
494
- builder.childLimit = this.childLimit;
495
- builder.childProjection = this.childProjection;
496
- return builder;
497
- }
498
- take(n) {
499
- const builder = new _OrmIncludeChildBuilderImpl(
500
- { context: this.context },
501
- this.childModelName
502
- );
503
- builder.childWhere = this.childWhere;
504
- builder.childOrderBy = this.childOrderBy;
505
- builder.childLimit = n;
506
- builder.childProjection = this.childProjection;
507
- return builder;
508
- }
509
- select(fn) {
510
- const builder = new _OrmIncludeChildBuilderImpl({ context: this.context }, this.childModelName);
511
- builder.childWhere = this.childWhere;
512
- builder.childOrderBy = this.childOrderBy;
513
- builder.childLimit = this.childLimit;
514
- builder.childProjection = fn(this._getModelAccessor());
515
- return builder;
516
- }
517
- getState() {
518
- return {
519
- ...this.childWhere !== void 0 ? { childWhere: this.childWhere } : {},
520
- ...this.childOrderBy !== void 0 ? { childOrderBy: this.childOrderBy } : {},
521
- ...this.childLimit !== void 0 ? { childLimit: this.childLimit } : {},
522
- ...this.childProjection !== void 0 ? { childProjection: this.childProjection } : {}
523
- };
524
- }
525
- _getModelAccessor() {
526
- const tableName = this.contract.mappings.modelToTable?.[this.childModelName];
527
- if (!tableName) {
528
- throw planInvalid2(`Model ${this.childModelName} not found in mappings`);
529
- }
530
- const schemaHandle = schema(this.context);
531
- const table = schemaHandle.tables[tableName];
532
- if (!table) {
533
- throw planInvalid2(`Table ${tableName} not found in schema`);
534
- }
535
- const accessor = {};
536
- const model = this.contract.models[this.childModelName];
537
- if (!model || typeof model !== "object" || !("fields" in model)) {
538
- throw planInvalid2(`Model ${this.childModelName} does not have fields`);
539
- }
540
- const modelFields = model.fields;
541
- for (const fieldName in modelFields) {
542
- const field = modelFields[fieldName];
543
- if (!field) continue;
544
- const columnName = this.contract.mappings.fieldToColumn?.[this.childModelName]?.[fieldName] ?? field.column ?? fieldName;
545
- const column = table.columns[columnName];
546
- if (column) {
547
- accessor[fieldName] = column;
548
- }
549
- }
550
- return accessor;
551
- }
552
- };
553
-
554
- // src/orm-relation-filter.ts
555
- import { planInvalid as planInvalid3 } from "@prisma-next/plan";
556
- import { schema as schema2 } from "@prisma-next/sql-relational-core/schema";
557
- var OrmRelationFilterBuilderImpl = class _OrmRelationFilterBuilderImpl {
558
- context;
559
- contract;
560
- childModelName;
561
- wherePredicate = void 0;
562
- modelAccessor = void 0;
563
- constructor(options, childModelName) {
564
- this.context = options.context;
565
- this.contract = options.context.contract;
566
- this.childModelName = childModelName;
567
- this.modelAccessor = this._getModelAccessor();
568
- }
569
- where(fn) {
570
- const builder = new _OrmRelationFilterBuilderImpl(
571
- { context: this.context },
572
- this.childModelName
573
- );
574
- builder.modelAccessor = this.modelAccessor;
575
- if (this.modelAccessor) {
576
- builder.wherePredicate = fn(this.modelAccessor);
577
- }
578
- return builder;
579
- }
580
- getWherePredicate() {
581
- return this.wherePredicate;
582
- }
583
- getChildModelName() {
584
- return this.childModelName;
585
- }
586
- getModelAccessor() {
587
- if (!this.modelAccessor) {
588
- this.modelAccessor = this._getModelAccessor();
589
- }
590
- if (!this.modelAccessor) {
591
- throw planInvalid3(`Failed to get model accessor for ${this.childModelName}`);
592
- }
593
- return this.modelAccessor;
594
- }
595
- _getModelAccessor() {
596
- const tableName = this.contract.mappings.modelToTable?.[this.childModelName];
597
- if (!tableName) {
598
- throw planInvalid3(`Model ${this.childModelName} not found in mappings`);
599
- }
600
- const schemaHandle = schema2(this.context);
601
- const table = schemaHandle.tables[tableName];
602
- if (!table) {
603
- throw planInvalid3(`Table ${tableName} not found in schema`);
604
- }
605
- const accessor = {};
606
- const model = this.contract.models[this.childModelName];
607
- if (!model || typeof model !== "object" || !("fields" in model)) {
608
- throw planInvalid3(`Model ${this.childModelName} does not have fields`);
609
- }
610
- const modelFields = model.fields;
611
- for (const fieldName in modelFields) {
612
- const field = modelFields[fieldName];
613
- if (!field) continue;
614
- const columnName = this.contract.mappings.fieldToColumn?.[this.childModelName]?.[fieldName] ?? field.column ?? fieldName;
615
- const column = table.columns[columnName];
616
- if (column) {
617
- accessor[fieldName] = column;
618
- }
619
- }
620
- return accessor;
621
- }
622
- };
623
-
624
- // src/plan/plan-assembly.ts
625
- import { planInvalid as planInvalid4 } from "@prisma-next/plan";
626
- import { compact } from "@prisma-next/sql-relational-core/ast";
627
- import {
628
- collectColumnRefs,
629
- getColumnInfo as getColumnInfo2,
630
- getColumnMeta as getColumnMeta2,
631
- isOperationExpr
632
- } from "@prisma-next/sql-relational-core/utils/guards";
633
- function buildMeta(args) {
634
- const refsColumns = /* @__PURE__ */ new Map();
635
- const refsTables = /* @__PURE__ */ new Set([args.table.name]);
636
- for (const column of args.projection.columns) {
637
- const operationExpr = column._operationExpr;
638
- if (operationExpr) {
639
- const allRefs = collectColumnRefs(operationExpr);
640
- for (const ref of allRefs) {
641
- refsColumns.set(`${ref.table}.${ref.column}`, {
642
- table: ref.table,
643
- column: ref.column
644
- });
645
- }
646
- } else {
647
- const col = column;
648
- if (col.table && col.column) {
649
- refsColumns.set(`${col.table}.${col.column}`, {
650
- table: col.table,
651
- column: col.column
652
- });
653
- }
654
- }
655
- }
656
- if (args.includes) {
657
- for (const include of args.includes) {
658
- refsTables.add(include.table.name);
659
- const onLeft = include.on.left;
660
- const onRight = include.on.right;
661
- if (onLeft.table && onLeft.column && onRight.table && onRight.column) {
662
- refsColumns.set(`${onLeft.table}.${onLeft.column}`, {
663
- table: onLeft.table,
664
- column: onLeft.column
665
- });
666
- refsColumns.set(`${onRight.table}.${onRight.column}`, {
667
- table: onRight.table,
668
- column: onRight.column
669
- });
670
- }
671
- for (const column of include.childProjection.columns) {
672
- const col = column;
673
- if (col.table && col.column) {
674
- refsColumns.set(`${col.table}.${col.column}`, {
675
- table: col.table,
676
- column: col.column
677
- });
678
- }
679
- }
680
- if (include.childWhere) {
681
- const colInfo = getColumnInfo2(include.childWhere.left);
682
- refsColumns.set(`${colInfo.table}.${colInfo.column}`, {
683
- table: colInfo.table,
684
- column: colInfo.column
685
- });
686
- }
687
- if (include.childOrderBy) {
688
- const orderBy = include.childOrderBy;
689
- if (orderBy.expr) {
690
- const colInfo = getColumnInfo2(orderBy.expr);
691
- refsColumns.set(`${colInfo.table}.${colInfo.column}`, {
692
- table: colInfo.table,
693
- column: colInfo.column
694
- });
695
- }
696
- }
697
- }
698
- }
699
- if (args.where) {
700
- const whereLeft = args.where.left;
701
- const operationExpr = whereLeft._operationExpr;
702
- if (operationExpr) {
703
- const allRefs = collectColumnRefs(operationExpr);
704
- for (const ref of allRefs) {
705
- refsColumns.set(`${ref.table}.${ref.column}`, {
706
- table: ref.table,
707
- column: ref.column
708
- });
709
- }
710
- } else {
711
- const colBuilder = whereLeft;
712
- if (colBuilder.table && colBuilder.column) {
713
- refsColumns.set(`${colBuilder.table}.${colBuilder.column}`, {
714
- table: colBuilder.table,
715
- column: colBuilder.column
716
- });
717
- }
718
- }
719
- }
720
- if (args.orderBy) {
721
- const orderBy = args.orderBy;
722
- const orderByExpr = orderBy.expr;
723
- if (orderByExpr) {
724
- if (isOperationExpr(orderByExpr)) {
725
- const allRefs = collectColumnRefs(orderByExpr);
726
- for (const ref of allRefs) {
727
- refsColumns.set(`${ref.table}.${ref.column}`, {
728
- table: ref.table,
729
- column: ref.column
730
- });
731
- }
732
- } else {
733
- const colBuilder = orderByExpr;
734
- if (colBuilder.table && colBuilder.column) {
735
- refsColumns.set(`${colBuilder.table}.${colBuilder.column}`, {
736
- table: colBuilder.table,
737
- column: colBuilder.column
738
- });
739
- }
740
- }
741
- }
742
- }
743
- const includeAliases = new Set(args.includes?.map((inc) => inc.alias) ?? []);
744
- const projectionMap = Object.fromEntries(
745
- args.projection.aliases.map((alias, index) => {
746
- if (includeAliases.has(alias)) {
747
- return [alias, `include:${alias}`];
748
- }
749
- const column = args.projection.columns[index];
750
- if (!column) {
751
- throw planInvalid4(`Missing column for alias ${alias} at index ${index}`);
752
- }
753
- const col = column;
754
- if (!col.table || !col.column) {
755
- return [alias, `include:${alias}`];
756
- }
757
- const operationExpr = col._operationExpr;
758
- if (operationExpr) {
759
- return [alias, `operation:${operationExpr.method}`];
760
- }
761
- return [alias, `${col.table}.${col.column}`];
762
- })
763
- );
764
- const projectionTypes = {};
765
- for (let i = 0; i < args.projection.aliases.length; i++) {
766
- const alias = args.projection.aliases[i];
767
- if (!alias || includeAliases.has(alias)) {
768
- continue;
769
- }
770
- const col = args.projection.columns[i];
771
- if (!col) {
772
- continue;
773
- }
774
- const operationExpr = col._operationExpr;
775
- if (operationExpr) {
776
- if (operationExpr.returns.kind === "typeId") {
777
- projectionTypes[alias] = operationExpr.returns.type;
778
- } else if (operationExpr.returns.kind === "builtin") {
779
- projectionTypes[alias] = operationExpr.returns.type;
780
- }
781
- } else {
782
- const columnMeta = getColumnMeta2(col);
783
- const codecId = columnMeta?.codecId;
784
- if (codecId) {
785
- projectionTypes[alias] = codecId;
786
- }
787
- }
788
- }
789
- const projectionCodecs = {};
790
- for (let i = 0; i < args.projection.aliases.length; i++) {
791
- const alias = args.projection.aliases[i];
792
- if (!alias || includeAliases.has(alias)) {
793
- continue;
794
- }
795
- const column = args.projection.columns[i];
796
- if (!column) {
797
- continue;
798
- }
799
- const operationExpr = column._operationExpr;
800
- if (operationExpr) {
801
- if (operationExpr.returns.kind === "typeId") {
802
- projectionCodecs[alias] = operationExpr.returns.type;
803
- }
804
- } else {
805
- const columnMeta = getColumnMeta2(column);
806
- const codecId = columnMeta?.codecId;
807
- if (codecId) {
808
- projectionCodecs[alias] = codecId;
809
- }
810
- }
811
- }
812
- const allCodecs = {
813
- ...projectionCodecs,
814
- ...args.paramCodecs ? args.paramCodecs : {}
815
- };
816
- return Object.freeze(
817
- compact({
818
- target: args.contract.target,
819
- targetFamily: args.contract.targetFamily,
820
- coreHash: args.contract.coreHash,
821
- lane: "dsl",
822
- refs: {
823
- tables: Array.from(refsTables),
824
- columns: Array.from(refsColumns.values())
825
- },
826
- projection: projectionMap,
827
- projectionTypes: Object.keys(projectionTypes).length > 0 ? projectionTypes : void 0,
828
- annotations: Object.keys(allCodecs).length > 0 ? Object.freeze({ codecs: Object.freeze(allCodecs) }) : void 0,
829
- paramDescriptors: args.paramDescriptors,
830
- profileHash: args.contract.profileHash
831
- })
832
- );
833
- }
834
-
835
- // src/relations/include-plan.ts
836
- import { compact as compact2 } from "@prisma-next/sql-relational-core/ast";
837
- import { schema as schema3 } from "@prisma-next/sql-relational-core/schema";
838
-
839
- // src/orm/capabilities.ts
840
- function checkIncludeCapabilities(contract) {
841
- const target = contract.target;
842
- const capabilities = contract.capabilities;
843
- if (!capabilities || !capabilities[target]) {
844
- errorIncludeRequiresCapabilities();
845
- }
846
- const targetCapabilities = capabilities[target];
847
- if (capabilities[target]["lateral"] !== true || targetCapabilities["jsonAgg"] !== true) {
848
- errorIncludeCapabilitiesNotTrue();
849
- }
850
- }
851
-
852
- // src/selection/join.ts
853
- function buildJoinOnExpr(parentTableName, parentColName, childTableName, childColName) {
854
- const leftCol = createColumnRef(parentTableName, parentColName);
855
- const rightCol = createColumnRef(childTableName, childColName);
856
- return createJoinOnExpr(leftCol, rightCol);
857
- }
858
-
859
- // src/selection/ordering.ts
860
- import {
861
- extractBaseColumnRef,
862
- isOperationExpr as isOperationExpr2
863
- } from "@prisma-next/sql-relational-core/utils/guards";
864
- function buildOrderByClause(orderBy) {
865
- if (!orderBy) {
866
- return void 0;
867
- }
868
- const orderByBuilder = orderBy;
869
- const orderExpr = orderByBuilder.expr;
870
- const expr = isOperationExpr2(orderExpr) ? orderExpr : (() => {
871
- const colBuilder = orderExpr;
872
- return createColumnRef(colBuilder.table, colBuilder.column);
873
- })();
874
- return [createOrderByItem(expr, orderByBuilder.dir)];
875
- }
876
- function buildChildOrderByClause(orderBy) {
877
- if (!orderBy) {
878
- return void 0;
879
- }
880
- const orderByBuilder = orderBy;
881
- const orderExpr = orderByBuilder.expr;
882
- const expr = (() => {
883
- if (isOperationExpr2(orderExpr)) {
884
- const baseCol = extractBaseColumnRef(orderExpr);
885
- return createColumnRef(baseCol.table, baseCol.column);
886
- }
887
- const colBuilder = orderExpr;
888
- return createColumnRef(colBuilder.table, colBuilder.column);
889
- })();
890
- return [createOrderByItem(expr, orderByBuilder.dir)];
891
- }
892
-
893
- // src/selection/projection.ts
894
- import { isColumnBuilder as isColumnBuilder2 } from "@prisma-next/sql-relational-core/utils/guards";
895
- function generateAlias(path) {
896
- if (path.length === 0) {
897
- errorAliasPathEmpty();
898
- }
899
- return path.join("_");
900
- }
901
- var AliasTracker = class {
902
- aliases = /* @__PURE__ */ new Set();
903
- aliasToPath = /* @__PURE__ */ new Map();
904
- register(path) {
905
- const alias = generateAlias(path);
906
- if (this.aliases.has(alias)) {
907
- const existingPath = this.aliasToPath.get(alias);
908
- errorAliasCollision(path, alias, existingPath);
909
- }
910
- this.aliases.add(alias);
911
- this.aliasToPath.set(alias, path);
912
- return alias;
913
- }
914
- getPath(alias) {
915
- return this.aliasToPath.get(alias);
916
- }
917
- has(alias) {
918
- return this.aliases.has(alias);
919
- }
920
- };
921
- function flattenProjection(projection, tracker, currentPath = []) {
922
- const aliases = [];
923
- const columns = [];
924
- for (const [key, value] of Object.entries(projection)) {
925
- const path = [...currentPath, key];
926
- if (isColumnBuilder2(value)) {
927
- const alias = tracker.register(path);
928
- aliases.push(alias);
929
- columns.push(value);
930
- } else if (typeof value === "object" && value !== null) {
931
- const nested = flattenProjection(value, tracker, path);
932
- aliases.push(...nested.aliases);
933
- columns.push(...nested.columns);
934
- } else {
935
- errorInvalidProjectionValue(path);
936
- }
937
- }
938
- return { aliases, columns };
939
- }
940
- function buildProjectionState(_table, projection, includes) {
941
- const tracker = new AliasTracker();
942
- const aliases = [];
943
- const columns = [];
944
- for (const [key, value] of Object.entries(projection)) {
945
- if (value === true) {
946
- const matchingInclude = includes?.find((inc) => inc.alias === key);
947
- if (!matchingInclude) {
948
- errorIncludeAliasNotFound(key);
949
- }
950
- aliases.push(key);
951
- columns.push({
952
- kind: "column",
953
- table: matchingInclude.table.name,
954
- column: "",
955
- columnMeta: {
956
- nativeType: "jsonb",
957
- codecId: "core/json@1",
958
- nullable: true
959
- }
960
- });
961
- } else if (isColumnBuilder2(value)) {
962
- const alias = tracker.register([key]);
963
- aliases.push(alias);
964
- columns.push(value);
965
- } else if (typeof value === "object" && value !== null) {
966
- const nested = flattenProjection(value, tracker, [key]);
967
- aliases.push(...nested.aliases);
968
- columns.push(...nested.columns);
969
- } else {
970
- errorInvalidProjectionKey(key);
971
- }
972
- }
973
- if (aliases.length === 0) {
974
- errorProjectionEmpty();
975
- }
976
- return { aliases, columns };
977
- }
978
-
979
- // src/relations/include-plan.ts
980
- function buildIncludeAsts(input) {
981
- const {
982
- includes,
983
- contract,
984
- context,
985
- modelName,
986
- paramsMap,
987
- paramDescriptors,
988
- paramValues,
989
- paramCodecs
990
- } = input;
991
- const includesAst = [];
992
- const includesForMeta = [];
993
- for (const includeState of includes) {
994
- checkIncludeCapabilities(contract);
995
- const parentTableName = contract.mappings.modelToTable?.[modelName];
996
- if (!parentTableName) {
997
- errorModelNotFound(modelName);
998
- }
999
- const parentSchemaHandle = schema3(context);
1000
- const parentSchemaTable = parentSchemaHandle.tables[parentTableName];
1001
- if (!parentSchemaTable) {
1002
- errorTableNotFound(parentTableName);
1003
- }
1004
- const childSchemaHandle = schema3(context);
1005
- const childSchemaTable = childSchemaHandle.tables[includeState.childTable.name];
1006
- if (!childSchemaTable) {
1007
- errorTableNotFound(includeState.childTable.name);
1008
- }
1009
- if (includeState.relation.on.parentCols.length !== 1 || includeState.relation.on.childCols.length !== 1) {
1010
- errorMultiColumnJoinsNotSupported();
1011
- }
1012
- const parentColName = includeState.relation.on.parentCols[0];
1013
- const childColName = includeState.relation.on.childCols[0];
1014
- if (!parentColName || !childColName) {
1015
- errorJoinColumnsMustBeDefined();
1016
- }
1017
- const parentCol = parentSchemaTable.columns[parentColName];
1018
- const childCol = childSchemaTable.columns[childColName];
1019
- if (!parentCol) {
1020
- errorColumnNotFound(parentColName, parentTableName);
1021
- }
1022
- if (!childCol) {
1023
- errorColumnNotFound(childColName, includeState.childTable.name);
1024
- }
1025
- const onExpr = buildJoinOnExpr(
1026
- parentTableName,
1027
- parentColName,
1028
- includeState.childTable.name,
1029
- childColName
1030
- );
1031
- if (!includeState.childProjection) {
1032
- errorChildProjectionMustBeSpecified();
1033
- }
1034
- const filteredProjection = {};
1035
- for (const [key, value] of Object.entries(includeState.childProjection)) {
1036
- if (value !== true && value !== false) {
1037
- filteredProjection[key] = value;
1038
- }
1039
- }
1040
- if (Object.keys(filteredProjection).length === 0) {
1041
- errorChildProjectionEmpty();
1042
- }
1043
- const childProjectionState = buildProjectionState(
1044
- includeState.childTable,
1045
- filteredProjection
1046
- );
1047
- let childWhere;
1048
- if (includeState.childWhere) {
1049
- const whereResult = buildWhereExpr(
1050
- includeState.childWhere,
1051
- contract,
1052
- paramsMap,
1053
- paramDescriptors,
1054
- paramValues
1055
- );
1056
- childWhere = whereResult.expr;
1057
- if (whereResult.codecId && whereResult.paramName) {
1058
- paramCodecs[whereResult.paramName] = whereResult.codecId;
1059
- }
1060
- }
1061
- const childOrderBy = buildChildOrderByClause(includeState.childOrderBy);
1062
- const childProjectionItems = [];
1063
- for (let i = 0; i < childProjectionState.aliases.length; i++) {
1064
- const alias = childProjectionState.aliases[i];
1065
- if (!alias) {
1066
- errorMissingAlias(i);
1067
- }
1068
- const column = childProjectionState.columns[i];
1069
- if (!column) {
1070
- errorMissingColumn(alias, i);
1071
- }
1072
- const operationExpr = column._operationExpr;
1073
- if (operationExpr) {
1074
- childProjectionItems.push({ alias, expr: operationExpr });
1075
- } else {
1076
- const col = column;
1077
- childProjectionItems.push({ alias, expr: createColumnRef(col.table, col.column) });
1078
- }
1079
- }
1080
- const includeAst = compact2({
1081
- kind: "includeMany",
1082
- alias: includeState.alias,
1083
- child: compact2({
1084
- table: includeState.childTable,
1085
- on: onExpr,
1086
- project: childProjectionItems,
1087
- where: childWhere,
1088
- orderBy: childOrderBy,
1089
- limit: includeState.childLimit
1090
- })
1091
- });
1092
- includesAst.push(includeAst);
1093
- const includeForMeta = compact2({
1094
- alias: includeState.alias,
1095
- table: includeState.childTable,
1096
- on: {
1097
- kind: "join-on",
1098
- left: parentCol,
1099
- right: childCol
1100
- },
1101
- childProjection: childProjectionState,
1102
- childWhere: includeState.childWhere,
1103
- childOrderBy: includeState.childOrderBy,
1104
- childLimit: includeState.childLimit
1105
- });
1106
- includesForMeta.push(includeForMeta);
1107
- }
1108
- return { includesAst, includesForMeta };
1109
- }
1110
- function buildExistsSubqueries(relationFilters, contract, modelName, options) {
1111
- const existsExprs = [];
1112
- for (const filter of relationFilters) {
1113
- const childTableName = contract.mappings.modelToTable?.[filter.childModelName];
1114
- if (!childTableName) {
1115
- errorModelNotFound(filter.childModelName);
1116
- }
1117
- const childTable = { kind: "table", name: childTableName };
1118
- const parentTableName = contract.mappings.modelToTable?.[modelName];
1119
- if (!parentTableName) {
1120
- errorModelNotFound(modelName);
1121
- }
1122
- const joinConditions = [];
1123
- for (let i = 0; i < filter.relation.on.parentCols.length; i++) {
1124
- const parentCol = filter.relation.on.parentCols[i];
1125
- const childCol = filter.relation.on.childCols[i];
1126
- if (!parentCol || !childCol) {
1127
- continue;
1128
- }
1129
- joinConditions.push({
1130
- left: { kind: "col", table: parentTableName, column: parentCol },
1131
- right: { kind: "col", table: childTableName, column: childCol }
1132
- });
1133
- }
1134
- let childWhere;
1135
- if (filter.childWhere) {
1136
- const paramsMap = options?.params ?? {};
1137
- const paramDescriptors = [];
1138
- const paramValues = [];
1139
- const whereResult = buildWhereExpr(
1140
- filter.childWhere,
1141
- contract,
1142
- paramsMap,
1143
- paramDescriptors,
1144
- paramValues
1145
- );
1146
- childWhere = whereResult.expr;
1147
- }
1148
- let subqueryWhere = childWhere;
1149
- if (joinConditions.length > 0) {
1150
- const firstJoinCondition = joinConditions[0];
1151
- if (firstJoinCondition) {
1152
- const joinWhere = {
1153
- kind: "bin",
1154
- op: "eq",
1155
- left: firstJoinCondition.left,
1156
- right: firstJoinCondition.right
1157
- };
1158
- if (childWhere) {
1159
- subqueryWhere = joinWhere;
1160
- } else {
1161
- subqueryWhere = joinWhere;
1162
- }
1163
- }
1164
- }
1165
- const projectionColumn = joinConditions[0]?.right ?? createColumnRef(childTableName, "id");
1166
- const subquery = createSelectAst({
1167
- from: childTable,
1168
- project: [{ alias: "_exists", expr: projectionColumn }],
1169
- where: subqueryWhere
1170
- });
1171
- const notExists = filter.filterType === "none" || filter.filterType === "every";
1172
- const existsExpr = {
1173
- kind: "exists",
1174
- subquery,
1175
- not: notExists
1176
- };
1177
- existsExprs.push(existsExpr);
1178
- }
1179
- return existsExprs;
1180
- }
1181
- function combineWhereClauses(mainWhere, existsExprs) {
1182
- if (existsExprs.length === 1) {
1183
- return existsExprs[0];
1184
- }
1185
- if (mainWhere) {
1186
- return mainWhere;
1187
- }
1188
- if (existsExprs.length > 0) {
1189
- return existsExprs[0];
1190
- }
1191
- return void 0;
1192
- }
1193
-
1194
- // src/selection/select-builder.ts
1195
- function buildProjectionItems(projectionState, includesForMeta) {
1196
- const projectEntries = [];
1197
- for (let i = 0; i < projectionState.aliases.length; i++) {
1198
- const alias = projectionState.aliases[i];
1199
- if (!alias) {
1200
- errorMissingAlias(i);
1201
- }
1202
- const column = projectionState.columns[i];
1203
- if (!column) {
1204
- errorMissingColumn(alias, i);
1205
- }
1206
- const matchingInclude = includesForMeta.find((inc) => inc.alias === alias);
1207
- if (matchingInclude) {
1208
- projectEntries.push({
1209
- alias,
1210
- expr: { kind: "includeRef", alias }
1211
- });
1212
- } else {
1213
- const operationExpr = column._operationExpr;
1214
- if (operationExpr) {
1215
- projectEntries.push({
1216
- alias,
1217
- expr: operationExpr
1218
- });
1219
- } else {
1220
- const col = column;
1221
- const tableName = col.table;
1222
- const columnName = col.column;
1223
- if (!tableName || !columnName) {
1224
- errorInvalidColumn(alias, i);
1225
- }
1226
- projectEntries.push({
1227
- alias,
1228
- expr: createColumnRef(tableName, columnName)
1229
- });
1230
- }
1231
- }
1232
- }
1233
- return projectEntries;
1234
- }
1235
- function buildSelectAst(params) {
1236
- const { table, projectEntries, includesAst, whereExpr, orderByClause, limit } = params;
1237
- return createSelectAst({
1238
- from: createTableRef(table.name),
1239
- project: projectEntries,
1240
- ...includesAst ? { includes: includesAst } : {},
1241
- ...whereExpr ? { where: whereExpr } : {},
1242
- ...orderByClause ? { orderBy: orderByClause } : {},
1243
- ...limit !== void 0 ? { limit } : {}
1244
- });
1245
- }
1246
-
1247
- // src/orm/context.ts
1248
- function createOrmContext(context) {
1249
- return context;
1250
- }
1251
-
1252
- // src/orm/builder.ts
1253
- var OrmModelBuilderImpl = class _OrmModelBuilderImpl {
1254
- context;
1255
- contract;
1256
- modelName;
1257
- table;
1258
- wherePredicate = void 0;
1259
- relationFilters = [];
1260
- includes = [];
1261
- orderByExpr = void 0;
1262
- limitValue = void 0;
1263
- offsetValue = void 0;
1264
- projection = void 0;
1265
- constructor(options, modelName) {
1266
- this.context = options.context;
1267
- this.contract = options.context.contract;
1268
- this.modelName = modelName;
1269
- const tableName = this.contract.mappings.modelToTable?.[modelName];
1270
- if (!tableName) {
1271
- errorModelNotFound(modelName);
1272
- }
1273
- const schemaHandle = schema4(options.context);
1274
- const table = schemaHandle.tables[tableName];
1275
- if (!table) {
1276
- errorTableNotFound(tableName);
1277
- }
1278
- this.table = table;
1279
- }
1280
- get where() {
1281
- const whereFn = (fn) => {
1282
- const builder = new _OrmModelBuilderImpl(
1283
- { context: this.context },
1284
- this.modelName
1285
- );
1286
- builder["table"] = this.table;
1287
- builder.wherePredicate = fn(this._getModelAccessor());
1288
- builder.relationFilters = this.relationFilters;
1289
- builder.includes = this.includes;
1290
- builder.orderByExpr = this.orderByExpr;
1291
- builder.limitValue = this.limitValue;
1292
- builder.offsetValue = this.offsetValue;
1293
- builder.projection = this.projection;
1294
- return builder;
1295
- };
1296
- const related = this._createRelatedProxy();
1297
- return Object.assign(whereFn, { related });
1298
- }
1299
- get include() {
1300
- return this._createIncludeProxy();
1301
- }
1302
- _createIncludeProxy() {
1303
- const self = this;
1304
- const tableName = this.contract.mappings.modelToTable?.[this.modelName];
1305
- if (!tableName) {
1306
- return {};
1307
- }
1308
- const modelRelations = this.contract.relations?.[tableName];
1309
- if (!modelRelations || typeof modelRelations !== "object") {
1310
- return {};
1311
- }
1312
- return new Proxy({}, {
1313
- get(_target, prop) {
1314
- if (typeof prop !== "string") {
1315
- return void 0;
1316
- }
1317
- const relation = modelRelations[prop];
1318
- if (!relation || typeof relation !== "object" || !("to" in relation)) {
1319
- throw planInvalid5(`Relation ${prop} not found on model ${self.modelName}`);
1320
- }
1321
- const childModelName = relation.to;
1322
- const relationDef = relation;
1323
- const relationName = prop;
1324
- const includeFn = ((child) => {
1325
- return self._applyInclude(
1326
- relationName,
1327
- childModelName,
1328
- child,
1329
- relationDef
1330
- );
1331
- });
1332
- return includeFn;
1333
- }
1334
- });
1335
- }
1336
- _applyInclude(relationName, childModelName, childBuilderFn, relationDef) {
1337
- const childTableName = this.contract.mappings.modelToTable?.[childModelName];
1338
- if (!childTableName) {
1339
- errorModelNotFound(childModelName);
1340
- }
1341
- const childTable = { kind: "table", name: childTableName };
1342
- const childBuilder = new OrmIncludeChildBuilderImpl(
1343
- { context: this.context },
1344
- childModelName
1345
- );
1346
- const builtChild = childBuilderFn(
1347
- childBuilder
1348
- );
1349
- const childState = builtChild.getState();
1350
- const includeState = {
1351
- relationName,
1352
- childModelName,
1353
- childTable,
1354
- childWhere: childState.childWhere,
1355
- childOrderBy: childState.childOrderBy,
1356
- childLimit: childState.childLimit,
1357
- childProjection: childState.childProjection,
1358
- alias: relationName,
1359
- relation: relationDef
1360
- };
1361
- const builder = new _OrmModelBuilderImpl({ context: this.context }, this.modelName);
1362
- builder["table"] = this.table;
1363
- builder.wherePredicate = this.wherePredicate;
1364
- builder.relationFilters = this.relationFilters;
1365
- builder.includes = [...this.includes, includeState];
1366
- builder.orderByExpr = this.orderByExpr;
1367
- builder.limitValue = this.limitValue;
1368
- builder.offsetValue = this.offsetValue;
1369
- builder.projection = this.projection;
1370
- return builder;
1371
- }
1372
- _createRelatedProxy() {
1373
- const self = this;
1374
- const tableName = this.contract.mappings.modelToTable?.[this.modelName];
1375
- if (!tableName) {
1376
- return {};
1377
- }
1378
- const modelRelations = this.contract.relations?.[tableName];
1379
- if (!modelRelations || typeof modelRelations !== "object") {
1380
- return {};
1381
- }
1382
- return new Proxy(
1383
- {},
1384
- {
1385
- get(_target, prop) {
1386
- if (typeof prop !== "string") {
1387
- return void 0;
1388
- }
1389
- const relation = modelRelations[prop];
1390
- if (!relation || typeof relation !== "object" || !("to" in relation)) {
1391
- throw planInvalid5(`Relation ${prop} not found on model ${self.modelName}`);
1392
- }
1393
- const childModelName = relation.to;
1394
- const relationDef = relation;
1395
- const filterBuilder = new OrmRelationFilterBuilderImpl({ context: self.context }, childModelName);
1396
- const modelAccessor = filterBuilder.getModelAccessor();
1397
- const builderWithAccessor = Object.assign(
1398
- filterBuilder,
1399
- modelAccessor
1400
- );
1401
- return {
1402
- some: (fn) => {
1403
- const result = fn(builderWithAccessor);
1404
- if (result && "kind" in result && result.kind === "binary") {
1405
- const wrappedBuilder = new OrmRelationFilterBuilderImpl({ context: self.context }, childModelName);
1406
- wrappedBuilder["wherePredicate"] = result;
1407
- return self._applyRelationFilter(
1408
- prop,
1409
- childModelName,
1410
- "some",
1411
- () => wrappedBuilder,
1412
- relationDef
1413
- );
1414
- }
1415
- return self._applyRelationFilter(
1416
- prop,
1417
- childModelName,
1418
- "some",
1419
- () => result,
1420
- relationDef
1421
- );
1422
- },
1423
- none: (fn) => {
1424
- const result = fn(builderWithAccessor);
1425
- if (result && "kind" in result && result.kind === "binary") {
1426
- const wrappedBuilder = new OrmRelationFilterBuilderImpl({ context: self.context }, childModelName);
1427
- wrappedBuilder["wherePredicate"] = result;
1428
- return self._applyRelationFilter(
1429
- prop,
1430
- childModelName,
1431
- "none",
1432
- () => wrappedBuilder,
1433
- relationDef
1434
- );
1435
- }
1436
- return self._applyRelationFilter(
1437
- prop,
1438
- childModelName,
1439
- "none",
1440
- () => result,
1441
- relationDef
1442
- );
1443
- },
1444
- every: (fn) => {
1445
- const result = fn(builderWithAccessor);
1446
- if (result && "kind" in result && result.kind === "binary") {
1447
- const wrappedBuilder = new OrmRelationFilterBuilderImpl({ context: self.context }, childModelName);
1448
- wrappedBuilder["wherePredicate"] = result;
1449
- return self._applyRelationFilter(
1450
- prop,
1451
- childModelName,
1452
- "every",
1453
- () => wrappedBuilder,
1454
- relationDef
1455
- );
1456
- }
1457
- return self._applyRelationFilter(
1458
- prop,
1459
- childModelName,
1460
- "every",
1461
- () => result,
1462
- relationDef
1463
- );
1464
- }
1465
- };
1466
- }
1467
- }
1468
- );
1469
- }
1470
- _applyRelationFilter(relationName, childModelName, filterType, fn, relationDef) {
1471
- const filterBuilder = new OrmRelationFilterBuilderImpl(
1472
- { context: this.context },
1473
- childModelName
1474
- );
1475
- const appliedFilter = fn(
1476
- filterBuilder
1477
- );
1478
- const childWhere = appliedFilter.getWherePredicate();
1479
- const relationFilter = {
1480
- relationName,
1481
- childModelName,
1482
- filterType,
1483
- childWhere,
1484
- relation: relationDef
1485
- };
1486
- const builder = new _OrmModelBuilderImpl(
1487
- { context: this.context },
1488
- this.modelName
1489
- );
1490
- builder["table"] = this.table;
1491
- builder.wherePredicate = this.wherePredicate;
1492
- builder.relationFilters = [...this.relationFilters, relationFilter];
1493
- builder.includes = this.includes;
1494
- builder.orderByExpr = this.orderByExpr;
1495
- builder.limitValue = this.limitValue;
1496
- builder.offsetValue = this.offsetValue;
1497
- builder.projection = this.projection;
1498
- return builder;
1499
- }
1500
- orderBy(fn) {
1501
- const builder = new _OrmModelBuilderImpl(
1502
- { context: this.context },
1503
- this.modelName
1504
- );
1505
- builder["table"] = this.table;
1506
- builder.wherePredicate = this.wherePredicate;
1507
- builder.relationFilters = this.relationFilters;
1508
- builder.includes = this.includes;
1509
- builder.orderByExpr = fn(this._getModelAccessor());
1510
- builder.limitValue = this.limitValue;
1511
- builder.offsetValue = this.offsetValue;
1512
- builder.projection = this.projection;
1513
- return builder;
1514
- }
1515
- take(n) {
1516
- const builder = new _OrmModelBuilderImpl(
1517
- { context: this.context },
1518
- this.modelName
1519
- );
1520
- builder["table"] = this.table;
1521
- builder.wherePredicate = this.wherePredicate;
1522
- builder.relationFilters = this.relationFilters;
1523
- builder.includes = this.includes;
1524
- builder.orderByExpr = this.orderByExpr;
1525
- builder.limitValue = n;
1526
- builder.offsetValue = this.offsetValue;
1527
- builder.projection = this.projection;
1528
- return builder;
1529
- }
1530
- skip(n) {
1531
- const builder = new _OrmModelBuilderImpl(
1532
- { context: this.context },
1533
- this.modelName
1534
- );
1535
- builder["table"] = this.table;
1536
- builder.wherePredicate = this.wherePredicate;
1537
- builder.relationFilters = this.relationFilters;
1538
- builder.includes = this.includes;
1539
- builder.orderByExpr = this.orderByExpr;
1540
- builder.limitValue = this.limitValue;
1541
- builder.offsetValue = n;
1542
- builder.projection = this.projection;
1543
- return builder;
1544
- }
1545
- select(fn) {
1546
- const builder = new _OrmModelBuilderImpl({ context: this.context }, this.modelName);
1547
- builder["table"] = this.table;
1548
- builder.wherePredicate = this.wherePredicate;
1549
- builder.relationFilters = this.relationFilters;
1550
- builder.includes = this.includes;
1551
- builder.orderByExpr = this.orderByExpr;
1552
- builder.limitValue = this.limitValue;
1553
- builder.offsetValue = this.offsetValue;
1554
- builder.projection = fn(this._getModelAccessor());
1555
- return builder;
1556
- }
1557
- findMany(options) {
1558
- const paramsMap = options?.params ?? {};
1559
- const contractTable = this.contract.storage.tables[this.table.name];
1560
- if (!contractTable) {
1561
- errorUnknownTable(this.table.name);
1562
- }
1563
- const paramDescriptors = [];
1564
- const paramValues = [];
1565
- const paramCodecs = {};
1566
- const projectionInput = this.projection ?? (() => {
1567
- const modelAccessor = this._getModelAccessor();
1568
- const defaultProjection = {};
1569
- for (const fieldName in modelAccessor) {
1570
- defaultProjection[fieldName] = modelAccessor[fieldName];
1571
- }
1572
- return defaultProjection;
1573
- })();
1574
- const { includesAst, includesForMeta } = buildIncludeAsts({
1575
- includes: this.includes,
1576
- contract: this.contract,
1577
- context: this.context,
1578
- modelName: this.modelName,
1579
- paramsMap,
1580
- paramDescriptors,
1581
- paramValues,
1582
- paramCodecs
1583
- });
1584
- const projectionState = buildProjectionState(
1585
- this.table,
1586
- projectionInput,
1587
- includesForMeta.length > 0 ? includesForMeta : void 0
1588
- );
1589
- const whereResult = this.wherePredicate ? buildWhereExpr(this.wherePredicate, this.contract, paramsMap, paramDescriptors, paramValues) : void 0;
1590
- const whereExpr = whereResult?.expr;
1591
- if (whereResult?.codecId && whereResult.paramName) {
1592
- paramCodecs[whereResult.paramName] = whereResult.codecId;
1593
- }
1594
- const orderByClause = buildOrderByClause(this.orderByExpr);
1595
- const projectEntries = buildProjectionItems(projectionState, includesForMeta);
1596
- const ast = buildSelectAst({
1597
- table: this.table,
1598
- projectEntries,
1599
- ...includesAst.length > 0 ? { includesAst } : {},
1600
- ...whereExpr ? { whereExpr } : {},
1601
- ...orderByClause ? { orderByClause } : {},
1602
- ...this.limitValue !== void 0 ? { limit: this.limitValue } : {}
1603
- });
1604
- const planMeta = buildMeta({
1605
- contract: this.contract,
1606
- table: createTableRef(this.table.name),
1607
- projection: projectionState,
1608
- includes: includesForMeta.length > 0 ? includesForMeta : void 0,
1609
- paramDescriptors,
1610
- paramCodecs: Object.keys(paramCodecs).length > 0 ? paramCodecs : void 0,
1611
- where: this.wherePredicate,
1612
- orderBy: this.orderByExpr
1613
- });
1614
- if (this.relationFilters.length > 0) {
1615
- const existsExprs = buildExistsSubqueries(
1616
- this.relationFilters,
1617
- this.contract,
1618
- this.modelName,
1619
- options
1620
- );
1621
- if (existsExprs.length > 0) {
1622
- const combinedWhere = combineWhereClauses(ast.where, existsExprs);
1623
- const modifiedAst = {
1624
- ...ast,
1625
- ...combinedWhere !== void 0 ? { where: combinedWhere } : {}
1626
- };
1627
- return Object.freeze({
1628
- ast: modifiedAst,
1629
- params: paramValues,
1630
- meta: {
1631
- ...planMeta,
1632
- lane: "orm"
1633
- }
1634
- });
1635
- }
1636
- }
1637
- return Object.freeze({
1638
- ast,
1639
- params: paramValues,
1640
- meta: {
1641
- ...planMeta,
1642
- lane: "orm"
1643
- }
1644
- });
1645
- }
1646
- findFirst(options) {
1647
- const queryPlan = this.take(1).findMany(options);
1648
- return queryPlan;
1649
- }
1650
- findUnique(where, options) {
1651
- return this.where(where).take(1).findMany(options);
1652
- }
1653
- create(data, options) {
1654
- const context = createOrmContext(this.context);
1655
- return buildInsertPlan(context, this.modelName, data, options);
1656
- }
1657
- update(where, data, options) {
1658
- const context = createOrmContext(this.context);
1659
- return buildUpdatePlan(
1660
- context,
1661
- this.modelName,
1662
- where,
1663
- () => this._getModelAccessor(),
1664
- data,
1665
- options
1666
- );
1667
- }
1668
- delete(where, options) {
1669
- const context = createOrmContext(this.context);
1670
- return buildDeletePlan(
1671
- context,
1672
- this.modelName,
1673
- where,
1674
- () => this._getModelAccessor(),
1675
- options
1676
- );
1677
- }
1678
- _getModelAccessor() {
1679
- const tableName = this.contract.mappings.modelToTable?.[this.modelName];
1680
- if (!tableName) {
1681
- errorModelNotFound(this.modelName);
1682
- }
1683
- const schemaHandle = schema4(this.context);
1684
- const table = schemaHandle.tables[tableName];
1685
- if (!table) {
1686
- errorTableNotFound(tableName);
1687
- }
1688
- const accessor = {};
1689
- const model = this.contract.models[this.modelName];
1690
- if (!model || typeof model !== "object" || !("fields" in model)) {
1691
- throw planInvalid5(`Model ${this.modelName} does not have fields`);
1692
- }
1693
- const modelFields = model.fields;
1694
- for (const fieldName in modelFields) {
1695
- const field = modelFields[fieldName];
1696
- if (!field) continue;
1697
- const columnName = this.contract.mappings.fieldToColumn?.[this.modelName]?.[fieldName] ?? field.column ?? fieldName;
1698
- const column = table.columns[columnName];
1699
- if (column) {
1700
- accessor[fieldName] = column;
1701
- }
1702
- }
1703
- return accessor;
1704
- }
1705
- };
1706
-
1707
- // src/orm.ts
1708
- import { planInvalid as planInvalid6 } from "@prisma-next/plan";
1709
- function orm(options) {
1710
- const contract = options.context.contract;
1711
- return new Proxy({}, {
1712
- get(_target, prop) {
1713
- if (typeof prop !== "string") {
1714
- return void 0;
1715
- }
1716
- const modelName = prop.charAt(0).toUpperCase() + prop.slice(1);
1717
- if (!contract.models || typeof contract.models !== "object" || !(modelName in contract.models)) {
1718
- throw planInvalid6(`Model ${prop} (resolved to ${modelName}) not found in contract`);
1719
- }
1720
- return () => new OrmModelBuilderImpl(options, modelName);
1721
- },
1722
- has(_target, prop) {
1723
- if (typeof prop !== "string") {
1724
- return false;
1725
- }
1726
- const modelName = prop.charAt(0).toUpperCase() + prop.slice(1);
1727
- return contract.models && typeof contract.models === "object" && modelName in contract.models;
1728
- }
1729
- });
1730
- }
1731
-
1732
- export {
1733
- OrmModelBuilderImpl,
1734
- orm
1735
- };
1736
- //# sourceMappingURL=chunk-3DNKIXXB.js.map