@prisma-next/adapter-postgres 0.3.0-dev.11 → 0.3.0-dev.113

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 (92) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +64 -2
  3. package/dist/adapter-CWmWEFe1.mjs +361 -0
  4. package/dist/adapter-CWmWEFe1.mjs.map +1 -0
  5. package/dist/adapter.d.mts +23 -0
  6. package/dist/adapter.d.mts.map +1 -0
  7. package/dist/adapter.mjs +3 -0
  8. package/dist/codec-ids-Bsm9c7ns.mjs +29 -0
  9. package/dist/codec-ids-Bsm9c7ns.mjs.map +1 -0
  10. package/dist/codec-types.d.mts +141 -0
  11. package/dist/codec-types.d.mts.map +1 -0
  12. package/dist/codec-types.mjs +3 -0
  13. package/dist/codecs-DgJcyEBR.mjs +254 -0
  14. package/dist/codecs-DgJcyEBR.mjs.map +1 -0
  15. package/dist/column-types.d.mts +110 -0
  16. package/dist/column-types.d.mts.map +1 -0
  17. package/dist/column-types.mjs +180 -0
  18. package/dist/column-types.mjs.map +1 -0
  19. package/dist/control.d.mts +77 -0
  20. package/dist/control.d.mts.map +1 -0
  21. package/dist/control.mjs +773 -0
  22. package/dist/control.mjs.map +1 -0
  23. package/dist/descriptor-meta-l_dv8Nnn.mjs +884 -0
  24. package/dist/descriptor-meta-l_dv8Nnn.mjs.map +1 -0
  25. package/dist/runtime.d.mts +19 -0
  26. package/dist/runtime.d.mts.map +1 -0
  27. package/dist/runtime.mjs +99 -0
  28. package/dist/runtime.mjs.map +1 -0
  29. package/dist/sql-utils-CSfAGEwF.mjs +78 -0
  30. package/dist/sql-utils-CSfAGEwF.mjs.map +1 -0
  31. package/dist/types-aQLL6QVb.d.mts +19 -0
  32. package/dist/types-aQLL6QVb.d.mts.map +1 -0
  33. package/dist/types.d.mts +2 -0
  34. package/dist/types.mjs +1 -0
  35. package/package.json +39 -46
  36. package/src/core/adapter.ts +529 -256
  37. package/src/core/codec-ids.ts +28 -0
  38. package/src/core/codecs.ts +385 -36
  39. package/src/core/control-adapter.ts +404 -179
  40. package/src/core/control-mutation-defaults.ts +335 -0
  41. package/src/core/default-normalizer.ts +138 -0
  42. package/src/core/descriptor-meta.ts +296 -9
  43. package/src/core/enum-control-hooks.ts +733 -0
  44. package/src/core/json-schema-type-expression.ts +131 -0
  45. package/src/core/json-schema-validator.ts +53 -0
  46. package/src/core/sql-utils.ts +111 -0
  47. package/src/core/standard-schema.ts +71 -0
  48. package/src/core/types.ts +5 -3
  49. package/src/exports/codec-types.ts +73 -1
  50. package/src/exports/column-types.ts +233 -9
  51. package/src/exports/control.ts +20 -9
  52. package/src/exports/runtime.ts +76 -19
  53. package/dist/chunk-HD5YISNQ.js +0 -47
  54. package/dist/chunk-HD5YISNQ.js.map +0 -1
  55. package/dist/chunk-J3XSOAM2.js +0 -162
  56. package/dist/chunk-J3XSOAM2.js.map +0 -1
  57. package/dist/chunk-T6S3A6VT.js +0 -301
  58. package/dist/chunk-T6S3A6VT.js.map +0 -1
  59. package/dist/core/adapter.d.ts +0 -19
  60. package/dist/core/adapter.d.ts.map +0 -1
  61. package/dist/core/codecs.d.ts +0 -110
  62. package/dist/core/codecs.d.ts.map +0 -1
  63. package/dist/core/control-adapter.d.ts +0 -33
  64. package/dist/core/control-adapter.d.ts.map +0 -1
  65. package/dist/core/descriptor-meta.d.ts +0 -72
  66. package/dist/core/descriptor-meta.d.ts.map +0 -1
  67. package/dist/core/types.d.ts +0 -16
  68. package/dist/core/types.d.ts.map +0 -1
  69. package/dist/exports/adapter.d.ts +0 -2
  70. package/dist/exports/adapter.d.ts.map +0 -1
  71. package/dist/exports/adapter.js +0 -8
  72. package/dist/exports/adapter.js.map +0 -1
  73. package/dist/exports/codec-types.d.ts +0 -11
  74. package/dist/exports/codec-types.d.ts.map +0 -1
  75. package/dist/exports/codec-types.js +0 -7
  76. package/dist/exports/codec-types.js.map +0 -1
  77. package/dist/exports/column-types.d.ts +0 -17
  78. package/dist/exports/column-types.d.ts.map +0 -1
  79. package/dist/exports/column-types.js +0 -49
  80. package/dist/exports/column-types.js.map +0 -1
  81. package/dist/exports/control.d.ts +0 -8
  82. package/dist/exports/control.d.ts.map +0 -1
  83. package/dist/exports/control.js +0 -279
  84. package/dist/exports/control.js.map +0 -1
  85. package/dist/exports/runtime.d.ts +0 -15
  86. package/dist/exports/runtime.d.ts.map +0 -1
  87. package/dist/exports/runtime.js +0 -20
  88. package/dist/exports/runtime.js.map +0 -1
  89. package/dist/exports/types.d.ts +0 -2
  90. package/dist/exports/types.d.ts.map +0 -1
  91. package/dist/exports/types.js +0 -1
  92. package/dist/exports/types.js.map +0 -1
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -27,6 +27,7 @@ Provide PostgreSQL-specific adapter implementation, codecs, and capabilities. En
27
27
  - **Codec Definitions**: Define PostgreSQL codecs for type conversion
28
28
  - Wire format to JavaScript type decoding
29
29
  - JavaScript type to wire format encoding
30
+ - **Storage Type Control Hooks**: Provide control-plane hooks for contract-defined storage types (e.g., enums)
30
31
  - **Codec Types**: Export TypeScript types for PostgreSQL codecs
31
32
  - **Descriptors**: Provide adapter descriptors declaring capabilities and codec type imports
32
33
 
@@ -97,7 +98,11 @@ flowchart TD
97
98
  **Codecs (`codecs.ts`)**
98
99
  - PostgreSQL codec definitions
99
100
  - Type conversion between wire format and JavaScript
100
- - Supports PostgreSQL types: `int2`, `int4`, `int8`, `float4`, `float8`, `text`, `timestamp`, `timestamptz`, `bool`
101
+ - SQL base codecs: `sql/char`, `sql/varchar`, `sql/int`, `sql/float`
102
+ - PostgreSQL aliases for base codecs: `pg/char`, `pg/varchar`, `pg/int`, `pg/float`
103
+ - Supports PostgreSQL types: `int2`, `int4`, `int8`, `float4`, `float8`, `text`, `bool`, `enum`
104
+ - Supports PostgreSQL types: `int2`, `int4`, `int8`, `float4`, `float8`, `text`, `timestamp`, `timestamptz`, `bool`, `enum`, `json`, `jsonb`
105
+ - Parameterized types: `character(n)`, `character varying(n)`, `numeric(p,s)`, `bit(n)`, `bit varying(n)`, `timestamp(p)`, `timestamptz(p)`, `time(p)`, `timetz(p)`, `interval(p)`
101
106
 
102
107
  **Types (`types.ts`)**
103
108
  - PostgreSQL-specific types and utilities
@@ -122,6 +127,15 @@ flowchart TD
122
127
  **Types Export (`types.ts`)**
123
128
  - Re-exports PostgreSQL-specific types
124
129
 
130
+ **Column Types Export (`column-types.ts`)**
131
+ - Exports column descriptors for built-in types and enum helpers (`enumType`, `enumColumn(typeRef, nativeType)`)
132
+ - Parameterized helpers: `charColumn(length)`, `varcharColumn(length)`, `numericColumn(precision, scale?)`, `bitColumn(length)`, `varbitColumn(length)`, `timeColumn(precision?)`, `timetzColumn(precision?)`, `intervalColumn(precision?)`
133
+
134
+ - Exports JSON helpers:
135
+ - `jsonColumn`, `jsonbColumn`
136
+ - `json(schema?)`, `jsonb(schema?)` where `schema` is a Standard Schema value (e.g., Arktype)
137
+ - When a schema is provided, `typeParams` metadata is derived from the schema's `~standard` interface
138
+
125
139
  ## Dependencies
126
140
 
127
141
  - **`@prisma-next/sql-contract`**: SQL contract types
@@ -142,6 +156,7 @@ flowchart TD
142
156
  - [ADR 068 - Error mapping to RuntimeError](../../../../docs/architecture%20docs/adrs/ADR%20068%20-%20Error%20mapping%20to%20RuntimeError.md)
143
157
  - [ADR 112 - Target Extension Packs](../../../../docs/architecture%20docs/adrs/ADR%20112%20-%20Target%20Extension%20Packs.md)
144
158
  - [ADR 114 - Extension codecs & branded types](../../../../docs/architecture%20docs/adrs/ADR%20114%20-%20Extension%20codecs%20&%20branded%20types.md)
159
+ - [ADR 163 - Postgres JSON and JSONB typed columns](../../../../docs/architecture%20docs/adrs/ADR%20163%20-%20Postgres%20JSON%20and%20JSONB%20typed%20columns.md)
145
160
 
146
161
  ## Usage
147
162
 
@@ -180,6 +195,7 @@ The adapter declares the following PostgreSQL capabilities:
180
195
  - **`lateral: true`** - Supports LATERAL joins for `includeMany` nested array includes
181
196
  - **`jsonAgg: true`** - Supports JSON aggregation functions (`json_agg`) for `includeMany`
182
197
  - **`returning: true`** - Supports RETURNING clauses for DML operations (INSERT, UPDATE, DELETE)
198
+ - **`sql.enums: true`** - Supports contract-defined enum storage types
183
199
 
184
200
  **Important**: Capabilities must be declared in **both** places:
185
201
 
@@ -241,10 +257,56 @@ DELETE FROM "user" WHERE "user"."id" = $1 RETURNING "user"."id", "user"."email"
241
257
 
242
258
  **Note:** MySQL does not support RETURNING clauses. A future MySQL adapter would declare `returning: false` and either reject plans with RETURNING or provide an alternative implementation.
243
259
 
260
+ ## JSON and JSONB support
261
+
262
+ The adapter supports PostgreSQL-native `json` and `jsonb` columns.
263
+
264
+ ### Value semantics
265
+
266
+ Both `json` and `jsonb` accept any valid JSON value:
267
+
268
+ - object
269
+ - array
270
+ - string
271
+ - number
272
+ - boolean
273
+ - JSON `null` (distinct from SQL `NULL`)
274
+
275
+ `jsonb` uses normalized binary storage, so whitespace and object key order are not preserved.
276
+
277
+ ### Authoring helpers
278
+
279
+ ```typescript
280
+ import { json, jsonb } from '@prisma-next/adapter-postgres/column-types';
281
+ import { type as arktype } from 'arktype';
282
+
283
+ const auditPayloadSchema = arktype({
284
+ action: 'string',
285
+ actorId: 'number',
286
+ });
287
+
288
+ table('event', (t) =>
289
+ t
290
+ .column('payload', { type: jsonb(auditPayloadSchema), nullable: false })
291
+ .column('raw', { type: json(), nullable: true }),
292
+ );
293
+ ```
294
+
295
+ ### Typed fallback behavior
296
+
297
+ - If a schema value is provided, emitted `contract.d.ts` derives a concrete type from that schema.
298
+ - If no schema is provided, emitted type falls back to `JsonValue`.
299
+ - Runtime values still encode/decode as JSON-compatible values.
300
+
301
+ ### Standard Schema integration
302
+
303
+ `json(schema)` and `jsonb(schema)` accept Standard Schema values. Arktype schemas work out of the box via their Standard Schema adapter (`schema['~standard']`).
304
+
244
305
  ## Exports
245
306
 
246
307
  - `./adapter`: Adapter implementation (`createPostgresAdapter`)
247
- - `./codec-types`: PostgreSQL codec types (`CodecTypes`, `dataTypes`)
308
+ - `./codec-types`: PostgreSQL codec types (`CodecTypes`, `JsonValue`, `dataTypes`)
309
+ - `./column-types`: Column type descriptors and authoring helpers (`json`, `jsonb`, `jsonColumn`, `jsonbColumn`, `enumType`, `enumColumn`, `textColumn`, `int4Column`, etc.)
248
310
  - `./types`: PostgreSQL-specific types
249
311
  - `./control`: Control-plane entry point (adapter descriptor)
250
312
  - `./runtime`: Runtime-plane entry point (runtime adapter descriptor)
@@ -0,0 +1,361 @@
1
+ import { m as PG_JSON_CODEC_ID, p as PG_JSONB_CODEC_ID } from "./codec-ids-Bsm9c7ns.mjs";
2
+ import { t as codecDefinitions } from "./codecs-DgJcyEBR.mjs";
3
+ import { i as quoteIdentifier, n as escapeLiteral } from "./sql-utils-CSfAGEwF.mjs";
4
+ import { LiteralExpr, createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
5
+ import { ifDefined } from "@prisma-next/utils/defined";
6
+
7
+ //#region src/core/adapter.ts
8
+ const VECTOR_CODEC_ID = "pg/vector@1";
9
+ function getCodecParamCast(codecId) {
10
+ if (codecId === VECTOR_CODEC_ID) return "vector";
11
+ if (codecId === PG_JSON_CODEC_ID) return "json";
12
+ if (codecId === PG_JSONB_CODEC_ID) return "jsonb";
13
+ }
14
+ function renderTypedParam(index, codecId) {
15
+ const cast = getCodecParamCast(codecId);
16
+ return cast ? `$${index}::${cast}` : `$${index}`;
17
+ }
18
+ const defaultCapabilities = Object.freeze({
19
+ postgres: {
20
+ orderBy: true,
21
+ limit: true,
22
+ lateral: true,
23
+ jsonAgg: true,
24
+ returning: true
25
+ },
26
+ sql: { enums: true }
27
+ });
28
+ const parameterizedCodecs = Object.values(codecDefinitions).map((definition) => definition.codec).filter((codec$1) => codec$1.paramsSchema !== void 0).map((codec$1) => Object.freeze({
29
+ codecId: codec$1.id,
30
+ paramsSchema: codec$1.paramsSchema,
31
+ ...ifDefined("init", codec$1.init)
32
+ }));
33
+ var PostgresAdapterImpl = class {
34
+ familyId = "sql";
35
+ targetId = "postgres";
36
+ profile;
37
+ codecRegistry = (() => {
38
+ const registry = createCodecRegistry();
39
+ for (const definition of Object.values(codecDefinitions)) registry.register(definition.codec);
40
+ return registry;
41
+ })();
42
+ constructor(options) {
43
+ this.profile = Object.freeze({
44
+ id: options?.profileId ?? "postgres/default@1",
45
+ target: "postgres",
46
+ capabilities: defaultCapabilities,
47
+ codecs: () => this.codecRegistry
48
+ });
49
+ }
50
+ parameterizedCodecs() {
51
+ return parameterizedCodecs;
52
+ }
53
+ lower(ast, context) {
54
+ const collectedParamRefs = ast.collectParamRefs();
55
+ const paramIndexMap = /* @__PURE__ */ new Map();
56
+ const params = [];
57
+ for (const ref of collectedParamRefs) {
58
+ if (paramIndexMap.has(ref)) continue;
59
+ paramIndexMap.set(ref, params.length + 1);
60
+ params.push(ref.value);
61
+ }
62
+ let sql;
63
+ const node = ast;
64
+ switch (node.kind) {
65
+ case "select":
66
+ sql = renderSelect(node, context.contract, paramIndexMap);
67
+ break;
68
+ case "insert":
69
+ sql = renderInsert(node, context.contract, paramIndexMap);
70
+ break;
71
+ case "update":
72
+ sql = renderUpdate(node, context.contract, paramIndexMap);
73
+ break;
74
+ case "delete":
75
+ sql = renderDelete(node, context.contract, paramIndexMap);
76
+ break;
77
+ default: throw new Error(`Unsupported AST node kind: ${node.kind}`);
78
+ }
79
+ return Object.freeze({
80
+ profileId: this.profile.id,
81
+ body: Object.freeze({
82
+ sql,
83
+ params
84
+ })
85
+ });
86
+ }
87
+ };
88
+ function renderSelect(ast, contract, pim) {
89
+ return [
90
+ `SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(ast.projection, contract, pim)}`,
91
+ `FROM ${renderSource(ast.from, contract, pim)}`,
92
+ ast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(" ") : "",
93
+ ast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : "",
94
+ ast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(", ")}` : "",
95
+ ast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : "",
96
+ ast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => {
97
+ return `${renderExpr(order.expr, contract, pim)} ${order.dir.toUpperCase()}`;
98
+ }).join(", ")}` : "",
99
+ typeof ast.limit === "number" ? `LIMIT ${ast.limit}` : "",
100
+ typeof ast.offset === "number" ? `OFFSET ${ast.offset}` : ""
101
+ ].filter((part) => part.length > 0).join(" ").trim();
102
+ }
103
+ function renderProjection(projection, contract, pim) {
104
+ return projection.map((item) => {
105
+ const alias = quoteIdentifier(item.alias);
106
+ if (item.expr.kind === "literal") return `${renderLiteral(item.expr)} AS ${alias}`;
107
+ return `${renderExpr(item.expr, contract, pim)} AS ${alias}`;
108
+ }).join(", ");
109
+ }
110
+ function renderDistinctPrefix(distinct, distinctOn, contract, pim) {
111
+ if (distinctOn && distinctOn.length > 0) return `DISTINCT ON (${distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(", ")}) `;
112
+ if (distinct) return "DISTINCT ";
113
+ return "";
114
+ }
115
+ function renderSource(source, contract, pim) {
116
+ const node = source;
117
+ switch (node.kind) {
118
+ case "table-source": {
119
+ const table = quoteIdentifier(node.name);
120
+ if (!node.alias) return table;
121
+ return `${table} AS ${quoteIdentifier(node.alias)}`;
122
+ }
123
+ case "derived-table-source": return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;
124
+ default: throw new Error(`Unsupported source node kind: ${node.kind}`);
125
+ }
126
+ }
127
+ function assertScalarSubquery(query) {
128
+ if (query.projection.length !== 1) throw new Error("Subquery expressions must project exactly one column");
129
+ }
130
+ function renderSubqueryExpr(expr, contract, pim) {
131
+ assertScalarSubquery(expr.query);
132
+ return `(${renderSelect(expr.query, contract, pim)})`;
133
+ }
134
+ function renderWhere(expr, contract, pim) {
135
+ return renderExpr(expr, contract, pim);
136
+ }
137
+ function renderNullCheck(expr, contract, pim) {
138
+ const rendered = renderExpr(expr.expr, contract, pim);
139
+ const renderedExpr = expr.expr.kind === "operation" || expr.expr.kind === "subquery" ? `(${rendered})` : rendered;
140
+ return expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;
141
+ }
142
+ function renderBinary(expr, contract, pim) {
143
+ if (expr.right.kind === "list" && expr.right.values.length === 0) {
144
+ if (expr.op === "in") return "FALSE";
145
+ if (expr.op === "notIn") return "TRUE";
146
+ }
147
+ const leftExpr = expr.left;
148
+ const left = renderExpr(leftExpr, contract, pim);
149
+ const leftRendered = leftExpr.kind === "operation" || leftExpr.kind === "subquery" ? `(${left})` : left;
150
+ const rightNode = expr.right;
151
+ let right;
152
+ switch (rightNode.kind) {
153
+ case "list":
154
+ right = renderListLiteral(rightNode, pim);
155
+ break;
156
+ case "literal":
157
+ right = renderLiteral(rightNode);
158
+ break;
159
+ case "column-ref":
160
+ right = renderColumn(rightNode);
161
+ break;
162
+ case "param-ref":
163
+ right = renderParamRef(rightNode, pim);
164
+ break;
165
+ default:
166
+ right = renderExpr(rightNode, contract, pim);
167
+ break;
168
+ }
169
+ return `${leftRendered} ${{
170
+ eq: "=",
171
+ neq: "!=",
172
+ gt: ">",
173
+ lt: "<",
174
+ gte: ">=",
175
+ lte: "<=",
176
+ like: "LIKE",
177
+ ilike: "ILIKE",
178
+ in: "IN",
179
+ notIn: "NOT IN"
180
+ }[expr.op]} ${right}`;
181
+ }
182
+ function renderListLiteral(expr, pim) {
183
+ if (expr.values.length === 0) return "(NULL)";
184
+ return `(${expr.values.map((v) => {
185
+ if (v.kind === "param-ref") return renderParamRef(v, pim);
186
+ if (v.kind === "literal") return renderLiteral(v);
187
+ return renderExpr(v, void 0, pim);
188
+ }).join(", ")})`;
189
+ }
190
+ function renderColumn(ref) {
191
+ if (ref.table === "excluded") return `excluded.${quoteIdentifier(ref.column)}`;
192
+ return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;
193
+ }
194
+ function renderAggregateExpr(expr, contract, pim) {
195
+ const fn = expr.fn.toUpperCase();
196
+ if (!expr.expr) return `${fn}(*)`;
197
+ return `${fn}(${renderExpr(expr.expr, contract, pim)})`;
198
+ }
199
+ function renderJsonObjectExpr(expr, contract, pim) {
200
+ return `json_build_object(${expr.entries.flatMap((entry) => {
201
+ const key = `'${escapeLiteral(entry.key)}'`;
202
+ if (entry.value.kind === "literal") return [key, renderLiteral(entry.value)];
203
+ return [key, renderExpr(entry.value, contract, pim)];
204
+ }).join(", ")})`;
205
+ }
206
+ function renderOrderByItems(items, contract, pim) {
207
+ return items.map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`).join(", ");
208
+ }
209
+ function renderJsonArrayAggExpr(expr, contract, pim) {
210
+ const aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : "";
211
+ const aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;
212
+ if (expr.onEmpty === "emptyArray") return `coalesce(${aggregated}, json_build_array())`;
213
+ return aggregated;
214
+ }
215
+ function renderExpr(expr, contract, pim) {
216
+ const node = expr;
217
+ switch (node.kind) {
218
+ case "column-ref": return renderColumn(node);
219
+ case "identifier-ref": return quoteIdentifier(node.name);
220
+ case "operation": return renderOperation(node, contract, pim);
221
+ case "subquery": return renderSubqueryExpr(node, contract, pim);
222
+ case "aggregate": return renderAggregateExpr(node, contract, pim);
223
+ case "json-object": return renderJsonObjectExpr(node, contract, pim);
224
+ case "json-array-agg": return renderJsonArrayAggExpr(node, contract, pim);
225
+ case "binary": return renderBinary(node, contract, pim);
226
+ case "and":
227
+ if (node.exprs.length === 0) return "TRUE";
228
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" AND ")})`;
229
+ case "or":
230
+ if (node.exprs.length === 0) return "FALSE";
231
+ return `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(" OR ")})`;
232
+ case "exists": return `${node.notExists ? "NOT " : ""}EXISTS (${renderSelect(node.subquery, contract, pim)})`;
233
+ case "null-check": return renderNullCheck(node, contract, pim);
234
+ case "not": return `NOT (${renderExpr(node.expr, contract, pim)})`;
235
+ case "param-ref": return renderParamRef(node, pim);
236
+ case "literal": return renderLiteral(node);
237
+ case "list": return renderListLiteral(node, pim);
238
+ default: throw new Error(`Unsupported expression node kind: ${node.kind}`);
239
+ }
240
+ }
241
+ function renderParamRef(ref, pim) {
242
+ const index = pim?.get(ref);
243
+ if (index === void 0) throw new Error("ParamRef not found in index map");
244
+ return renderTypedParam(index, ref.codecId);
245
+ }
246
+ function renderLiteral(expr) {
247
+ if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
248
+ if (typeof expr.value === "number" || typeof expr.value === "boolean") return String(expr.value);
249
+ if (typeof expr.value === "bigint") return String(expr.value);
250
+ if (expr.value === null) return "NULL";
251
+ if (expr.value === void 0) return "NULL";
252
+ if (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;
253
+ if (Array.isArray(expr.value)) return `ARRAY[${expr.value.map((v) => renderLiteral(new LiteralExpr(v))).join(", ")}]`;
254
+ const json = JSON.stringify(expr.value);
255
+ if (json === void 0) return "NULL";
256
+ return `'${escapeLiteral(json)}'`;
257
+ }
258
+ function renderOperation(expr, contract, pim) {
259
+ const self = renderExpr(expr.self, contract, pim);
260
+ const args = expr.args.map((arg) => {
261
+ return renderExpr(arg, contract, pim);
262
+ });
263
+ let result = expr.lowering.template;
264
+ result = result.replace(/\{\{self\}\}/g, self);
265
+ for (let i = 0; i < args.length; i++) result = result.replace(new RegExp(`\\{\\{arg${i}\\}\\}`, "g"), args[i] ?? "");
266
+ return result;
267
+ }
268
+ function renderJoin(join, contract, pim) {
269
+ return `${join.joinType.toUpperCase()} JOIN ${join.lateral ? "LATERAL " : ""}${renderSource(join.source, contract, pim)} ON ${renderJoinOn(join.on, contract, pim)}`;
270
+ }
271
+ function renderJoinOn(on, contract, pim) {
272
+ if (on.kind === "eq-col-join-on") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;
273
+ return renderWhere(on, contract, pim);
274
+ }
275
+ function getInsertColumnOrder(rows, contract, tableName) {
276
+ const orderedColumns = [];
277
+ const seenColumns = /* @__PURE__ */ new Set();
278
+ for (const row of rows) for (const column of Object.keys(row)) {
279
+ if (seenColumns.has(column)) continue;
280
+ seenColumns.add(column);
281
+ orderedColumns.push(column);
282
+ }
283
+ if (orderedColumns.length > 0) return orderedColumns;
284
+ return Object.keys(contract.storage.tables[tableName]?.columns ?? {});
285
+ }
286
+ function renderInsertValue(value, pim) {
287
+ if (!value || value.kind === "default-value") return "DEFAULT";
288
+ switch (value.kind) {
289
+ case "param-ref": return renderParamRef(value, pim);
290
+ case "column-ref": return renderColumn(value);
291
+ default: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);
292
+ }
293
+ }
294
+ function renderInsert(ast, contract, pim) {
295
+ const table = quoteIdentifier(ast.table.name);
296
+ const rows = ast.rows;
297
+ if (rows.length === 0) throw new Error("INSERT requires at least one row");
298
+ const hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);
299
+ return `${(() => {
300
+ if (!hasExplicitValues) {
301
+ if (rows.length === 1) return `INSERT INTO ${table} DEFAULT VALUES`;
302
+ const defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);
303
+ if (defaultColumns.length === 0) return `INSERT INTO ${table} VALUES ${rows.map(() => "()").join(", ")}`;
304
+ const quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));
305
+ const defaultRow = `(${defaultColumns.map(() => "DEFAULT").join(", ")})`;
306
+ return `INSERT INTO ${table} (${quotedColumns.join(", ")}) VALUES ${rows.map(() => defaultRow).join(", ")}`;
307
+ }
308
+ const columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);
309
+ const columns = columnOrder.map((column) => quoteIdentifier(column));
310
+ const values = rows.map((row) => {
311
+ return `(${columnOrder.map((column) => renderInsertValue(row[column], pim)).join(", ")})`;
312
+ }).join(", ");
313
+ return `INSERT INTO ${table} (${columns.join(", ")}) VALUES ${values}`;
314
+ })()}${ast.onConflict ? (() => {
315
+ const conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));
316
+ if (conflictColumns.length === 0) throw new Error("INSERT onConflict requires at least one conflict column");
317
+ const action = ast.onConflict.action;
318
+ switch (action.kind) {
319
+ case "do-nothing": return ` ON CONFLICT (${conflictColumns.join(", ")}) DO NOTHING`;
320
+ case "do-update-set": {
321
+ const updates = Object.entries(action.set).map(([colName, value]) => {
322
+ const target = quoteIdentifier(colName);
323
+ if (value.kind === "param-ref") return `${target} = ${renderParamRef(value, pim)}`;
324
+ return `${target} = ${renderColumn(value)}`;
325
+ });
326
+ return ` ON CONFLICT (${conflictColumns.join(", ")}) DO UPDATE SET ${updates.join(", ")}`;
327
+ }
328
+ default: throw new Error(`Unsupported onConflict action: ${action.kind}`);
329
+ }
330
+ })() : ""}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(", ")}` : ""}`;
331
+ }
332
+ function renderUpdate(ast, contract, pim) {
333
+ const table = quoteIdentifier(ast.table.name);
334
+ const setClauses = Object.entries(ast.set).map(([col, val]) => {
335
+ const column = quoteIdentifier(col);
336
+ let value;
337
+ switch (val.kind) {
338
+ case "param-ref":
339
+ value = renderParamRef(val, pim);
340
+ break;
341
+ case "column-ref":
342
+ value = renderColumn(val);
343
+ break;
344
+ default: throw new Error(`Unsupported value node in UPDATE: ${val.kind}`);
345
+ }
346
+ return `${column} = ${value}`;
347
+ });
348
+ const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : "";
349
+ const returningClause = ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(", ")}` : "";
350
+ return `UPDATE ${table} SET ${setClauses.join(", ")}${whereClause}${returningClause}`;
351
+ }
352
+ function renderDelete(ast, contract, pim) {
353
+ return `DELETE FROM ${quoteIdentifier(ast.table.name)}${ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : ""}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(", ")}` : ""}`;
354
+ }
355
+ function createPostgresAdapter(options) {
356
+ return Object.freeze(new PostgresAdapterImpl(options));
357
+ }
358
+
359
+ //#endregion
360
+ export { createPostgresAdapter as t };
361
+ //# sourceMappingURL=adapter-CWmWEFe1.mjs.map