@prisma/orm-sqlite 8.0.0-rc.18-dev.39 → 8.0.0-rc.18-dev.41

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.
@@ -1,4 +1,4 @@
1
- import { a as SqliteQueryMembers, c as SqliteTransactionContext, i as SqliteOrm, l as sqlite, n as SqliteOptions, r as SqliteOptionsBase, s as SqliteTargetId, t as SqliteClient } from "./sqlite-nkzz9Mmw-Bp47g4Ms.mjs";
1
+ import { a as SqliteQueryMembers, c as SqliteTargetId, i as SqliteOrm, l as SqliteTransactionContext, n as SqliteOptions, r as SqliteOptionsBase, s as SqliteStaticMembers, t as SqliteClient, u as sqlite } from "./sqlite-Yizsft25-m9Hoa392.mjs";
2
2
  import { Runtime, SqlRuntimeBase } from "@prisma/orm-family-sql/runtime";
3
3
  import "@prisma/orm-target-sqlite/driver/runtime";
4
4
  import { Contract } from "@prisma/orm-framework/contract/types";
@@ -20,5 +20,5 @@ type SqliteBindingInput = {
20
20
  interface SqliteRuntime extends Runtime {}
21
21
  declare class SqliteRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> extends SqlRuntimeBase<TContract> {}
22
22
  //#endregion
23
- export { type SqliteBindingInput, type SqliteClient, type SqliteOptions, type SqliteOptionsBase, type SqliteOrm, type SqliteQueryMembers, type SqliteRuntime, SqliteRuntimeImpl, type SqliteTargetId, type SqliteTransactionContext, sqlite as default };
23
+ export { type SqliteBindingInput, type SqliteClient, type SqliteOptions, type SqliteOptionsBase, type SqliteOrm, type SqliteQueryMembers, type SqliteRuntime, SqliteRuntimeImpl, type SqliteStaticMembers, type SqliteTargetId, type SqliteTransactionContext, sqlite as default };
24
24
  //# sourceMappingURL=runtime.d.mts.map
package/dist/runtime.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { i as validateSqliteContract, t as buildSqliteStaticContext } from "./sqlite-static-QqgEQcIR-DcT933u6.mjs";
1
+ import { i as validateSqliteContract, t as buildSqliteStaticContext } from "./sqlite-static-DxkzgdPG-qGCRRq7m.mjs";
2
2
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
3
3
  import sqliteAdapter from "@prisma/orm-target-sqlite/adapter/runtime";
4
4
  import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
@@ -8,7 +8,6 @@ import sqliteTarget from "@prisma/orm-target-sqlite/target/runtime";
8
8
  import { assertDefined } from "@prisma/orm-framework/utils/assertions";
9
9
  import { blindCast } from "@prisma/orm-framework/utils/casts";
10
10
  import sqliteDriver from "@prisma/orm-target-sqlite/driver/runtime";
11
- import { instantiateExecutionStack } from "@prisma/orm-framework/components/execution";
12
11
  import { orm, prepareQuery } from "@prisma/orm-family-sql/orm-client";
13
12
  import { InternalError } from "@prisma/orm-framework/utils/internal-error";
14
13
  import { structuredError } from "@prisma/orm-framework/utils/structured-error";
@@ -39,7 +38,7 @@ function sqliteOrm(orm) {
39
38
  * Builds the members of a SQLite transaction over `txCtx`, so every statement they run goes through the transaction. Preparing sends nothing to the database, so `prepare` uses `prepareRuntime`; the prepared statement runs on the queryable it is given.
40
39
  */
41
40
  function buildSqliteTransactionMembers(options, txCtx) {
42
- const { context, collections, rawCodecInferer, enums, prepareRuntime } = options;
41
+ const { context, collections, rawCodecInferer, enums, toSql, prepareRuntime } = options;
43
42
  const sqlNamespace = sql({
44
43
  context,
45
44
  rawCodecInferer
@@ -65,6 +64,7 @@ function buildSqliteTransactionMembers(options, txCtx) {
65
64
  rawCodecInferer
66
65
  }),
67
66
  enums,
67
+ toSql,
68
68
  prepare(declaration, callback) {
69
69
  return prepareQuery(prepareRuntime(), declaration, callback);
70
70
  }
@@ -101,7 +101,7 @@ function sqlite(options) {
101
101
  stack,
102
102
  driver: sqliteDriver
103
103
  });
104
- const { sql, raw: rawSqlTag, enums } = buildSqliteStaticContext(contract, context, stack.adapter.rawCodecInferer);
104
+ const { sql, raw: rawSqlTag, enums, toSql } = buildSqliteStaticContext(contract, context, stack);
105
105
  let runtimeInstance;
106
106
  let runtimeDriver;
107
107
  let driverConnected = false;
@@ -127,7 +127,7 @@ function sqlite(options) {
127
127
  if (closed) throw sqliteError("DRIVER.NOT_CONNECTED", "SQLite client is closed", { meta: { extension: "sqlite" } });
128
128
  if (backgroundConnectError !== void 0) throw backgroundConnectError;
129
129
  if (runtimeInstance) return runtimeInstance;
130
- const stackInstance = instantiateExecutionStack(stack);
130
+ const adapter = stack.adapter.create(stack);
131
131
  const driverDescriptor = stack.driver;
132
132
  if (!driverDescriptor) throw new InternalError("Driver descriptor missing from execution stack");
133
133
  const driver = driverDescriptor.create();
@@ -136,11 +136,12 @@ function sqlite(options) {
136
136
  if (binding !== void 0) connectDriver(binding).catch(() => void 0);
137
137
  runtimeInstance = new SqliteRuntimeImpl({
138
138
  context,
139
- adapter: stackInstance.adapter,
139
+ adapter,
140
140
  driver,
141
141
  ...ifDefined("verifyMarker", options.verifyMarker),
142
142
  ...ifDefined("middleware", options.middleware),
143
143
  ...ifDefined("log", options.log),
144
+ ...ifDefined("mode", options.mode),
144
145
  closeRefusal: "at-once"
145
146
  });
146
147
  return runtimeInstance;
@@ -169,9 +170,16 @@ function sqlite(options) {
169
170
  orm: orm$1,
170
171
  enums,
171
172
  raw: rawSqlTag,
173
+ toSql,
172
174
  context,
173
175
  contract,
174
176
  stack,
177
+ query(plan, execOptions) {
178
+ return getRuntime().query(plan, execOptions);
179
+ },
180
+ execute(plan, execOptions) {
181
+ return getRuntime().execute(plan, execOptions);
182
+ },
175
183
  async connect(bindingInput) {
176
184
  if (closed) throw sqliteError("DRIVER.NOT_CONNECTED", "SQLite client is closed", { meta: { extension: "sqlite" } });
177
185
  if (driverConnected || connectPromise) throw sqliteError("DRIVER.ALREADY_CONNECTED", "SQLite client already connected", { meta: { extension: "sqlite" } });
@@ -200,6 +208,7 @@ function sqlite(options) {
200
208
  collections: options.collections,
201
209
  rawCodecInferer: stack.adapter.rawCodecInferer,
202
210
  enums,
211
+ toSql,
203
212
  prepareRuntime: getRuntime
204
213
  }, txCtx)));
205
214
  });
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/runtime.mjs"],"sourcesContent":["import { i as validateSqliteContract, t as buildSqliteStaticContext } from \"./sqlite-static-QqgEQcIR.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport sqliteDriver from \"@internal/driver-sqlite/runtime\";\nimport { instantiateExecutionStack } from \"@internal/framework-components/execution\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { orm, prepareQuery } from \"@internal/sql-orm-client\";\nimport { SqlRuntimeBase, activitySource, createExecutionContext, createSqlExecutionStack, delegatingActivitySource, withTransaction, withTransactionMembers } from \"@internal/sql-runtime\";\nimport sqliteTarget from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/errors.ts\nfunction sqliteError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\n//#endregion\n//#region src/runtime/binding.ts\nfunction resolveSqliteBinding(input) {\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: input.path\n\t};\n}\nfunction resolveOptionalSqliteBinding(options) {\n\tif (options.path === void 0) return;\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: options.path\n\t};\n}\n//#endregion\n//#region src/runtime/sqlite-runtime.ts\nvar SqliteRuntimeImpl = class extends SqlRuntimeBase {};\n//#endregion\n//#region src/runtime/sqlite.ts\nfunction sqliteOrm(orm) {\n\tconst namespace = orm[UNBOUND_NAMESPACE_ID];\n\tassertDefined(namespace, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn blindCast(Reflect.get(namespace, \"fragment\") === void 0 ? Object.create(namespace, { fragment: { value: Reflect.get(orm, \"fragment\") } }) : namespace);\n}\n/**\n* Builds the members of a SQLite transaction over `txCtx`, so every statement they run goes through the transaction. Preparing sends nothing to the database, so `prepare` uses `prepareRuntime`; the prepared statement runs on the queryable it is given.\n*/\nfunction buildSqliteTransactionMembers(options, txCtx) {\n\tconst { context, collections, rawCodecInferer, enums, prepareRuntime } = options;\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tsql: blindCast(sqlNamespace),\n\t\torm: sqliteOrm(orm({\n\t\t\truntime: {\n\t\t\t\tquery(plan) {\n\t\t\t\t\treturn txCtx.query(plan);\n\t\t\t\t},\n\t\t\t\texecute(plan) {\n\t\t\t\t\treturn txCtx.execute(plan);\n\t\t\t\t},\n\t\t\t\t[activitySource]: delegatingActivitySource(() => txCtx)\n\t\t\t},\n\t\t\tcontext,\n\t\t\t...ifDefined(\"collections\", collections)\n\t\t})),\n\t\traw: createRawLane({\n\t\t\tcontext,\n\t\t\trawCodecInferer\n\t\t}),\n\t\tenums,\n\t\tprepare(declaration, callback) {\n\t\t\treturn prepareQuery(prepareRuntime(), declaration, callback);\n\t\t}\n\t};\n}\n/**\n* Creates a lazy SQLite client. The client infers its contract type from `contract`: a value from\n* `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is\n* validated once, however many clients are built from it. The database opens on the first query\n* or `connect()`.\n*\n* @example\n* ```ts\n* import { contractFromJson } from '@prisma/orm-sqlite/static';\n* import sqlite from '@prisma/orm-sqlite/runtime';\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* export const db = sqlite({ contract, path: './dev.db' });\n* ```\n*/\nfunction sqlite(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tlet binding = resolveOptionalSqliteBinding(options);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\tdriver: sqliteDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst context = createExecutionContext({\n\t\tcontract,\n\t\tstack,\n\t\tdriver: sqliteDriver\n\t});\n\tconst { sql, raw: rawSqlTag, enums } = buildSqliteStaticContext(contract, context, stack.adapter.rawCodecInferer);\n\tlet runtimeInstance;\n\tlet runtimeDriver;\n\tlet driverConnected = false;\n\tlet connectPromise;\n\tlet closePromise;\n\tlet backgroundConnectError;\n\tlet closed = false;\n\tlet ownedDispose;\n\tconst connectDriver = async (resolvedBinding) => {\n\t\tif (driverConnected) return;\n\t\tif (!runtimeDriver) throw new InternalError(\"SQLite runtime driver missing\");\n\t\tif (connectPromise) return connectPromise;\n\t\tconnectPromise = runtimeDriver.connect(resolvedBinding).then(() => {\n\t\t\tdriverConnected = true;\n\t\t}).catch((err) => {\n\t\t\tbackgroundConnectError = err;\n\t\t\tconnectPromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn connectPromise;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\tif (backgroundConnectError !== void 0) throw backgroundConnectError;\n\t\tif (runtimeInstance) return runtimeInstance;\n\t\tconst stackInstance = instantiateExecutionStack(stack);\n\t\tconst driverDescriptor = stack.driver;\n\t\tif (!driverDescriptor) throw new InternalError(\"Driver descriptor missing from execution stack\");\n\t\tconst driver = driverDescriptor.create();\n\t\townedDispose = () => driver.close();\n\t\truntimeDriver = driver;\n\t\tif (binding !== void 0) connectDriver(binding).catch(() => void 0);\n\t\truntimeInstance = new SqliteRuntimeImpl({\n\t\t\tcontext,\n\t\t\tadapter: stackInstance.adapter,\n\t\t\tdriver,\n\t\t\t...ifDefined(\"verifyMarker\", options.verifyMarker),\n\t\t\t...ifDefined(\"middleware\", options.middleware),\n\t\t\t...ifDefined(\"log\", options.log),\n\t\t\tcloseRefusal: \"at-once\"\n\t\t});\n\t\treturn runtimeInstance;\n\t};\n\tconst orm$1 = sqliteOrm(orm({\n\t\tcontext,\n\t\t...ifDefined(\"collections\", options.collections),\n\t\truntime: {\n\t\t\tquery(plan) {\n\t\t\t\treturn getRuntime().query(plan);\n\t\t\t},\n\t\t\texecute(plan) {\n\t\t\t\treturn getRuntime().execute(plan);\n\t\t\t},\n\t\t\tconnection() {\n\t\t\t\treturn getRuntime().connection();\n\t\t\t},\n\t\t\t[activitySource]: delegatingActivitySource(() => getRuntime())\n\t\t}\n\t}));\n\tfunction prepare(declaration, callback) {\n\t\treturn prepareQuery(getRuntime(), declaration, callback);\n\t}\n\treturn {\n\t\tsql,\n\t\torm: orm$1,\n\t\tenums,\n\t\traw: rawSqlTag,\n\t\tcontext,\n\t\tcontract,\n\t\tstack,\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\t\tif (driverConnected || connectPromise) throw sqliteError(\"DRIVER.ALREADY_CONNECTED\", \"SQLite client already connected\", { meta: { extension: \"sqlite\" } });\n\t\t\tbackgroundConnectError = void 0;\n\t\t\tif (bindingInput !== void 0) binding = resolveSqliteBinding(bindingInput);\n\t\t\tif (binding === void 0) throw sqliteError(\"RUNTIME.BINDING_MISSING\", \"SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).\", { meta: { extension: \"sqlite\" } });\n\t\t\tconst runtime = getRuntime();\n\t\t\tif (driverConnected) return runtime;\n\t\t\tawait connectDriver(binding);\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tprepare,\n\t\ttransaction(fn) {\n\t\t\tlet runtime;\n\t\t\ttry {\n\t\t\t\truntime = getRuntime();\n\t\t\t} catch (err) {\n\t\t\t\treturn Promise.reject(err);\n\t\t\t}\n\t\t\treturn withTransaction(runtime, (txCtx) => {\n\t\t\t\treturn fn(withTransactionMembers(txCtx, buildSqliteTransactionMembers({\n\t\t\t\t\tcontext,\n\t\t\t\t\tcollections: options.collections,\n\t\t\t\t\trawCodecInferer: stack.adapter.rawCodecInferer,\n\t\t\t\t\tenums,\n\t\t\t\t\tprepareRuntime: getRuntime\n\t\t\t\t}, txCtx)));\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) return closePromise;\n\t\t\tclosed = true;\n\t\t\tclosePromise = (async () => {\n\t\t\t\tawait connectPromise?.catch(() => void 0);\n\t\t\t\tawait ownedDispose?.();\n\t\t\t})();\n\t\t\treturn closePromise;\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { SqliteRuntimeImpl, sqlite as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAS,YAAY,MAAM,SAAS,SAAS;CAC5C,OAAO,gBAAgB,MAAM,SAAS,OAAO;AAC9C;AAGA,SAAS,qBAAqB,OAAO;CACpC,OAAO;EACN,MAAM;EACN,MAAM,MAAM;CACb;AACD;AACA,SAAS,6BAA6B,SAAS;CAC9C,IAAI,QAAQ,SAAS,KAAK,GAAG;CAC7B,OAAO;EACN,MAAM;EACN,MAAM,QAAQ;CACf;AACD;AAGA,IAAI,oBAAoB,cAAc,eAAe,CAAC;AAGtD,SAAS,UAAU,KAAK;CACvB,MAAM,YAAY,IAAI;CACtB,cAAc,WAAW,gEAAgE;CACzF,OAAO,UAAU,QAAQ,IAAI,WAAW,UAAU,MAAM,KAAK,IAAI,OAAO,OAAO,WAAW,EAAE,UAAU,EAAE,OAAO,QAAQ,IAAI,KAAK,UAAU,EAAE,EAAE,CAAC,IAAI,SAAS;AAC7J;;;;AAIA,SAAS,8BAA8B,SAAS,OAAO;CACtD,MAAM,EAAE,SAAS,aAAa,iBAAiB,OAAO,mBAAmB;CACzE,MA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AW,SAAS,EAAE,CAAC;GAClH,IAAI,mBAAmB,gBAAgB,MAAM,YAAY,4BAA4B,mCAAmC,EAAE,MAAM,EAAE,WAAW,SAAS,EAAE,CAAC;GACzJ,yBAAyB,KAAK;GAC9B,IAAI,iBAAiB,KAAK,GAAG,UAAU,qBAAqB,YAAY;GACxE,IAAI,YAAY,KAAK,GAAG,MAAM,YAAY,2BAA2B,yFAAyF,EAAE,MAAM,EAAE,WAAW,SAAS,EAAE,CAAC;GAC/L,MAAM,UAAU,WAAW;GAC3B,IAAI,iBAAiB,OAAO;GAC5B,MAAM,cAAc,OAAO;GAC3B,OAAO;EACR;EACA,UAAU;GACT,OAAO,WAAW;EACnB;EACA;EACA,YAAY,IAAI;GACf,IAAI;GACJ,IAAI;IACH,UAAU,WAAW;GACtB,SAAS,KAAK;IACb,OAAO,QAAQ,OAAO,GAAG;GAC1B;GACA,OAAO,gBAAgB,UAAU,UAAU;IAC1C,OAAO,GAAG,uBAAuB,OAAO,8BAA8B;KACrE;KACA,aAAa,QAAQ;KACrB,iBAAiB,MAAM,QAAQ;KAC/B;KACA,gBAAgB;IACjB,GAAG,KAAK,CAAC,CAAC;GACX,CAAC;EACF;EACA,QAAQ;GACP,IAAI,cAAc,OAAO;GACzB,SAAS;GACT,gBAAgB,YAAY;IAC3B,MAAM,gBAAgB,YAAY,KAAK,CAAC;IACxC,MAAM,eAAe;GACtB,EAAA,CAAG;GACH,OAAO;EACR;EACA,CAAC,OAAO,gBAAgB;GACvB,OAAO,KAAK,MAAM;EACnB;CACD;AACD"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/runtime.mjs"],"sourcesContent":["import { i as validateSqliteContract, t as buildSqliteStaticContext } from \"./sqlite-static-DxkzgdPG.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport sqliteDriver from \"@internal/driver-sqlite/runtime\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { orm, prepareQuery } from \"@internal/sql-orm-client\";\nimport { SqlRuntimeBase, activitySource, createExecutionContext, createSqlExecutionStack, delegatingActivitySource, withTransaction, withTransactionMembers } from \"@internal/sql-runtime\";\nimport sqliteTarget from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { structuredError } from \"@internal/utils/structured-error\";\n//#region src/errors.ts\nfunction sqliteError(code, message, options) {\n\treturn structuredError(code, message, options);\n}\n//#endregion\n//#region src/runtime/binding.ts\nfunction resolveSqliteBinding(input) {\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: input.path\n\t};\n}\nfunction resolveOptionalSqliteBinding(options) {\n\tif (options.path === void 0) return;\n\treturn {\n\t\tkind: \"path\",\n\t\tpath: options.path\n\t};\n}\n//#endregion\n//#region src/runtime/sqlite-runtime.ts\nvar SqliteRuntimeImpl = class extends SqlRuntimeBase {};\n//#endregion\n//#region src/runtime/sqlite.ts\nfunction sqliteOrm(orm) {\n\tconst namespace = orm[UNBOUND_NAMESPACE_ID];\n\tassertDefined(namespace, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn blindCast(Reflect.get(namespace, \"fragment\") === void 0 ? Object.create(namespace, { fragment: { value: Reflect.get(orm, \"fragment\") } }) : namespace);\n}\n/**\n* Builds the members of a SQLite transaction over `txCtx`, so every statement they run goes through the transaction. Preparing sends nothing to the database, so `prepare` uses `prepareRuntime`; the prepared statement runs on the queryable it is given.\n*/\nfunction buildSqliteTransactionMembers(options, txCtx) {\n\tconst { context, collections, rawCodecInferer, enums, toSql, prepareRuntime } = options;\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tsql: blindCast(sqlNamespace),\n\t\torm: sqliteOrm(orm({\n\t\t\truntime: {\n\t\t\t\tquery(plan) {\n\t\t\t\t\treturn txCtx.query(plan);\n\t\t\t\t},\n\t\t\t\texecute(plan) {\n\t\t\t\t\treturn txCtx.execute(plan);\n\t\t\t\t},\n\t\t\t\t[activitySource]: delegatingActivitySource(() => txCtx)\n\t\t\t},\n\t\t\tcontext,\n\t\t\t...ifDefined(\"collections\", collections)\n\t\t})),\n\t\traw: createRawLane({\n\t\t\tcontext,\n\t\t\trawCodecInferer\n\t\t}),\n\t\tenums,\n\t\ttoSql,\n\t\tprepare(declaration, callback) {\n\t\t\treturn prepareQuery(prepareRuntime(), declaration, callback);\n\t\t}\n\t};\n}\n/**\n* Creates a lazy SQLite client. The client infers its contract type from `contract`: a value from\n* `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is\n* validated once, however many clients are built from it. The database opens on the first query\n* or `connect()`.\n*\n* @example\n* ```ts\n* import { contractFromJson } from '@prisma/orm-sqlite/static';\n* import sqlite from '@prisma/orm-sqlite/runtime';\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* export const db = sqlite({ contract, path: './dev.db' });\n* ```\n*/\nfunction sqlite(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tlet binding = resolveOptionalSqliteBinding(options);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\tdriver: sqliteDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst context = createExecutionContext({\n\t\tcontract,\n\t\tstack,\n\t\tdriver: sqliteDriver\n\t});\n\tconst { sql, raw: rawSqlTag, enums, toSql } = buildSqliteStaticContext(contract, context, stack);\n\tlet runtimeInstance;\n\tlet runtimeDriver;\n\tlet driverConnected = false;\n\tlet connectPromise;\n\tlet closePromise;\n\tlet backgroundConnectError;\n\tlet closed = false;\n\tlet ownedDispose;\n\tconst connectDriver = async (resolvedBinding) => {\n\t\tif (driverConnected) return;\n\t\tif (!runtimeDriver) throw new InternalError(\"SQLite runtime driver missing\");\n\t\tif (connectPromise) return connectPromise;\n\t\tconnectPromise = runtimeDriver.connect(resolvedBinding).then(() => {\n\t\t\tdriverConnected = true;\n\t\t}).catch((err) => {\n\t\t\tbackgroundConnectError = err;\n\t\t\tconnectPromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn connectPromise;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\tif (backgroundConnectError !== void 0) throw backgroundConnectError;\n\t\tif (runtimeInstance) return runtimeInstance;\n\t\tconst adapter = stack.adapter.create(stack);\n\t\tconst driverDescriptor = stack.driver;\n\t\tif (!driverDescriptor) throw new InternalError(\"Driver descriptor missing from execution stack\");\n\t\tconst driver = driverDescriptor.create();\n\t\townedDispose = () => driver.close();\n\t\truntimeDriver = driver;\n\t\tif (binding !== void 0) connectDriver(binding).catch(() => void 0);\n\t\truntimeInstance = new SqliteRuntimeImpl({\n\t\t\tcontext,\n\t\t\tadapter,\n\t\t\tdriver,\n\t\t\t...ifDefined(\"verifyMarker\", options.verifyMarker),\n\t\t\t...ifDefined(\"middleware\", options.middleware),\n\t\t\t...ifDefined(\"log\", options.log),\n\t\t\t...ifDefined(\"mode\", options.mode),\n\t\t\tcloseRefusal: \"at-once\"\n\t\t});\n\t\treturn runtimeInstance;\n\t};\n\tconst orm$1 = sqliteOrm(orm({\n\t\tcontext,\n\t\t...ifDefined(\"collections\", options.collections),\n\t\truntime: {\n\t\t\tquery(plan) {\n\t\t\t\treturn getRuntime().query(plan);\n\t\t\t},\n\t\t\texecute(plan) {\n\t\t\t\treturn getRuntime().execute(plan);\n\t\t\t},\n\t\t\tconnection() {\n\t\t\t\treturn getRuntime().connection();\n\t\t\t},\n\t\t\t[activitySource]: delegatingActivitySource(() => getRuntime())\n\t\t}\n\t}));\n\tfunction prepare(declaration, callback) {\n\t\treturn prepareQuery(getRuntime(), declaration, callback);\n\t}\n\treturn {\n\t\tsql,\n\t\torm: orm$1,\n\t\tenums,\n\t\traw: rawSqlTag,\n\t\ttoSql,\n\t\tcontext,\n\t\tcontract,\n\t\tstack,\n\t\tquery(plan, execOptions) {\n\t\t\treturn getRuntime().query(plan, execOptions);\n\t\t},\n\t\texecute(plan, execOptions) {\n\t\t\treturn getRuntime().execute(plan, execOptions);\n\t\t},\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw sqliteError(\"DRIVER.NOT_CONNECTED\", \"SQLite client is closed\", { meta: { extension: \"sqlite\" } });\n\t\t\tif (driverConnected || connectPromise) throw sqliteError(\"DRIVER.ALREADY_CONNECTED\", \"SQLite client already connected\", { meta: { extension: \"sqlite\" } });\n\t\t\tbackgroundConnectError = void 0;\n\t\t\tif (bindingInput !== void 0) binding = resolveSqliteBinding(bindingInput);\n\t\t\tif (binding === void 0) throw sqliteError(\"RUNTIME.BINDING_MISSING\", \"SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).\", { meta: { extension: \"sqlite\" } });\n\t\t\tconst runtime = getRuntime();\n\t\t\tif (driverConnected) return runtime;\n\t\t\tawait connectDriver(binding);\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tprepare,\n\t\ttransaction(fn) {\n\t\t\tlet runtime;\n\t\t\ttry {\n\t\t\t\truntime = getRuntime();\n\t\t\t} catch (err) {\n\t\t\t\treturn Promise.reject(err);\n\t\t\t}\n\t\t\treturn withTransaction(runtime, (txCtx) => {\n\t\t\t\treturn fn(withTransactionMembers(txCtx, buildSqliteTransactionMembers({\n\t\t\t\t\tcontext,\n\t\t\t\t\tcollections: options.collections,\n\t\t\t\t\trawCodecInferer: stack.adapter.rawCodecInferer,\n\t\t\t\t\tenums,\n\t\t\t\t\ttoSql,\n\t\t\t\t\tprepareRuntime: getRuntime\n\t\t\t\t}, txCtx)));\n\t\t\t});\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) return closePromise;\n\t\t\tclosed = true;\n\t\t\tclosePromise = (async () => {\n\t\t\t\tawait connectPromise?.catch(() => void 0);\n\t\t\t\tawait ownedDispose?.();\n\t\t\t})();\n\t\t\treturn closePromise;\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { SqliteRuntimeImpl, sqlite as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,YAAY,MAAM,SAAS,SAAS;CAC5C,OAAO,gBAAgB,MAAM,SAAS,OAAO;AAC9C;AAGA,SAAS,qBAAqB,OAAO;CACpC,OAAO;EACN,MAAM;EACN,MAAM,MAAM;CACb;AACD;AACA,SAAS,6BAA6B,SAAS;CAC9C,IAAI,QAAQ,SAAS,KAAK,GAAG;CAC7B,OAAO;EACN,MAAM;EACN,MAAM,QAAQ;CACf;AACD;AAGA,IAAI,oBAAoB,cAAc,eAAe,CAAC;AAGtD,SAAS,UAAU,KAAK;CACvB,MAAM,YAAY,IAAI;CACtB,cAAc,WAAW,gEAAgE;CACzF,OAAO,UAAU,QAAQ,IAAI,WAAW,UAAU,MAAM,KAAK,IAAI,OAAO,OAAO,WAAW,EAAE,UAAU,EAAE,OAAO,QAAQ,IAAI,KAAK,UAAU,EAAE,EAAE,CAAC,IAAI,SAAS;AAC7J;;;;AAIA,SAAS,8BAA8B,SAAS,OAAO;CACtD,MAAM,EAAE,SAAS,aAAa,iBAAiB,OAAO,OAAO,mBAAmB;CAChF,MAAM,eAAe,IAAI;EACxB;EACA;CACD,CAAC,CAAC,CAAC;CACH,cAAc,cAAc,gEAAgE;CAC5F,OAAO;EACN,KAAK,UAAU,YAAY;EAC3B,KAAK,UAAU,IAAI;GAClB,SAAS;IACR,MAAM,MAAM;KACX,OA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AA2B,EAAE,MAAM,EAAE,WAAW,SAAS,EAAE,CAAC;GAClH,IAAI,mBAAmB,gBAAgB,MAAM,YAAY,4BAA4B,mCAAmC,EAAE,MAAM,EAAE,WAAW,SAAS,EAAE,CAAC;GACzJ,yBAAyB,KAAK;GAC9B,IAAI,iBAAiB,KAAK,GAAG,UAAU,qBAAqB,YAAY;GACxE,IAAI,YAAY,KAAK,GAAG,MAAM,YAAY,2BAA2B,yFAAyF,EAAE,MAAM,EAAE,WAAW,SAAS,EAAE,CAAC;GAC/L,MAAM,UAAU,WAAW;GAC3B,IAAI,iBAAiB,OAAO;GAC5B,MAAM,cAAc,OAAO;GAC3B,OAAO;EACR;EACA,UAAU;GACT,OAAO,WAAW;EACnB;EACA;EACA,YAAY,IAAI;GACf,IAAI;GACJ,IAAI;IACH,UAAU,WAAW;GACtB,SAAS,KAAK;IACb,OAAO,QAAQ,OAAO,GAAG;GAC1B;GACA,OAAO,gBAAgB,UAAU,UAAU;IAC1C,OAAO,GAAG,uBAAuB,OAAO,8BAA8B;KACrE;KACA,aAAa,QAAQ;KACrB,iBAAiB,MAAM,QAAQ;KAC/B;KACA;KACA,gBAAgB;IACjB,GAAG,KAAK,CAAC,CAAC;GACX,CAAC;EACF;EACA,QAAQ;GACP,IAAI,cAAc,OAAO;GACzB,SAAS;GACT,gBAAgB,YAAY;IAC3B,MAAM,gBAAgB,YAAY,KAAK,CAAC;IACxC,MAAM,eAAe;GACtB,EAAA,CAAG;GACH,OAAO;EACR;EACA,CAAC,OAAO,gBAAgB;GACvB,OAAO,KAAK,MAAM;EACnB;CACD;AACD"}
@@ -1,16 +1,16 @@
1
1
  import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
2
- import { ExecutionContext, Log, Runtime, SqlExecutionStackWithDriver, SqlMiddleware, SqlRuntimeExtensionDescriptor, TransactionContext, VerifyMarkerOption } from "@prisma/orm-family-sql/runtime";
2
+ import { ExecutionContext, Log, Runtime, RuntimeMode, SqlExecutionStackWithDriver, SqlMiddleware, SqlRuntimeExtensionDescriptor, ToSqlMember, TransactionContext, VerifyMarkerOption } from "@prisma/orm-family-sql/runtime";
3
3
  import { NamespacedEnums } from "@prisma/orm-framework/contract/enum-accessor";
4
4
  import { CollectionClasses, NoCollectionClasses, OrmClientRootMembers, PrepareMember, orm } from "@prisma/orm-family-sql/orm-client";
5
5
  import { Contract } from "@prisma/orm-framework/contract/types";
6
6
  import { SqlStorage } from "@prisma/orm-family-sql/contract/types";
7
7
  import { Db, RawLane } from "@prisma/orm-family-sql/builder/types";
8
- import "@prisma/orm-family-sql/relational-core/expression";
9
- //#region ../../../3-extensions/sqlite/dist/sqlite-nkzz9Mmw.d.mts
8
+ import { RuntimeScope } from "@prisma/orm-family-sql/relational-core/types";
9
+ //#region ../../../3-extensions/sqlite/dist/sqlite-Yizsft25.d.mts
10
10
  //#region src/static/sqlite-static.d.ts
11
11
  type UnboundSql$1<TContract extends Contract<SqlStorage>> = Db<TContract>[typeof UNBOUND_NAMESPACE_ID];
12
12
  type UnboundEnums<TContract extends Contract<SqlStorage>> = NamespacedEnums<TContract>[typeof UNBOUND_NAMESPACE_ID];
13
- interface SqliteStaticContext<TContract extends Contract<SqlStorage>> {
13
+ interface SqliteStaticContext<TContract extends Contract<SqlStorage>> extends ToSqlMember {
14
14
  readonly context: ExecutionContext<TContract>;
15
15
  readonly contract: TContract;
16
16
  readonly enums: UnboundEnums<TContract>;
@@ -18,8 +18,8 @@ interface SqliteStaticContext<TContract extends Contract<SqlStorage>> {
18
18
  readonly raw: RawLane<TContract>;
19
19
  }
20
20
  /**
21
- * The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where
22
- * loading `node:sqlite` is not wanted.
21
+ * The query surfaces of a SQLite client without a driver: `sql`, `raw`, `enums` and `toSql`. Use
22
+ * it where loading `node:sqlite` is not wanted.
23
23
  *
24
24
  * @example
25
25
  * ```ts
@@ -39,7 +39,7 @@ type UnboundOrm<TContract extends Contract<SqlStorage>, TCollections extends Col
39
39
  /** The models of SQLite's single namespace, and `fragment` unless a model is named `fragment`. */
40
40
  type SqliteOrm<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> = 'fragment' extends keyof UnboundOrm<TContract, TCollections> ? UnboundOrm<TContract, TCollections> : UnboundOrm<TContract, TCollections> & OrmClientRootMembers<TContract>;
41
41
  /** The query members of a SQLite client, which its transactions offer with the same types. */
42
- interface SqliteQueryMembers<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> extends PrepareMember<TContract> {
42
+ interface SqliteQueryMembers<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> extends PrepareMember<TContract>, RuntimeScope, ToSqlMember {
43
43
  readonly sql: UnboundSql<TContract>;
44
44
  readonly orm: SqliteOrm<TContract, TCollections>;
45
45
  readonly raw: RawLane<TContract>;
@@ -47,11 +47,10 @@ interface SqliteQueryMembers<TContract extends Contract<SqlStorage>, TCollection
47
47
  interface SqliteTransactionContext<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> extends TransactionContext, SqliteQueryMembers<TContract, TCollections> {
48
48
  readonly enums: SqliteStaticContext<TContract>['enums'];
49
49
  }
50
- interface SqliteClient<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> extends SqliteQueryMembers<TContract, TCollections> {
51
- readonly enums: SqliteStaticContext<TContract>['enums'];
52
- readonly context: ExecutionContext<TContract>;
53
- readonly contract: TContract;
50
+ interface SqliteStaticMembers<TContract extends Contract<SqlStorage>> extends SqliteStaticContext<TContract> {
54
51
  readonly stack: SqlExecutionStackWithDriver<SqliteTargetId>;
52
+ }
53
+ interface SqliteClient<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> extends SqliteQueryMembers<TContract, TCollections>, SqliteStaticMembers<TContract> {
55
54
  connect(bindingInput?: {
56
55
  readonly path: string;
57
56
  }): Promise<Runtime>;
@@ -65,6 +64,7 @@ interface SqliteOptionsBase {
65
64
  readonly middleware?: readonly SqlMiddleware[];
66
65
  readonly verifyMarker?: VerifyMarkerOption;
67
66
  readonly log?: Log;
67
+ readonly mode?: RuntimeMode;
68
68
  }
69
69
  type SqliteOptions<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses> = SqliteOptionsBase & {
70
70
  readonly contract: TContract;
@@ -90,5 +90,5 @@ type SqliteOptions<TContract extends Contract<SqlStorage>, TCollections extends
90
90
  */
91
91
  declare function sqlite<TContract extends Contract<SqlStorage>, TCollections extends CollectionClasses = NoCollectionClasses>(options: SqliteOptions<TContract, TCollections>): SqliteClient<TContract, TCollections>;
92
92
  //#endregion
93
- export { SqliteQueryMembers as a, SqliteTransactionContext as c, SqliteOrm as i, sqlite as l, SqliteOptions as n, SqliteStaticContext as o, SqliteOptionsBase as r, SqliteTargetId as s, SqliteClient as t, sqliteStatic as u };
94
- //# sourceMappingURL=sqlite-nkzz9Mmw-Bp47g4Ms.d.mts.map
93
+ export { SqliteQueryMembers as a, SqliteTargetId as c, sqliteStatic as d, SqliteOrm as i, SqliteTransactionContext as l, SqliteOptions as n, SqliteStaticContext as o, SqliteOptionsBase as r, SqliteStaticMembers as s, SqliteClient as t, sqlite as u };
94
+ //# sourceMappingURL=sqlite-Yizsft25-m9Hoa392.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-Yizsft25-m9Hoa392.d.mts","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-Yizsft25.d.mts"],"mappings":";;;;;;;;;;KASK,aAAa,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC5E,aAAa,kBAAkB,SAAS,eAAe,gBAAgB,kBAAkB;UACpF,oBAAoB,kBAAkB,SAAS,qBAAqB;WACnE,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,aAAa;WACpB,KAAK,aAAa;WAClB,KAAK,QAAQ;;;;;;;;;;;iBAWP,aAAa,kBAAkB,SAAS,aA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,14 @@
1
1
  import sqliteAdapter from "@prisma/orm-target-sqlite/adapter/runtime";
2
2
  import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
3
3
  import { createRawLane, sql } from "@prisma/orm-family-sql/builder/runtime";
4
- import { createExecutionContext, createSqlExecutionStack } from "@prisma/orm-family-sql/runtime";
4
+ import { createExecutionContext, createSqlExecutionStack, createToSql } from "@prisma/orm-family-sql/runtime";
5
5
  import sqliteTarget, { SqliteContractSerializer } from "@prisma/orm-target-sqlite/target/runtime";
6
6
  import { assertDefined } from "@prisma/orm-framework/utils/assertions";
7
7
  import { blindCast } from "@prisma/orm-framework/utils/casts";
8
8
  import { validateContractOnce } from "@prisma/orm-framework/contract/validate-once";
9
9
  import { buildNamespacedEnums } from "@prisma/orm-framework/contract/enum-accessor";
10
- //#region ../../../3-extensions/sqlite/dist/sqlite-static-QqgEQcIR.mjs
11
- var version = "8.0.0-rc.18-dev.39";
10
+ //#region ../../../3-extensions/sqlite/dist/sqlite-static-DxkzgdPG.mjs
11
+ var version = "8.0.0-rc.18-dev.41";
12
12
  const serializer = new SqliteContractSerializer();
13
13
  const validator = `${sqliteTarget.targetId}@${version}`;
14
14
  /**
@@ -33,7 +33,8 @@ function contractFromJson(json) {
33
33
  function validateSqliteContract(contract) {
34
34
  return validateContractOnce(contract, validator, () => serializer.deserializeContract(serializer.serializeContract(contract)));
35
35
  }
36
- function buildSqliteStaticContext(contract, context, rawCodecInferer) {
36
+ function buildSqliteStaticContext(contract, context, stack) {
37
+ const { rawCodecInferer } = stack.adapter;
37
38
  const sqlNamespace = sql({
38
39
  context,
39
40
  rawCodecInferer
@@ -51,12 +52,13 @@ function buildSqliteStaticContext(contract, context, rawCodecInferer) {
51
52
  contract,
52
53
  enums,
53
54
  sql: sqlDb,
54
- raw
55
+ raw,
56
+ toSql: createToSql(stack, contract)
55
57
  };
56
58
  }
57
59
  /**
58
- * The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where
59
- * loading `node:sqlite` is not wanted.
60
+ * The query surfaces of a SQLite client without a driver: `sql`, `raw`, `enums` and `toSql`. Use
61
+ * it where loading `node:sqlite` is not wanted.
60
62
  *
61
63
  * @example
62
64
  * ```ts
@@ -73,9 +75,9 @@ function sqliteStatic(options) {
73
75
  return buildSqliteStaticContext(contract, createExecutionContext({
74
76
  contract,
75
77
  stack
76
- }), stack.adapter.rawCodecInferer);
78
+ }), stack);
77
79
  }
78
80
  //#endregion
79
81
  export { validateSqliteContract as i, contractFromJson as n, sqliteStatic as r, buildSqliteStaticContext as t };
80
82
 
81
- //# sourceMappingURL=sqlite-static-QqgEQcIR-DcT933u6.mjs.map
83
+ //# sourceMappingURL=sqlite-static-DxkzgdPG-qGCRRq7m.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-static-DxkzgdPG-qGCRRq7m.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-static-DxkzgdPG.mjs"],"sourcesContent":["import sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { createExecutionContext, createSqlExecutionStack, createToSql } from \"@internal/sql-runtime\";\nimport sqliteTarget, { SqliteContractSerializer } from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { validateContractOnce } from \"@internal/contract/validate-once\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\n//#region package.json\nvar version = \"8.0.0-rc.18-dev.41\";\n//#endregion\n//#region src/static/contract-from-json.ts\nconst serializer = new SqliteContractSerializer();\nconst validator = `${sqliteTarget.targetId}@${version}`;\n/**\n* Validates an emitted SQLite `contract.json` and returns it as the contract type the application\n* names, ready to pass to `sqlite({ contract })` and `sqliteStatic({ contract })`. Clients built\n* from the result do not validate it again.\n*\n* The returned value's top level is frozen; its nested objects are not. Do not change `json` or the\n* returned value after the call: clients built from the value later do not validate it again.\n*\n* @example\n* ```ts\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* ```\n*/\nfunction contractFromJson(json) {\n\treturn validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));\n}\nfunction validateSqliteContract(contract) {\n\treturn validateContractOnce(contract, validator, () => serializer.deserializeContract(serializer.serializeContract(contract)));\n}\n//#endregion\n//#region src/static/sqlite-static.ts\nfunction buildSqliteStaticContext(contract, context, stack) {\n\tconst { rawCodecInferer } = stack.adapter;\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\tconst sqlDb = blindCast(sqlNamespace);\n\tconst raw = createRawLane({\n\t\tcontext,\n\t\trawCodecInferer\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract,\n\t\tenums,\n\t\tsql: sqlDb,\n\t\traw,\n\t\ttoSql: createToSql(stack, contract)\n\t};\n}\n/**\n* The query surfaces of a SQLite client without a driver: `sql`, `raw`, `enums` and `toSql`. Use\n* it where loading `node:sqlite` is not wanted.\n*\n* @example\n* ```ts\n* const { enums } = sqliteStatic({ contract: contractFromJson<Contract>(contractJson) });\n* ```\n*/\nfunction sqliteStatic(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildSqliteStaticContext(contract, createExecutionContext({\n\t\tcontract,\n\t\tstack\n\t}), stack);\n}\n//#endregion\nexport { validateSqliteContract as i, sqliteStatic as n, contractFromJson as r, buildSqliteStaticContext as t };\n\n//# sourceMappingURL=sqlite-static-DxkzgdPG.mjs.map"],"mappings":";;;;;;;;;;AAUA,IAAI,UAAU;AAGd,MAAM,aAAa,IAAI,yBAAyB;AAChD,MAAM,YAAY,GAAG,aAAa,SAAS,GAAG;;;;;;;;;;;;;;;;;AAiB9C,SAAS,iBAAiB,MAAM;CAC/B,OAAO,qBAAqB,MAAM,YAAY,UAAU,WAAW,oBAAoB,KAAK,CAAC;AAC9F;AACA,SAAS,uBAAuB,UAAU;CACzC,OAAO,qBAAqB,UAAU,iBAAiB,WAAW,oBAAoB,WAAW,kBAAkB,QAAQ,CAAC,CAAC;AAC9H;AAGA,SAAS,yBAAyB,UAAU,SAAS,OAAO;CAC3D,MAAM,EAAE,oBAAoB,MAAM;CAClC,MAAM,eAAe,IAAI;EACxB;EACA;CACD,CAAC,CAAC,CAAC;CACH,cAAc,cAAc,gEAAgE;CAC5F,MAAM,QAAQ,UAAU,YAAY;CACpC,MAAM,MAAM,cAAc;EACzB;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,SAAS,YAAY,QAAQ,eAAe,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;CACzI,cAAc,OAAO,gEAAgE;CACrF,OAAO;EACN;EACA;EACA;EACA,KAAK;EACL;EACA,OAAO,YAAY,OAAO,QAAQ;CACnC;AACD;;;;;;;;;;AAUA,SAAS,aAAa,SAAS;CAC9B,MAAM,WAAW,uBAAuB,QAAQ,QAAQ;CACxD,MAAM,QAAQ,wBAAwB;EACrC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,yBAAyB,UAAU,uBAAuB;EAChE;EACA;CACD,CAAC,GAAG,KAAK;AACV"}
package/dist/static.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as SqliteStaticContext, u as sqliteStatic } from "./sqlite-nkzz9Mmw-Bp47g4Ms.mjs";
1
+ import { d as sqliteStatic, o as SqliteStaticContext } from "./sqlite-Yizsft25-m9Hoa392.mjs";
2
2
  import { Contract } from "@prisma/orm-framework/contract/types";
3
3
  import { SqlStorage } from "@prisma/orm-family-sql/contract/types";
4
4
  //#region ../../../3-extensions/sqlite/dist/static.d.mts
package/dist/static.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as contractFromJson, r as sqliteStatic } from "./sqlite-static-QqgEQcIR-DcT933u6.mjs";
1
+ import { n as contractFromJson, r as sqliteStatic } from "./sqlite-static-DxkzgdPG-qGCRRq7m.mjs";
2
2
  export { contractFromJson, sqliteStatic as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/orm-sqlite",
3
- "version": "8.0.0-rc.18-dev.39",
3
+ "version": "8.0.0-rc.18-dev.41",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -10,17 +10,17 @@
10
10
  "skills"
11
11
  ],
12
12
  "dependencies": {
13
- "@prisma/orm-family-sql": "8.0.0-rc.18-dev.39",
14
- "@prisma/orm-framework": "8.0.0-rc.18-dev.39",
15
- "@prisma/orm-target-sqlite": "8.0.0-rc.18-dev.39",
16
- "@prisma/orm-toolchain": "8.0.0-rc.18-dev.39",
13
+ "@prisma/orm-family-sql": "8.0.0-rc.18-dev.41",
14
+ "@prisma/orm-framework": "8.0.0-rc.18-dev.41",
15
+ "@prisma/orm-target-sqlite": "8.0.0-rc.18-dev.41",
16
+ "@prisma/orm-toolchain": "8.0.0-rc.18-dev.41",
17
17
  "pathe": "^2.0.3",
18
18
  "tinyglobby": "^0.2.17"
19
19
  },
20
20
  "devDependencies": {
21
- "@internal/sqlite": "8.0.0-rc.18-dev.39",
22
- "@repo/tsconfig": "8.0.0-rc.18-dev.39",
23
- "@repo/tsdown": "8.0.0-rc.18-dev.39",
21
+ "@internal/sqlite": "8.0.0-rc.18-dev.41",
22
+ "@repo/tsconfig": "8.0.0-rc.18-dev.41",
23
+ "@repo/tsdown": "8.0.0-rc.18-dev.41",
24
24
  "tsdown": "0.22.14",
25
25
  "typescript": "5.9.3"
26
26
  },
@@ -15,7 +15,7 @@ description: >-
15
15
  ORM 7 or earlier (schema.prisma + @prisma/client).
16
16
  metadata:
17
17
  library: '@prisma/orm-sqlite'
18
- library_version: '8.0.0-rc.18-dev.39'
18
+ library_version: '8.0.0-rc.18-dev.41'
19
19
  version: '2026-09-12'
20
20
  ---
21
21
 
@@ -101,7 +101,7 @@ The single source of truth: read the envelope, find the row by `code`, follow th
101
101
  | `CLI.CONSENT_UNUSED` | `migration plan` / `db update` | Every question was answered, and a `--delete` or `--allow` was left over: a typo, a subject the plan does not touch, or a `--confirm` (which consents to nothing). Fix or drop the flag. A typo next to a question nobody answered is reported as `CLI.CONSENT_REQUIRED` instead, which names the flag that matched nothing. On `db update --dry-run` the same mistake is `MIGRATION.STATEMENT_ANSWERS_NO_QUESTION`. |
102
102
  | `MIGRATION.STATEMENT_DID_NOT_RESOLVE_LOSS` | A rename typed at the data-loss prompt | The rename still loses the subject's data. Answer with `delete`, or give a rename whose old name is the subject. |
103
103
  | `MIGRATION.NO_INVARIANT_PATH` / `MIGRATION.UNKNOWN_INVARIANT` | `db migrate` | Concurrent-migration and invariant flows — `references/migration-review.md`. |
104
- | `DRIVER.NOT_CONNECTED` with message `Runtime is closed` | A query, prepared statement or `db.runtime().connection()` that starts after `db.close()` and after the runtime was idle for one turn of the event loop, or after the `await using` scope that held a serverless connection ended | The work started after the runtime closed. Almost always it is a lazy read (`db.orm...all()`, `db.runtime().query(...)`) returned without `await`, which starts only when the caller awaits it, or work that waited on something other than the database first. Write `return await ...`, or move the call before `close()`. See `references/runtime.md` § *Workflow — Serverless and per-request runtimes*. |
104
+ | `DRIVER.NOT_CONNECTED` with message `Runtime is closed` | A query, prepared statement or `db.runtime().connection()` that starts after `db.close()` and after the runtime was idle for one turn of the event loop, or after the `await using` scope that held a serverless connection ended | The work started after the runtime closed. Almost always it is a lazy read (`db.orm...all()`, `db.query(...)`) returned without `await`, which starts only when the caller awaits it, or work that waited on something other than the database first. Write `return await ...`, or move the call before `close()`. See `references/runtime.md` § *Workflow — Serverless and per-request runtimes*. |
105
105
  | `await db.close()` or the end of an `await using` scope never settles in a test | A test that installed fake timers (`vi.useFakeTimers()`, Jest's modern fake timers) before the Prisma runtime module was imported | `close()` waits one turn of the event loop through a `setTimeout(0)` that the runtime module takes when it loads. Install fake timers after the imports, or advance the fake clock (`await vi.runAllTimersAsync()`) before awaiting the close. |
106
106
  | `MIGRATION.PATH_UNREACHABLE` / `MIGRATION.MARKER_MISMATCH` | `db migrate`; `db migrate --show` raises `MARKER_MISMATCH` too | For `PATH_UNREACHABLE`, run `db migrate --show --db $URL` to inspect the path. Then run `migration plan --from <from> --to <target>`, or `migration list` to audit the graph — see `references/migration-review.md`. |
107
107
  | `MIGRATION.PLAN_ORIGIN_UNKNOWN` / `MIGRATION.HASH_NOT_IN_GRAPH` / `MIGRATION.SNAPSHOT_MISSING` | `migration plan`, `migration new` | Origin resolution — `references/migration-model.md` § *The trap* and `references/migrations.md` § *Dev → ship transition*. |
@@ -9,7 +9,7 @@ Shared concepts (result consumption, script teardown, cross-target pitfalls, cap
9
9
  **Postgres** (`postgres({ contract, ... })` from `@internal/postgres/runtime`):
10
10
 
11
11
  - **`db.orm.<ns>.<Model>`** — ORM, PascalCase model name (`db.orm.public.User`). Fluent `.where(...).select(...).orderBy(...).all()`, fully typed against `Contract`. Default lane for CRUD with relations.
12
- - **`db.sql.<ns>.<table>`** — SQL builder, lowercase storage name (`db.sql.public.user`). Produces a *plan*. A plan that returns rows (`select`, or a write with `.returning(...)`) runs through `db.runtime().query(plan)`; a write with no `RETURNING` runs through `db.runtime().execute(plan)`, which resolves `{ affectedRows }`. Use when the ORM is too high-level — explicit `JOIN`, computed projections, set operations, window functions.
12
+ - **`db.sql.<ns>.<table>`** — SQL builder, lowercase storage name (`db.sql.public.user`). Produces a *plan*. A plan that returns rows (`select`, or a write with `.returning(...)`) runs through `db.query(plan)`; a write with no `RETURNING` runs through `db.execute(plan)`, which resolves `{ affectedRows }`. Use when the ORM is too high-level — explicit `JOIN`, computed projections, set operations, window functions.
13
13
 
14
14
  Reach for the ORM first; drop to `db.sql` when the ORM can't express the shape. Lane choice is local — one query function picks one lane, not the whole app.
15
15
 
@@ -539,7 +539,7 @@ If `?? 0` is showing up on every aggregate, that's a signal you're calling `sum`
539
539
 
540
540
  ## Workflow — SQL builder (`db.sql.<ns>.<table>`)
541
541
 
542
- The concept: `db.sql.<ns>.<table>` is a table-shaped builder that produces a *plan*. The plan is a serialisable description of the query (AST + parameters); you run it through the runtime. Pick the runtime method by the result the plan declares: `db.runtime().query(plan)` for rows (it returns the same `AsyncIterableResult` as `.all()`, so `await` it for an array), `db.runtime().execute(plan)` for a write with no `RETURNING` (it resolves `{ affectedRows }` and returns no rows). The builder gives you the lanes the ORM doesn't express — explicit `JOIN`, arbitrary expression projection, target-specific operations through extension helpers — without dropping to raw SQL.
542
+ The concept: `db.sql.<ns>.<table>` is a table-shaped builder that produces a *plan*. The plan is a serialisable description of the query (AST + parameters); you run it through the client. Pick the method by the result the plan declares: `db.query(plan)` for rows (it returns the same `AsyncIterableResult` as `.all()`, so `await` it for an array), `db.execute(plan)` for a write with no `RETURNING` (it resolves `{ affectedRows }` and returns no rows). The builder gives you the lanes the ORM doesn't express — explicit `JOIN`, arbitrary expression projection, target-specific operations through extension helpers — without dropping to raw SQL.
543
543
 
544
544
  ```typescript
545
545
  // src/queries/posts.ts — adjust the relative import to match file depth.
@@ -552,7 +552,7 @@ const plan = db.sql.public.post
552
552
  .limit(limit)
553
553
  .build();
554
554
 
555
- const rows = await db.runtime().query(plan);
555
+ const rows = await db.query(plan);
556
556
  ```
557
557
 
558
558
  The `.where(...)` callback receives `(fields, fns)` — `fields` is the field proxy (column references), `fns` is the operator namespace (`fns.eq`, `fns.ne`, `fns.gt`, …). Extensions inject extension-shaped helpers into the same `fns` namespace (`fns.distanceSphere`, `fns.cosineDistance`, etc.).
@@ -565,7 +565,7 @@ const plan = db.sql.public.user
565
565
  .insert([{ email }])
566
566
  .returning('id', 'email')
567
567
  .build();
568
- const [row] = await db.runtime().query(plan);
568
+ const [row] = await db.query(plan);
569
569
 
570
570
  // Update with predicate and returning.
571
571
  const updatePlan = db.sql.public.user
@@ -573,14 +573,14 @@ const updatePlan = db.sql.public.user
573
573
  .where((f, fns) => fns.eq(f.id, userId))
574
574
  .returning('id', 'email')
575
575
  .build();
576
- const rows = await db.runtime().query(updatePlan);
576
+ const rows = await db.query(updatePlan);
577
577
 
578
578
  // Delete with predicate, no RETURNING — `execute` resolves the affected count.
579
579
  const deletePlan = db.sql.public.user
580
580
  .delete()
581
581
  .where((f, fns) => fns.eq(f.id, userId))
582
582
  .build();
583
- const { affectedRows } = await db.runtime().execute(deletePlan);
583
+ const { affectedRows } = await db.execute(deletePlan);
584
584
  ```
585
585
 
586
586
  `.returning(...)` requires the target adapter to advertise the `returning` capability. The Postgres adapter advertises it by default.
@@ -596,7 +596,7 @@ const plan = db.sql.public.cafe
596
596
  .orderBy((f) => f.id, { direction: 'asc' })
597
597
  .limit(limit)
598
598
  .build();
599
- const rows = await db.runtime().query(plan);
599
+ const rows = await db.query(plan);
600
600
 
601
601
  // Self-join with an alias.
602
602
  db.sql.public.post
@@ -609,7 +609,7 @@ The SQL builder's `.orderBy(column, { direction, nulls })` takes the same null p
609
609
 
610
610
  ## Workflow — Transactions
611
611
 
612
- The concept: `db.transaction(fn)` opens a transaction and passes a `tx` context to the callback. `tx` offers the client's query members with the same types, and each runs inside the transaction: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query(plan)` (rows) and `execute(plan)` (affected count), plus `enums` and `nativeEnums`. A prepared statement runs on what it is given, so `ps.query(tx, params)` runs inside the transaction. See *Workflow — Transactions* in `references/runtime.md` for raw SQL and `tx.prepare`. The transaction commits on the callback's successful return and rolls back on any thrown error.
612
+ The concept: `db.transaction(fn)` opens a transaction and passes a `tx` context to the callback. `tx` offers the client's query members with the same types, and each runs inside the transaction: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query(plan)` (rows) and `execute(plan)` (affected count), plus `toSql`, `enums` and `nativeEnums`. A prepared statement runs on what it is given, so `ps.query(tx, params)` runs inside the transaction. See *Workflow — Transactions* in `references/runtime.md` for raw SQL and `tx.prepare`. The transaction commits on the callback's successful return and rolls back on any thrown error.
613
613
 
614
614
  ```typescript
615
615
  await db.transaction(async (tx) => {
@@ -658,7 +658,7 @@ On Postgres both `db.sql` and `db.orm` are keyed by storage namespace (the Postg
658
658
  // db.sql.<namespace>.<table>
659
659
  const plan = db.sql.public.user.select('id', 'email').build();
660
660
  const authPlan = db.sql.auth.users.select('id', 'token').build();
661
- const rows = await db.runtime().query(plan);
661
+ const rows = await db.query(plan);
662
662
 
663
663
  // db.orm.<namespace>.<Model>
664
664
  const user = await db.orm.public.User.create({ id: 1, email: 'a@x.io' });
@@ -677,10 +677,10 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
677
677
  4. **Reaching for `.between(a, b)` on a field proxy.** It doesn't exist. Either chain `.where((m) => m.field.gte(a)).where((m) => m.field.lte(b))` or use `and(m.field.gte(a), m.field.lte(b))` inside one `.where()` clause.
678
678
  5. **Importing `and` / `or` / `not` from an internal package.** They are exported from `@prisma/orm-postgres/orm-client`; do not reach into `@internal/sql-orm-client`.
679
679
  6. **Trying to `db.sql.from(tables.user)`.** That surface does not exist. The builder is table-shaped: `db.sql.<ns>.<tableName>.select(...)`. There is no `db.schema.tables` either.
680
- 7. **Trying to `db.execute(plan)` directly, or reading rows with `execute`.** Plans run through the runtime: `db.runtime().query(plan)` for rows, `db.runtime().execute(plan)` for a non-returning write (`{ affectedRows }`). Inside a transaction, `tx.query(plan)` / `tx.execute(plan)`. `execute` never yields rows — a `select` or `.returning(...)` plan passed to it gives you statistics, not data.
680
+ 7. **Reading rows with `execute`.** Plans run through the client: `db.query(plan)` for rows, `db.execute(plan)` for a non-returning write (`{ affectedRows }`). Inside a transaction, `tx.query(plan)` / `tx.execute(plan)`. `execute` never yields rows — a `select` or `.returning(...)` plan passed to it gives you statistics, not data.
681
681
  8. **Setting `capabilities: { lateral: true }` in `prisma.config.ts`.** The ORM config (`ormConfig({...})`) does not take `capabilities`. Capabilities are declared by the active adapter and become part of the emitted contract; the Postgres adapter advertises `lateral`, `jsonAgg`, and `returning` out of the box. Enable extension capabilities through `extensions: [...]` in the config (see `references/contract.md`).
682
682
  9. **Confabulating a TypedSQL or `.stream()` surface.** Neither exists. Raw SQL does: the client's raw lane, ``db.raw.sql`…` ``. Reusable statements do: `db.prepare(...)` (see *Prepared statements* in [`queries.md`](./queries.md)). Streaming: `for await` over a read terminal or `runtime.query(plan)` — with the caveats in *Streaming* in [`queries.md`](./queries.md).
683
- 10. **Mixing the ORM mutation return with `runtime.query(plan)` / `runtime.execute(plan)`.** ORM terminals issue the query themselves and return rows. The runtime methods are for SQL-builder plans.
683
+ 10. **Mixing the ORM mutation return with `db.query(plan)` / `db.execute(plan)`.** ORM terminals issue the query themselves and return rows. `query` and `execute` are for plans.
684
684
  11. **Adding a `cursor()` to a relation, count, operation or `nulls` order.** It throws `ORM.ARGUMENT_INVALID`. Use `.limit(n).offset(n)`, or order by plain columns.
685
685
  12. **Ordering grouped rows by an aggregate metric.** The grouped collection supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but it cannot order by an aggregate alias such as `SUM(amount)`. Sorting the materialized aggregate result in JS is fine at small cardinalities; for large grouped result sets, drop to `db.sql.<ns>.<table>`.
686
686
  13. **Locking a parent row with `forUpdate()` while other transactions write rows that reference it.** Every insert or update of a row with a foreign key to the locked row takes `FOR KEY SHARE` on it to check the key, and `FOR KEY SHARE` conflicts with `FOR UPDATE`, so those writes wait and can deadlock. Use `forNoKeyUpdate()`: it still blocks writes to the row, but not the foreign-key check.
@@ -702,7 +702,7 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
702
702
  - [ ] For cursor pagination, used `.orderBy(...).cursor({ field: lastValue }).limit(n).all()` — did NOT hand-write a `.where(p => p.field.lt(cursor))` workaround when the `.cursor()` API serves the same purpose.
703
703
  - [ ] For ORM combinators, imported `and` / `or` / `not` from `@prisma/orm-postgres/orm-client`.
704
704
  - [ ] Wrote a query piece shared between places as a function: a query fragment from `db.orm.fragment(fields, body)` or `collection.fragment(body)` run with `.with(...)`, a `where` callback typed with `CodecField`, or `orderByField` for an order parameter from a request.
705
- - [ ] Ran SQL-builder plans via `db.runtime().query(plan)` when they return rows and `db.runtime().execute(plan)` only for non-returning writes (`tx.query` / `tx.execute` inside a transaction). Passed `insert()` an array of rows.
705
+ - [ ] Ran SQL-builder plans via `db.query(plan)` when they return rows and `db.execute(plan)` only for non-returning writes (`tx.query` / `tx.execute` inside a transaction). Passed `insert()` an array of rows.
706
706
  - [ ] Wrapped multi-statement work in `db.transaction(async (tx) => { ... })` where atomicity matters.
707
707
  - [ ] For top-N grouped aggregates at meaningful scale, dropped to `db.sql.<ns>.<table>` rather than JS-side sort + slice over `groupBy(...).aggregate(...)`.
708
708
  - [ ] Did NOT confabulate TypedSQL, `.stream()`, `db.batch`, `.between(...)`, a collection-level `.count()`, a `capabilities` field on the config, or a `db.sql.from(tables.user)` API — routed to *What Prisma 8 doesn't do yet* / `references/feedback.md` instead. Raw SQL is spelled `db.raw.sql`, not `db.sql.raw`.
@@ -125,12 +125,25 @@ console.log('Seeded.');
125
125
  await db.close();
126
126
  ```
127
127
 
128
+ ## Running a plan and printing its SQL (SQL targets)
129
+
130
+ A plan from `db.sql`, `db.raw` or the ORM (`.prepared.all().plan`) runs on the client: `db.query(plan)` returns its rows as an `AsyncIterableResult`, and `db.execute(plan)` resolves `{ affectedRows }` with no rows. Inside a transaction use `tx.query` / `tx.execute`; they have the same types. On Supabase, call them on a role-bound client (`db.asAnon()`, `await db.asUser(jwt)`). `db.query` on an ORM plan yields the database rows, not the result the ORM builds from them. To run a plan, use `db.query` and `db.execute`, not `db.runtime()`. `db.runtime()` remains for runtime-level work: `connection()`, `close()`, `telemetry()`, and as the target of a prepared statement (`ps.query(db.runtime(), params)`).
131
+
132
+ `db.toSql(plan)` returns `{ sql, params }` and needs no database, so a script can import `db.ts` with no `DATABASE_URL` set and print what a query would send. `params` are the plan's values before codecs encode them for the driver. Middleware rewrites (`beforeCompile`) are not applied. A plan with `prepare` bind sites throws `RUNTIME.PREPARE_BIND_ON_ADHOC`. `postgresStatic()` and `sqliteStatic()` have `toSql` too.
133
+
134
+ ```typescript
135
+ import { db } from '../src/prisma/db';
136
+
137
+ const plan = db.orm.public.Post.where({ published: true }).prepared.all().plan;
138
+ console.log(db.toSql(plan));
139
+ ```
140
+
128
141
  ## Streaming
129
142
 
130
- Every read terminal (`.all()`, and `runtime.query(plan)` for a SQL-builder plan) returns an `AsyncIterableResult`, so `for await` is always available. What it buys you depends on the `cursor` option, which `postgres()` and `postgresServerless()` (`@prisma/orm-postgres/serverless`) both accept:
143
+ Every read terminal (`.all()`, and `db.query(plan)` for a SQL-builder plan) returns an `AsyncIterableResult`, so `for await` is always available. What it buys you depends on the `cursor` option, which `postgres()` and `postgresServerless()` (`@prisma/orm-postgres/serverless`) both accept:
131
144
 
132
145
  - **Default (cursors off), on a client and on a connection:** the full result set is fetched from the server before the first row is yielded; only *decoding* happens per row. `for await` therefore does not bound the memory held by the raw result. For very large sets, paginate (`.limit()` / `.offset()`, or `.orderBy(...).cursor(...)`) instead.
133
- - **`cursor` set in the options of `postgres()` or `postgresServerless()` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call; there is no flag that turns cursors off):** the driver reads through a server-side cursor in batches of that size, so `for await` over `db.orm...all()` or `db.runtime().query(plan)` really does stream, and an early `break` stops reading. In a Worker, put the option only on a second serverless client that the streaming paths open their connections from, and keep the serverless client every other path uses without it. On a connection with cursors on, finish or `break` the `for await` loop before sending another query through `db`: the cursor holds the connection's only database connection until the loop ends, so a query inside the loop waits forever. On a client, the same query takes another database connection from the pool. Behind Cloudflare Hyperdrive, reads with cursors on hang, so the streaming paths hang there and the other paths do not.
146
+ - **`cursor` set in the options of `postgres()` or `postgresServerless()` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call; there is no flag that turns cursors off):** the driver reads through a server-side cursor in batches of that size, so `for await` over `db.orm...all()` or `db.query(plan)` really does stream, and an early `break` stops reading. In a Worker, put the option only on a second serverless client that the streaming paths open their connections from, and keep the serverless client every other path uses without it. On a connection with cursors on, finish or `break` the `for await` loop before sending another query through `db`: the cursor holds the connection's only database connection until the loop ends, so a query inside the loop waits forever. On a client, the same query takes another database connection from the pool. Behind Cloudflare Hyperdrive, reads with cursors on hang, so the streaming paths hang there and the other paths do not.
134
147
 
135
148
  There is no `.stream()` method on a client or on a connection.
136
149
 
@@ -214,7 +227,7 @@ Target-specific pitfalls live in the per-target guides.
214
227
  - **Many-to-many relations work through the junction.** `.include('tags', (tag) => tag.select(...))` traverses an N:M relation's `through` table, and nested `create` / `connect` / `disconnect` on an N:M relation write the junction rows for you (`examples/prisma-8-demo/src/orm-client/get-post-tags.ts`, `create-post-with-tags.ts`). The one refusal: a junction with required payload columns the relation API cannot populate throws `ORM.RELATION_MUTATION_UNSUPPORTED` — write that junction directly or use the SQL builder.
215
228
  - **Ordering grouped aggregates by an aggregate alias (Postgres).** `db.orm.<ns>.<Model>.groupBy(...)` supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but the grouped collection cannot order by an aggregate alias such as `SUM(amount)`. A "top-N groups by SUM" query therefore falls back to JS-side sort + slice over the full grouped result, which is fine at small cardinalities and bad at scale. Workarounds: (a) drop to `db.sql.<ns>.<table>` and write the `GROUP BY` + `ORDER BY` + `LIMIT` against the aggregated table directly; (b) live with the JS-side sort/slice if the grouped cardinality is bounded. File a feature request via `references/feedback.md` if this is hitting you in production.
216
229
  - **A raw-SQL lane.** This one exists. Write whole-query raw SQL through the client's raw lane: ``db.raw.sql`SELECT ...`.returnsRow({ ... }).build()`` for rows, or `.affectedCount()` for a mutation's row count. Each declared column names the codec that decodes it, so the row stays typed. For an expression fragment inside a builder query, use `fns.raw` in a `.select(...)` callback instead.
217
- - **TypedSQL (`.sql` files compiled into typed callables).** Not implemented. For a repeated query, use `db.prepare(...)` (see *Prepared statements* above) or a function that returns the built plan and `db.runtime().query(plan)` at the call site. If you want a `.sql`-file compile path, file a feature request via `references/feedback.md`.
230
+ - **TypedSQL (`.sql` files compiled into typed callables).** Not implemented. For a repeated query, use `db.prepare(...)` (see *Prepared statements* above) or a function that returns the built plan and `db.query(plan)` at the call site. If you want a `.sql`-file compile path, file a feature request via `references/feedback.md`.
218
231
  - **`EXPLAIN` / query-plan inspection.** Prisma 8 does not expose an `.explain()` method. Workaround: connect a `pg.Pool` you control via the runtime's `pg:` binding (see `references/runtime.md`) and issue `EXPLAIN ANALYZE` through it. If you want a first-class plan-inspection surface, file a feature request via `references/feedback.md`.
219
232
  - **Multi-statement batching (Prisma-7-style `db.$transaction([call1, call2])`).** Prisma 8 runs each call sequentially. Workaround: wrap atomically-related work in `db.transaction(async (tx) => { ... })` on Postgres. If you want batch-as-array semantics, file a feature request via `references/feedback.md`.
220
233
  - **Mongo façade transactions.** `@internal/mongo/runtime` does not expose `db.transaction(...)`. Multi-document atomicity is not yet wrapped in the Prisma 8 Mongo façade. Workaround: use the MongoDB driver's session API directly if you control the client binding (`mongoClient:` option). File a feature request via `references/feedback.md` if you need a first-class façade surface.
@@ -132,7 +132,7 @@ Servers (HTTP handlers, workers in a request loop) **do not call `db.close()`**
132
132
 
133
133
  - **`close()` is idempotent.** Calling it twice is a no-op.
134
134
  - **`close()` is terminal.** There is no reconnect on a closed `db` — construct a new client if you need to reach the database again. After close, `db.runtime()`, `db.connect(...)`, `db.transaction(...)`, and `db.prepare(...)` reject with `Error('<target> client is closed')` (e.g. `'Postgres client is closed'`, `'SQLite client is closed'`, `'Mongo client is closed'`).
135
- - **`close()` waits for work already running and refuses new work.** On a Postgres client built from `{ url }`, `close()` refuses every new call at once with `DRIVER.NOT_CONNECTED` ("Postgres client is closed"), and a runtime captured with `db.runtime()` before `close()` is refused at once with "Runtime is closed"; it waits for the queries, transactions and ORM calls already in flight, then ends the pool. An ORM call that resolves to one value, such as `first()`, `create()` or a nested create with its reload, starts when it is called, so `close()` waits for it and it completes. On a serverless connection, `close()` waits until the runtime has been idle for one turn of the event loop, so a chain of queries that keeps it busy from the close onward completes, then ends the `pg.Client`; work that starts after that rejects with `DRIVER.NOT_CONNECTED` ("Runtime is closed"). A lazy result such as `db.orm...all()` or `db.runtime().query(plan)` starts when it is awaited or iterated, not when it is built; awaited after `close()`, an ORM `all()` is refused with "Postgres client is closed". A Postgres client given a caller's `pg.Pool` or `pg.Client` does not close its runtime, so work through a runtime taken before `close()` keeps running on the caller's pool. `await` outstanding work before calling `close()`.
135
+ - **`close()` waits for work already running and refuses new work.** On a Postgres client built from `{ url }`, `close()` refuses every new call at once with `DRIVER.NOT_CONNECTED` ("Postgres client is closed"), and a runtime captured with `db.runtime()` before `close()` is refused at once with "Runtime is closed"; it waits for the queries, transactions and ORM calls already in flight, then ends the pool. An ORM call that resolves to one value, such as `first()`, `create()` or a nested create with its reload, starts when it is called, so `close()` waits for it and it completes. On a serverless connection, `close()` waits until the runtime has been idle for one turn of the event loop, so a chain of queries that keeps it busy from the close onward completes, then ends the `pg.Client`; work that starts after that rejects with `DRIVER.NOT_CONNECTED` ("Runtime is closed"). A lazy result such as `db.orm...all()` or `db.query(plan)` starts when it is awaited or iterated, not when it is built; awaited after `close()`, an ORM `all()` is refused with "Postgres client is closed". A Postgres client given a caller's `pg.Pool` or `pg.Client` does not close its runtime, so work through a runtime taken before `close()` keeps running on the caller's pool. `await` outstanding work before calling `close()`.
136
136
  - **Ownership.** `close()` releases only what the façade constructed (`pg.Pool` from `{ url }`, `MongoClient` from `{ url }` / `{ uri, dbName }`, SQLite handle from `{ path }`). If you supplied your own `pg.Pool` / `pg.Client` (Postgres `pg:` option), `mongodb.MongoClient` (Mongo `mongoClient:` option), or a pre-built `binding`, `db.close()` does **not** touch those — you own their lifecycle.
137
137
 
138
138
  **`db.end()` does not exist.** The universal `node-postgres` name is `pool.end()` on a `pg.Pool`; the Prisma 8 runtime client is not a `pg.Pool`. The right call is `await db.close()`.
@@ -163,13 +163,13 @@ export default {
163
163
  };
164
164
  ```
165
165
 
166
- The rule to remember: inside a request, `db` does everything the `db` from `postgres()` does, so any documented `db.orm...`, `db.sql...`, `db.raw...`, `db.transaction(...)`, `db.prepare(...)` or `db.runtime().query(...)` snippet works unchanged. Await every query before the `await using` scope ends. The connection's `close()` waits until the runtime has been idle for one turn of the event loop (a `setTimeout(0)`), then refuses new work. A lazy ORM read such as `db.orm.public.User.all()`, or `db.runtime().query(plan)`, returned from the scope without `await` starts only when the caller awaits it, after the scope has closed, so it rejects with `DRIVER.NOT_CONNECTED` ("Runtime is closed"), whose `fix` names the missing `await`. Work that keeps the runtime busy from the close onward completes: a `first()`, `execute()` or `transaction()`, an ORM write and its reload, including `include(...).create()` and a nested `create()`, and an async helper whose steps go through `db.orm`, `db.transaction()` or `db.prepare()`; a transaction commits. Such work is never refused because of the close; if it fails for its own reason, it rejects like any unawaited promise. A helper that calls `db.runtime()` after the scope has ended throws "Postgres connection is closed" at that call. Work that starts after the runtime was idle for a turn is refused. Whether a query sent after waiting on something other than the database counts as idle depends on when that callback runs relative to the timer, so do not rely on it. An unawaited promise that fails then, or fails for its own reason, rejects like any unawaited promise, and Node reports it as unhandled. Write `return await db.orm...`, not `return db.orm...`.
166
+ The rule to remember: inside a request, `db` does everything the `db` from `postgres()` does, so any documented `db.orm...`, `db.sql...`, `db.raw...`, `db.transaction(...)`, `db.prepare(...)` or `db.query(...)` snippet works unchanged. Await every query before the `await using` scope ends. The connection's `close()` waits until the runtime has been idle for one turn of the event loop (a `setTimeout(0)`), then refuses new work. A lazy ORM read such as `db.orm.public.User.all()`, or `db.query(plan)`, returned from the scope without `await` starts only when the caller awaits it, after the scope has closed, so it rejects with `DRIVER.NOT_CONNECTED` ("Runtime is closed"), whose `fix` names the missing `await`. Work that keeps the runtime busy from the close onward completes: a `first()`, `execute()` or `transaction()`, an ORM write and its reload, including `include(...).create()` and a nested `create()`, and an async helper whose steps go through `db.orm`, `db.transaction()` or `db.prepare()`; a transaction commits. Such work is never refused because of the close; if it fails for its own reason, it rejects like any unawaited promise. A helper that calls `db.runtime()` after the scope has ended throws "Postgres connection is closed" at that call. Work that starts after the runtime was idle for a turn is refused. Whether a query sent after waiting on something other than the database counts as idle depends on when that callback runs relative to the timer, so do not rely on it. An unawaited promise that fails then, or fails for its own reason, rejects like any unawaited promise, and Node reports it as unhandled. Write `return await db.orm...`, not `return db.orm...`.
167
167
 
168
168
  - **`connect` connects before it returns.** When the database refuses the connection, rejects the credentials, or does not answer within 20 seconds, `postgres.connect({ url })` rejects with `DRIVER.CONNECTION_FAILED` and leaves nothing open; an empty URL, a string that is not a URL, or a scheme other than `postgres://` or `postgresql://` rejects with `RUNTIME.BINDING_INVALID`. Handle an unreachable database at the `connect` call, not at the first query. Answer a request that needs no query, such as an unknown route, before `connect`, because `connect` opens a database connection whether or not a query follows.
169
169
  - **Never call `connect` at module scope.** A connection opened there is shared by every request in the isolate, and fails in four ways: its database connection goes stale after the isolate idles, concurrent requests queue behind each other on one `pg.Client`, nothing closes it when a request ends, and Cloudflare Workers reject a socket used across requests.
170
170
  - **`db.orm` is the way to use the ORM.** For custom collection classes, pass `collections` to `postgresServerless({ contract, collections })` at module scope; every connection's `db.orm` and `tx.orm` then returns the classes. See *Workflow — Custom collection classes* in [`queries-postgres.md`](queries-postgres.md).
171
171
  - **Anything that takes a runtime gets `db.runtime()`.** That includes `withTransaction(runtime, fn)` and a prepared statement's `query(runtime, params)`. Do not pass `db` itself.
172
- - **Inside `db.transaction(async (tx) => ...)`, run every query through `tx`.** A connection has one database connection, so inside `db.transaction(async (tx) => ...)` a query through `db` is not independent of the transaction; run every query through `tx`. A query that uses the connection's database connection directly, such as a `db.orm` read, a `db.orm` create of one row, an `updateAll(...)` or `deleteAll()`, or `db.runtime().query(...)`, runs inside the open transaction without saying so. An operation that asks for a database connection of its own, such as a `db.orm` `update(...)` or `delete()` of one row, `db.runtime().connection()`, a `db.orm` create that also writes related rows, or a nested `db.transaction(...)`, waits for the database connection the transaction holds, and the request hangs.
172
+ - **Inside `db.transaction(async (tx) => ...)`, run every query through `tx`.** A connection has one database connection, so inside `db.transaction(async (tx) => ...)` a query through `db` is not independent of the transaction; run every query through `tx`. A query that uses the connection's database connection directly, such as a `db.orm` read, a `db.orm` create of one row, an `updateAll(...)` or `deleteAll()`, or `db.query(...)`, runs inside the open transaction without saying so. An operation that asks for a database connection of its own, such as a `db.orm` `update(...)` or `delete()` of one row, `db.runtime().connection()`, a `db.orm` create that also writes related rows, or a nested `db.transaction(...)`, waits for the database connection the transaction holds, and the request hangs.
173
173
  - **After `db.close()`** (or the end of the `await using` scope), `db.runtime()` throws `DRIVER.NOT_CONNECTED` ("Postgres connection is closed"), and ORM queries, `db.transaction(...)` and prepared statements that start after the runtime was idle for a turn reject with `DRIVER.NOT_CONNECTED` ("Runtime is closed"). Call `postgres.connect({ url })` again for a new connection.
174
174
 
175
175
  How connections read rows, and the `cursor` option on the serverless client (with the Hyperdrive caveat), is in `references/queries.md` § *Streaming*.
@@ -250,6 +250,8 @@ export const db = postgres({
250
250
  });
251
251
  ```
252
252
 
253
+ `mode` decides what a budget violation does. It is `'strict'` by default, and every `budgets()` violation throws. Pass `mode: 'permissive'` to `postgres()`, `postgresServerless()`, `sqlite()` or `supabase()`, and a violation whose severity is `'warn'` goes to `log.warn` instead, and the query runs; a violation whose severity is `'error'` still throws. `budgets()` gives latency `'warn'` and the row count `'error'` by default, so a row-count limit warns only with `severities: { rowCount: 'warn' }`.
254
+
253
255
  For the full option surface, read the source: `packages/2-sql/5-runtime/src/middleware/lints.ts` and `.../budgets.ts`. The `severities` keys (`selectStar`, `noLimit`, `deleteWithoutWhere`, `updateWithoutWhere`, `readOnlyMutation` for lints; `rowCount`, `latency` for budgets) are the source of truth; do not extrapolate to a key that is not in those two files. `lints()` with no argument uses the default severities.
254
256
 
255
257
  ## Workflow — Cache middleware
@@ -307,7 +309,7 @@ Order matters: `beforeEncode` runs in registration order for every middleware be
307
309
 
308
310
  ## Workflow — Configure the connection
309
311
 
310
- The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` — *not* `driverOptions`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the marker-verification warnings `CONTRACT.MARKER_MISSING` and `CONTRACT.MARKER_MISMATCH` from the first query, the warnings `lints()` emits for rules whose severity is `warn`, and the errors a middleware's `activityEnded` or `activityFinalized` hook throws, which the runtime logs and swallows. If `log` has a `debug` method, it also receives debug events, for example when a middleware intercepts a statement. `budgets()` violations never reach `log`: the client runs its runtime in strict mode, so a violation throws, until the client exposes `mode` (TML-3567). Without `log`, the runtime drops these events. `postgresServerless()`, `sqlite()` and `supabase()` take the same option.
312
+ The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` — *not* `driverOptions`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the marker-verification warnings `CONTRACT.MARKER_MISSING` and `CONTRACT.MARKER_MISMATCH` from the first query, the warnings `lints()` emits for rules whose severity is `warn`, and the errors a middleware's `activityEnded` or `activityFinalized` hook throws, which the runtime logs and swallows. If `log` has a `debug` method, it also receives debug events, for example when a middleware intercepts a statement. `budgets()` violations reach `log` only in `mode: 'permissive'` (see *Lints and budgets middleware*). Without `log`, the runtime drops these events. `postgresServerless()`, `sqlite()` and `supabase()` take the same option.
311
313
 
312
314
  ```typescript
313
315
  // Default — URL string, factory constructs the pool.
@@ -355,7 +357,7 @@ export const db = postgres({
355
357
 
356
358
  ## Workflow — Transactions
357
359
 
358
- The concept applies to **Postgres, SQLite and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows) and `execute` (affected count). Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's has `enums`. `tx` has no `close`, `[Symbol.asyncDispose]`, `transaction` or `runtime()`. Inside the callback, send every query through `tx`, not `db`, so it runs inside the transaction. A Supabase role-bound client (`asUser`, `asAnon`, `asServiceRole`) has `transaction(fn)` too, and its `tx` runs every statement under the bound role. The Mongo façade does not expose `db.transaction(...)`.
360
+ The concept applies to **Postgres, SQLite and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows), `execute` (affected count) and `toSql`. Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's has `enums`. `tx` has no `close`, `[Symbol.asyncDispose]`, `transaction` or `runtime()`. Inside the callback, send every query through `tx`, not `db`, so it runs inside the transaction. A Supabase role-bound client (`asUser`, `asAnon`, `asServiceRole`) has `transaction(fn)` too, and its `tx` runs every statement under the bound role. The Mongo façade does not expose `db.transaction(...)`.
359
361
 
360
362
  ```typescript
361
363
  await db.transaction(async (tx) => {
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-nkzz9Mmw-Bp47g4Ms.d.mts","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-nkzz9Mmw.d.mts"],"mappings":";;;;;;;;;;KASK,aAAa,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC5E,aAAa,kBAAkB,SAAS,eAAe,gBAAgB,kBAAkB;UACpF,oBAAoB,kBAAkB,SAAS;WAC9C,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,aAAa;WACpB,KAAK,aAAa;WAClB,KAAK,QAAQ;;;;;;;;;;;iBAWP,aAAa,kBAAkB,SAAS,aAAa;WAC3D,UAAU;WACV,sBAAsB,8BAA8B;IAC3D,oBAAoB;;;KAGnB;KACA,UAAU,kBAAkB,SAAS,aAAa,qBAAqB,qBAAqB,kBAAkB,IAAI,WAAW;KAC7H,WAAW,kBAAkB,SAAS,eAAe,GAAG,kBAAkB;KAC1E,WAAW,kBAAkB,SAAS,aAAa,qBAAqB,qBAAqB,UAAU,WAAW,qBAAqB;;KAEvI,UAAU,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,gDAAgD,WAAW,WAAW,gBAAgB,WAAW,WAAW,gBAAgB,WAAW,WAAW,gBAAgB,qBAAqB;;UAE7Q,mBAAmB,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,cAAc;WAC9I,KAAK,WAAW;WAChB,KAAK,UAAU,WAAW;WAC1B,KAAK,QAAQ;;UAEd,yBAAyB,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,oBAAoB,mBAAmB,WAAW;WACxL,OAAO,oBAAoB;;UAE5B,aAAa,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,mBAAmB,WAAW;WACxJ,OAAO,oBAAoB;WAC3B,SAAS,iBAAiB;WAC1B,UAAU;WACV,OAAO,4BAA4B;EAC5C,QAAQ;aACG;MACP,QAAQ;EACZ,WAAW;EACX,YAAY,GAAG,KAAK,IAAI,yBAAyB,WAAW,kBAAkB,YAAY,KAAK,QAAQ;EACvG,SAAS;GACR,OAAO,iBAAiB;;UAEjB;WACC,sBAAsB,8BAA8B;WACpD,sBAAsB;WACtB,eAAe;WACf,MAAM;;KAEZ,cAAc,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,uBAAuB;WAChH,UAAU;WACV,cAAc;WACd;;;;;;;;;;;;;;;;;;;iBAmBM,OAAO,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,qBAAqB,SAAS,cAAc,WAAW,gBAAgB,aAAa,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sqlite-static-QqgEQcIR-DcT933u6.mjs","names":[],"sources":["../../../../3-extensions/sqlite/dist/sqlite-static-QqgEQcIR.mjs"],"sourcesContent":["import sqliteAdapter from \"@internal/adapter-sqlite/runtime\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { createRawLane, sql } from \"@internal/sql-builder/runtime\";\nimport { createExecutionContext, createSqlExecutionStack } from \"@internal/sql-runtime\";\nimport sqliteTarget, { SqliteContractSerializer } from \"@internal/target-sqlite/runtime\";\nimport { assertDefined } from \"@internal/utils/assertions\";\nimport { blindCast } from \"@internal/utils/casts\";\nimport { validateContractOnce } from \"@internal/contract/validate-once\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\n//#region package.json\nvar version = \"8.0.0-rc.18-dev.39\";\n//#endregion\n//#region src/static/contract-from-json.ts\nconst serializer = new SqliteContractSerializer();\nconst validator = `${sqliteTarget.targetId}@${version}`;\n/**\n* Validates an emitted SQLite `contract.json` and returns it as the contract type the application\n* names, ready to pass to `sqlite({ contract })` and `sqliteStatic({ contract })`. Clients built\n* from the result do not validate it again.\n*\n* The returned value's top level is frozen; its nested objects are not. Do not change `json` or the\n* returned value after the call: clients built from the value later do not validate it again.\n*\n* @example\n* ```ts\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* ```\n*/\nfunction contractFromJson(json) {\n\treturn validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));\n}\nfunction validateSqliteContract(contract) {\n\treturn validateContractOnce(contract, validator, () => serializer.deserializeContract(serializer.serializeContract(contract)));\n}\n//#endregion\n//#region src/static/sqlite-static.ts\nfunction buildSqliteStaticContext(contract, context, rawCodecInferer) {\n\tconst sqlNamespace = sql({\n\t\tcontext,\n\t\trawCodecInferer\n\t})[UNBOUND_NAMESPACE_ID];\n\tassertDefined(sqlNamespace, \"the unbound namespace always exists on a sqlite builder output\");\n\tconst sqlDb = blindCast(sqlNamespace);\n\tconst raw = createRawLane({\n\t\tcontext,\n\t\trawCodecInferer\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, (codecId) => context.contractCodecs.forCodecRef({ codecId })))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a sqlite builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract,\n\t\tenums,\n\t\tsql: sqlDb,\n\t\traw\n\t};\n}\n/**\n* The query surfaces of a SQLite client without a driver: `sql`, `raw` and `enums`. Use it where\n* loading `node:sqlite` is not wanted.\n*\n* @example\n* ```ts\n* const { enums } = sqliteStatic({ contract: contractFromJson<Contract>(contractJson) });\n* ```\n*/\nfunction sqliteStatic(options) {\n\tconst contract = validateSqliteContract(options.contract);\n\tconst stack = createSqlExecutionStack({\n\t\ttarget: sqliteTarget,\n\t\tadapter: sqliteAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildSqliteStaticContext(contract, createExecutionContext({\n\t\tcontract,\n\t\tstack\n\t}), stack.adapter.rawCodecInferer);\n}\n//#endregion\nexport { validateSqliteContract as i, sqliteStatic as n, contractFromJson as r, buildSqliteStaticContext as t };\n\n//# sourceMappingURL=sqlite-static-QqgEQcIR.mjs.map"],"mappings":";;;;;;;;;;AAUA,IAAI,UAAU;AAGd,MAAM,aAAa,IAAI,yBAAyB;AAChD,MAAM,YAAY,GAAG,aAAa,SAAS,GAAG;;;;;;;;;;;;;;;;;AAiB9C,SAAS,iBAAiB,MAAM;CAC/B,OAAO,qBAAqB,MAAM,YAAY,UAAU,WAAW,oBAAoB,KAAK,CAAC;AAC9F;AACA,SAAS,uBAAuB,UAAU;CACzC,OAAO,qBAAqB,UAAU,iBAAiB,WAAW,oBAAoB,WAAW,kBAAkB,QAAQ,CAAC,CAAC;AAC9H;AAGA,SAAS,yBAAyB,UAAU,SAAS,iBAAiB;CACrE,MAAM,eAAe,IAAI;EACxB;EACA;CACD,CAAC,CAAC,CAAC;CACH,cAAc,cAAc,gEAAgE;CAC5F,MAAM,QAAQ,UAAU,YAAY;CACpC,MAAM,MAAM,cAAc;EACzB;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,SAAS,YAAY,QAAQ,eAAe,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;CACzI,cAAc,OAAO,gEAAgE;CACrF,OAAO;EACN;EACA;EACA;EACA,KAAK;EACL;CACD;AACD;;;;;;;;;;AAUA,SAAS,aAAa,SAAS;CAC9B,MAAM,WAAW,uBAAuB,QAAQ,QAAQ;CACxD,MAAM,QAAQ,wBAAwB;EACrC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,yBAAyB,UAAU,uBAAuB;EAChE;EACA;CACD,CAAC,GAAG,MAAM,QAAQ,eAAe;AAClC"}