@prisma-next/adapter-postgres 0.3.0-dev.4 → 0.3.0-dev.40

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 (75) hide show
  1. package/README.md +64 -2
  2. package/dist/adapter-DB1CK2jM.mjs +265 -0
  3. package/dist/adapter-DB1CK2jM.mjs.map +1 -0
  4. package/dist/adapter.d.mts +23 -0
  5. package/dist/adapter.d.mts.map +1 -0
  6. package/dist/adapter.mjs +3 -0
  7. package/dist/codec-ids-Bsm9c7ns.mjs +29 -0
  8. package/dist/codec-ids-Bsm9c7ns.mjs.map +1 -0
  9. package/dist/codec-types.d.mts +141 -0
  10. package/dist/codec-types.d.mts.map +1 -0
  11. package/dist/codec-types.mjs +3 -0
  12. package/dist/codecs-DcC1nPzh.mjs +206 -0
  13. package/dist/codecs-DcC1nPzh.mjs.map +1 -0
  14. package/dist/column-types.d.mts +110 -0
  15. package/dist/column-types.d.mts.map +1 -0
  16. package/dist/column-types.mjs +180 -0
  17. package/dist/column-types.mjs.map +1 -0
  18. package/dist/control.d.mts +111 -0
  19. package/dist/control.d.mts.map +1 -0
  20. package/dist/control.mjs +405 -0
  21. package/dist/control.mjs.map +1 -0
  22. package/dist/descriptor-meta-D7pxo-wo.mjs +996 -0
  23. package/dist/descriptor-meta-D7pxo-wo.mjs.map +1 -0
  24. package/dist/runtime.d.mts +19 -0
  25. package/dist/runtime.d.mts.map +1 -0
  26. package/dist/runtime.mjs +85 -0
  27. package/dist/runtime.mjs.map +1 -0
  28. package/dist/types-BY395pUv.d.mts +19 -0
  29. package/dist/types-BY395pUv.d.mts.map +1 -0
  30. package/dist/types.d.mts +2 -0
  31. package/dist/types.mjs +1 -0
  32. package/package.json +39 -47
  33. package/src/core/adapter.ts +513 -0
  34. package/src/core/codec-ids.ts +28 -0
  35. package/src/core/codecs.ts +491 -0
  36. package/src/core/control-adapter.ts +536 -0
  37. package/src/core/default-normalizer.ts +77 -0
  38. package/src/core/descriptor-meta.ts +253 -0
  39. package/src/core/enum-control-hooks.ts +735 -0
  40. package/src/core/json-schema-type-expression.ts +131 -0
  41. package/src/core/json-schema-validator.ts +53 -0
  42. package/src/core/parameterized-types.ts +118 -0
  43. package/src/core/sql-utils.ts +111 -0
  44. package/src/core/standard-schema.ts +71 -0
  45. package/src/core/types.ts +53 -0
  46. package/src/exports/adapter.ts +1 -0
  47. package/src/exports/codec-types.ts +83 -0
  48. package/src/exports/column-types.ts +277 -0
  49. package/src/exports/control.ts +27 -0
  50. package/src/exports/runtime.ts +75 -0
  51. package/src/exports/types.ts +14 -0
  52. package/dist/exports/adapter.d.ts +0 -21
  53. package/dist/exports/adapter.js +0 -8
  54. package/dist/exports/adapter.js.map +0 -1
  55. package/dist/exports/chunk-B5SU5BVC.js +0 -47
  56. package/dist/exports/chunk-B5SU5BVC.js.map +0 -1
  57. package/dist/exports/chunk-CPAKRHXM.js +0 -162
  58. package/dist/exports/chunk-CPAKRHXM.js.map +0 -1
  59. package/dist/exports/chunk-ZHJOVBWT.js +0 -301
  60. package/dist/exports/chunk-ZHJOVBWT.js.map +0 -1
  61. package/dist/exports/codec-types.d.ts +0 -38
  62. package/dist/exports/codec-types.js +0 -7
  63. package/dist/exports/codec-types.js.map +0 -1
  64. package/dist/exports/column-types.d.ts +0 -20
  65. package/dist/exports/column-types.js +0 -49
  66. package/dist/exports/column-types.js.map +0 -1
  67. package/dist/exports/control.d.ts +0 -9
  68. package/dist/exports/control.js +0 -279
  69. package/dist/exports/control.js.map +0 -1
  70. package/dist/exports/runtime.d.ts +0 -17
  71. package/dist/exports/runtime.js +0 -20
  72. package/dist/exports/runtime.js.map +0 -1
  73. package/dist/exports/types.d.ts +0 -19
  74. package/dist/exports/types.js +0 -1
  75. package/dist/exports/types.js.map +0 -1
@@ -0,0 +1,513 @@
1
+ import type {
2
+ Adapter,
3
+ AdapterProfile,
4
+ BinaryExpr,
5
+ CodecParamsDescriptor,
6
+ ColumnRef,
7
+ DeleteAst,
8
+ IncludeRef,
9
+ InsertAst,
10
+ JoinAst,
11
+ LiteralExpr,
12
+ LowererContext,
13
+ NullCheckExpr,
14
+ OperationExpr,
15
+ ParamRef,
16
+ QueryAst,
17
+ SelectAst,
18
+ UpdateAst,
19
+ WhereExpr,
20
+ } from '@prisma-next/sql-relational-core/ast';
21
+ import { createCodecRegistry, isOperationExpr } from '@prisma-next/sql-relational-core/ast';
22
+ import { ifDefined } from '@prisma-next/utils/defined';
23
+ import { PG_JSON_CODEC_ID, PG_JSONB_CODEC_ID } from './codec-ids';
24
+ import { codecDefinitions } from './codecs';
25
+ import type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';
26
+
27
+ const VECTOR_CODEC_ID = 'pg/vector@1' as const;
28
+
29
+ function getCodecParamCast(codecId: string | undefined): string | undefined {
30
+ if (codecId === VECTOR_CODEC_ID) {
31
+ return 'vector';
32
+ }
33
+ if (codecId === PG_JSON_CODEC_ID) {
34
+ return 'json';
35
+ }
36
+ if (codecId === PG_JSONB_CODEC_ID) {
37
+ return 'jsonb';
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ function renderTypedParam(index: number, codecId: string | undefined): string {
43
+ const cast = getCodecParamCast(codecId);
44
+ return cast ? `$${index}::${cast}` : `$${index}`;
45
+ }
46
+
47
+ const defaultCapabilities = Object.freeze({
48
+ postgres: {
49
+ orderBy: true,
50
+ limit: true,
51
+ lateral: true,
52
+ jsonAgg: true,
53
+ returning: true,
54
+ },
55
+ sql: {
56
+ enums: true,
57
+ },
58
+ });
59
+
60
+ type AdapterCodec = (typeof codecDefinitions)[keyof typeof codecDefinitions]['codec'];
61
+ type ParameterizedCodec = AdapterCodec & {
62
+ readonly paramsSchema: NonNullable<AdapterCodec['paramsSchema']>;
63
+ };
64
+
65
+ const parameterizedCodecs: ReadonlyArray<CodecParamsDescriptor> = Object.values(codecDefinitions)
66
+ .map((definition) => definition.codec)
67
+ .filter((codec): codec is ParameterizedCodec => codec.paramsSchema !== undefined)
68
+ .map((codec) =>
69
+ Object.freeze({
70
+ codecId: codec.id,
71
+ paramsSchema: codec.paramsSchema,
72
+ ...ifDefined('init', codec.init),
73
+ }),
74
+ );
75
+
76
+ class PostgresAdapterImpl implements Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {
77
+ // These fields make the adapter instance structurally compatible with
78
+ // RuntimeAdapterInstance<'sql', 'postgres'> without introducing a runtime-plane dependency.
79
+ readonly familyId = 'sql' as const;
80
+ readonly targetId = 'postgres' as const;
81
+
82
+ readonly profile: AdapterProfile<'postgres'>;
83
+ private readonly codecRegistry = (() => {
84
+ const registry = createCodecRegistry();
85
+ for (const definition of Object.values(codecDefinitions)) {
86
+ registry.register(definition.codec);
87
+ }
88
+ return registry;
89
+ })();
90
+
91
+ constructor(options?: PostgresAdapterOptions) {
92
+ this.profile = Object.freeze({
93
+ id: options?.profileId ?? 'postgres/default@1',
94
+ target: 'postgres',
95
+ capabilities: defaultCapabilities,
96
+ codecs: () => this.codecRegistry,
97
+ });
98
+ }
99
+
100
+ parameterizedCodecs(): ReadonlyArray<CodecParamsDescriptor> {
101
+ return parameterizedCodecs;
102
+ }
103
+
104
+ lower(ast: QueryAst, context: LowererContext<PostgresContract>) {
105
+ let sql: string;
106
+ const params = context.params ? [...context.params] : [];
107
+
108
+ if (ast.kind === 'select') {
109
+ sql = renderSelect(ast, context.contract);
110
+ } else if (ast.kind === 'insert') {
111
+ sql = renderInsert(ast, context.contract);
112
+ } else if (ast.kind === 'update') {
113
+ sql = renderUpdate(ast, context.contract);
114
+ } else if (ast.kind === 'delete') {
115
+ sql = renderDelete(ast, context.contract);
116
+ } else {
117
+ throw new Error(`Unsupported AST kind: ${(ast as { kind: string }).kind}`);
118
+ }
119
+
120
+ return Object.freeze({
121
+ profileId: this.profile.id,
122
+ body: Object.freeze({ sql, params }),
123
+ });
124
+ }
125
+ }
126
+
127
+ function renderSelect(ast: SelectAst, contract?: PostgresContract): string {
128
+ const selectClause = `SELECT ${renderProjection(ast, contract)}`;
129
+ const fromClause = `FROM ${quoteIdentifier(ast.from.name)}`;
130
+
131
+ const joinsClause = ast.joins?.length
132
+ ? ast.joins.map((join) => renderJoin(join, contract)).join(' ')
133
+ : '';
134
+ const includesClause = ast.includes?.length
135
+ ? ast.includes.map((include) => renderInclude(include, contract)).join(' ')
136
+ : '';
137
+
138
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract)}` : '';
139
+ const orderClause = ast.orderBy?.length
140
+ ? ` ORDER BY ${ast.orderBy
141
+ .map((order) => {
142
+ const expr = renderExpr(order.expr as ColumnRef | OperationExpr, contract);
143
+ return `${expr} ${order.dir.toUpperCase()}`;
144
+ })
145
+ .join(', ')}`
146
+ : '';
147
+ const limitClause = typeof ast.limit === 'number' ? ` LIMIT ${ast.limit}` : '';
148
+
149
+ const clauses = [joinsClause, includesClause].filter(Boolean).join(' ');
150
+ return `${selectClause} ${fromClause}${clauses ? ` ${clauses}` : ''}${whereClause}${orderClause}${limitClause}`.trim();
151
+ }
152
+
153
+ function renderProjection(ast: SelectAst, contract?: PostgresContract): string {
154
+ return ast.project
155
+ .map((item) => {
156
+ const expr = item.expr as ColumnRef | IncludeRef | OperationExpr | LiteralExpr;
157
+ if (expr.kind === 'includeRef') {
158
+ // For include references, select the column from the LATERAL join alias
159
+ // The LATERAL subquery returns a single column (the JSON array) with the alias
160
+ // The table is aliased as {alias}_lateral, and the column inside is aliased as the include alias
161
+ // We select it using table_alias.column_alias
162
+ const tableAlias = `${expr.alias}_lateral`;
163
+ return `${quoteIdentifier(tableAlias)}.${quoteIdentifier(expr.alias)} AS ${quoteIdentifier(item.alias)}`;
164
+ }
165
+ if (expr.kind === 'operation') {
166
+ const operation = renderOperation(expr, contract);
167
+ const alias = quoteIdentifier(item.alias);
168
+ return `${operation} AS ${alias}`;
169
+ }
170
+ if (expr.kind === 'literal') {
171
+ const literal = renderLiteral(expr);
172
+ const alias = quoteIdentifier(item.alias);
173
+ return `${literal} AS ${alias}`;
174
+ }
175
+ const column = renderColumn(expr as ColumnRef);
176
+ const alias = quoteIdentifier(item.alias);
177
+ return `${column} AS ${alias}`;
178
+ })
179
+ .join(', ');
180
+ }
181
+
182
+ function renderWhere(expr: WhereExpr, contract?: PostgresContract): string {
183
+ if (expr.kind === 'exists') {
184
+ const notKeyword = expr.not ? 'NOT ' : '';
185
+ const subquery = renderSelect(expr.subquery, contract);
186
+ return `${notKeyword}EXISTS (${subquery})`;
187
+ }
188
+ if (expr.kind === 'nullCheck') {
189
+ return renderNullCheck(expr, contract);
190
+ }
191
+ if (expr.kind === 'and') {
192
+ if (expr.exprs.length === 0) {
193
+ return 'TRUE';
194
+ }
195
+ return `(${expr.exprs.map((part) => renderWhere(part, contract)).join(' AND ')})`;
196
+ }
197
+ if (expr.kind === 'or') {
198
+ if (expr.exprs.length === 0) {
199
+ return 'FALSE';
200
+ }
201
+ return `(${expr.exprs.map((part) => renderWhere(part, contract)).join(' OR ')})`;
202
+ }
203
+ return renderBinary(expr, contract);
204
+ }
205
+
206
+ function renderNullCheck(expr: NullCheckExpr, contract?: PostgresContract): string {
207
+ const rendered = renderExpr(expr.expr as ColumnRef | OperationExpr, contract);
208
+ // Only wrap in parentheses if it's an operation expression
209
+ const renderedExpr = isOperationExpr(expr.expr) ? `(${rendered})` : rendered;
210
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
211
+ }
212
+
213
+ function renderBinary(expr: BinaryExpr, contract?: PostgresContract): string {
214
+ const leftExpr = expr.left as ColumnRef | OperationExpr;
215
+ const left = renderExpr(leftExpr, contract);
216
+ // Only wrap in parentheses if it's an operation expression
217
+ const leftRendered = isOperationExpr(leftExpr) ? `(${left})` : left;
218
+ const right = renderBinaryRight(expr.right, contract);
219
+ const operatorMap: Record<BinaryExpr['op'], string> = {
220
+ eq: '=',
221
+ neq: '!=',
222
+ gt: '>',
223
+ lt: '<',
224
+ gte: '>=',
225
+ lte: '<=',
226
+ like: 'LIKE',
227
+ ilike: 'ILIKE',
228
+ in: 'IN',
229
+ notIn: 'NOT IN',
230
+ };
231
+
232
+ return `${leftRendered} ${operatorMap[expr.op]} ${right}`;
233
+ }
234
+
235
+ function renderBinaryRight(right: BinaryExpr['right'], contract?: PostgresContract): string {
236
+ if (right.kind === 'col') {
237
+ return renderColumn(right);
238
+ }
239
+ if (right.kind === 'param') {
240
+ return renderParam(right, contract);
241
+ }
242
+ if (right.kind === 'literal') {
243
+ return renderLiteral(right);
244
+ }
245
+ if (right.kind === 'operation') {
246
+ return renderExpr(right, contract);
247
+ }
248
+ if (right.kind === 'listLiteral') {
249
+ if (right.values.length === 0) {
250
+ return '(NULL)';
251
+ }
252
+ const values = right.values.map((value) =>
253
+ value.kind === 'param' ? renderParam(value, contract) : renderLiteral(value),
254
+ );
255
+ return `(${values.join(', ')})`;
256
+ }
257
+
258
+ throw new Error(`Unsupported binary right expression kind: ${(right as { kind: string }).kind}`);
259
+ }
260
+
261
+ function renderColumn(ref: ColumnRef): string {
262
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
263
+ }
264
+
265
+ function renderExpr(expr: ColumnRef | OperationExpr, contract?: PostgresContract): string {
266
+ if (isOperationExpr(expr)) {
267
+ return renderOperation(expr, contract);
268
+ }
269
+ return renderColumn(expr);
270
+ }
271
+
272
+ function renderParam(
273
+ ref: ParamRef,
274
+ contract?: PostgresContract,
275
+ tableName?: string,
276
+ columnName?: string,
277
+ ): string {
278
+ if (contract && tableName && columnName) {
279
+ const tableMeta = contract.storage.tables[tableName];
280
+ const columnMeta = tableMeta?.columns[columnName];
281
+ return renderTypedParam(ref.index, columnMeta?.codecId);
282
+ }
283
+ return `$${ref.index}`;
284
+ }
285
+
286
+ function renderLiteral(expr: LiteralExpr): string {
287
+ if (typeof expr.value === 'string') {
288
+ return `'${expr.value.replace(/'/g, "''")}'`;
289
+ }
290
+ if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {
291
+ return String(expr.value);
292
+ }
293
+ if (expr.value === null) {
294
+ return 'NULL';
295
+ }
296
+ if (Array.isArray(expr.value)) {
297
+ return `ARRAY[${expr.value.map((v: unknown) => renderLiteral({ kind: 'literal', value: v })).join(', ')}]`;
298
+ }
299
+ return JSON.stringify(expr.value);
300
+ }
301
+
302
+ function renderOperation(expr: OperationExpr, contract?: PostgresContract): string {
303
+ const self = renderExpr(expr.self, contract);
304
+ // For vector operations, cast param arguments to vector type
305
+ const isVectorOperation = expr.forTypeId === VECTOR_CODEC_ID;
306
+ const args = expr.args.map((arg: ColumnRef | ParamRef | LiteralExpr | OperationExpr) => {
307
+ if (arg.kind === 'col') {
308
+ return renderColumn(arg);
309
+ }
310
+ if (arg.kind === 'param') {
311
+ // Cast vector operation parameters to vector type
312
+ return isVectorOperation ? `$${arg.index}::vector` : renderParam(arg, contract);
313
+ }
314
+ if (arg.kind === 'literal') {
315
+ return renderLiteral(arg);
316
+ }
317
+ if (arg.kind === 'operation') {
318
+ return renderOperation(arg, contract);
319
+ }
320
+ const _exhaustive: never = arg;
321
+ throw new Error(`Unsupported argument kind: ${(_exhaustive as { kind: string }).kind}`);
322
+ });
323
+
324
+ let result = expr.lowering.template;
325
+ result = result.replace(/\$\{self\}/g, self);
326
+ for (let i = 0; i < args.length; i++) {
327
+ result = result.replace(new RegExp(`\\$\\{arg${i}\\}`, 'g'), args[i] ?? '');
328
+ }
329
+
330
+ if (expr.lowering.strategy === 'function') {
331
+ return result;
332
+ }
333
+
334
+ return result;
335
+ }
336
+
337
+ function renderJoin(join: JoinAst, _contract?: PostgresContract): string {
338
+ const joinType = join.joinType.toUpperCase();
339
+ const table = quoteIdentifier(join.table.name);
340
+ const onClause = renderJoinOn(join.on);
341
+ return `${joinType} JOIN ${table} ON ${onClause}`;
342
+ }
343
+
344
+ function renderJoinOn(on: JoinAst['on']): string {
345
+ if (on.kind === 'eqCol') {
346
+ const left = renderColumn(on.left);
347
+ const right = renderColumn(on.right);
348
+ return `${left} = ${right}`;
349
+ }
350
+ throw new Error(`Unsupported join ON expression kind: ${on.kind}`);
351
+ }
352
+
353
+ function renderInclude(
354
+ include: NonNullable<SelectAst['includes']>[number],
355
+ contract?: PostgresContract,
356
+ ): string {
357
+ const alias = include.alias;
358
+
359
+ // Build the lateral subquery
360
+ const childProjection = include.child.project
361
+ .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {
362
+ const expr = renderExpr(item.expr, contract);
363
+ return `'${item.alias}', ${expr}`;
364
+ })
365
+ .join(', ');
366
+
367
+ const jsonBuildObject = `json_build_object(${childProjection})`;
368
+
369
+ // Build the ON condition from the include's ON clause - this goes in the WHERE clause
370
+ const onCondition = renderJoinOn(include.child.on);
371
+
372
+ // Build WHERE clause: combine ON condition with any additional WHERE clauses
373
+ let whereClause = ` WHERE ${onCondition}`;
374
+ if (include.child.where) {
375
+ whereClause += ` AND ${renderWhere(include.child.where, contract)}`;
376
+ }
377
+
378
+ // Add ORDER BY if present - it goes inside json_agg() call
379
+ const childOrderBy = include.child.orderBy?.length
380
+ ? ` ORDER BY ${include.child.orderBy
381
+ .map(
382
+ (order: { expr: ColumnRef | OperationExpr; dir: string }) =>
383
+ `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`,
384
+ )
385
+ .join(', ')}`
386
+ : '';
387
+
388
+ // Add LIMIT if present
389
+ const childLimit = typeof include.child.limit === 'number' ? ` LIMIT ${include.child.limit}` : '';
390
+
391
+ // Build the lateral subquery
392
+ // When ORDER BY is present without LIMIT, it goes inside json_agg() call: json_agg(expr ORDER BY ...)
393
+ // When LIMIT is present (with or without ORDER BY), we need to wrap in a subquery
394
+ const childTable = quoteIdentifier(include.child.table.name);
395
+ let subquery: string;
396
+ if (typeof include.child.limit === 'number') {
397
+ // With LIMIT, we need to wrap in a subquery
398
+ // Select individual columns in inner query, then aggregate
399
+ // Create a map of column references to their aliases for ORDER BY
400
+ // Only ColumnRef can be mapped (OperationExpr doesn't have table/column properties)
401
+ const columnAliasMap = new Map<string, string>();
402
+ for (const item of include.child.project) {
403
+ if (item.expr.kind === 'col') {
404
+ const columnKey = `${item.expr.table}.${item.expr.column}`;
405
+ columnAliasMap.set(columnKey, item.alias);
406
+ }
407
+ }
408
+
409
+ const innerColumns = include.child.project
410
+ .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {
411
+ const expr = renderExpr(item.expr, contract);
412
+ return `${expr} AS ${quoteIdentifier(item.alias)}`;
413
+ })
414
+ .join(', ');
415
+
416
+ // For ORDER BY, use column aliases if the column is in the SELECT list
417
+ const childOrderByWithAliases = include.child.orderBy?.length
418
+ ? ` ORDER BY ${include.child.orderBy
419
+ .map((order: { expr: ColumnRef | OperationExpr; dir: string }) => {
420
+ if (order.expr.kind === 'col') {
421
+ const columnKey = `${order.expr.table}.${order.expr.column}`;
422
+ const alias = columnAliasMap.get(columnKey);
423
+ if (alias) {
424
+ return `${quoteIdentifier(alias)} ${order.dir.toUpperCase()}`;
425
+ }
426
+ }
427
+ return `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`;
428
+ })
429
+ .join(', ')}`
430
+ : '';
431
+
432
+ const innerSelect = `SELECT ${innerColumns} FROM ${childTable}${whereClause}${childOrderByWithAliases}${childLimit}`;
433
+ subquery = `(SELECT json_agg(row_to_json(sub.*)) AS ${quoteIdentifier(alias)} FROM (${innerSelect}) sub)`;
434
+ } else if (childOrderBy) {
435
+ // With ORDER BY but no LIMIT, ORDER BY goes inside json_agg()
436
+ subquery = `(SELECT json_agg(${jsonBuildObject}${childOrderBy}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;
437
+ } else {
438
+ // No ORDER BY or LIMIT
439
+ subquery = `(SELECT json_agg(${jsonBuildObject}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;
440
+ }
441
+
442
+ // Return the LATERAL join with ON true (the condition is in the WHERE clause)
443
+ // The subquery returns a single column (the JSON array) with the alias
444
+ // We use a different alias for the table to avoid ambiguity when selecting the column
445
+ const tableAlias = `${alias}_lateral`;
446
+ return `LEFT JOIN LATERAL ${subquery} AS ${quoteIdentifier(tableAlias)} ON true`;
447
+ }
448
+
449
+ function quoteIdentifier(identifier: string): string {
450
+ return `"${identifier.replace(/"/g, '""')}"`;
451
+ }
452
+
453
+ function renderInsert(ast: InsertAst, contract: PostgresContract): string {
454
+ const table = quoteIdentifier(ast.table.name);
455
+ const columns = Object.keys(ast.values).map((col) => quoteIdentifier(col));
456
+ const tableMeta = contract.storage.tables[ast.table.name];
457
+ const values = Object.entries(ast.values).map(([colName, val]) => {
458
+ if (val.kind === 'param') {
459
+ const columnMeta = tableMeta?.columns[colName];
460
+ return renderTypedParam(val.index, columnMeta?.codecId);
461
+ }
462
+ if (val.kind === 'col') {
463
+ return `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;
464
+ }
465
+ throw new Error(`Unsupported value kind in INSERT: ${(val as { kind: string }).kind}`);
466
+ });
467
+
468
+ const insertClause = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${values.join(', ')})`;
469
+ const returningClause = ast.returning?.length
470
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
471
+ : '';
472
+
473
+ return `${insertClause}${returningClause}`;
474
+ }
475
+
476
+ function renderUpdate(ast: UpdateAst, contract: PostgresContract): string {
477
+ const table = quoteIdentifier(ast.table.name);
478
+ const tableMeta = contract.storage.tables[ast.table.name];
479
+ const setClauses = Object.entries(ast.set).map(([col, val]) => {
480
+ const column = quoteIdentifier(col);
481
+ let value: string;
482
+ if (val.kind === 'param') {
483
+ const columnMeta = tableMeta?.columns[col];
484
+ value = renderTypedParam(val.index, columnMeta?.codecId);
485
+ } else if (val.kind === 'col') {
486
+ value = `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;
487
+ } else {
488
+ throw new Error(`Unsupported value kind in UPDATE: ${(val as { kind: string }).kind}`);
489
+ }
490
+ return `${column} = ${value}`;
491
+ });
492
+
493
+ const whereClause = ` WHERE ${renderWhere(ast.where, contract)}`;
494
+ const returningClause = ast.returning?.length
495
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
496
+ : '';
497
+
498
+ return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;
499
+ }
500
+
501
+ function renderDelete(ast: DeleteAst, contract?: PostgresContract): string {
502
+ const table = quoteIdentifier(ast.table.name);
503
+ const whereClause = ` WHERE ${renderWhere(ast.where, contract)}`;
504
+ const returningClause = ast.returning?.length
505
+ ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`
506
+ : '';
507
+
508
+ return `DELETE FROM ${table}${whereClause}${returningClause}`;
509
+ }
510
+
511
+ export function createPostgresAdapter(options?: PostgresAdapterOptions) {
512
+ return Object.freeze(new PostgresAdapterImpl(options));
513
+ }
@@ -0,0 +1,28 @@
1
+ export {
2
+ SQL_CHAR_CODEC_ID,
3
+ SQL_FLOAT_CODEC_ID,
4
+ SQL_INT_CODEC_ID,
5
+ SQL_VARCHAR_CODEC_ID,
6
+ } from '@prisma-next/sql-relational-core/ast';
7
+ export const PG_TEXT_CODEC_ID = 'pg/text@1' as const;
8
+ export const PG_ENUM_CODEC_ID = 'pg/enum@1' as const;
9
+ export const PG_CHAR_CODEC_ID = 'pg/char@1' as const;
10
+ export const PG_VARCHAR_CODEC_ID = 'pg/varchar@1' as const;
11
+ export const PG_INT_CODEC_ID = 'pg/int@1' as const;
12
+ export const PG_INT2_CODEC_ID = 'pg/int2@1' as const;
13
+ export const PG_INT4_CODEC_ID = 'pg/int4@1' as const;
14
+ export const PG_INT8_CODEC_ID = 'pg/int8@1' as const;
15
+ export const PG_FLOAT_CODEC_ID = 'pg/float@1' as const;
16
+ export const PG_FLOAT4_CODEC_ID = 'pg/float4@1' as const;
17
+ export const PG_FLOAT8_CODEC_ID = 'pg/float8@1' as const;
18
+ export const PG_NUMERIC_CODEC_ID = 'pg/numeric@1' as const;
19
+ export const PG_BOOL_CODEC_ID = 'pg/bool@1' as const;
20
+ export const PG_BIT_CODEC_ID = 'pg/bit@1' as const;
21
+ export const PG_VARBIT_CODEC_ID = 'pg/varbit@1' as const;
22
+ export const PG_TIMESTAMP_CODEC_ID = 'pg/timestamp@1' as const;
23
+ export const PG_TIMESTAMPTZ_CODEC_ID = 'pg/timestamptz@1' as const;
24
+ export const PG_TIME_CODEC_ID = 'pg/time@1' as const;
25
+ export const PG_TIMETZ_CODEC_ID = 'pg/timetz@1' as const;
26
+ export const PG_INTERVAL_CODEC_ID = 'pg/interval@1' as const;
27
+ export const PG_JSON_CODEC_ID = 'pg/json@1' as const;
28
+ export const PG_JSONB_CODEC_ID = 'pg/jsonb@1' as const;