@prisma-next/postgres 0.3.0-dev.43 → 0.3.0-dev.45
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/README.md +22 -14
- package/dist/runtime.d.mts +30 -6
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +95 -67
- package/dist/runtime.mjs.map +1 -1
- package/package.json +13 -22
- package/src/exports/runtime.ts +1 -1
- package/src/runtime/binding.ts +31 -45
- package/src/runtime/postgres.ts +143 -48
package/README.md
CHANGED
|
@@ -1,23 +1,26 @@
|
|
|
1
1
|
# @prisma-next/postgres
|
|
2
2
|
|
|
3
|
-
|
|
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**:
|
|
8
|
-
- **Layer**:
|
|
7
|
+
- **Domain**: extensions
|
|
8
|
+
- **Layer**: adapters
|
|
9
9
|
- **Plane**: runtime
|
|
10
10
|
|
|
11
11
|
## Overview
|
|
12
12
|
|
|
13
|
-
`@prisma-next/postgres
|
|
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(runtime)`
|
|
16
17
|
- `db.schema`
|
|
18
|
+
- `db.orm`
|
|
17
19
|
- `db.context`
|
|
18
20
|
- `db.stack`
|
|
19
21
|
|
|
20
|
-
Runtime
|
|
22
|
+
Runtime resources are deferred until `db.runtime()` or `db.connect(...)` is called.
|
|
23
|
+
Connection binding can be provided up front (`url`, `pg`, `binding`) or deferred via `db.connect(...)`.
|
|
21
24
|
|
|
22
25
|
When URL binding is used, pool timeouts are configurable via `poolOptions`:
|
|
23
26
|
|
|
@@ -27,11 +30,12 @@ When URL binding is used, pool timeouts are configurable via `poolOptions`:
|
|
|
27
30
|
## Responsibilities
|
|
28
31
|
|
|
29
32
|
- Build a static Postgres execution stack from target, adapter, and driver descriptors
|
|
30
|
-
- Build
|
|
33
|
+
- Build typed SQL and Kysely lane instances from the same execution context
|
|
34
|
+
- Build static schema and ORM roots from the execution context
|
|
31
35
|
- Normalize runtime binding input (`binding`, `url`, `pg`)
|
|
32
|
-
- Lazily instantiate
|
|
33
|
-
- Connect driver
|
|
34
|
-
- Memoize runtime so repeated `
|
|
36
|
+
- Lazily instantiate runtime resources on first `db.runtime()` or `db.connect(...)` call
|
|
37
|
+
- Connect the internal Postgres driver through `db.connect(...)` or from initial binding options
|
|
38
|
+
- Memoize runtime so repeated `db.runtime()` calls return one instance
|
|
35
39
|
|
|
36
40
|
## Dependencies
|
|
37
41
|
|
|
@@ -41,23 +45,26 @@ When URL binding is used, pool timeouts are configurable via `poolOptions`:
|
|
|
41
45
|
- `@prisma-next/adapter-postgres` for adapter descriptor
|
|
42
46
|
- `@prisma-next/driver-postgres` for driver descriptor
|
|
43
47
|
- `@prisma-next/sql-lane` for `sql(...)`
|
|
48
|
+
- `@prisma-next/integration-kysely` for `KyselyPrismaDialect` and contract-to-Kysely typing
|
|
44
49
|
- `@prisma-next/sql-relational-core` for `schema(...)`
|
|
50
|
+
- `@prisma-next/sql-orm-client` for `orm(...)`
|
|
45
51
|
- `@prisma-next/sql-contract` for `validateContract(...)` and contract types
|
|
46
|
-
- `
|
|
52
|
+
- `kysely` for query-builder API surface
|
|
53
|
+
- `pg` for lazy `Pool` construction when using URL binding
|
|
47
54
|
|
|
48
55
|
## Architecture
|
|
49
56
|
|
|
50
57
|
```mermaid
|
|
51
58
|
flowchart TD
|
|
52
59
|
App[App Code] --> Client[postgres(...)]
|
|
53
|
-
Client --> Static[
|
|
60
|
+
Client --> Static[Roots: sql kysely(runtime) schema orm context stack]
|
|
54
61
|
Client --> Lazy[runtime()]
|
|
55
62
|
|
|
56
63
|
Lazy --> Instantiate[instantiateExecutionStack]
|
|
57
64
|
Lazy --> Bind[Resolve binding: url or pg]
|
|
58
|
-
Bind -->
|
|
59
|
-
|
|
60
|
-
|
|
65
|
+
Bind --> Pool[pg.Pool for url binding]
|
|
66
|
+
Bind --> Reuse[Reuse Pool or Client for pg binding]
|
|
67
|
+
Lazy --> Runtime[createRuntime]
|
|
61
68
|
|
|
62
69
|
Runtime --> Target[@prisma-next/target-postgres]
|
|
63
70
|
Runtime --> Adapter[@prisma-next/adapter-postgres]
|
|
@@ -71,3 +78,4 @@ flowchart TD
|
|
|
71
78
|
- 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`
|
package/dist/runtime.d.mts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { KyselifyContract } from "@prisma-next/integration-kysely";
|
|
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";
|
|
6
|
+
import { Kysely } from "kysely";
|
|
5
7
|
import { Client, Pool } from "pg";
|
|
6
8
|
import { ExtractCodecTypes, ExtractOperationTypes, SqlContract, SqlStorage } from "@prisma-next/sql-contract/types";
|
|
7
9
|
import { OperationTypeSignature, OperationTypes } from "@prisma-next/sql-relational-core/types";
|
|
8
10
|
|
|
9
11
|
//#region src/runtime/binding.d.ts
|
|
12
|
+
type PostgresBinding = {
|
|
13
|
+
readonly kind: 'url';
|
|
14
|
+
readonly url: string;
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: 'pgPool';
|
|
17
|
+
readonly pool: Pool;
|
|
18
|
+
} | {
|
|
19
|
+
readonly kind: 'pgClient';
|
|
20
|
+
readonly client: Client;
|
|
21
|
+
};
|
|
10
22
|
type PostgresBindingInput = {
|
|
11
|
-
readonly binding: PostgresBinding
|
|
23
|
+
readonly binding: PostgresBinding;
|
|
12
24
|
readonly url?: never;
|
|
13
25
|
readonly pg?: never;
|
|
14
26
|
} | {
|
|
@@ -25,24 +37,36 @@ type PostgresBindingInput = {
|
|
|
25
37
|
type NormalizeOperationTypes<T> = { [TypeId in keyof T]: { [Method in keyof T[TypeId]]: T[TypeId][Method] extends OperationTypeSignature ? T[TypeId][Method] : OperationTypeSignature } };
|
|
26
38
|
type ToSchemaOperationTypes<T> = T extends OperationTypes ? T : NormalizeOperationTypes<T>;
|
|
27
39
|
type PostgresTargetId = 'postgres';
|
|
40
|
+
type OrmClient<TContract extends SqlContract<SqlStorage>> = ReturnType<typeof orm<TContract>>;
|
|
28
41
|
interface PostgresClient<TContract extends SqlContract<SqlStorage>> {
|
|
29
42
|
readonly sql: SelectBuilder<TContract, unknown, ExtractCodecTypes<TContract>, ExtractOperationTypes<TContract>>;
|
|
43
|
+
kysely(runtime: Runtime): Kysely<KyselifyContract<TContract>>;
|
|
30
44
|
readonly schema: SchemaHandle<TContract, ExtractCodecTypes<TContract>, ToSchemaOperationTypes<ExtractOperationTypes<TContract>>>;
|
|
45
|
+
readonly orm: OrmClient<TContract>;
|
|
31
46
|
readonly context: ExecutionContext<TContract>;
|
|
32
47
|
readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;
|
|
33
|
-
|
|
48
|
+
connect(bindingInput?: PostgresBindingInput): Promise<Runtime>;
|
|
49
|
+
runtime(): Runtime;
|
|
34
50
|
}
|
|
35
51
|
interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {
|
|
36
52
|
readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];
|
|
37
53
|
readonly plugins?: readonly Plugin<TContract>[];
|
|
38
54
|
readonly verify?: RuntimeVerifyOptions;
|
|
39
|
-
readonly
|
|
55
|
+
readonly poolOptions?: {
|
|
56
|
+
readonly connectionTimeoutMillis?: number;
|
|
57
|
+
readonly idleTimeoutMillis?: number;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
interface PostgresBindingOptions {
|
|
61
|
+
readonly binding?: PostgresBinding;
|
|
62
|
+
readonly url?: string;
|
|
63
|
+
readonly pg?: Pool | Client;
|
|
40
64
|
}
|
|
41
|
-
type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> =
|
|
65
|
+
type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> = PostgresBindingOptions & PostgresOptionsBase<TContract> & {
|
|
42
66
|
readonly contract: TContract;
|
|
43
67
|
readonly contractJson?: never;
|
|
44
68
|
};
|
|
45
|
-
type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> =
|
|
69
|
+
type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> = PostgresBindingOptions & PostgresOptionsBase<TContract> & {
|
|
46
70
|
readonly contractJson: unknown;
|
|
47
71
|
readonly contract?: never;
|
|
48
72
|
};
|
package/dist/runtime.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/runtime/binding.ts","../src/runtime/postgres.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/runtime/binding.ts","../src/runtime/postgres.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;KAGY,eAAA;;;;;iBAEkC;;;mBACI;;AAHtC,KAKA,oBAAA,GAHkC;EAGlC,SAAA,OAAA,EAEY,eAFQ;EAER,SAAA,GAAA,CAAA,EAAA,KAAA;EAUL,SAAA,EAAA,CAAA,EAAA,KAAA;CAAO,GAAA;EAAM,SAAA,GAAA,EAAA,MAAA;;;;ECuB3B,SAAA,EAAA,ED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Fc,SAtFd,CAAA;AAJY,iBA2FQ,QA3FR,CAAA,kBA2FmC,WA3FnC,CA2F+C,UA3F/C,CAAA,CAAA,CAAA,OAAA,EA4FL,+BA5FK,CA4F2B,SA5F3B,CAAA,CAAA,EA6Fb,cA7Fa,CA6FE,SA7FF,CAAA"}
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,61 +1,38 @@
|
|
|
1
1
|
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
|
+
import { KyselyPrismaDialect } from "@prisma-next/integration-kysely";
|
|
4
5
|
import { validateContract } from "@prisma-next/sql-contract/validate";
|
|
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 {
|
|
11
|
+
import { Kysely } from "kysely";
|
|
10
12
|
import { Client, Pool } from "pg";
|
|
11
13
|
|
|
12
14
|
//#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
15
|
function validatePostgresUrl(url) {
|
|
28
16
|
const trimmed = url.trim();
|
|
29
|
-
if (trimmed.length === 0) throw
|
|
30
|
-
field: "url",
|
|
31
|
-
reason: "empty"
|
|
32
|
-
});
|
|
17
|
+
if (trimmed.length === 0) throw new Error("Postgres URL must be a non-empty string");
|
|
33
18
|
let parsed;
|
|
34
19
|
try {
|
|
35
20
|
parsed = new URL(trimmed);
|
|
36
21
|
} catch {
|
|
37
|
-
throw
|
|
38
|
-
field: "url",
|
|
39
|
-
reason: "invalid-url"
|
|
40
|
-
});
|
|
22
|
+
throw new Error("Postgres URL must be a valid URL");
|
|
41
23
|
}
|
|
42
|
-
if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") throw
|
|
43
|
-
field: "url",
|
|
44
|
-
reason: "invalid-protocol",
|
|
45
|
-
protocol: parsed.protocol
|
|
46
|
-
});
|
|
24
|
+
if (parsed.protocol !== "postgres:" && parsed.protocol !== "postgresql:") throw new Error("Postgres URL must use postgres:// or postgresql://");
|
|
47
25
|
return trimmed;
|
|
48
26
|
}
|
|
49
27
|
function resolvePostgresBinding(options) {
|
|
50
|
-
|
|
51
|
-
if (providedCount !== 1) throw bindingError("Provide one binding input: binding, url, or pg", { providedCount });
|
|
28
|
+
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
29
|
if (options.binding !== void 0) return options.binding;
|
|
53
30
|
if (options.url !== void 0) return {
|
|
54
31
|
kind: "url",
|
|
55
32
|
url: validatePostgresUrl(options.url)
|
|
56
33
|
};
|
|
57
34
|
const pgBinding = options.pg;
|
|
58
|
-
if (pgBinding === void 0) throw
|
|
35
|
+
if (pgBinding === void 0) throw new Error("Invariant violation: expected pg binding after validation");
|
|
59
36
|
if (pgBinding instanceof Pool) return {
|
|
60
37
|
kind: "pgPool",
|
|
61
38
|
pool: pgBinding
|
|
@@ -64,7 +41,11 @@ function resolvePostgresBinding(options) {
|
|
|
64
41
|
kind: "pgClient",
|
|
65
42
|
client: pgBinding
|
|
66
43
|
};
|
|
67
|
-
throw
|
|
44
|
+
throw new Error("Unable to determine pg binding type from pg input; use binding with explicit kind");
|
|
45
|
+
}
|
|
46
|
+
function resolveOptionalPostgresBinding(options) {
|
|
47
|
+
if (Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.pg !== void 0) === 0) return;
|
|
48
|
+
return resolvePostgresBinding(options);
|
|
68
49
|
}
|
|
69
50
|
|
|
70
51
|
//#endregion
|
|
@@ -75,18 +56,24 @@ function hasContractJson(options) {
|
|
|
75
56
|
function resolveContract(options) {
|
|
76
57
|
return validateContract(hasContractJson(options) ? options.contractJson : options.contract);
|
|
77
58
|
}
|
|
59
|
+
function toRuntimeBinding(binding, options) {
|
|
60
|
+
if (binding.kind !== "url") return binding;
|
|
61
|
+
return {
|
|
62
|
+
kind: "pgPool",
|
|
63
|
+
pool: new Pool({
|
|
64
|
+
connectionString: binding.url,
|
|
65
|
+
connectionTimeoutMillis: options.poolOptions?.connectionTimeoutMillis ?? 2e4,
|
|
66
|
+
idleTimeoutMillis: options.poolOptions?.idleTimeoutMillis ?? 3e4
|
|
67
|
+
})
|
|
68
|
+
};
|
|
69
|
+
}
|
|
78
70
|
function postgres(options) {
|
|
79
71
|
const contract = resolveContract(options);
|
|
80
|
-
|
|
72
|
+
let binding = resolveOptionalPostgresBinding(options);
|
|
81
73
|
const stack = createSqlExecutionStack({
|
|
82
74
|
target: postgresTarget,
|
|
83
75
|
adapter: postgresAdapter,
|
|
84
|
-
driver:
|
|
85
|
-
...postgresDriver,
|
|
86
|
-
create() {
|
|
87
|
-
return postgresDriver.create({ cursor: options.cursor });
|
|
88
|
-
}
|
|
89
|
-
},
|
|
76
|
+
driver: postgresDriver,
|
|
90
77
|
extensionPacks: options.extensions ?? []
|
|
91
78
|
});
|
|
92
79
|
const context = createExecutionContext({
|
|
@@ -95,39 +82,80 @@ function postgres(options) {
|
|
|
95
82
|
});
|
|
96
83
|
const schema$1 = schema(context);
|
|
97
84
|
const sql$1 = sql({ context });
|
|
98
|
-
let
|
|
85
|
+
let runtimeInstance;
|
|
86
|
+
let runtimeDriver;
|
|
87
|
+
let driverConnected = false;
|
|
88
|
+
let connectPromise;
|
|
89
|
+
let backgroundConnectError;
|
|
90
|
+
const connectDriver = async (resolvedBinding) => {
|
|
91
|
+
if (driverConnected) return;
|
|
92
|
+
if (!runtimeDriver) throw new Error("Postgres runtime driver missing");
|
|
93
|
+
if (connectPromise) return connectPromise;
|
|
94
|
+
const runtimeBinding = toRuntimeBinding(resolvedBinding, options);
|
|
95
|
+
connectPromise = runtimeDriver.connect(runtimeBinding).then(() => {
|
|
96
|
+
driverConnected = true;
|
|
97
|
+
}).catch(async (err) => {
|
|
98
|
+
backgroundConnectError = err;
|
|
99
|
+
connectPromise = void 0;
|
|
100
|
+
if (resolvedBinding.kind === "url" && runtimeBinding.kind === "pgPool") await runtimeBinding.pool.end().catch(() => void 0);
|
|
101
|
+
throw err;
|
|
102
|
+
});
|
|
103
|
+
return connectPromise;
|
|
104
|
+
};
|
|
105
|
+
const getRuntime = () => {
|
|
106
|
+
if (backgroundConnectError !== void 0) throw backgroundConnectError;
|
|
107
|
+
if (runtimeInstance) return runtimeInstance;
|
|
108
|
+
const stackInstance = instantiateExecutionStack(stack);
|
|
109
|
+
const driverDescriptor = stack.driver;
|
|
110
|
+
if (!driverDescriptor) throw new Error("Driver descriptor missing from execution stack");
|
|
111
|
+
const driver = driverDescriptor.create({ cursor: { disabled: true } });
|
|
112
|
+
runtimeDriver = driver;
|
|
113
|
+
if (binding !== void 0) connectDriver(binding).catch(() => void 0);
|
|
114
|
+
runtimeInstance = createRuntime({
|
|
115
|
+
stackInstance,
|
|
116
|
+
context,
|
|
117
|
+
driver,
|
|
118
|
+
verify: options.verify ?? {
|
|
119
|
+
mode: "onFirstUse",
|
|
120
|
+
requireMarker: false
|
|
121
|
+
},
|
|
122
|
+
...options.plugins ? { plugins: options.plugins } : {}
|
|
123
|
+
});
|
|
124
|
+
return runtimeInstance;
|
|
125
|
+
};
|
|
99
126
|
return {
|
|
100
127
|
sql: sql$1,
|
|
128
|
+
kysely(runtime) {
|
|
129
|
+
return new Kysely({ dialect: new KyselyPrismaDialect({
|
|
130
|
+
runtime,
|
|
131
|
+
contract
|
|
132
|
+
}) });
|
|
133
|
+
},
|
|
101
134
|
schema: schema$1,
|
|
135
|
+
orm: orm({
|
|
136
|
+
contract,
|
|
137
|
+
runtime: {
|
|
138
|
+
execute(plan) {
|
|
139
|
+
return getRuntime().execute(plan);
|
|
140
|
+
},
|
|
141
|
+
connection() {
|
|
142
|
+
return getRuntime().connection();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}),
|
|
102
146
|
context,
|
|
103
147
|
stack,
|
|
104
|
-
async
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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;
|
|
148
|
+
async connect(bindingInput) {
|
|
149
|
+
if (driverConnected || connectPromise) throw new Error("Postgres client already connected");
|
|
150
|
+
if (bindingInput !== void 0) binding = resolvePostgresBinding(bindingInput);
|
|
151
|
+
if (binding === void 0) throw new Error("Postgres binding not configured. Pass url/pg/binding to postgres(...) or call db.connect({ ... }).");
|
|
152
|
+
const runtime = getRuntime();
|
|
153
|
+
if (driverConnected) return runtime;
|
|
154
|
+
await connectDriver(binding);
|
|
155
|
+
return runtime;
|
|
156
|
+
},
|
|
157
|
+
runtime() {
|
|
158
|
+
return getRuntime();
|
|
131
159
|
}
|
|
132
160
|
};
|
|
133
161
|
}
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -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,QAAQ;GACT,CAAC;;AAGJ,KAAI,OAAO,aAAa,eAAe,OAAO,aAAa,cACzD,OAAM,aAAa,sDAAsD;EACvE,OAAO;EACP,QAAQ;EACR,UAAU,OAAO;EAClB,CAAC;AAGJ,QAAO;;AAGT,SAAgB,uBAAuB,SAAgD;CACrF,MAAM,gBACJ,OAAO,QAAQ,YAAY,OAAU,GACrC,OAAO,QAAQ,QAAQ,OAAU,GACjC,OAAO,QAAQ,OAAO,OAAU;AAElC,KAAI,kBAAkB,EACpB,OAAM,aAAa,kDAAkD,EACnE,eACD,CAAC;AAGJ,KAAI,QAAQ,YAAY,OACtB,QAAO,QAAQ;AAGjB,KAAI,QAAQ,QAAQ,OAClB,QAAO;EAAE,MAAM;EAAO,KAAK,oBAAoB,QAAQ,IAAI;EAAE;CAG/D,MAAM,YAAY,QAAQ;AAC1B,KAAI,cAAc,OAChB,OAAM,aAAa,6DAA6D,EAC9E,QAA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AU;AAC3C,WAAM;;OAEN;AAEJ,kBAAe,YAAY;AACzB,qBAAiB;KACjB;AAEF,UAAO;;EAEV"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":["parsed: URL","PgPool","PgClient","schema: PostgresClient<TContract>['schema']","schemaBuilder","sql","sqlBuilder","runtimeInstance: Runtime | undefined","runtimeDriver: { connect(binding: unknown): Promise<void> } | undefined","connectPromise: Promise<void> | undefined","backgroundConnectError: unknown","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 KyselifyContract, KyselyPrismaDialect } from '@prisma-next/integration-kysely';\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 { 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 { Kysely } from 'kysely';\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<TContract extends SqlContract<SqlStorage>> {\n readonly sql: SelectBuilder<\n TContract,\n unknown,\n ExtractCodecTypes<TContract>,\n ExtractOperationTypes<TContract>\n >;\n kysely(runtime: Runtime): Kysely<KyselifyContract<TContract>>;\n readonly schema: SchemaHandle<\n TContract,\n ExtractCodecTypes<TContract>,\n ToSchemaOperationTypes<ExtractOperationTypes<TContract>>\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 */\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 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: PostgresClient<TContract>['schema'] = schemaBuilder(context);\n const sql = sqlBuilder({ 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 contract,\n runtime: {\n execute(plan) {\n return getRuntime().execute(plan);\n },\n connection() {\n return getRuntime().connection();\n },\n },\n });\n\n return {\n sql,\n kysely(runtime: Runtime) {\n return new Kysely<KyselifyContract<TContract>>({\n dialect: new KyselyPrismaDialect({ runtime, contract }),\n });\n },\n 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,IAAI,MAAM;AAC1B,KAAI,QAAQ,WAAW,EACrB,OAAM,IAAI,MAAM,0CAA0C;CAG5D,IAAIA;AACJ,KAAI;AACF,WAAS,IAAI,IAAI,QAAQ;SACnB;AACN,QAAM,IAAI,MAAM,mCAAmC;;AAGrD,KAAI,OAAO,aAAa,eAAe,OAAO,aAAa,cACzD,OAAM,IAAI,MAAM,qDAAqD;AAGvE,QAAO;;AAGT,SAAgB,uBAAuB,SAAgD;AAMrF,KAJE,OAAO,QAAQ,YAAY,OAAU,GACrC,OAAO,QAAQ,QAAQ,OAAU,GACjC,OAAO,QAAQ,OAAO,OAAU,KAEZ,EACpB,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,QAAQ,YAAY,OACtB,QAAO,QAAQ;AAGjB,KAAI,QAAQ,QAAQ,OAClB,QAAO;EAAE,MAAM;EAAO,KAAK,oBAAoB,QAAQ,IAAI;EAAE;CAG/D,MAAM,YAAY,QAAQ;AAC1B,KAAI,cAAc,OAChB,OAAM,IAAI,MAAM,4DAA4D;AAG9E,KAAI,qBAAqBC,KACvB,QAAO;EAAE,MAAM;EAAU,MAAM;EAAW;AAG5C,KAAI,qBAAqBC,OACvB,QAAO;EAAE,MAAM;EAAY,QAAQ;EAAW;AAGhD,OAAM,IAAI,MACR,oFACD;;AAGH,SAAgB,+BACd,SAC6B;AAM7B,KAJE,OAAO,QAAQ,YAA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
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/postgres",
|
|
3
|
-
"version": "0.3.0-dev.
|
|
3
|
+
"version": "0.3.0-dev.45",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "One-liner lazy Postgres client composition for Prisma Next",
|
|
7
7
|
"dependencies": {
|
|
8
|
+
"kysely": "0.28.10",
|
|
8
9
|
"pg": "8.16.3",
|
|
9
|
-
"@prisma-next/adapter-postgres": "0.3.0-dev.
|
|
10
|
-
"@prisma-next/core-execution-plane": "0.3.0-dev.
|
|
11
|
-
"@prisma-next/driver-postgres": "0.3.0-dev.
|
|
12
|
-
"@prisma-next/
|
|
13
|
-
"@prisma-next/sql-
|
|
14
|
-
"@prisma-next/sql-
|
|
15
|
-
"@prisma-next/sql-
|
|
16
|
-
"@prisma-next/
|
|
17
|
-
"@prisma-next/
|
|
10
|
+
"@prisma-next/adapter-postgres": "0.3.0-dev.45",
|
|
11
|
+
"@prisma-next/core-execution-plane": "0.3.0-dev.45",
|
|
12
|
+
"@prisma-next/driver-postgres": "0.3.0-dev.45",
|
|
13
|
+
"@prisma-next/integration-kysely": "0.3.0-dev.45",
|
|
14
|
+
"@prisma-next/sql-contract": "0.3.0-dev.45",
|
|
15
|
+
"@prisma-next/sql-lane": "0.3.0-dev.45",
|
|
16
|
+
"@prisma-next/sql-orm-client": "0.3.0-dev.45",
|
|
17
|
+
"@prisma-next/sql-relational-core": "0.3.0-dev.45",
|
|
18
|
+
"@prisma-next/sql-runtime": "0.3.0-dev.45",
|
|
19
|
+
"@prisma-next/target-postgres": "0.3.0-dev.45"
|
|
18
20
|
},
|
|
19
21
|
"devDependencies": {
|
|
20
22
|
"@types/pg": "8.16.0",
|
|
@@ -33,20 +35,9 @@
|
|
|
33
35
|
"node": ">=20"
|
|
34
36
|
},
|
|
35
37
|
"exports": {
|
|
36
|
-
"
|
|
37
|
-
"types": "./dist/runtime.d.mts",
|
|
38
|
-
"import": "./dist/runtime.mjs"
|
|
39
|
-
},
|
|
38
|
+
"./runtime": "./dist/runtime.mjs",
|
|
40
39
|
"./package.json": "./package.json"
|
|
41
40
|
},
|
|
42
|
-
"main": "./dist/runtime.mjs",
|
|
43
|
-
"module": "./dist/runtime.mjs",
|
|
44
|
-
"types": "./dist/runtime.d.mts",
|
|
45
|
-
"repository": {
|
|
46
|
-
"type": "git",
|
|
47
|
-
"url": "https://github.com/prisma/prisma-next.git",
|
|
48
|
-
"directory": "packages/3-targets/8-clients/postgres"
|
|
49
|
-
},
|
|
50
41
|
"scripts": {
|
|
51
42
|
"build": "tsdown",
|
|
52
43
|
"test": "vitest run",
|
package/src/exports/runtime.ts
CHANGED
package/src/runtime/binding.ts
CHANGED
|
@@ -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
|
-
|
|
23
|
-
readonly
|
|
24
|
-
readonly
|
|
25
|
-
readonly
|
|
26
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
+
}
|
package/src/runtime/postgres.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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';
|
|
4
|
+
import { type KyselifyContract, KyselyPrismaDialect } from '@prisma-next/integration-kysely';
|
|
5
5
|
import type {
|
|
6
6
|
ExtractCodecTypes,
|
|
7
7
|
ExtractOperationTypes,
|
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
import { validateContract } from '@prisma-next/sql-contract/validate';
|
|
12
12
|
import type { SelectBuilder } from '@prisma-next/sql-lane';
|
|
13
13
|
import { sql as sqlBuilder } from '@prisma-next/sql-lane';
|
|
14
|
+
import { orm as ormBuilder } from '@prisma-next/sql-orm-client';
|
|
14
15
|
import type { SchemaHandle } from '@prisma-next/sql-relational-core/schema';
|
|
15
16
|
import { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';
|
|
16
17
|
import type {
|
|
@@ -31,8 +32,14 @@ import {
|
|
|
31
32
|
createSqlExecutionStack,
|
|
32
33
|
} from '@prisma-next/sql-runtime';
|
|
33
34
|
import postgresTarget from '@prisma-next/target-postgres/runtime';
|
|
34
|
-
import {
|
|
35
|
-
import { type
|
|
35
|
+
import { Kysely } from 'kysely';
|
|
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,6 +52,9 @@ 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
59
|
export interface PostgresClient<TContract extends SqlContract<SqlStorage>> {
|
|
50
60
|
readonly sql: SelectBuilder<
|
|
@@ -53,32 +63,44 @@ export interface PostgresClient<TContract extends SqlContract<SqlStorage>> {
|
|
|
53
63
|
ExtractCodecTypes<TContract>,
|
|
54
64
|
ExtractOperationTypes<TContract>
|
|
55
65
|
>;
|
|
66
|
+
kysely(runtime: Runtime): Kysely<KyselifyContract<TContract>>;
|
|
56
67
|
readonly schema: SchemaHandle<
|
|
57
68
|
TContract,
|
|
58
69
|
ExtractCodecTypes<TContract>,
|
|
59
70
|
ToSchemaOperationTypes<ExtractOperationTypes<TContract>>
|
|
60
71
|
>;
|
|
72
|
+
readonly orm: OrmClient<TContract>;
|
|
61
73
|
readonly context: ExecutionContext<TContract>;
|
|
62
74
|
readonly stack: SqlExecutionStackWithDriver<PostgresTargetId>;
|
|
63
|
-
|
|
75
|
+
connect(bindingInput?: PostgresBindingInput): Promise<Runtime>;
|
|
76
|
+
runtime(): Runtime;
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
export interface PostgresOptionsBase<TContract extends SqlContract<SqlStorage>> {
|
|
67
80
|
readonly extensions?: readonly SqlRuntimeExtensionDescriptor<PostgresTargetId>[];
|
|
68
81
|
readonly plugins?: readonly Plugin<TContract>[];
|
|
69
82
|
readonly verify?: RuntimeVerifyOptions;
|
|
70
|
-
readonly
|
|
83
|
+
readonly poolOptions?: {
|
|
84
|
+
readonly connectionTimeoutMillis?: number;
|
|
85
|
+
readonly idleTimeoutMillis?: number;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface PostgresBindingOptions {
|
|
90
|
+
readonly binding?: PostgresBinding;
|
|
91
|
+
readonly url?: string;
|
|
92
|
+
readonly pg?: Pool | Client;
|
|
71
93
|
}
|
|
72
94
|
|
|
73
95
|
export type PostgresOptionsWithContract<TContract extends SqlContract<SqlStorage>> =
|
|
74
|
-
|
|
96
|
+
PostgresBindingOptions &
|
|
75
97
|
PostgresOptionsBase<TContract> & {
|
|
76
98
|
readonly contract: TContract;
|
|
77
99
|
readonly contractJson?: never;
|
|
78
100
|
};
|
|
79
101
|
|
|
80
102
|
export type PostgresOptionsWithContractJson<TContract extends SqlContract<SqlStorage>> =
|
|
81
|
-
|
|
103
|
+
PostgresBindingOptions &
|
|
82
104
|
PostgresOptionsBase<TContract> & {
|
|
83
105
|
readonly contractJson: unknown;
|
|
84
106
|
readonly contract?: never;
|
|
@@ -101,6 +123,24 @@ function resolveContract<TContract extends SqlContract<SqlStorage>>(
|
|
|
101
123
|
return validateContract<TContract>(contractInput);
|
|
102
124
|
}
|
|
103
125
|
|
|
126
|
+
function toRuntimeBinding<TContract extends SqlContract<SqlStorage>>(
|
|
127
|
+
binding: PostgresBinding,
|
|
128
|
+
options: PostgresOptions<TContract>,
|
|
129
|
+
) {
|
|
130
|
+
if (binding.kind !== 'url') {
|
|
131
|
+
return binding;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
kind: 'pgPool',
|
|
136
|
+
pool: new Pool({
|
|
137
|
+
connectionString: binding.url,
|
|
138
|
+
connectionTimeoutMillis: options.poolOptions?.connectionTimeoutMillis ?? 20_000,
|
|
139
|
+
idleTimeoutMillis: options.poolOptions?.idleTimeoutMillis ?? 30_000,
|
|
140
|
+
}),
|
|
141
|
+
} as const;
|
|
142
|
+
}
|
|
143
|
+
|
|
104
144
|
/**
|
|
105
145
|
* Creates a lazy Postgres client from either `contractJson` or a TypeScript-authored `contract`.
|
|
106
146
|
* Static query surfaces are available immediately, while `runtime()` instantiates the driver/pool on first call.
|
|
@@ -115,19 +155,11 @@ export default function postgres<TContract extends SqlContract<SqlStorage>>(
|
|
|
115
155
|
options: PostgresOptions<TContract>,
|
|
116
156
|
): PostgresClient<TContract> {
|
|
117
157
|
const contract = resolveContract(options);
|
|
118
|
-
|
|
158
|
+
let binding = resolveOptionalPostgresBinding(options);
|
|
119
159
|
const stack = createSqlExecutionStack({
|
|
120
160
|
target: postgresTarget,
|
|
121
161
|
adapter: postgresAdapter,
|
|
122
|
-
driver:
|
|
123
|
-
options.cursor === undefined
|
|
124
|
-
? postgresDriver
|
|
125
|
-
: {
|
|
126
|
-
...postgresDriver,
|
|
127
|
-
create() {
|
|
128
|
-
return postgresDriver.create({ cursor: options.cursor });
|
|
129
|
-
},
|
|
130
|
-
},
|
|
162
|
+
driver: postgresDriver,
|
|
131
163
|
extensionPacks: options.extensions ?? [],
|
|
132
164
|
});
|
|
133
165
|
|
|
@@ -138,49 +170,112 @@ export default function postgres<TContract extends SqlContract<SqlStorage>>(
|
|
|
138
170
|
|
|
139
171
|
const schema: PostgresClient<TContract>['schema'] = schemaBuilder(context);
|
|
140
172
|
const sql = sqlBuilder({ context });
|
|
173
|
+
let runtimeInstance: Runtime | undefined;
|
|
174
|
+
let runtimeDriver: { connect(binding: unknown): Promise<void> } | undefined;
|
|
175
|
+
let driverConnected = false;
|
|
176
|
+
let connectPromise: Promise<void> | undefined;
|
|
177
|
+
let backgroundConnectError: unknown;
|
|
178
|
+
const connectDriver = async (resolvedBinding: PostgresBinding): Promise<void> => {
|
|
179
|
+
if (driverConnected) return;
|
|
180
|
+
if (!runtimeDriver) throw new Error('Postgres runtime driver missing');
|
|
181
|
+
if (connectPromise) return connectPromise;
|
|
182
|
+
const runtimeBinding = toRuntimeBinding(resolvedBinding, options);
|
|
183
|
+
connectPromise = runtimeDriver
|
|
184
|
+
.connect(runtimeBinding)
|
|
185
|
+
.then(() => {
|
|
186
|
+
driverConnected = true;
|
|
187
|
+
})
|
|
188
|
+
.catch(async (err) => {
|
|
189
|
+
backgroundConnectError = err;
|
|
190
|
+
connectPromise = undefined;
|
|
191
|
+
if (resolvedBinding.kind === 'url' && runtimeBinding.kind === 'pgPool') {
|
|
192
|
+
await runtimeBinding.pool.end().catch(() => undefined);
|
|
193
|
+
}
|
|
194
|
+
throw err;
|
|
195
|
+
});
|
|
196
|
+
return connectPromise;
|
|
197
|
+
};
|
|
198
|
+
const getRuntime = (): Runtime => {
|
|
199
|
+
if (backgroundConnectError !== undefined) {
|
|
200
|
+
throw backgroundConnectError;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (runtimeInstance) {
|
|
204
|
+
return runtimeInstance;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const stackInstance = instantiateExecutionStack(stack);
|
|
208
|
+
const driverDescriptor = stack.driver;
|
|
209
|
+
if (!driverDescriptor) {
|
|
210
|
+
throw new Error('Driver descriptor missing from execution stack');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const driver = driverDescriptor.create({
|
|
214
|
+
cursor: { disabled: true },
|
|
215
|
+
});
|
|
216
|
+
runtimeDriver = driver;
|
|
217
|
+
if (binding !== undefined) {
|
|
218
|
+
void connectDriver(binding).catch(() => undefined);
|
|
219
|
+
}
|
|
141
220
|
|
|
142
|
-
|
|
221
|
+
runtimeInstance = createRuntime({
|
|
222
|
+
stackInstance,
|
|
223
|
+
context,
|
|
224
|
+
driver,
|
|
225
|
+
verify: options.verify ?? { mode: 'onFirstUse', requireMarker: false },
|
|
226
|
+
...(options.plugins ? { plugins: options.plugins } : {}),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
return runtimeInstance;
|
|
230
|
+
};
|
|
231
|
+
const orm: OrmClient<TContract> = ormBuilder({
|
|
232
|
+
contract,
|
|
233
|
+
runtime: {
|
|
234
|
+
execute(plan) {
|
|
235
|
+
return getRuntime().execute(plan);
|
|
236
|
+
},
|
|
237
|
+
connection() {
|
|
238
|
+
return getRuntime().connection();
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
});
|
|
143
242
|
|
|
144
243
|
return {
|
|
145
244
|
sql,
|
|
245
|
+
kysely(runtime: Runtime) {
|
|
246
|
+
return new Kysely<KyselifyContract<TContract>>({
|
|
247
|
+
dialect: new KyselyPrismaDialect({ runtime, contract }),
|
|
248
|
+
});
|
|
249
|
+
},
|
|
146
250
|
schema,
|
|
251
|
+
orm,
|
|
147
252
|
context,
|
|
148
253
|
stack,
|
|
149
|
-
async
|
|
150
|
-
if (
|
|
151
|
-
|
|
254
|
+
async connect(bindingInput) {
|
|
255
|
+
if (driverConnected || connectPromise) {
|
|
256
|
+
throw new Error('Postgres client already connected');
|
|
152
257
|
}
|
|
153
258
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (driver === undefined) {
|
|
158
|
-
throw new Error('Relational runtime requires a driver descriptor on the execution stack');
|
|
159
|
-
}
|
|
259
|
+
if (bindingInput !== undefined) {
|
|
260
|
+
binding = resolvePostgresBinding(bindingInput);
|
|
261
|
+
}
|
|
160
262
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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
|
-
})();
|
|
263
|
+
if (binding === undefined) {
|
|
264
|
+
throw new Error(
|
|
265
|
+
'Postgres binding not configured. Pass url/pg/binding to postgres(...) or call db.connect({ ... }).',
|
|
266
|
+
);
|
|
267
|
+
}
|
|
178
268
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
269
|
+
const runtime = getRuntime();
|
|
270
|
+
if (driverConnected) {
|
|
271
|
+
return runtime;
|
|
272
|
+
}
|
|
182
273
|
|
|
183
|
-
|
|
274
|
+
await connectDriver(binding);
|
|
275
|
+
return runtime;
|
|
276
|
+
},
|
|
277
|
+
runtime() {
|
|
278
|
+
return getRuntime();
|
|
184
279
|
},
|
|
185
280
|
};
|
|
186
281
|
}
|