@prisma-next/adapter-postgres 0.4.1 → 0.5.0-dev.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 (48) hide show
  1. package/dist/adapter-hNElNHo4.mjs +60 -0
  2. package/dist/adapter-hNElNHo4.mjs.map +1 -0
  3. package/dist/adapter.d.mts +2 -8
  4. package/dist/adapter.d.mts.map +1 -1
  5. package/dist/adapter.mjs +1 -1
  6. package/dist/column-types.mjs +1 -1
  7. package/dist/column-types.mjs.map +1 -1
  8. package/dist/control.d.mts +3 -70
  9. package/dist/control.d.mts.map +1 -1
  10. package/dist/control.mjs +19 -160
  11. package/dist/control.mjs.map +1 -1
  12. package/dist/{descriptor-meta-BB9XPAFi.mjs → descriptor-meta-RTDzyrae.mjs} +7 -7
  13. package/dist/descriptor-meta-RTDzyrae.mjs.map +1 -0
  14. package/dist/runtime.d.mts +1 -1
  15. package/dist/runtime.mjs +7 -7
  16. package/dist/runtime.mjs.map +1 -1
  17. package/dist/{adapter-Du9Hr9Rl.mjs → sql-renderer-pEaSP82_.mjs} +102 -100
  18. package/dist/sql-renderer-pEaSP82_.mjs.map +1 -0
  19. package/dist/{types-TyL62f9Y.d.mts → types-CfRPdAk8.d.mts} +1 -1
  20. package/dist/{types-TyL62f9Y.d.mts.map → types-CfRPdAk8.d.mts.map} +1 -1
  21. package/dist/types.d.mts +1 -1
  22. package/package.json +21 -16
  23. package/src/core/adapter.ts +4 -625
  24. package/src/core/control-adapter.ts +21 -47
  25. package/src/core/descriptor-meta.ts +5 -5
  26. package/src/core/enum-control-hooks.ts +7 -2
  27. package/src/core/json-schema-validator.ts +2 -1
  28. package/src/core/sql-renderer.ts +710 -0
  29. package/src/exports/column-types.ts +1 -1
  30. package/src/exports/control.ts +9 -4
  31. package/src/exports/runtime.ts +3 -3
  32. package/dist/adapter-Du9Hr9Rl.mjs.map +0 -1
  33. package/dist/codec-ids-5g4Gwrgm.mjs +0 -29
  34. package/dist/codec-ids-5g4Gwrgm.mjs.map +0 -1
  35. package/dist/codec-types.d.mts +0 -107
  36. package/dist/codec-types.d.mts.map +0 -1
  37. package/dist/codec-types.mjs +0 -3
  38. package/dist/codecs-DiPlMi3-.mjs +0 -385
  39. package/dist/codecs-DiPlMi3-.mjs.map +0 -1
  40. package/dist/descriptor-meta-BB9XPAFi.mjs.map +0 -1
  41. package/dist/sql-utils-DkUJyZmA.mjs +0 -78
  42. package/dist/sql-utils-DkUJyZmA.mjs.map +0 -1
  43. package/src/core/codec-ids.ts +0 -30
  44. package/src/core/codecs.ts +0 -645
  45. package/src/core/default-normalizer.ts +0 -145
  46. package/src/core/json-schema-type-expression.ts +0 -131
  47. package/src/core/sql-utils.ts +0 -111
  48. package/src/exports/codec-types.ts +0 -44
@@ -0,0 +1,710 @@
1
+ import {
2
+ type AggregateExpr,
3
+ type AnyExpression,
4
+ type AnyFromSource,
5
+ type AnyQueryAst,
6
+ type BinaryExpr,
7
+ type ColumnRef,
8
+ type DeleteAst,
9
+ type InsertAst,
10
+ type InsertValue,
11
+ type JoinAst,
12
+ type JoinOnExpr,
13
+ type JsonArrayAggExpr,
14
+ type JsonObjectExpr,
15
+ type ListExpression,
16
+ LiteralExpr,
17
+ type NullCheckExpr,
18
+ type OperationExpr,
19
+ type OrderByItem,
20
+ type ParamRef,
21
+ type ProjectionItem,
22
+ type SelectAst,
23
+ type SubqueryExpr,
24
+ type UpdateAst,
25
+ } from '@prisma-next/sql-relational-core/ast';
26
+ import { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from '@prisma-next/target-postgres/codec-ids';
27
+ import { escapeLiteral, quoteIdentifier } from '@prisma-next/target-postgres/sql-utils';
28
+ import type { PostgresContract } from './types';
29
+
30
+ // Mirrors `VECTOR_CODEC_ID` in `@prisma-next/extension-pgvector/core/constants`.
31
+ // Duplicated here rather than imported because the canonical export is not
32
+ // part of the extension's public subpath surface, and `@prisma-next/adapter-postgres`
33
+ // does not (and should not) take a runtime dependency on the extension package
34
+ // just for one constant. The whole `getCodecParamCast` switch is slated for
35
+ // removal under TML-2310 ("Move SQL param-cast metadata onto codec descriptors"),
36
+ // at which point this and the JSON/JSONB IDs below also disappear.
37
+ const VECTOR_CODEC_ID = 'pg/vector@1' as const;
38
+
39
+ /**
40
+ * Map a codec ID to its `::cast` suffix, if Postgres requires one for
41
+ * parameterized values (e.g. `$1::vector`, `$1::jsonb`).
42
+ *
43
+ * NOTE: hardcoded codec IDs here are a known wart, tracked separately by
44
+ * TML-2310 ("Move SQL param-cast metadata onto codec descriptors").
45
+ * Until that lands the cast lives on the renderer rather than the codec.
46
+ */
47
+ function getCodecParamCast(codecId: string | undefined): string | undefined {
48
+ if (codecId === VECTOR_CODEC_ID) {
49
+ return 'vector';
50
+ }
51
+ if (codecId === PG_JSON_CODEC_ID) {
52
+ return 'json';
53
+ }
54
+ if (codecId === PG_JSONB_CODEC_ID) {
55
+ return 'jsonb';
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ function renderTypedParam(index: number, codecId: string | undefined): string {
61
+ const cast = getCodecParamCast(codecId);
62
+ return cast ? `$${index}::${cast}` : `$${index}`;
63
+ }
64
+
65
+ type ParamIndexMap = Map<ParamRef, number>;
66
+
67
+ /**
68
+ * Render a SQL query AST to a Postgres-flavored `{ sql, params }` payload.
69
+ *
70
+ * Shared between the runtime (`PostgresAdapterImpl.lower`) and control
71
+ * (`PostgresControlAdapter.lower`) entrypoints so emit-time and run-time
72
+ * paths produce byte-identical output for the same AST.
73
+ */
74
+ export function renderLoweredSql(
75
+ ast: AnyQueryAst,
76
+ contract: PostgresContract,
77
+ ): { readonly sql: string; readonly params: readonly unknown[] } {
78
+ const collectedParamRefs = ast.collectParamRefs();
79
+ const paramIndexMap: ParamIndexMap = new Map();
80
+ const params: unknown[] = [];
81
+ for (const ref of collectedParamRefs) {
82
+ if (paramIndexMap.has(ref)) {
83
+ continue;
84
+ }
85
+ paramIndexMap.set(ref, params.length + 1);
86
+ params.push(ref.value);
87
+ }
88
+
89
+ const node = ast;
90
+ let sql: string;
91
+ switch (node.kind) {
92
+ case 'select':
93
+ sql = renderSelect(node, contract, paramIndexMap);
94
+ break;
95
+ case 'insert':
96
+ sql = renderInsert(node, contract, paramIndexMap);
97
+ break;
98
+ case 'update':
99
+ sql = renderUpdate(node, contract, paramIndexMap);
100
+ break;
101
+ case 'delete':
102
+ sql = renderDelete(node, contract, paramIndexMap);
103
+ break;
104
+ // v8 ignore next 4
105
+ default:
106
+ throw new Error(
107
+ `Unsupported AST node kind: ${(node satisfies never as { kind: string }).kind}`,
108
+ );
109
+ }
110
+
111
+ return Object.freeze({ sql, params: Object.freeze(params) });
112
+ }
113
+
114
+ function renderSelect(ast: SelectAst, contract: PostgresContract, pim: ParamIndexMap): string {
115
+ const selectClause = `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(
116
+ ast.projection,
117
+ contract,
118
+ pim,
119
+ )}`;
120
+ const fromClause = `FROM ${renderSource(ast.from, contract, pim)}`;
121
+
122
+ const joinsClause = ast.joins?.length
123
+ ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(' ')
124
+ : '';
125
+
126
+ const whereClause = ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : '';
127
+ const groupByClause = ast.groupBy?.length
128
+ ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(', ')}`
129
+ : '';
130
+ const havingClause = ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : '';
131
+ const orderClause = ast.orderBy?.length
132
+ ? `ORDER BY ${ast.orderBy
133
+ .map((order) => {
134
+ const expr = renderExpr(order.expr, contract, pim);
135
+ return `${expr} ${order.dir.toUpperCase()}`;
136
+ })
137
+ .join(', ')}`
138
+ : '';
139
+ const limitClause = typeof ast.limit === 'number' ? `LIMIT ${ast.limit}` : '';
140
+ const offsetClause = typeof ast.offset === 'number' ? `OFFSET ${ast.offset}` : '';
141
+
142
+ const clauses = [
143
+ selectClause,
144
+ fromClause,
145
+ joinsClause,
146
+ whereClause,
147
+ groupByClause,
148
+ havingClause,
149
+ orderClause,
150
+ limitClause,
151
+ offsetClause,
152
+ ]
153
+ .filter((part) => part.length > 0)
154
+ .join(' ');
155
+ return clauses.trim();
156
+ }
157
+
158
+ function renderProjection(
159
+ projection: ReadonlyArray<ProjectionItem>,
160
+ contract: PostgresContract,
161
+ pim: ParamIndexMap,
162
+ ): string {
163
+ return projection
164
+ .map((item) => {
165
+ const alias = quoteIdentifier(item.alias);
166
+ if (item.expr.kind === 'literal') {
167
+ return `${renderLiteral(item.expr)} AS ${alias}`;
168
+ }
169
+ return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;
170
+ })
171
+ .join(', ');
172
+ }
173
+
174
+ function renderDistinctPrefix(
175
+ distinct: true | undefined,
176
+ distinctOn: ReadonlyArray<AnyExpression> | undefined,
177
+ contract: PostgresContract,
178
+ pim: ParamIndexMap,
179
+ ): string {
180
+ if (distinctOn && distinctOn.length > 0) {
181
+ const rendered = distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(', ');
182
+ return `DISTINCT ON (${rendered}) `;
183
+ }
184
+ if (distinct) {
185
+ return 'DISTINCT ';
186
+ }
187
+ return '';
188
+ }
189
+
190
+ function renderSource(
191
+ source: AnyFromSource,
192
+ contract: PostgresContract,
193
+ pim: ParamIndexMap,
194
+ ): string {
195
+ const node = source;
196
+ switch (node.kind) {
197
+ case 'table-source': {
198
+ const table = quoteIdentifier(node.name);
199
+ if (!node.alias) {
200
+ return table;
201
+ }
202
+ return `${table} AS ${quoteIdentifier(node.alias)}`;
203
+ }
204
+ case 'derived-table-source':
205
+ return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;
206
+ // v8 ignore next 4
207
+ default:
208
+ throw new Error(
209
+ `Unsupported source node kind: ${(node satisfies never as { kind: string }).kind}`,
210
+ );
211
+ }
212
+ }
213
+
214
+ function assertScalarSubquery(query: SelectAst): void {
215
+ if (query.projection.length !== 1) {
216
+ throw new Error('Subquery expressions must project exactly one column');
217
+ }
218
+ }
219
+
220
+ function renderSubqueryExpr(
221
+ expr: SubqueryExpr,
222
+ contract: PostgresContract,
223
+ pim: ParamIndexMap,
224
+ ): string {
225
+ assertScalarSubquery(expr.query);
226
+ return `(${renderSelect(expr.query, contract, pim)})`;
227
+ }
228
+
229
+ function renderWhere(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {
230
+ return renderExpr(expr, contract, pim);
231
+ }
232
+
233
+ function renderNullCheck(
234
+ expr: NullCheckExpr,
235
+ contract: PostgresContract,
236
+ pim: ParamIndexMap,
237
+ ): string {
238
+ const rendered = renderExpr(expr.expr, contract, pim);
239
+ const renderedExpr = isAtomicExpressionKind(expr.expr.kind) ? rendered : `(${rendered})`;
240
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
241
+ }
242
+
243
+ /**
244
+ * Atomic expression kinds whose rendered SQL is already self-delimited
245
+ * (a column reference, parameter, literal, function call, aggregate, etc.)
246
+ * and therefore does not need surrounding parentheses when used as the
247
+ * left operand of a postfix predicate like `IS NULL` or `IS NOT NULL`,
248
+ * or as either operand of a binary infix operator.
249
+ *
250
+ * Anything not in this set is treated as composite (binary, AND/OR/NOT,
251
+ * EXISTS, nested IS NULL, subqueries, operation templates) and gets
252
+ * wrapped to preserve grouping.
253
+ */
254
+ function isAtomicExpressionKind(kind: AnyExpression['kind']): boolean {
255
+ switch (kind) {
256
+ case 'column-ref':
257
+ case 'identifier-ref':
258
+ case 'param-ref':
259
+ case 'literal':
260
+ case 'aggregate':
261
+ case 'json-object':
262
+ case 'json-array-agg':
263
+ case 'list':
264
+ return true;
265
+ case 'subquery':
266
+ case 'operation':
267
+ case 'binary':
268
+ case 'and':
269
+ case 'or':
270
+ case 'exists':
271
+ case 'null-check':
272
+ case 'not':
273
+ return false;
274
+ }
275
+ }
276
+
277
+ function renderBinary(expr: BinaryExpr, contract: PostgresContract, pim: ParamIndexMap): string {
278
+ if (expr.right.kind === 'list' && expr.right.values.length === 0) {
279
+ if (expr.op === 'in') {
280
+ return 'FALSE';
281
+ }
282
+ if (expr.op === 'notIn') {
283
+ return 'TRUE';
284
+ }
285
+ }
286
+
287
+ const leftExpr = expr.left;
288
+ const left = renderExpr(leftExpr, contract, pim);
289
+ const leftRendered =
290
+ leftExpr.kind === 'operation' || leftExpr.kind === 'subquery' ? `(${left})` : left;
291
+
292
+ const rightNode = expr.right;
293
+ let right: string;
294
+ switch (rightNode.kind) {
295
+ case 'list':
296
+ right = renderListLiteral(rightNode, contract, pim);
297
+ break;
298
+ case 'literal':
299
+ right = renderLiteral(rightNode);
300
+ break;
301
+ case 'column-ref':
302
+ right = renderColumn(rightNode);
303
+ break;
304
+ case 'param-ref':
305
+ right = renderParamRef(rightNode, pim);
306
+ break;
307
+ default:
308
+ right = renderExpr(rightNode, contract, pim);
309
+ break;
310
+ }
311
+
312
+ const operatorMap: Record<BinaryExpr['op'], string> = {
313
+ eq: '=',
314
+ neq: '!=',
315
+ gt: '>',
316
+ lt: '<',
317
+ gte: '>=',
318
+ lte: '<=',
319
+ like: 'LIKE',
320
+ in: 'IN',
321
+ notIn: 'NOT IN',
322
+ };
323
+
324
+ return `${leftRendered} ${operatorMap[expr.op]} ${right}`;
325
+ }
326
+
327
+ function renderListLiteral(
328
+ expr: ListExpression,
329
+ contract: PostgresContract,
330
+ pim: ParamIndexMap,
331
+ ): string {
332
+ if (expr.values.length === 0) {
333
+ return '(NULL)';
334
+ }
335
+ const values = expr.values
336
+ .map((v) => {
337
+ if (v.kind === 'param-ref') return renderParamRef(v, pim);
338
+ if (v.kind === 'literal') return renderLiteral(v);
339
+ return renderExpr(v, contract, pim);
340
+ })
341
+ .join(', ');
342
+ return `(${values})`;
343
+ }
344
+
345
+ function renderColumn(ref: ColumnRef): string {
346
+ if (ref.table === 'excluded') {
347
+ return `excluded.${quoteIdentifier(ref.column)}`;
348
+ }
349
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
350
+ }
351
+
352
+ function renderAggregateExpr(
353
+ expr: AggregateExpr,
354
+ contract: PostgresContract,
355
+ pim: ParamIndexMap,
356
+ ): string {
357
+ const fn = expr.fn.toUpperCase();
358
+ if (!expr.expr) {
359
+ return `${fn}(*)`;
360
+ }
361
+ return `${fn}(${renderExpr(expr.expr, contract, pim)})`;
362
+ }
363
+
364
+ function renderJsonObjectExpr(
365
+ expr: JsonObjectExpr,
366
+ contract: PostgresContract,
367
+ pim: ParamIndexMap,
368
+ ): string {
369
+ const args = expr.entries
370
+ .flatMap((entry): [string, string] => {
371
+ const key = `'${escapeLiteral(entry.key)}'`;
372
+ if (entry.value.kind === 'literal') {
373
+ return [key, renderLiteral(entry.value)];
374
+ }
375
+ return [key, renderExpr(entry.value, contract, pim)];
376
+ })
377
+ .join(', ');
378
+ return `json_build_object(${args})`;
379
+ }
380
+
381
+ function renderOrderByItems(
382
+ items: ReadonlyArray<OrderByItem>,
383
+ contract: PostgresContract,
384
+ pim: ParamIndexMap,
385
+ ): string {
386
+ return items
387
+ .map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`)
388
+ .join(', ');
389
+ }
390
+
391
+ function renderJsonArrayAggExpr(
392
+ expr: JsonArrayAggExpr,
393
+ contract: PostgresContract,
394
+ pim: ParamIndexMap,
395
+ ): string {
396
+ const aggregateOrderBy =
397
+ expr.orderBy && expr.orderBy.length > 0
398
+ ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}`
399
+ : '';
400
+ const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;
401
+ if (expr.onEmpty === 'emptyArray') {
402
+ return `coalesce(${aggregated}, json_build_array())`;
403
+ }
404
+ return aggregated;
405
+ }
406
+
407
+ function renderExpr(expr: AnyExpression, contract: PostgresContract, pim: ParamIndexMap): string {
408
+ const node = expr;
409
+ switch (node.kind) {
410
+ case 'column-ref':
411
+ return renderColumn(node);
412
+ case 'identifier-ref':
413
+ return quoteIdentifier(node.name);
414
+ case 'operation':
415
+ return renderOperation(node, contract, pim);
416
+ case 'subquery':
417
+ return renderSubqueryExpr(node, contract, pim);
418
+ case 'aggregate':
419
+ return renderAggregateExpr(node, contract, pim);
420
+ case 'json-object':
421
+ return renderJsonObjectExpr(node, contract, pim);
422
+ case 'json-array-agg':
423
+ return renderJsonArrayAggExpr(node, contract, pim);
424
+ case 'binary':
425
+ return renderBinary(node, contract, pim);
426
+ case 'and':
427
+ if (node.exprs.length === 0) {
428
+ return 'TRUE';
429
+ }
430
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' AND ')})`;
431
+ case 'or':
432
+ if (node.exprs.length === 0) {
433
+ return 'FALSE';
434
+ }
435
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(' OR ')})`;
436
+ case 'exists': {
437
+ const notKeyword = node.notExists ? 'NOT ' : '';
438
+ const subquery = renderSelect(node.subquery, contract, pim);
439
+ return `${notKeyword}EXISTS (${subquery})`;
440
+ }
441
+ case 'null-check':
442
+ return renderNullCheck(node, contract, pim);
443
+ case 'not':
444
+ return `NOT (${renderExpr(node.expr, contract, pim)})`;
445
+ case 'param-ref':
446
+ return renderParamRef(node, pim);
447
+ case 'literal':
448
+ return renderLiteral(node);
449
+ case 'list':
450
+ return renderListLiteral(node, contract, pim);
451
+ // v8 ignore next 4
452
+ default:
453
+ throw new Error(
454
+ `Unsupported expression node kind: ${(node satisfies never as { kind: string }).kind}`,
455
+ );
456
+ }
457
+ }
458
+
459
+ function renderParamRef(ref: ParamRef, pim: ParamIndexMap): string {
460
+ const index = pim.get(ref);
461
+ if (index === undefined) {
462
+ throw new Error('ParamRef not found in index map');
463
+ }
464
+ return renderTypedParam(index, ref.codecId);
465
+ }
466
+
467
+ function renderLiteral(expr: LiteralExpr): string {
468
+ if (typeof expr.value === 'string') {
469
+ return `'${escapeLiteral(expr.value)}'`;
470
+ }
471
+ if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {
472
+ return String(expr.value);
473
+ }
474
+ if (typeof expr.value === 'bigint') {
475
+ return String(expr.value);
476
+ }
477
+ if (expr.value === null) {
478
+ return 'NULL';
479
+ }
480
+ if (expr.value === undefined) {
481
+ return 'NULL';
482
+ }
483
+ if (expr.value instanceof Date) {
484
+ return `'${escapeLiteral(expr.value.toISOString())}'`;
485
+ }
486
+ if (Array.isArray(expr.value)) {
487
+ return `ARRAY[${expr.value.map((v: unknown) => renderLiteral(new LiteralExpr(v))).join(', ')}]`;
488
+ }
489
+ const json = JSON.stringify(expr.value);
490
+ if (json === undefined) {
491
+ return 'NULL';
492
+ }
493
+ return `'${escapeLiteral(json)}'`;
494
+ }
495
+
496
+ function renderOperation(
497
+ expr: OperationExpr,
498
+ contract: PostgresContract,
499
+ pim: ParamIndexMap,
500
+ ): string {
501
+ const self = renderExpr(expr.self, contract, pim);
502
+ const args = expr.args.map((arg) => {
503
+ return renderExpr(arg, contract, pim);
504
+ });
505
+
506
+ // Resolve `{{self}}` and `{{argN}}` from the original template in a single
507
+ // pass. Doing this with sequential `String.prototype.replace` calls is
508
+ // unsafe: a substituted fragment can itself contain text that matches a
509
+ // later token (e.g. an arg literal containing the substring `{{arg1}}`),
510
+ // and the next iteration would corrupt it. A single regex callback never
511
+ // re-scans already-substituted output.
512
+ return expr.lowering.template.replace(
513
+ /\{\{self\}\}|\{\{arg(\d+)\}\}/g,
514
+ (token, argIndex: string | undefined) => {
515
+ if (token === '{{self}}') {
516
+ return self;
517
+ }
518
+ const arg = args[Number(argIndex)];
519
+ if (arg === undefined) {
520
+ throw new Error(
521
+ `Operation lowering template for "${expr.method}" referenced missing argument {{arg${argIndex}}}; template has ${args.length} arg(s)`,
522
+ );
523
+ }
524
+ return arg;
525
+ },
526
+ );
527
+ }
528
+
529
+ function renderJoin(join: JoinAst, contract: PostgresContract, pim: ParamIndexMap): string {
530
+ const joinType = join.joinType.toUpperCase();
531
+ const lateral = join.lateral ? 'LATERAL ' : '';
532
+ const source = renderSource(join.source, contract, pim);
533
+ const onClause = renderJoinOn(join.on, contract, pim);
534
+ return `${joinType} JOIN ${lateral}${source} ON ${onClause}`;
535
+ }
536
+
537
+ function renderJoinOn(on: JoinOnExpr, contract: PostgresContract, pim: ParamIndexMap): string {
538
+ if (on.kind === 'eq-col-join-on') {
539
+ const left = renderColumn(on.left);
540
+ const right = renderColumn(on.right);
541
+ return `${left} = ${right}`;
542
+ }
543
+ return renderWhere(on, contract, pim);
544
+ }
545
+
546
+ function getInsertColumnOrder(
547
+ rows: ReadonlyArray<Record<string, InsertValue>>,
548
+ contract: PostgresContract,
549
+ tableName: string,
550
+ ): string[] {
551
+ const orderedColumns: string[] = [];
552
+ const seenColumns = new Set<string>();
553
+
554
+ for (const row of rows) {
555
+ for (const column of Object.keys(row)) {
556
+ if (seenColumns.has(column)) {
557
+ continue;
558
+ }
559
+ seenColumns.add(column);
560
+ orderedColumns.push(column);
561
+ }
562
+ }
563
+
564
+ if (orderedColumns.length > 0) {
565
+ return orderedColumns;
566
+ }
567
+
568
+ const table = contract.storage.tables[tableName];
569
+ if (!table) {
570
+ throw new Error(`INSERT target table not found in contract storage: ${tableName}`);
571
+ }
572
+ return Object.keys(table.columns);
573
+ }
574
+
575
+ function renderInsertValue(value: InsertValue | undefined, pim: ParamIndexMap): string {
576
+ if (!value || value.kind === 'default-value') {
577
+ return 'DEFAULT';
578
+ }
579
+
580
+ switch (value.kind) {
581
+ case 'param-ref':
582
+ return renderParamRef(value, pim);
583
+ case 'column-ref':
584
+ return renderColumn(value);
585
+ // v8 ignore next 4
586
+ default:
587
+ throw new Error(
588
+ `Unsupported value node in INSERT: ${(value satisfies never as { kind: string }).kind}`,
589
+ );
590
+ }
591
+ }
592
+
593
+ function renderInsert(ast: InsertAst, contract: PostgresContract, pim: ParamIndexMap): string {
594
+ const table = quoteIdentifier(ast.table.name);
595
+ const rows = ast.rows;
596
+ if (rows.length === 0) {
597
+ throw new Error('INSERT requires at least one row');
598
+ }
599
+ const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);
600
+ const insertClause = (() => {
601
+ if (!hasExplicitValues) {
602
+ if (rows.length === 1) {
603
+ return `INSERT INTO ${table} DEFAULT VALUES`;
604
+ }
605
+
606
+ const defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);
607
+ if (defaultColumns.length === 0) {
608
+ return `INSERT INTO ${table} VALUES ${rows.map(() => '()').join(', ')}`;
609
+ }
610
+
611
+ const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));
612
+ const defaultRow = `(${defaultColumns.map(() => 'DEFAULT').join(', ')})`;
613
+ return `INSERT INTO ${table} (${quotedColumns.join(', ')}) VALUES ${rows
614
+ .map(() => defaultRow)
615
+ .join(', ')}`;
616
+ }
617
+
618
+ const columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);
619
+ const columns = columnOrder.map((column) => quoteIdentifier(column));
620
+ const values = rows
621
+ .map((row) => {
622
+ const renderedRow = columnOrder.map((column) => renderInsertValue(row[column], pim));
623
+ return `(${renderedRow.join(', ')})`;
624
+ })
625
+ .join(', ');
626
+
627
+ return `INSERT INTO ${table} (${columns.join(', ')}) VALUES ${values}`;
628
+ })();
629
+ const onConflictClause = ast.onConflict
630
+ ? (() => {
631
+ const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));
632
+ if (conflictColumns.length === 0) {
633
+ throw new Error('INSERT onConflict requires at least one conflict column');
634
+ }
635
+
636
+ const action = ast.onConflict.action;
637
+ switch (action.kind) {
638
+ case 'do-nothing':
639
+ return ` ON CONFLICT (${conflictColumns.join(', ')}) DO NOTHING`;
640
+ case 'do-update-set': {
641
+ const updateEntries = Object.entries(action.set);
642
+ if (updateEntries.length === 0) {
643
+ throw new Error('INSERT onConflict do-update-set requires at least one assignment');
644
+ }
645
+ const updates = updateEntries.map(([colName, value]) => {
646
+ const target = quoteIdentifier(colName);
647
+ if (value.kind === 'param-ref') {
648
+ return `${target} = ${renderParamRef(value, pim)}`;
649
+ }
650
+ return `${target} = ${renderColumn(value)}`;
651
+ });
652
+ return ` ON CONFLICT (${conflictColumns.join(', ')}) DO UPDATE SET ${updates.join(', ')}`;
653
+ }
654
+ // v8 ignore next 4
655
+ default:
656
+ throw new Error(
657
+ `Unsupported onConflict action: ${(action satisfies never as { kind: string }).kind}`,
658
+ );
659
+ }
660
+ })()
661
+ : '';
662
+ const returningClause = ast.returning?.length
663
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
664
+ : '';
665
+
666
+ return `${insertClause}${onConflictClause}${returningClause}`;
667
+ }
668
+
669
+ function renderUpdate(ast: UpdateAst, contract: PostgresContract, pim: ParamIndexMap): string {
670
+ const table = quoteIdentifier(ast.table.name);
671
+ const setEntries = Object.entries(ast.set);
672
+ if (setEntries.length === 0) {
673
+ throw new Error('UPDATE requires at least one SET assignment');
674
+ }
675
+ const setClauses = setEntries.map(([col, val]) => {
676
+ const column = quoteIdentifier(col);
677
+ let value: string;
678
+ switch (val.kind) {
679
+ case 'param-ref':
680
+ value = renderParamRef(val, pim);
681
+ break;
682
+ case 'column-ref':
683
+ value = renderColumn(val);
684
+ break;
685
+ // v8 ignore next 4
686
+ default:
687
+ throw new Error(
688
+ `Unsupported value node in UPDATE: ${(val satisfies never as { kind: string }).kind}`,
689
+ );
690
+ }
691
+ return `${column} = ${value}`;
692
+ });
693
+
694
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';
695
+ const returningClause = ast.returning?.length
696
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
697
+ : '';
698
+
699
+ return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;
700
+ }
701
+
702
+ function renderDelete(ast: DeleteAst, contract: PostgresContract, pim: ParamIndexMap): string {
703
+ const table = quoteIdentifier(ast.table.name);
704
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : '';
705
+ const returningClause = ast.returning?.length
706
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
707
+ : '';
708
+
709
+ return `DELETE FROM ${table}${whereClause}${returningClause}`;
710
+ }