@prisma-next/postgres 0.0.1 → 0.3.0-dev.122

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.
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
@@ -1,23 +1,28 @@
1
1
  # @prisma-next/postgres
2
2
 
3
- One-liner lazy Postgres client for Prisma Next runtime composition.
3
+ Composition-root Postgres helper that builds a Prisma Next runtime client and exposes SQL, ORM, schema, and Kysely-integrated query access.
4
4
 
5
5
  ## Package Classification
6
6
 
7
- - **Domain**: targets
8
- - **Layer**: clients
7
+ - **Domain**: extensions
8
+ - **Layer**: adapters
9
9
  - **Plane**: runtime
10
10
 
11
11
  ## Overview
12
12
 
13
- `@prisma-next/postgres/runtime` exposes a single `postgres(...)` helper that composes the SQL execution stack for Postgres and returns static query roots immediately:
13
+ `@prisma-next/postgres/runtime` exposes a single `postgres(...)` helper that composes the Postgres execution stack and returns query/runtime roots:
14
14
 
15
15
  - `db.sql`
16
+ - `db.kysely` (lane-owned build-only authoring surface: `build(query)` + `whereExpr(query)`)
16
17
  - `db.schema`
18
+ - `db.orm`
17
19
  - `db.context`
18
20
  - `db.stack`
19
21
 
20
- Runtime and connection resources are deferred until `await db.runtime()` is called. The getter returns `Promise<Runtime>`.
22
+ `db.kysely` is produced by `@prisma-next/sql-kysely-lane` and intentionally exposes lane behavior, not raw Kysely execution APIs. `build(query)` infers plan row type from `query.compile()`, and `whereExpr(query)` produces `ToWhereExpr` payloads for ORM `.where(...)` interop.
23
+
24
+ Runtime resources are deferred until `db.runtime()` or `db.connect(...)` is called.
25
+ Connection binding can be provided up front (`url`, `pg`, `binding`) or deferred via `db.connect(...)`.
21
26
 
22
27
  When URL binding is used, pool timeouts are configurable via `poolOptions`:
23
28
 
@@ -27,11 +32,12 @@ When URL binding is used, pool timeouts are configurable via `poolOptions`:
27
32
  ## Responsibilities
28
33
 
29
34
  - Build a static Postgres execution stack from target, adapter, and driver descriptors
30
- - Build static query roots from the execution context
35
+ - Build typed SQL and a build-only Kysely authoring surface from the same execution context
36
+ - Build static schema and ORM roots from the execution context
31
37
  - Normalize runtime binding input (`binding`, `url`, `pg`)
32
- - Lazily instantiate stack and driver on first `await db.runtime()` call
33
- - Connect driver with resolved binding before creating runtime
34
- - Memoize runtime so repeated `await db.runtime()` calls return one instance
38
+ - Lazily instantiate runtime resources on first `db.runtime()` or `db.connect(...)` call
39
+ - Connect the internal Postgres driver through `db.connect(...)` or from initial binding options
40
+ - Memoize runtime so repeated `db.runtime()` calls return one instance
35
41
 
36
42
  ## Dependencies
37
43
 
@@ -41,23 +47,25 @@ When URL binding is used, pool timeouts are configurable via `poolOptions`:
41
47
  - `@prisma-next/adapter-postgres` for adapter descriptor
42
48
  - `@prisma-next/driver-postgres` for driver descriptor
43
49
  - `@prisma-next/sql-lane` for `sql(...)`
50
+ - `@prisma-next/sql-kysely-lane` for contract-to-Kysely typing and build-only Kysely plan assembly
44
51
  - `@prisma-next/sql-relational-core` for `schema(...)`
52
+ - `@prisma-next/sql-orm-client` for `orm(...)`
45
53
  - `@prisma-next/sql-contract` for `validateContract(...)` and contract types
46
- - `pg` for binding validation when using `pg` (Pool or Client) input
54
+ - `pg` for lazy `Pool` construction when using URL binding
47
55
 
48
56
  ## Architecture
49
57
 
50
58
  ```mermaid
51
59
  flowchart TD
52
60
  App[App Code] --> Client[postgres(...)]
53
- Client --> Static[Static roots: sql schema context stack]
61
+ Client --> Static[Roots: sql kysely(build-only) schema orm context stack]
54
62
  Client --> Lazy[runtime()]
55
63
 
56
64
  Lazy --> Instantiate[instantiateExecutionStack]
57
65
  Lazy --> Bind[Resolve binding: url or pg]
58
- Bind --> Assert[Assert stackInstance.driver]
59
- Assert --> Connect[driver.connect binding]
60
- Connect --> Runtime[createRuntime]
66
+ Bind --> Pool[pg.Pool for url binding]
67
+ Bind --> Reuse[Reuse Pool or Client for pg binding]
68
+ Lazy --> Runtime[createRuntime]
61
69
 
62
70
  Runtime --> Target[@prisma-next/target-postgres]
63
71
  Runtime --> Adapter[@prisma-next/adapter-postgres]
@@ -68,6 +76,6 @@ flowchart TD
68
76
 
69
77
  ## Related Docs
70
78
 
71
- - Spec: `agent-os/specs/2026-02-10-postgres-one-liner-lazy-client/spec.md`
72
79
  - Architecture: `docs/Architecture Overview.md`
73
80
  - Subsystem: `docs/architecture docs/subsystems/4. Runtime & Plugin Framework.md`
81
+ - Subsystem: `docs/architecture docs/subsystems/5. Adapters & Targets.md`
@@ -1,14 +1,25 @@
1
- import { PostgresBinding, PostgresBinding as PostgresBinding$1, PostgresDriverCreateOptions } from "@prisma-next/driver-postgres/runtime";
1
+ import { KyselyQueryLane, KyselyQueryLane as KyselyQueryLane$1 } from "@prisma-next/sql-kysely-lane";
2
2
  import { SelectBuilder } from "@prisma-next/sql-lane";
3
+ import { orm } from "@prisma-next/sql-orm-client";
3
4
  import { SchemaHandle } from "@prisma-next/sql-relational-core/schema";
4
5
  import { ExecutionContext, Plugin, Runtime, RuntimeVerifyOptions, SqlExecutionStackWithDriver, SqlRuntimeExtensionDescriptor } from "@prisma-next/sql-runtime";
5
6
  import { Client, Pool } from "pg";
6
- import { ExtractCodecTypes, ExtractOperationTypes, SqlContract, SqlStorage } from "@prisma-next/sql-contract/types";
7
+ import { ExtractTypeMapsFromContract, ResolveCodecTypes, ResolveOperationTypes, SqlContract, SqlStorage } from "@prisma-next/sql-contract/types";
7
8
  import { OperationTypeSignature, OperationTypes } from "@prisma-next/sql-relational-core/types";
8
9
 
9
10
  //#region src/runtime/binding.d.ts
11
+ type PostgresBinding = {
12
+ readonly kind: 'url';
13
+ readonly url: string;
14
+ } | {
15
+ readonly kind: 'pgPool';
16
+ readonly pool: Pool;
17
+ } | {
18
+ readonly kind: 'pgClient';
19
+ readonly client: Client;
20
+ };
10
21
  type PostgresBindingInput = {
11
- readonly binding: PostgresBinding$1;
22
+ readonly binding: PostgresBinding;
12
23
  readonly url?: never;
13
24
  readonly pg?: never;
14
25
  } | {
@@ -25,24 +36,36 @@ type PostgresBindingInput = {
25
36
  type NormalizeOperationTypes<T> = { [TypeId in keyof T]: { [Method in keyof T[TypeId]]: T[TypeId][Method] extends OperationTypeSignature ? T[TypeId][Method] : OperationTypeSignature } };
26
37
  type ToSchemaOperationTypes<T> = T extends OperationTypes ? T : NormalizeOperationTypes<T>;
27
38
  type PostgresTargetId = 'postgres';
28
- interface PostgresClient<TContract extends SqlContract<SqlStorage>> {
29
- readonly sql: SelectBuilder<TContract, unknown, ExtractCodecTypes<TContract>, ExtractOperationTypes<TContract>>;
30
- readonly schema: SchemaHandle<TContract, ExtractCodecTypes<TContract>, ToSchemaOperationTypes<ExtractOperationTypes<TContract>>>;
39
+ type OrmClient<TContract extends SqlContract<SqlStorage>> = ReturnType<typeof orm<TContract>>;
40
+ interface PostgresClient<TContract extends SqlContract<SqlStorage>, TTypeMaps = ExtractTypeMapsFromContract<TContract>> {
41
+ readonly sql: SelectBuilder<TContract, unknown, ResolveCodecTypes<TContract, TTypeMaps>, ResolveOperationTypes<TContract, TTypeMaps>>;
42
+ readonly kysely: KyselyQueryLane$1<TContract>;
43
+ readonly schema: SchemaHandle<TContract, ResolveCodecTypes<TContract, TTypeMaps>, ToSchemaOperationTypes<ResolveOperationTypes<TContract, TTypeMaps>>>;
44
+ readonly orm: OrmClient<TContract>;
31
45
  readonly context: ExecutionContext<TContract>;
32
46
  readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;
33
- runtime(): Promise<Runtime>;
47
+ connect(bindingInput?: PostgresBindingInput): Promise<Runtime>;
48
+ runtime(): Runtime;
34
49
  }
35
50
  interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {
36
51
  readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];
37
52
  readonly plugins?: readonly Plugin<TContract>[];
38
53
  readonly verify?: RuntimeVerifyOptions;
39
- readonly cursor?: PostgresDriverCreateOptions['cursor'];
54
+ readonly poolOptions?: {
55
+ readonly connectionTimeoutMillis?: number;
56
+ readonly idleTimeoutMillis?: number;
57
+ };
58
+ }
59
+ interface PostgresBindingOptions {
60
+ readonly binding?: PostgresBinding;
61
+ readonly url?: string;
62
+ readonly pg?: Pool | Client;
40
63
  }
41
- type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> = PostgresBindingInput & PostgresOptionsBase<TContract> & {
64
+ type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> = PostgresBindingOptions & PostgresOptionsBase<TContract> & {
42
65
  readonly contract: TContract;
43
66
  readonly contractJson?: never;
44
67
  };
45
- type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> = PostgresBindingInput & PostgresOptionsBase<TContract> & {
68
+ type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> = PostgresBindingOptions & PostgresOptionsBase<TContract> & {
46
69
  readonly contractJson: unknown;
47
70
  readonly contract?: never;
48
71
  };
@@ -50,9 +73,12 @@ type PostgresOptions<TContract extends SqlContract<SqlStorage>> = PostgresOption
50
73
  /**
51
74
  * Creates a lazy Postgres client from either `contractJson` or a TypeScript-authored `contract`.
52
75
  * Static query surfaces are available immediately, while `runtime()` instantiates the driver/pool on first call.
76
+ *
77
+ * - No-emit: infers TypeMaps from ContractWithTypeMaps. Example: postgres({ contract })
78
+ * - Emitted: pass TypeMaps explicitly. Example: postgres<Contract, TypeMaps>({ contractJson, url })
53
79
  */
54
- declare function postgres<TContract extends SqlContract<SqlStorage>>(options: PostgresOptionsWithContract<TContract>): PostgresClient<TContract>;
55
- declare function postgres<TContract extends SqlContract<SqlStorage>>(options: PostgresOptionsWithContractJson<TContract>): PostgresClient<TContract>;
80
+ declare function postgres<TContract extends SqlContract<SqlStorage>, TTypeMaps = ExtractTypeMapsFromContract<TContract>>(options: PostgresOptionsWithContract<TContract>): PostgresClient<TContract, TTypeMaps>;
81
+ declare function postgres<TContract extends SqlContract<SqlStorage>, TTypeMaps = ExtractTypeMapsFromContract<TContract>>(options: PostgresOptionsWithContractJson<TContract>): PostgresClient<TContract, TTypeMaps>;
56
82
  //#endregion
57
- export { type PostgresBinding, type PostgresClient, type PostgresOptions, type PostgresOptionsBase, type PostgresOptionsWithContract, type PostgresOptionsWithContractJson, postgres as default };
83
+ export { type KyselyQueryLane, type PostgresBinding, type PostgresClient, type PostgresOptions, type PostgresOptionsBase, type PostgresOptionsWithContract, type PostgresOptionsWithContractJson, postgres as default };
58
84
  //# sourceMappingURL=runtime.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/runtime/binding.ts","../src/runtime/postgres.ts"],"sourcesContent":[],"mappings":";;;;;;;;;KAIY,oBAAA;oBAEY;;;;;;EAFZ,SAAA,EAAA,CAAA,EAAA,KAAA;CAEY,GAAA;EAUL,SAAA,EAAA,EAAA,IAAA,GAAO,MAAP;EAAO,SAAA,OAAA,CAAA,EAAA,KAAA;EAAM,SAAA,GAAA,CAAA,EAAA,KAAA;;;;KCoB3B,gDACc,iBDjCP,MCkCS,CDlCT,CCkCW,MDlCS,CAAA,GCkCC,CDlCD,CCkCG,MDlCH,CAAA,CCkCW,MDlCX,CAAA,SCkC2B,sBDlC3B,GCmCxB,CDnCwB,CCmCtB,MDnCsB,CAAA,CCmCd,MDnCc,CAAA,GCoCxB,sBDpCwB,EAER,EAUL;KC4Bd,sBD5BqB,CAAA,CAAA,CAAA,GC4BO,CD5BP,SC4BiB,cD5BjB,GC4BkC,CD5BlC,GC4BsC,uBD5BtC,CC4B8D,CD5B9D,CAAA;AAAM,KC8BpB,gBAAA,GD9BoB,UAAA;UCgCf,iCAAiC,YAAY;gBAC9C,cACZ,oBAEA,kBAAkB,YAClB,sBAAsB;mBAEP,aACf,WACA,kBAAkB,YAClB,uBAAuB,sBAAsB;EAtB5C,SAAA,OAAA,EAwBe,gBAxBQ,CAwBS,SAxBT,CAAA;EACT,SAAA,KAAA,EAwBD,2BA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CAkDc,UAlDd,CAAA,CAAA,GAmD1D,sBAnD0D,GAoDxD,mBApDwD,CAoDpC,SApDoC,CAAA,GAAA;EAAU,SAAA,YAAA,EAAA,OAAA;EAIrD,SAAA,QAAc,CAAA,EAAA,KAAA;CACC;AAAZ,KAoDR,eApDQ,CAAA,kBAoD0B,WApD1B,CAoDsC,UApDtC,CAAA,CAAA,GAqDhB,2BArDgB,CAqDY,SArDZ,CAAA,GAsDhB,+BAtDgB,CAsDgB,SAtDhB,CAAA;;;;;;;;AAOiB,iBAuFb,QAvFa,CAAA,kBAwFjB,WAxFiB,CAwFL,UAxFK,CAAA,EAAA,YAyFvB,2BAzFuB,CAyFK,SAzFL,CAAA,CAAA,CAAA,OAAA,EA0F1B,2BA1F0B,CA0FE,SA1FF,CAAA,CAAA,EA0Fe,cA1Ff,CA0F8B,SA1F9B,EA0FyC,SA1FzC,CAAA;AAAjC,iBA2FoB,QA3FpB,CAAA,kBA4FgB,WA5FhB,CA4F4B,UA5F5B,CAAA,EAAA,YA6FU,2BA7FV,CA6FsC,SA7FtC,CAAA,CAAA,CAAA,OAAA,EA8FO,+BA9FP,CA8FuC,SA9FvC,CAAA,CAAA,EA8FoD,cA9FpD,CA8FmE,SA9FnE,EA8F8E,SA9F9E,CAAA"}
package/dist/runtime.mjs CHANGED
@@ -2,60 +2,36 @@ import postgresAdapter from "@prisma-next/adapter-postgres/runtime";
2
2
  import { instantiateExecutionStack } from "@prisma-next/core-execution-plane/stack";
3
3
  import postgresDriver from "@prisma-next/driver-postgres/runtime";
4
4
  import { validateContract } from "@prisma-next/sql-contract/validate";
5
+ import { createKyselyLane } from "@prisma-next/sql-kysely-lane";
5
6
  import { sql } from "@prisma-next/sql-lane";
7
+ import { orm } from "@prisma-next/sql-orm-client";
6
8
  import { schema } from "@prisma-next/sql-relational-core/schema";
7
9
  import { createExecutionContext, createRuntime, createSqlExecutionStack } from "@prisma-next/sql-runtime";
8
10
  import postgresTarget from "@prisma-next/target-postgres/runtime";
9
- import { ifDefined } from "@prisma-next/utils/defined";
10
11
  import { Client, Pool } from "pg";
11
12
 
12
13
  //#region src/runtime/binding.ts
13
- function bindingError(message, details) {
14
- const error = new Error(message);
15
- Object.defineProperty(error, "name", {
16
- value: "RuntimeError",
17
- configurable: true
18
- });
19
- return Object.assign(error, {
20
- code: "DRIVER.BINDING_INVALID",
21
- category: "RUNTIME",
22
- severity: "error",
23
- message,
24
- details
25
- });
26
- }
27
14
  function validatePostgresUrl(url) {
28
15
  const trimmed = url.trim();
29
- if (trimmed.length === 0) throw bindingError("Postgres URL must be a non-empty string", {
30
- field: "url",
31
- reason: "empty"
32
- });
16
+ if (trimmed.length === 0) throw new Error("Postgres URL must be a non-empty string");
33
17
  let parsed;
34
18
  try {
35
19
  parsed = new URL(trimmed);
36
20
  } catch {
37
- throw bindingError("Postgres URL must be a valid URL", {
38
- field: "url",
39
- reason: "invalid-url"
40
- });
21
+ throw new Error("Postgres URL must be a valid URL");
41
22
  }
42
- if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") throw bindingError("Postgres URL must use postgres:// or postgresql://", {
43
- field: "url",
44
- reason: "invalid-protocol",
45
- protocol: parsed.protocol
46
- });
23
+ if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") throw new Error("Postgres URL must use postgres:// or postgresql://");
47
24
  return trimmed;
48
25
  }
49
26
  function resolvePostgresBinding(options) {
50
- const providedCount = Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.pg !== void 0);
51
- if (providedCount !== 1) throw bindingError("Provide one binding input: binding, url, or pg", { providedCount });
27
+ if (Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.pg !== void 0) !== 1) throw new Error("Provide one binding input: binding, url, or pg");
52
28
  if (options.binding !== void 0) return options.binding;
53
29
  if (options.url !== void 0) return {
54
30
  kind: "url",
55
31
  url: validatePostgresUrl(options.url)
56
32
  };
57
33
  const pgBinding = options.pg;
58
- if (pgBinding === void 0) throw bindingError("Invariant violation: expected pg binding after validation", { reason: "missing-pg-binding" });
34
+ if (pgBinding === void 0) throw new Error("Invariant violation: expected pg binding after validation");
59
35
  if (pgBinding instanceof Pool) return {
60
36
  kind: "pgPool",
61
37
  pool: pgBinding
@@ -64,7 +40,11 @@ function resolvePostgresBinding(options) {
64
40
  kind: "pgClient",
65
41
  client: pgBinding
66
42
  };
67
- throw bindingError("Unable to determine pg binding type from pg input; use binding with explicit kind", { reason: "unknown-pg-instance" });
43
+ throw new Error("Unable to determine pg binding type from pg input; use binding with explicit kind");
44
+ }
45
+ function resolveOptionalPostgresBinding(options) {
46
+ if (Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.pg !== void 0) === 0) return;
47
+ return resolvePostgresBinding(options);
68
48
  }
69
49
 
70
50
  //#endregion
@@ -75,18 +55,24 @@ function hasContractJson(options) {
75
55
  function resolveContract(options) {
76
56
  return validateContract(hasContractJson(options) ? options.contractJson : options.contract);
77
57
  }
58
+ function toRuntimeBinding(binding, options) {
59
+ if (binding.kind !== "url") return binding;
60
+ return {
61
+ kind: "pgPool",
62
+ pool: new Pool({
63
+ connectionString: binding.url,
64
+ connectionTimeoutMillis: options.poolOptions?.connectionTimeoutMillis ?? 2e4,
65
+ idleTimeoutMillis: options.poolOptions?.idleTimeoutMillis ?? 3e4
66
+ })
67
+ };
68
+ }
78
69
  function postgres(options) {
79
70
  const contract = resolveContract(options);
80
- const binding = resolvePostgresBinding(options);
71
+ let binding = resolveOptionalPostgresBinding(options);
81
72
  const stack = createSqlExecutionStack({
82
73
  target: postgresTarget,
83
74
  adapter: postgresAdapter,
84
- driver: options.cursor === void 0 ? postgresDriver : {
85
- ...postgresDriver,
86
- create() {
87
- return postgresDriver.create({ cursor: options.cursor });
88
- }
89
- },
75
+ driver: postgresDriver,
90
76
  extensionPacks: options.extensions ?? []
91
77
  });
92
78
  const context = createExecutionContext({
@@ -95,39 +81,76 @@ function postgres(options) {
95
81
  });
96
82
  const schema$1 = schema(context);
97
83
  const sql$1 = sql({ context });
98
- let runtimePromise;
84
+ let runtimeInstance;
85
+ let runtimeDriver;
86
+ let driverConnected = false;
87
+ let connectPromise;
88
+ let backgroundConnectError;
89
+ const connectDriver = async (resolvedBinding) => {
90
+ if (driverConnected) return;
91
+ if (!runtimeDriver) throw new Error("Postgres runtime driver missing");
92
+ if (connectPromise) return connectPromise;
93
+ const runtimeBinding = toRuntimeBinding(resolvedBinding, options);
94
+ connectPromise = runtimeDriver.connect(runtimeBinding).then(() => {
95
+ driverConnected = true;
96
+ }).catch(async (err) => {
97
+ backgroundConnectError = err;
98
+ connectPromise = void 0;
99
+ if (resolvedBinding.kind === "url" && runtimeBinding.kind === "pgPool") await runtimeBinding.pool.end().catch(() => void 0);
100
+ throw err;
101
+ });
102
+ return connectPromise;
103
+ };
104
+ const getRuntime = () => {
105
+ if (backgroundConnectError !== void 0) throw backgroundConnectError;
106
+ if (runtimeInstance) return runtimeInstance;
107
+ const stackInstance = instantiateExecutionStack(stack);
108
+ const driverDescriptor = stack.driver;
109
+ if (!driverDescriptor) throw new Error("Driver descriptor missing from execution stack");
110
+ const driver = driverDescriptor.create({ cursor: { disabled: true } });
111
+ runtimeDriver = driver;
112
+ if (binding !== void 0) connectDriver(binding).catch(() => void 0);
113
+ runtimeInstance = createRuntime({
114
+ stackInstance,
115
+ context,
116
+ driver,
117
+ verify: options.verify ?? {
118
+ mode: "onFirstUse",
119
+ requireMarker: false
120
+ },
121
+ ...options.plugins ? { plugins: options.plugins } : {}
122
+ });
123
+ return runtimeInstance;
124
+ };
125
+ const orm$1 = orm({
126
+ runtime: {
127
+ execute(plan) {
128
+ return getRuntime().execute(plan);
129
+ },
130
+ connection() {
131
+ return getRuntime().connection();
132
+ }
133
+ },
134
+ context
135
+ });
99
136
  return {
100
137
  sql: sql$1,
138
+ kysely: createKyselyLane(contract),
101
139
  schema: schema$1,
140
+ orm: orm$1,
102
141
  context,
103
142
  stack,
104
- async runtime() {
105
- if (runtimePromise) return runtimePromise;
106
- runtimePromise = (async () => {
107
- const stackInstance = instantiateExecutionStack(stack);
108
- const driver = stackInstance.driver;
109
- if (driver === void 0) throw new Error("Relational runtime requires a driver descriptor on the execution stack");
110
- try {
111
- await driver.connect(binding);
112
- return createRuntime({
113
- stackInstance,
114
- context,
115
- driver,
116
- verify: options.verify ?? {
117
- mode: "onFirstUse",
118
- requireMarker: false
119
- },
120
- ...ifDefined("plugins", options.plugins)
121
- });
122
- } catch (error) {
123
- await driver.close().catch(() => void 0);
124
- throw error;
125
- }
126
- })();
127
- runtimePromise.catch(() => {
128
- runtimePromise = void 0;
129
- });
130
- return runtimePromise;
143
+ async connect(bindingInput) {
144
+ if (driverConnected || connectPromise) throw new Error("Postgres client already connected");
145
+ if (bindingInput !== void 0) binding = resolvePostgresBinding(bindingInput);
146
+ if (binding === void 0) throw new Error("Postgres binding not configured. Pass url/pg/binding to postgres(...) or call db.connect({ ... }).");
147
+ const runtime = getRuntime();
148
+ if (driverConnected) return runtime;
149
+ await connectDriver(binding);
150
+ return runtime;
151
+ },
152
+ runtime() {
153
+ return getRuntime();
131
154
  }
132
155
  };
133
156
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["parsed: URL","PgPool","PgClient","schema: PostgresClient<TContract>['schema']","schemaBuilder","sql","sqlBuilder","runtimePromise: Promise<Runtime> | undefined"],"sources":["../src/runtime/binding.ts","../src/runtime/postgres.ts"],"sourcesContent":["import type { PostgresBinding } from '@prisma-next/driver-postgres/runtime';\nimport type { Client, Pool } from 'pg';\nimport { Client as PgClient, Pool as PgPool } from 'pg';\n\nexport type PostgresBindingInput =\n | {\n readonly binding: PostgresBinding;\n readonly url?: never;\n readonly pg?: never;\n }\n | {\n readonly url: string;\n readonly binding?: never;\n readonly pg?: never;\n }\n | {\n readonly pg: Pool | Client;\n readonly binding?: never;\n readonly url?: never;\n };\n\ninterface PostgresBindingError extends Error {\n readonly code: 'DRIVER.BINDING_INVALID';\n readonly category: 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\nfunction bindingError(message: string, details?: Record<string, unknown>): PostgresBindingError {\n const error = new Error(message) as PostgresBindingError;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n return Object.assign(error, {\n code: 'DRIVER.BINDING_INVALID' as const,\n category: 'RUNTIME' as const,\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction validatePostgresUrl(url: string): string {\n const trimmed = url.trim();\n if (trimmed.length === 0) {\n throw bindingError('Postgres URL must be a non-empty string', {\n field: 'url',\n reason: 'empty',\n });\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw bindingError('Postgres URL must be a valid URL', {\n field: 'url',\n reason: 'invalid-url',\n });\n }\n\n if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {\n throw bindingError('Postgres URL must use postgres:// or postgresql://', {\n field: 'url',\n reason: 'invalid-protocol',\n protocol: parsed.protocol,\n });\n }\n\n return trimmed;\n}\n\nexport function resolvePostgresBinding(options: PostgresBindingInput): PostgresBinding {\n const providedCount =\n Number(options.binding !== undefined) +\n Number(options.url !== undefined) +\n Number(options.pg !== undefined);\n\n if (providedCount !== 1) {\n throw bindingError('Provide one binding input: binding, url, or pg', {\n providedCount,\n });\n }\n\n if (options.binding !== undefined) {\n return options.binding;\n }\n\n if (options.url !== undefined) {\n return { kind: 'url', url: validatePostgresUrl(options.url) };\n }\n\n const pgBinding = options.pg;\n if (pgBinding === undefined) {\n throw bindingError('Invariant violation: expected pg binding after validation', {\n reason: 'missing-pg-binding',\n });\n }\n\n if (pgBinding instanceof PgPool) {\n return { kind: 'pgPool', pool: pgBinding };\n }\n\n if (pgBinding instanceof PgClient) {\n return { kind: 'pgClient', client: pgBinding };\n }\n\n throw bindingError(\n 'Unable to determine pg binding type from pg input; use binding with explicit kind',\n {\n reason: 'unknown-pg-instance',\n },\n );\n}\n","import postgresAdapter from '@prisma-next/adapter-postgres/runtime';\nimport { instantiateExecutionStack } from '@prisma-next/core-execution-plane/stack';\nimport type { PostgresDriverCreateOptions } from '@prisma-next/driver-postgres/runtime';\nimport postgresDriver from '@prisma-next/driver-postgres/runtime';\nimport type {\n ExtractCodecTypes,\n ExtractOperationTypes,\n SqlContract,\n SqlStorage,\n} from '@prisma-next/sql-contract/types';\nimport { validateContract } from '@prisma-next/sql-contract/validate';\nimport type { SelectBuilder } from '@prisma-next/sql-lane';\nimport { sql as sqlBuilder } from '@prisma-next/sql-lane';\nimport type { SchemaHandle } from '@prisma-next/sql-relational-core/schema';\nimport { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';\nimport type {\n OperationTypeSignature,\n OperationTypes,\n} from '@prisma-next/sql-relational-core/types';\nimport type {\n ExecutionContext,\n Plugin,\n Runtime,\n RuntimeVerifyOptions,\n SqlExecutionStackWithDriver,\n SqlRuntimeExtensionDescriptor,\n} from '@prisma-next/sql-runtime';\nimport {\n createExecutionContext,\n createRuntime,\n createSqlExecutionStack,\n} from '@prisma-next/sql-runtime';\nimport postgresTarget from '@prisma-next/target-postgres/runtime';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type PostgresBindingInput, resolvePostgresBinding } from './binding';\n\ntype NormalizeOperationTypes<T> = {\n [TypeId in keyof T]: {\n [Method in keyof T[TypeId]]: T[TypeId][Method] extends OperationTypeSignature\n ? T[TypeId][Method]\n : OperationTypeSignature;\n };\n};\n\ntype ToSchemaOperationTypes<T> = T extends OperationTypes ? T : NormalizeOperationTypes<T>;\n\nexport type PostgresTargetId = 'postgres';\n\nexport interface PostgresClient<TContract extends SqlContract<SqlStorage>> {\n readonly sql: SelectBuilder<\n TContract,\n unknown,\n ExtractCodecTypes<TContract>,\n ExtractOperationTypes<TContract>\n >;\n readonly schema: SchemaHandle<\n TContract,\n ExtractCodecTypes<TContract>,\n ToSchemaOperationTypes<ExtractOperationTypes<TContract>>\n >;\n readonly context: ExecutionContext<TContract>;\n readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;\n runtime(): Promise<Runtime>;\n}\n\nexport interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {\n readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];\n readonly plugins?: readonly Plugin<TContract>[];\n readonly verify?: RuntimeVerifyOptions;\n readonly cursor?: PostgresDriverCreateOptions['cursor'];\n}\n\nexport type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> =\n PostgresBindingInput &\n PostgresOptionsBase<TContract> & {\n readonly contract: TContract;\n readonly contractJson?: never;\n };\n\nexport type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> =\n PostgresBindingInput &\n PostgresOptionsBase<TContract> & {\n readonly contractJson: unknown;\n readonly contract?: never;\n };\n\nexport type PostgresOptions<TContract extends SqlContract<SqlStorage>> =\n | PostgresOptionsWithContract<TContract>\n | PostgresOptionsWithContractJson<TContract>;\n\nfunction hasContractJson<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptions<TContract>,\n): options is PostgresOptionsWithContractJson<TContract> {\n return 'contractJson' in options;\n}\n\nfunction resolveContract<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptions<TContract>,\n): TContract {\n const contractInput = hasContractJson(options) ? options.contractJson : options.contract;\n return validateContract<TContract>(contractInput);\n}\n\n/**\n * Creates a lazy Postgres client from either `contractJson` or a TypeScript-authored `contract`.\n * Static query surfaces are available immediately, while `runtime()` instantiates the driver/pool on first call.\n */\nexport default function postgres<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptionsWithContract<TContract>,\n): PostgresClient<TContract>;\nexport default function postgres<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptionsWithContractJson<TContract>,\n): PostgresClient<TContract>;\nexport default function postgres<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptions<TContract>,\n): PostgresClient<TContract> {\n const contract = resolveContract(options);\n const binding = resolvePostgresBinding(options);\n const stack = createSqlExecutionStack({\n target: postgresTarget,\n adapter: postgresAdapter,\n driver:\n options.cursor === undefined\n ? postgresDriver\n : {\n ...postgresDriver,\n create() {\n return postgresDriver.create({ cursor: options.cursor });\n },\n },\n extensionPacks: options.extensions ?? [],\n });\n\n const context = createExecutionContext({\n contract,\n stack,\n });\n\n const schema: PostgresClient<TContract>['schema'] = schemaBuilder(context);\n const sql = sqlBuilder({ context });\n\n let runtimePromise: Promise<Runtime> | undefined;\n\n return {\n sql,\n schema,\n context,\n stack,\n async runtime() {\n if (runtimePromise) {\n return runtimePromise;\n }\n\n runtimePromise = (async () => {\n const stackInstance = instantiateExecutionStack(stack);\n const driver = stackInstance.driver;\n if (driver === undefined) {\n throw new Error('Relational runtime requires a driver descriptor on the execution stack');\n }\n\n try {\n // `binding` is normalized by resolvePostgresBinding(), so this call site remains\n // type-safe in practice while SqlRuntimeDriverInstance currently uses SqlDriver<unknown>.\n await driver.connect(binding);\n\n return createRuntime({\n stackInstance,\n context,\n driver,\n verify: options.verify ?? { mode: 'onFirstUse', requireMarker: false },\n ...ifDefined('plugins', options.plugins),\n });\n } catch (error) {\n await driver.close().catch(() => undefined);\n throw error;\n }\n })();\n\n runtimePromise.catch(() => {\n runtimePromise = undefined;\n });\n\n return runtimePromise;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4BA,SAAS,aAAa,SAAiB,SAAyD;CAC9F,MAAM,QAAQ,IAAI,MAAM,QAAQ;AAChC,QAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;EACf,CAAC;AACF,QAAO,OAAO,OAAO,OAAO;EAC1B,MAAM;EACN,UAAU;EACV,UAAU;EACV;EACA;EACD,CAAC;;AAGJ,SAAS,oBAAoB,KAAqB;CAChD,MAAM,UAAU,IAAI,MAAM;AAC1B,KAAI,QAAQ,WAAW,EACrB,OAAM,aAAa,2CAA2C;EAC5D,OAAO;EACP,QAAQ;EACT,CAAC;CAGJ,IAAIA;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,QAAQ;SACnB;AACN,QAAM,aAAa,oCAAoC;GACrD,OAAO;GACP,Q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F,MAAM,UAAU,uBAAuB;EACrC;EACA;EACD,CAAC;CAEF,MAAMC,WAA8CC,OAAc,QAAQ;CAC1E,MAAMC,QAAMC,IAAW,EAAE,SAAS,CAAC;CAEnC,IAAIC;AAEJ,QAAO;EACL;EACA;EACA;EACA;EACA,MAAM,UAAU;AACd,OAAI,eACF,QAAO;AAGT,qBAAkB,YAAY;IAC5B,MAAM,gBAAgB,0BAA0B,MAAM;IACtD,MAAM,SAAS,cAAc;AAC7B,QAAI,WAAW,OACb,OAAM,IAAI,MAAM,yEAAyE;AAG3F,QAAI;AAGF,WAAM,OAAO,QAAQ,QAAQ;AAE7B,YAAO,cAAc;MACnB;MACA;MACA;MACA,QAAQ,QAAQ,UAAU;OAAE,MAAM;OAAc,eAAe;OAAO;MACtE,GAAG,UAAU,WAAW,QAAQ,QAAQ;MACzC,CAAC;aACK,OAAO;AACd,WAAM,OAAO,OAAO,CAAC,YAAY,OAAU;AAC3C,WAAM;;OAEN;AAEJ,kBAAe,YAAY;AACzB,qBAAiB;KACjB;AAEF,UAAO;;EAEV"}
1
+ {"version":3,"file":"runtime.mjs","names":["parsed: URL","PgPool","PgClient","schema","schemaBuilder","sql","sqlBuilder","runtimeInstance: Runtime | undefined","runtimeDriver: { connect(binding: unknown): Promise<void> } | undefined","connectPromise: Promise<void> | undefined","backgroundConnectError: unknown","orm: OrmClient<TContract>","ormBuilder"],"sources":["../src/runtime/binding.ts","../src/runtime/postgres.ts"],"sourcesContent":["import type { Client, Pool } from 'pg';\nimport { Client as PgClient, Pool as PgPool } from 'pg';\n\nexport type PostgresBinding =\n | { readonly kind: 'url'; readonly url: string }\n | { readonly kind: 'pgPool'; readonly pool: Pool }\n | { readonly kind: 'pgClient'; readonly client: Client };\n\nexport type PostgresBindingInput =\n | {\n readonly binding: PostgresBinding;\n readonly url?: never;\n readonly pg?: never;\n }\n | {\n readonly url: string;\n readonly binding?: never;\n readonly pg?: never;\n }\n | {\n readonly pg: Pool | Client;\n readonly binding?: never;\n readonly url?: never;\n };\n\ntype PostgresBindingFields = {\n readonly binding?: PostgresBinding;\n readonly url?: string;\n readonly pg?: Pool | Client;\n};\n\nfunction validatePostgresUrl(url: string): string {\n const trimmed = url.trim();\n if (trimmed.length === 0) {\n throw new Error('Postgres URL must be a non-empty string');\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw new Error('Postgres URL must be a valid URL');\n }\n\n if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {\n throw new Error('Postgres URL must use postgres:// or postgresql://');\n }\n\n return trimmed;\n}\n\nexport function resolvePostgresBinding(options: PostgresBindingInput): PostgresBinding {\n const providedCount =\n Number(options.binding !== undefined) +\n Number(options.url !== undefined) +\n Number(options.pg !== undefined);\n\n if (providedCount !== 1) {\n throw new Error('Provide one binding input: binding, url, or pg');\n }\n\n if (options.binding !== undefined) {\n return options.binding;\n }\n\n if (options.url !== undefined) {\n return { kind: 'url', url: validatePostgresUrl(options.url) };\n }\n\n const pgBinding = options.pg;\n if (pgBinding === undefined) {\n throw new Error('Invariant violation: expected pg binding after validation');\n }\n\n if (pgBinding instanceof PgPool) {\n return { kind: 'pgPool', pool: pgBinding };\n }\n\n if (pgBinding instanceof PgClient) {\n return { kind: 'pgClient', client: pgBinding };\n }\n\n throw new Error(\n 'Unable to determine pg binding type from pg input; use binding with explicit kind',\n );\n}\n\nexport function resolveOptionalPostgresBinding(\n options: PostgresBindingFields,\n): PostgresBinding | undefined {\n const providedCount =\n Number(options.binding !== undefined) +\n Number(options.url !== undefined) +\n Number(options.pg !== undefined);\n\n if (providedCount === 0) {\n return undefined;\n }\n\n return resolvePostgresBinding(options as PostgresBindingInput);\n}\n","import postgresAdapter from '@prisma-next/adapter-postgres/runtime';\nimport { instantiateExecutionStack } from '@prisma-next/core-execution-plane/stack';\nimport postgresDriver from '@prisma-next/driver-postgres/runtime';\nimport type {\n ExtractTypeMapsFromContract,\n ResolveCodecTypes,\n ResolveOperationTypes,\n SqlContract,\n SqlStorage,\n} from '@prisma-next/sql-contract/types';\nimport { validateContract } from '@prisma-next/sql-contract/validate';\nimport { createKyselyLane, type KyselyQueryLane } from '@prisma-next/sql-kysely-lane';\nimport type { SelectBuilder } from '@prisma-next/sql-lane';\nimport { sql as sqlBuilder } from '@prisma-next/sql-lane';\nimport { orm as ormBuilder } from '@prisma-next/sql-orm-client';\nimport type { SchemaHandle } from '@prisma-next/sql-relational-core/schema';\nimport { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';\nimport type {\n OperationTypeSignature,\n OperationTypes,\n} from '@prisma-next/sql-relational-core/types';\nimport type {\n ExecutionContext,\n Plugin,\n Runtime,\n RuntimeVerifyOptions,\n SqlExecutionStackWithDriver,\n SqlRuntimeExtensionDescriptor,\n} from '@prisma-next/sql-runtime';\nimport {\n createExecutionContext,\n createRuntime,\n createSqlExecutionStack,\n} from '@prisma-next/sql-runtime';\nimport postgresTarget from '@prisma-next/target-postgres/runtime';\nimport { type Client, Pool } from 'pg';\nimport {\n type PostgresBinding,\n type PostgresBindingInput,\n resolveOptionalPostgresBinding,\n resolvePostgresBinding,\n} from './binding';\n\ntype NormalizeOperationTypes<T> = {\n [TypeId in keyof T]: {\n [Method in keyof T[TypeId]]: T[TypeId][Method] extends OperationTypeSignature\n ? T[TypeId][Method]\n : OperationTypeSignature;\n };\n};\n\ntype ToSchemaOperationTypes<T> = T extends OperationTypes ? T : NormalizeOperationTypes<T>;\n\nexport type PostgresTargetId = 'postgres';\ntype OrmClient<TContract extends SqlContract<SqlStorage>> = ReturnType<\n typeof ormBuilder<TContract>\n>;\n\nexport interface PostgresClient<\n TContract extends SqlContract<SqlStorage>,\n TTypeMaps = ExtractTypeMapsFromContract<TContract>,\n> {\n readonly sql: SelectBuilder<\n TContract,\n unknown,\n ResolveCodecTypes<TContract, TTypeMaps>,\n ResolveOperationTypes<TContract, TTypeMaps>\n >;\n readonly kysely: KyselyQueryLane<TContract>;\n readonly schema: SchemaHandle<\n TContract,\n ResolveCodecTypes<TContract, TTypeMaps>,\n ToSchemaOperationTypes<ResolveOperationTypes<TContract, TTypeMaps>>\n >;\n readonly orm: OrmClient<TContract>;\n readonly context: ExecutionContext<TContract>;\n readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;\n connect(bindingInput?: PostgresBindingInput): Promise<Runtime>;\n runtime(): Runtime;\n}\n\nexport interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {\n readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];\n readonly plugins?: readonly Plugin<TContract>[];\n readonly verify?: RuntimeVerifyOptions;\n readonly poolOptions?: {\n readonly connectionTimeoutMillis?: number;\n readonly idleTimeoutMillis?: number;\n };\n}\n\nexport interface PostgresBindingOptions {\n readonly binding?: PostgresBinding;\n readonly url?: string;\n readonly pg?: Pool | Client;\n}\n\nexport type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> =\n PostgresBindingOptions &\n PostgresOptionsBase<TContract> & {\n readonly contract: TContract;\n readonly contractJson?: never;\n };\n\nexport type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> =\n PostgresBindingOptions &\n PostgresOptionsBase<TContract> & {\n readonly contractJson: unknown;\n readonly contract?: never;\n };\n\nexport type PostgresOptions<TContract extends SqlContract<SqlStorage>> =\n | PostgresOptionsWithContract<TContract>\n | PostgresOptionsWithContractJson<TContract>;\n\nfunction hasContractJson<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptions<TContract>,\n): options is PostgresOptionsWithContractJson<TContract> {\n return 'contractJson' in options;\n}\n\nfunction resolveContract<TContract extends SqlContract<SqlStorage>>(\n options: PostgresOptions<TContract>,\n): TContract {\n const contractInput = hasContractJson(options) ? options.contractJson : options.contract;\n return validateContract<TContract>(contractInput);\n}\n\nfunction toRuntimeBinding<TContract extends SqlContract<SqlStorage>>(\n binding: PostgresBinding,\n options: PostgresOptions<TContract>,\n) {\n if (binding.kind !== 'url') {\n return binding;\n }\n\n return {\n kind: 'pgPool',\n pool: new Pool({\n connectionString: binding.url,\n connectionTimeoutMillis: options.poolOptions?.connectionTimeoutMillis ?? 20_000,\n idleTimeoutMillis: options.poolOptions?.idleTimeoutMillis ?? 30_000,\n }),\n } as const;\n}\n\n/**\n * Creates a lazy Postgres client from either `contractJson` or a TypeScript-authored `contract`.\n * Static query surfaces are available immediately, while `runtime()` instantiates the driver/pool on first call.\n *\n * - No-emit: infers TypeMaps from ContractWithTypeMaps. Example: postgres({ contract })\n * - Emitted: pass TypeMaps explicitly. Example: postgres<Contract, TypeMaps>({ contractJson, url })\n */\nexport default function postgres<\n TContract extends SqlContract<SqlStorage>,\n TTypeMaps = ExtractTypeMapsFromContract<TContract>,\n>(options: PostgresOptionsWithContract<TContract>): PostgresClient<TContract, TTypeMaps>;\nexport default function postgres<\n TContract extends SqlContract<SqlStorage>,\n TTypeMaps = ExtractTypeMapsFromContract<TContract>,\n>(options: PostgresOptionsWithContractJson<TContract>): PostgresClient<TContract, TTypeMaps>;\nexport default function postgres<\n TContract extends SqlContract<SqlStorage>,\n TTypeMaps = ExtractTypeMapsFromContract<TContract>,\n>(options: PostgresOptions<TContract>): PostgresClient<TContract, TTypeMaps> {\n const contract = resolveContract(options);\n let binding = resolveOptionalPostgresBinding(options);\n const stack = createSqlExecutionStack({\n target: postgresTarget,\n adapter: postgresAdapter,\n driver: postgresDriver,\n extensionPacks: options.extensions ?? [],\n });\n\n const context = createExecutionContext({\n contract,\n stack,\n });\n\n const schema = schemaBuilder<TContract, TTypeMaps>(context);\n const sql = sqlBuilder<TContract, TTypeMaps>({ context });\n let runtimeInstance: Runtime | undefined;\n let runtimeDriver: { connect(binding: unknown): Promise<void> } | undefined;\n let driverConnected = false;\n let connectPromise: Promise<void> | undefined;\n let backgroundConnectError: unknown;\n const connectDriver = async (resolvedBinding: PostgresBinding): Promise<void> => {\n if (driverConnected) return;\n if (!runtimeDriver) throw new Error('Postgres runtime driver missing');\n if (connectPromise) return connectPromise;\n const runtimeBinding = toRuntimeBinding(resolvedBinding, options);\n connectPromise = runtimeDriver\n .connect(runtimeBinding)\n .then(() => {\n driverConnected = true;\n })\n .catch(async (err) => {\n backgroundConnectError = err;\n connectPromise = undefined;\n if (resolvedBinding.kind === 'url' && runtimeBinding.kind === 'pgPool') {\n await runtimeBinding.pool.end().catch(() => undefined);\n }\n throw err;\n });\n return connectPromise;\n };\n const getRuntime = (): Runtime => {\n if (backgroundConnectError !== undefined) {\n throw backgroundConnectError;\n }\n\n if (runtimeInstance) {\n return runtimeInstance;\n }\n\n const stackInstance = instantiateExecutionStack(stack);\n const driverDescriptor = stack.driver;\n if (!driverDescriptor) {\n throw new Error('Driver descriptor missing from execution stack');\n }\n\n const driver = driverDescriptor.create({\n cursor: { disabled: true },\n });\n runtimeDriver = driver;\n if (binding !== undefined) {\n void connectDriver(binding).catch(() => undefined);\n }\n\n runtimeInstance = createRuntime({\n stackInstance,\n context,\n driver,\n verify: options.verify ?? { mode: 'onFirstUse', requireMarker: false },\n ...(options.plugins ? { plugins: options.plugins } : {}),\n });\n\n return runtimeInstance;\n };\n const orm: OrmClient<TContract> = ormBuilder({\n runtime: {\n execute(plan) {\n return getRuntime().execute(plan);\n },\n connection() {\n return getRuntime().connection();\n },\n },\n context,\n });\n\n return {\n sql,\n kysely: createKyselyLane(contract),\n schema: schema as PostgresClient<TContract, TTypeMaps>['schema'],\n orm,\n context,\n stack,\n async connect(bindingInput) {\n if (driverConnected || connectPromise) {\n throw new Error('Postgres client already connected');\n }\n\n if (bindingInput !== undefined) {\n binding = resolvePostgresBinding(bindingInput);\n }\n\n if (binding === undefined) {\n throw new Error(\n 'Postgres binding not configured. Pass url/pg/binding to postgres(...) or call db.connect({ ... }).',\n );\n }\n\n const runtime = getRuntime();\n if (driverConnected) {\n return runtime;\n }\n\n await connectDriver(binding);\n return runtime;\n },\n runtime() {\n return getRuntime();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,SAAS,oBAAoB,KAAqB;CAChD,MAAM,UAAU,IA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AY,OACd,CAAK,cAAc,QAAQ,CAAC,YAAY,OAAU;AAGpD,oBAAkB,cAAc;GAC9B;GACA;GACA;GACA,QAAQ,QAAQ,UAAU;IAAE,MAAM;IAAc,eAAe;IAAO;GACtE,GAAI,QAAQ,UAAU,EAAE,SAAS,QAAQ,SAAS,GAAG,EAAE;GACxD,CAAC;AAEF,SAAO;;CAET,MAAMC,QAA4BC,IAAW;EAC3C,SAAS;GACP,QAAQ,MAAM;AACZ,WAAO,YAAY,CAAC,QAAQ,KAAK;;GAEnC,aAAa;AACX,WAAO,YAAY,CAAC,YAAY;;GAEnC;EACD;EACD,CAAC;AAEF,QAAO;EACL;EACA,QAAQ,iBAAiB,SAAS;EAClC,QAAQT;EACR;EACA;EACA;EACA,MAAM,QAAQ,cAAc;AAC1B,OAAI,mBAAmB,eACrB,OAAM,IAAI,MAAM,oCAAoC;AAGtD,OAAI,iBAAiB,OACnB,WAAU,uBAAuB,aAAa;AAGhD,OAAI,YAAY,OACd,OAAM,IAAI,MACR,qGACD;GAGH,MAAM,UAAU,YAAY;AAC5B,OAAI,gBACF,QAAO;AAGT,SAAM,cAAc,QAAQ;AAC5B,UAAO;;EAET,UAAU;AACR,UAAO,YAAY;;EAEtB"}
package/package.json CHANGED
@@ -1,20 +1,21 @@
1
1
  {
2
2
  "name": "@prisma-next/postgres",
3
- "version": "0.0.1",
3
+ "version": "0.3.0-dev.122",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "One-liner lazy Postgres client composition for Prisma Next",
7
7
  "dependencies": {
8
8
  "pg": "8.16.3",
9
- "@prisma-next/adapter-postgres": "0.0.1",
10
- "@prisma-next/core-execution-plane": "0.0.1",
11
- "@prisma-next/sql-contract": "0.0.1",
12
- "@prisma-next/driver-postgres": "0.0.1",
13
- "@prisma-next/sql-relational-core": "0.0.1",
14
- "@prisma-next/target-postgres": "0.0.1",
15
- "@prisma-next/sql-runtime": "0.0.1",
16
- "@prisma-next/sql-lane": "0.0.1",
17
- "@prisma-next/utils": "0.0.1"
9
+ "@prisma-next/adapter-postgres": "0.3.0-dev.122",
10
+ "@prisma-next/core-execution-plane": "0.3.0-dev.122",
11
+ "@prisma-next/sql-contract": "0.3.0-dev.122",
12
+ "@prisma-next/driver-postgres": "0.3.0-dev.122",
13
+ "@prisma-next/sql-kysely-lane": "0.3.0-dev.122",
14
+ "@prisma-next/sql-orm-client": "0.3.0-dev.122",
15
+ "@prisma-next/sql-lane": "0.3.0-dev.122",
16
+ "@prisma-next/sql-relational-core": "0.3.0-dev.122",
17
+ "@prisma-next/sql-runtime": "0.3.0-dev.122",
18
+ "@prisma-next/target-postgres": "0.3.0-dev.122"
18
19
  },
19
20
  "devDependencies": {
20
21
  "@types/pg": "8.16.0",
@@ -22,35 +23,28 @@
22
23
  "typescript": "5.9.3",
23
24
  "vitest": "4.0.17",
24
25
  "@prisma-next/tsconfig": "0.0.0",
25
- "@prisma-next/test-utils": "0.0.1",
26
- "@prisma-next/tsdown": "0.0.0"
26
+ "@prisma-next/tsdown": "0.0.0",
27
+ "@prisma-next/test-utils": "0.0.1"
27
28
  },
28
29
  "files": [
29
30
  "dist",
30
31
  "src"
31
32
  ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/prisma/prisma-next.git",
36
+ "directory": "packages/3-extensions/postgres"
37
+ },
32
38
  "engines": {
33
39
  "node": ">=20"
34
40
  },
35
41
  "exports": {
36
- ".": {
37
- "types": "./dist/runtime.d.mts",
38
- "import": "./dist/runtime.mjs"
39
- },
40
- "./runtime": {
41
- "types": "./dist/runtime.d.mts",
42
- "import": "./dist/runtime.mjs"
43
- },
42
+ ".": "./dist/runtime.mjs",
44
43
  "./package.json": "./package.json"
45
44
  },
46
45
  "main": "./dist/runtime.mjs",
47
46
  "module": "./dist/runtime.mjs",
48
47
  "types": "./dist/runtime.d.mts",
49
- "repository": {
50
- "type": "git",
51
- "url": "https://github.com/prisma/prisma-next.git",
52
- "directory": "packages/3-targets/8-clients/postgres"
53
- },
54
48
  "scripts": {
55
49
  "build": "tsdown",
56
50
  "test": "vitest run",
@@ -1,4 +1,5 @@
1
- export type { PostgresBinding } from '@prisma-next/driver-postgres/runtime';
1
+ export type { KyselyQueryLane } from '@prisma-next/sql-kysely-lane';
2
+ export type { PostgresBinding } from '../runtime/binding';
2
3
  export type {
3
4
  PostgresClient,
4
5
  PostgresOptions,
@@ -1,7 +1,11 @@
1
- import type { PostgresBinding } from '@prisma-next/driver-postgres/runtime';
2
1
  import type { Client, Pool } from 'pg';
3
2
  import { Client as PgClient, Pool as PgPool } from 'pg';
4
3
 
4
+ export type PostgresBinding =
5
+ | { readonly kind: 'url'; readonly url: string }
6
+ | { readonly kind: 'pgPool'; readonly pool: Pool }
7
+ | { readonly kind: 'pgClient'; readonly client: Client };
8
+
5
9
  export type PostgresBindingInput =
6
10
  | {
7
11
  readonly binding: PostgresBinding;
@@ -19,53 +23,27 @@ export type PostgresBindingInput =
19
23
  readonly url?: never;
20
24
  };
21
25
 
22
- interface PostgresBindingError extends Error {
23
- readonly code: 'DRIVER.BINDING_INVALID';
24
- readonly category: 'RUNTIME';
25
- readonly severity: 'error';
26
- readonly details?: Record<string, unknown>;
27
- }
28
-
29
- function bindingError(message: string, details?: Record<string, unknown>): PostgresBindingError {
30
- const error = new Error(message) as PostgresBindingError;
31
- Object.defineProperty(error, 'name', {
32
- value: 'RuntimeError',
33
- configurable: true,
34
- });
35
- return Object.assign(error, {
36
- code: 'DRIVER.BINDING_INVALID' as const,
37
- category: 'RUNTIME' as const,
38
- severity: 'error' as const,
39
- message,
40
- details,
41
- });
42
- }
26
+ type PostgresBindingFields = {
27
+ readonly binding?: PostgresBinding;
28
+ readonly url?: string;
29
+ readonly pg?: Pool | Client;
30
+ };
43
31
 
44
32
  function validatePostgresUrl(url: string): string {
45
33
  const trimmed = url.trim();
46
34
  if (trimmed.length === 0) {
47
- throw bindingError('Postgres URL must be a non-empty string', {
48
- field: 'url',
49
- reason: 'empty',
50
- });
35
+ throw new Error('Postgres URL must be a non-empty string');
51
36
  }
52
37
 
53
38
  let parsed: URL;
54
39
  try {
55
40
  parsed = new URL(trimmed);
56
41
  } catch {
57
- throw bindingError('Postgres URL must be a valid URL', {
58
- field: 'url',
59
- reason: 'invalid-url',
60
- });
42
+ throw new Error('Postgres URL must be a valid URL');
61
43
  }
62
44
 
63
45
  if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
64
- throw bindingError('Postgres URL must use postgres:// or postgresql://', {
65
- field: 'url',
66
- reason: 'invalid-protocol',
67
- protocol: parsed.protocol,
68
- });
46
+ throw new Error('Postgres URL must use postgres:// or postgresql://');
69
47
  }
70
48
 
71
49
  return trimmed;
@@ -78,9 +56,7 @@ export function resolvePostgresBinding(options: PostgresBindingInput): PostgresB
78
56
  Number(options.pg !== undefined);
79
57
 
80
58
  if (providedCount !== 1) {
81
- throw bindingError('Provide one binding input: binding, url, or pg', {
82
- providedCount,
83
- });
59
+ throw new Error('Provide one binding input: binding, url, or pg');
84
60
  }
85
61
 
86
62
  if (options.binding !== undefined) {
@@ -93,9 +69,7 @@ export function resolvePostgresBinding(options: PostgresBindingInput): PostgresB
93
69
 
94
70
  const pgBinding = options.pg;
95
71
  if (pgBinding === undefined) {
96
- throw bindingError('Invariant violation: expected pg binding after validation', {
97
- reason: 'missing-pg-binding',
98
- });
72
+ throw new Error('Invariant violation: expected pg binding after validation');
99
73
  }
100
74
 
101
75
  if (pgBinding instanceof PgPool) {
@@ -106,10 +80,22 @@ export function resolvePostgresBinding(options: PostgresBindingInput): PostgresB
106
80
  return { kind: 'pgClient', client: pgBinding };
107
81
  }
108
82
 
109
- throw bindingError(
83
+ throw new Error(
110
84
  'Unable to determine pg binding type from pg input; use binding with explicit kind',
111
- {
112
- reason: 'unknown-pg-instance',
113
- },
114
85
  );
115
86
  }
87
+
88
+ export function resolveOptionalPostgresBinding(
89
+ options: PostgresBindingFields,
90
+ ): PostgresBinding | undefined {
91
+ const providedCount =
92
+ Number(options.binding !== undefined) +
93
+ Number(options.url !== undefined) +
94
+ Number(options.pg !== undefined);
95
+
96
+ if (providedCount === 0) {
97
+ return undefined;
98
+ }
99
+
100
+ return resolvePostgresBinding(options as PostgresBindingInput);
101
+ }
@@ -1,16 +1,18 @@
1
1
  import postgresAdapter from '@prisma-next/adapter-postgres/runtime';
2
2
  import { instantiateExecutionStack } from '@prisma-next/core-execution-plane/stack';
3
- import type { PostgresDriverCreateOptions } from '@prisma-next/driver-postgres/runtime';
4
3
  import postgresDriver from '@prisma-next/driver-postgres/runtime';
5
4
  import type {
6
- ExtractCodecTypes,
7
- ExtractOperationTypes,
5
+ ExtractTypeMapsFromContract,
6
+ ResolveCodecTypes,
7
+ ResolveOperationTypes,
8
8
  SqlContract,
9
9
  SqlStorage,
10
10
  } from '@prisma-next/sql-contract/types';
11
11
  import { validateContract } from '@prisma-next/sql-contract/validate';
12
+ import { createKyselyLane, type KyselyQueryLane } from '@prisma-next/sql-kysely-lane';
12
13
  import type { SelectBuilder } from '@prisma-next/sql-lane';
13
14
  import { sql as sqlBuilder } from '@prisma-next/sql-lane';
15
+ import { orm as ormBuilder } from '@prisma-next/sql-orm-client';
14
16
  import type { SchemaHandle } from '@prisma-next/sql-relational-core/schema';
15
17
  import { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';
16
18
  import type {
@@ -31,8 +33,13 @@ import {
31
33
  createSqlExecutionStack,
32
34
  } from '@prisma-next/sql-runtime';
33
35
  import postgresTarget from '@prisma-next/target-postgres/runtime';
34
- import { ifDefined } from '@prisma-next/utils/defined';
35
- import { type PostgresBindingInput, resolvePostgresBinding } from './binding';
36
+ import { type Client, Pool } from 'pg';
37
+ import {
38
+ type PostgresBinding,
39
+ type PostgresBindingInput,
40
+ resolveOptionalPostgresBinding,
41
+ resolvePostgresBinding,
42
+ } from './binding';
36
43
 
37
44
  type NormalizeOperationTypes<T> = {
38
45
  [TypeId in keyof T]: {
@@ -45,40 +52,58 @@ type NormalizeOperationTypes<T> = {
45
52
  type ToSchemaOperationTypes<T> = T extends OperationTypes ? T : NormalizeOperationTypes<T>;
46
53
 
47
54
  export type PostgresTargetId = 'postgres';
55
+ type OrmClient<TContract extends SqlContract<SqlStorage>> = ReturnType<
56
+ typeof ormBuilder<TContract>
57
+ >;
48
58
 
49
- export interface PostgresClient<TContract extends SqlContract<SqlStorage>> {
59
+ export interface PostgresClient<
60
+ TContract extends SqlContract<SqlStorage>,
61
+ TTypeMaps = ExtractTypeMapsFromContract<TContract>,
62
+ > {
50
63
  readonly sql: SelectBuilder<
51
64
  TContract,
52
65
  unknown,
53
- ExtractCodecTypes<TContract>,
54
- ExtractOperationTypes<TContract>
66
+ ResolveCodecTypes<TContract, TTypeMaps>,
67
+ ResolveOperationTypes<TContract, TTypeMaps>
55
68
  >;
69
+ readonly kysely: KyselyQueryLane<TContract>;
56
70
  readonly schema: SchemaHandle<
57
71
  TContract,
58
- ExtractCodecTypes<TContract>,
59
- ToSchemaOperationTypes<ExtractOperationTypes<TContract>>
72
+ ResolveCodecTypes<TContract, TTypeMaps>,
73
+ ToSchemaOperationTypes<ResolveOperationTypes<TContract, TTypeMaps>>
60
74
  >;
75
+ readonly orm: OrmClient<TContract>;
61
76
  readonly context: ExecutionContext<TContract>;
62
77
  readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;
63
- runtime(): Promise<Runtime>;
78
+ connect(bindingInput?: PostgresBindingInput): Promise<Runtime>;
79
+ runtime(): Runtime;
64
80
  }
65
81
 
66
82
  export interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {
67
83
  readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];
68
84
  readonly plugins?: readonly Plugin<TContract>[];
69
85
  readonly verify?: RuntimeVerifyOptions;
70
- readonly cursor?: PostgresDriverCreateOptions['cursor'];
86
+ readonly poolOptions?: {
87
+ readonly connectionTimeoutMillis?: number;
88
+ readonly idleTimeoutMillis?: number;
89
+ };
90
+ }
91
+
92
+ export interface PostgresBindingOptions {
93
+ readonly binding?: PostgresBinding;
94
+ readonly url?: string;
95
+ readonly pg?: Pool | Client;
71
96
  }
72
97
 
73
98
  export type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> =
74
- PostgresBindingInput &
99
+ PostgresBindingOptions &
75
100
  PostgresOptionsBase<TContract> & {
76
101
  readonly contract: TContract;
77
102
  readonly contractJson?: never;
78
103
  };
79
104
 
80
105
  export type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> =
81
- PostgresBindingInput &
106
+ PostgresBindingOptions &
82
107
  PostgresOptionsBase<TContract> & {
83
108
  readonly contractJson: unknown;
84
109
  readonly contract?: never;
@@ -101,33 +126,49 @@ function resolveContract<TContract extends SqlContract<SqlStorage>>(
101
126
  return validateContract<TContract>(contractInput);
102
127
  }
103
128
 
129
+ function toRuntimeBinding<TContract extends SqlContract<SqlStorage>>(
130
+ binding: PostgresBinding,
131
+ options: PostgresOptions<TContract>,
132
+ ) {
133
+ if (binding.kind !== 'url') {
134
+ return binding;
135
+ }
136
+
137
+ return {
138
+ kind: 'pgPool',
139
+ pool: new Pool({
140
+ connectionString: binding.url,
141
+ connectionTimeoutMillis: options.poolOptions?.connectionTimeoutMillis ?? 20_000,
142
+ idleTimeoutMillis: options.poolOptions?.idleTimeoutMillis ?? 30_000,
143
+ }),
144
+ } as const;
145
+ }
146
+
104
147
  /**
105
148
  * Creates a lazy Postgres client from either `contractJson` or a TypeScript-authored `contract`.
106
149
  * Static query surfaces are available immediately, while `runtime()` instantiates the driver/pool on first call.
150
+ *
151
+ * - No-emit: infers TypeMaps from ContractWithTypeMaps. Example: postgres({ contract })
152
+ * - Emitted: pass TypeMaps explicitly. Example: postgres<Contract, TypeMaps>({ contractJson, url })
107
153
  */
108
- export default function postgres<TContract extends SqlContract<SqlStorage>>(
109
- options: PostgresOptionsWithContract<TContract>,
110
- ): PostgresClient<TContract>;
111
- export default function postgres<TContract extends SqlContract<SqlStorage>>(
112
- options: PostgresOptionsWithContractJson<TContract>,
113
- ): PostgresClient<TContract>;
114
- export default function postgres<TContract extends SqlContract<SqlStorage>>(
115
- options: PostgresOptions<TContract>,
116
- ): PostgresClient<TContract> {
154
+ export default function postgres<
155
+ TContract extends SqlContract<SqlStorage>,
156
+ TTypeMaps = ExtractTypeMapsFromContract<TContract>,
157
+ >(options: PostgresOptionsWithContract<TContract>): PostgresClient<TContract, TTypeMaps>;
158
+ export default function postgres<
159
+ TContract extends SqlContract<SqlStorage>,
160
+ TTypeMaps = ExtractTypeMapsFromContract<TContract>,
161
+ >(options: PostgresOptionsWithContractJson<TContract>): PostgresClient<TContract, TTypeMaps>;
162
+ export default function postgres<
163
+ TContract extends SqlContract<SqlStorage>,
164
+ TTypeMaps = ExtractTypeMapsFromContract<TContract>,
165
+ >(options: PostgresOptions<TContract>): PostgresClient<TContract, TTypeMaps> {
117
166
  const contract = resolveContract(options);
118
- const binding = resolvePostgresBinding(options);
167
+ let binding = resolveOptionalPostgresBinding(options);
119
168
  const stack = createSqlExecutionStack({
120
169
  target: postgresTarget,
121
170
  adapter: postgresAdapter,
122
- driver:
123
- options.cursor === undefined
124
- ? postgresDriver
125
- : {
126
- ...postgresDriver,
127
- create() {
128
- return postgresDriver.create({ cursor: options.cursor });
129
- },
130
- },
171
+ driver: postgresDriver,
131
172
  extensionPacks: options.extensions ?? [],
132
173
  });
133
174
 
@@ -136,51 +177,110 @@ export default function postgres<TContract extends SqlContract<SqlStorage>>(
136
177
  stack,
137
178
  });
138
179
 
139
- const schema: PostgresClient<TContract>['schema'] = schemaBuilder(context);
140
- const sql = sqlBuilder({ context });
180
+ const schema = schemaBuilder<TContract, TTypeMaps>(context);
181
+ const sql = sqlBuilder<TContract, TTypeMaps>({ context });
182
+ let runtimeInstance: Runtime | undefined;
183
+ let runtimeDriver: { connect(binding: unknown): Promise<void> } | undefined;
184
+ let driverConnected = false;
185
+ let connectPromise: Promise<void> | undefined;
186
+ let backgroundConnectError: unknown;
187
+ const connectDriver = async (resolvedBinding: PostgresBinding): Promise<void> => {
188
+ if (driverConnected) return;
189
+ if (!runtimeDriver) throw new Error('Postgres runtime driver missing');
190
+ if (connectPromise) return connectPromise;
191
+ const runtimeBinding = toRuntimeBinding(resolvedBinding, options);
192
+ connectPromise = runtimeDriver
193
+ .connect(runtimeBinding)
194
+ .then(() => {
195
+ driverConnected = true;
196
+ })
197
+ .catch(async (err) => {
198
+ backgroundConnectError = err;
199
+ connectPromise = undefined;
200
+ if (resolvedBinding.kind === 'url' && runtimeBinding.kind === 'pgPool') {
201
+ await runtimeBinding.pool.end().catch(() => undefined);
202
+ }
203
+ throw err;
204
+ });
205
+ return connectPromise;
206
+ };
207
+ const getRuntime = (): Runtime => {
208
+ if (backgroundConnectError !== undefined) {
209
+ throw backgroundConnectError;
210
+ }
211
+
212
+ if (runtimeInstance) {
213
+ return runtimeInstance;
214
+ }
141
215
 
142
- let runtimePromise: Promise<Runtime> | undefined;
216
+ const stackInstance = instantiateExecutionStack(stack);
217
+ const driverDescriptor = stack.driver;
218
+ if (!driverDescriptor) {
219
+ throw new Error('Driver descriptor missing from execution stack');
220
+ }
221
+
222
+ const driver = driverDescriptor.create({
223
+ cursor: { disabled: true },
224
+ });
225
+ runtimeDriver = driver;
226
+ if (binding !== undefined) {
227
+ void connectDriver(binding).catch(() => undefined);
228
+ }
229
+
230
+ runtimeInstance = createRuntime({
231
+ stackInstance,
232
+ context,
233
+ driver,
234
+ verify: options.verify ?? { mode: 'onFirstUse', requireMarker: false },
235
+ ...(options.plugins ? { plugins: options.plugins } : {}),
236
+ });
237
+
238
+ return runtimeInstance;
239
+ };
240
+ const orm: OrmClient<TContract> = ormBuilder({
241
+ runtime: {
242
+ execute(plan) {
243
+ return getRuntime().execute(plan);
244
+ },
245
+ connection() {
246
+ return getRuntime().connection();
247
+ },
248
+ },
249
+ context,
250
+ });
143
251
 
144
252
  return {
145
253
  sql,
146
- schema,
254
+ kysely: createKyselyLane(contract),
255
+ schema: schema as PostgresClient<TContract, TTypeMaps>['schema'],
256
+ orm,
147
257
  context,
148
258
  stack,
149
- async runtime() {
150
- if (runtimePromise) {
151
- return runtimePromise;
259
+ async connect(bindingInput) {
260
+ if (driverConnected || connectPromise) {
261
+ throw new Error('Postgres client already connected');
152
262
  }
153
263
 
154
- runtimePromise = (async () => {
155
- const stackInstance = instantiateExecutionStack(stack);
156
- const driver = stackInstance.driver;
157
- if (driver === undefined) {
158
- throw new Error('Relational runtime requires a driver descriptor on the execution stack');
159
- }
264
+ if (bindingInput !== undefined) {
265
+ binding = resolvePostgresBinding(bindingInput);
266
+ }
160
267
 
161
- try {
162
- // `binding` is normalized by resolvePostgresBinding(), so this call site remains
163
- // type-safe in practice while SqlRuntimeDriverInstance currently uses SqlDriver<unknown>.
164
- await driver.connect(binding);
165
-
166
- return createRuntime({
167
- stackInstance,
168
- context,
169
- driver,
170
- verify: options.verify ?? { mode: 'onFirstUse', requireMarker: false },
171
- ...ifDefined('plugins', options.plugins),
172
- });
173
- } catch (error) {
174
- await driver.close().catch(() => undefined);
175
- throw error;
176
- }
177
- })();
268
+ if (binding === undefined) {
269
+ throw new Error(
270
+ 'Postgres binding not configured. Pass url/pg/binding to postgres(...) or call db.connect({ ... }).',
271
+ );
272
+ }
178
273
 
179
- runtimePromise.catch(() => {
180
- runtimePromise = undefined;
181
- });
274
+ const runtime = getRuntime();
275
+ if (driverConnected) {
276
+ return runtime;
277
+ }
182
278
 
183
- return runtimePromise;
279
+ await connectDriver(binding);
280
+ return runtime;
281
+ },
282
+ runtime() {
283
+ return getRuntime();
184
284
  },
185
285
  };
186
286
  }