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