sqlstack 3.7.0-dev.0 → 3.7.0-dev.2

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.
@@ -2,5 +2,5 @@ export { createSqliteDb } from './sqlite';
2
2
  export { createPgDb } from './pg';
3
3
  export { createMysqlDb } from './mysql';
4
4
  export { createSqlegoDb } from './sqlego';
5
- export type { SqlegoClientLike, SqlegoTransactionLike, SqlegoTargetLike, SqlegoDbOptions } from './sqlego';
5
+ export type { SqlegoClientLike, SqlegoTransactionLike, SqlegoTargetLike, SqlegoDbOptions, SqlegoParams, SqlegoValue, } from './sqlego';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,YAAY,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,YAAY,EACV,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,WAAW,GACZ,MAAM,UAAU,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":";;;AAAA,mCAA0C;AAAjC,wGAAA,cAAc,OAAA;AACvB,2BAAkC;AAAzB,gGAAA,UAAU,OAAA;AACnB,iCAAwC;AAA/B,sGAAA,aAAa,OAAA;AACtB,mCAA0C;AAAjC,wGAAA,cAAc,OAAA","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport type { SqlegoClientLike, SqlegoTransactionLike, SqlegoTargetLike, SqlegoDbOptions } from './sqlego';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":";;;AAAA,mCAA0C;AAAjC,wGAAA,cAAc,OAAA;AACvB,2BAAkC;AAAzB,gGAAA,UAAU,OAAA;AACnB,iCAAwC;AAA/B,sGAAA,aAAa,OAAA;AACtB,mCAA0C;AAAjC,wGAAA,cAAc,OAAA","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport type {\n SqlegoClientLike,\n SqlegoTransactionLike,\n SqlegoTargetLike,\n SqlegoDbOptions,\n SqlegoParams,\n SqlegoValue,\n} from './sqlego';\n"]}
@@ -17,16 +17,29 @@ type ExecInfo = {
17
17
  changes: number;
18
18
  lastInsertRowid: number | bigint;
19
19
  };
20
- /** What both a client and a transaction expose. `statement`/`exec` arrive with protocol 3. */
20
+ /** A value sqlego binds (mirrors `@noego/sqlego`'s `SqlValue`). */
21
+ export type SqlegoValue = string | number | bigint | boolean | null | Uint8Array;
22
+ /**
23
+ * Bound parameters as sqlego accepts them (mirrors `@noego/sqlego`'s
24
+ * `SqlParams`). The client's methods take exactly this, so the interfaces
25
+ * below must too: a wider parameter type such as `unknown[]` would reject a
26
+ * real `SqlegoClient`, whose methods can't promise to accept arbitrary values.
27
+ */
28
+ export type SqlegoParams = ReadonlyArray<SqlegoValue> | Readonly<Record<string, SqlegoValue>>;
29
+ /**
30
+ * What both a client and a transaction expose. `statement`/`exec` arrive with
31
+ * protocol 3 (`@noego/sqlego` >= 0.0.3).
32
+ */
21
33
  export interface SqlegoTargetLike {
22
- query(sql: string, params?: readonly unknown[]): Promise<Row[]>;
23
- run(sql: string, params?: readonly unknown[]): Promise<RunInfo>;
24
- statement?(sql: string, params?: readonly unknown[]): Promise<StatementInfo>;
34
+ query(sql: string, params?: SqlegoParams): Promise<Row[]>;
35
+ run(sql: string, params?: SqlegoParams): Promise<RunInfo>;
36
+ statement?(sql: string, params?: SqlegoParams): Promise<StatementInfo>;
25
37
  exec?(sql: string): Promise<ExecInfo>;
26
38
  }
27
39
  /**
28
- * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses. Typed
29
- * structurally so sqlstack carries no hard dependency on sqlego.
40
+ * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses, typed
41
+ * structurally so sqlstack carries no runtime dependency on sqlego. A real
42
+ * `SqlegoClient` satisfies it as is (see tests/sqlego.types.test.ts).
30
43
  */
31
44
  export interface SqlegoClientLike extends SqlegoTargetLike {
32
45
  begin(options?: {
@@ -34,6 +47,12 @@ export interface SqlegoClientLike extends SqlegoTargetLike {
34
47
  leaseMs?: number;
35
48
  }): Promise<SqlegoTransactionLike>;
36
49
  close(): Promise<void> | void;
50
+ /** Optional for older clients/owners; capability alone does not enable it. */
51
+ readonly server?: {
52
+ readonly protocol?: number;
53
+ readonly capabilities?: readonly string[];
54
+ };
55
+ enableDetachedPlain?(): Promise<boolean>;
37
56
  }
38
57
  export interface SqlegoTransactionLike extends SqlegoTargetLike {
39
58
  commit(): Promise<void>;
@@ -50,13 +69,15 @@ export interface SqlegoDbOptions {
50
69
  /**
51
70
  * SQLite through a sqlego owner process.
52
71
  *
53
- * sqlego binds a transaction to the connection that opened it, and every
54
- * statement that connection sends while it is open runs inside it. So each
72
+ * sqlego binds a transaction to the connection that opened it; legacy sockets
73
+ * implicitly join plain statements to their own open transaction. Each
55
74
  * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens
56
75
  * a leased sqlego transaction there, its statements carry the transaction id,
57
76
  * and COMMIT/ROLLBACK end it. Statements other flows send to the shared
58
- * handle wait until it ends instead of joining it, and transactions from
59
- * different flows take turns. Savepoints pass through as SQL, so
77
+ * handle never join it. With negotiated detached-plain support they go to
78
+ * the owner immediately: reads see committed data on its reader, writes queue.
79
+ * Older owners keep the local gate. Transactions from different flows take
80
+ * turns. Savepoints pass through as SQL, so
60
81
  * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on
61
82
  * any SQLite connection.
62
83
  *
@@ -1 +1 @@
1
- {"version":3,"file":"sqlego.d.ts","sourceRoot":"","sources":["../../../src/adapters/sqlego.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAe,MAAM,aAAa,CAAC;AAIzD,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACnC,KAAK,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAAC;AACrE,qFAAqF;AACrF,KAAK,aAAa,GAAG;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,GAAG,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAAC;AACzG,+DAA+D;AAC/D,KAAK,QAAQ,GAAG;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAAC;AAE1F,8FAA8F;AAC9F,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,GAAG,EA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C,EAAE;QAAE,IAAI,CAAC,EAAE,UAAU,GAAG,WAAW,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC;IACvG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC9B,8EAA8E;IAC9E,QAAQ,CAAC,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,CAAC;IAC5F,mBAAmB,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1C;AAED,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;IAC7D,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAyDD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAsB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,gBAAgB,EAAE,OAAO,GAAE,eAAoB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmJ9H"}
@@ -66,7 +66,10 @@ function isSeveralStatementsRefusal(err) {
66
66
  const message = err?.message;
67
67
  return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);
68
68
  }
69
- async function execute(target, sql, params) {
69
+ async function execute(target, sql, rawParams) {
70
+ // sqlstack binds positional values as unknown[]; the sqlego client checks
71
+ // and encodes each value on send and rejects any it can't bind.
72
+ const params = rawParams;
70
73
  if (typeof target.statement === 'function') {
71
74
  try {
72
75
  const out = await target.statement(sql, params);
@@ -92,13 +95,15 @@ async function execute(target, sql, params) {
92
95
  /**
93
96
  * SQLite through a sqlego owner process.
94
97
  *
95
- * sqlego binds a transaction to the connection that opened it, and every
96
- * statement that connection sends while it is open runs inside it. So each
98
+ * sqlego binds a transaction to the connection that opened it; legacy sockets
99
+ * implicitly join plain statements to their own open transaction. Each
97
100
  * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens
98
101
  * a leased sqlego transaction there, its statements carry the transaction id,
99
102
  * and COMMIT/ROLLBACK end it. Statements other flows send to the shared
100
- * handle wait until it ends instead of joining it, and transactions from
101
- * different flows take turns. Savepoints pass through as SQL, so
103
+ * handle never join it. With negotiated detached-plain support they go to
104
+ * the owner immediately: reads see committed data on its reader, writes queue.
105
+ * Older owners keep the local gate. Transactions from different flows take
106
+ * turns. Savepoints pass through as SQL, so
102
107
  * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on
103
108
  * any SQLite connection.
104
109
  *
@@ -137,6 +142,19 @@ async function createSqlegoDb(fileOrClient, options = {}) {
137
142
  else {
138
143
  client = fileOrClient;
139
144
  }
145
+ // Negotiate on this socket before dropping the local plain-statement gate.
146
+ // An older client/owner (or a non-WAL file) retains the original behavior.
147
+ let detachedPlain = false;
148
+ try {
149
+ detachedPlain = client.server?.capabilities?.includes('detached-plain') === true
150
+ && typeof client.enableDetachedPlain === 'function'
151
+ && await client.enableDetachedPlain();
152
+ }
153
+ catch (error) {
154
+ if (owned)
155
+ await client.close();
156
+ throw error;
157
+ }
140
158
  // Settles when the transaction open on this client ends; null while none is
141
159
  // open. A sqlego connection holds at most one transaction at a time.
142
160
  let gate = null;
@@ -160,9 +178,9 @@ async function createSqlegoDb(fileOrClient, options = {}) {
160
178
  };
161
179
  }
162
180
  /**
163
- * One connection-like handle: statements after its own BEGIN join that
164
- * transaction; without one open, its statements wait out any other
165
- * handle's transaction.
181
+ * One connection-like handle: statements after its own BEGIN use its txId.
182
+ * Without one open, statements go directly to a negotiated owner; otherwise
183
+ * they wait out other handles' transactions in the legacy local gate.
166
184
  */
167
185
  function handle() {
168
186
  let tx;
@@ -239,10 +257,10 @@ async function createSqlegoDb(fileOrClient, options = {}) {
239
257
  try {
240
258
  if (tx)
241
259
  return await execute(tx, sql, params);
242
- // Wait out another flow's transaction, then send at once: requests
243
- // on one sqlego connection are served in order, so this statement
244
- // reaches the server before any BEGIN queued after it.
245
- while (gate)
260
+ // Legacy owners implicitly join plain statements on this socket:
261
+ // wait locally, then send without another await. Negotiated owners
262
+ // isolate plain statements themselves, including same-socket writes.
263
+ while (!detachedPlain && gate)
246
264
  await gate;
247
265
  return await execute(client, sql, params);
248
266
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sqlego.js","sourceRoot":"","sources":["../../../src/adapters/sqlego.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,wCAuIC;AAjQD,2CAA+E;AAC/E,qCAA8D;AA0C9D,6EAA6E;AAC7E,4DAA4D;AAC5D,SAAS,kBAAkB,CAAC,GAAW;IACrC,MAAM,IAAI,GAAG,IAAA,6BAAoB,EAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACrH,MAAM,KAAK,GAAG,8DAA8D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxF,IAAI,KAAK;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IACxH,IAAI,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC9E,IAAI,6BAA6B,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAA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ACjC,KAAK,CAAC,KAAK;YACT,IAAI,KAAK;gBAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAClC,CAAC;KACU,CAAC;AAChB,CAAC","sourcesContent":["import type { Database, QueryResult } from '../registry';\nimport { TransactionBusyError, TransactionExpiredError } from '../core/errors';\nimport { producesRows, stripLeadingComments } from './sqlite';\n\ntype Row = Record<string, unknown>;\ntype RunInfo = { changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `statement`: rows and changes for one statement of any kind. */\ntype StatementInfo = { reader: boolean; rows: Row[]; changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `exec`: a whole script, no parameters. */\ntype ExecInfo = { statements: number; changes: number; lastInsertRowid: number | bigint };\n\n/** What both a client and a transaction expose. `statement`/`exec` arrive with protocol 3. */\nexport interface SqlegoTargetLike {\n query(sql: string, params?: readonly unknown[]): Promise<Row[]>;\n run(sql: string, params?: readonly unknown[]): Promise<RunInfo>;\n statement?(sql: string, params?: readonly unknown[]): Promise<StatementInfo>;\n exec?(sql: string): Promise<ExecInfo>;\n}\n\n/**\n * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses. Typed\n * structurally so sqlstack carries no hard dependency on sqlego.\n */\nexport interface SqlegoClientLike extends SqlegoTargetLike {\n begin(options?: { mode?: 'deferred' | 'immediate'; leaseMs?: number }): Promise<SqlegoTransactionLike>;\n close(): Promise<void> | void;\n}\n\nexport interface SqlegoTransactionLike extends SqlegoTargetLike {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface SqlegoDbOptions {\n /**\n * Lease requested for each transaction: the server rolls it back when no\n * statement arrives for this long. The server caps it at its own lease\n * (sqlego default 10 000 ms), so it can only be shortened here.\n */\n leaseMs?: number;\n}\n\ntype Control = { kind: 'begin'; mode: 'deferred' | 'immediate' } | { kind: 'commit' } | { kind: 'rollback' };\n\n// Top-level transaction control only; `ROLLBACK TO [SAVEPOINT] x`, SAVEPOINT\n// and RELEASE are ordinary SQL inside a sqlego transaction.\nfunction transactionControl(sql: string): Control | null {\n const text = stripLeadingComments(String(sql)).trim().replace(/;\\s*$/, '').trim().toUpperCase().replace(/\\s+/g, ' ');\n const begin = /^BEGIN(?: (DEFERRED|IMMEDIATE|EXCLUSIVE))?(?: TRANSACTION)?$/.exec(text);\n if (begin) return { kind: 'begin', mode: begin[1] === undefined || begin[1] === 'DEFERRED' ? 'deferred' : 'immediate' };\n if (/^(?:COMMIT|END)(?: TRANSACTION)?$/.test(text)) return { kind: 'commit' };\n if (/^ROLLBACK(?: TRANSACTION)?$/.test(text)) return { kind: 'rollback' };\n return null;\n}\n\nfunction errorCode(err: unknown): unknown {\n return (err as { code?: unknown } | null)?.code;\n}\n\n/** sqlego's lease errors become typed sqlstack errors; anything else passes through. */\nfunction mapError(err: unknown): unknown {\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-busy') return err;\n const message = (err as { message?: unknown } | null)?.message;\n const text = typeof message === 'string' && message ? message : String(err);\n return code === 'tx-expired' ? new TransactionExpiredError(text, err) : new TransactionBusyError(text, err);\n}\n\n/** `statement` refuses text holding several statements, before running any of it. */\nfunction isSeveralStatementsRefusal(err: unknown): boolean {\n const message = (err as { message?: unknown } | null)?.message;\n return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);\n}\n\nasync function execute(target: SqlegoTargetLike, sql: string, params: unknown[]): Promise<QueryResult> {\n if (typeof target.statement === 'function') {\n try {\n const out = await target.statement(sql, params);\n if (out.reader) return out.rows;\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n } catch (err) {\n // Parameterless multi-statement text (a schema or migration script)\n // runs through `exec`, which splits it the way SQLite does.\n if (params.length > 0 || typeof target.exec !== 'function' || !isSeveralStatementsRefusal(err)) throw err;\n const out = await target.exec(sql);\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n }\n }\n // Protocol-2 clients report no column metadata: decide from the SQL text.\n if (producesRows(sql)) return await target.query(sql, params);\n const info = await target.run(sql, params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n}\n\n/**\n * SQLite through a sqlego owner process.\n *\n * sqlego binds a transaction to the connection that opened it, and every\n * statement that connection sends while it is open runs inside it. So each\n * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens\n * a leased sqlego transaction there, its statements carry the transaction id,\n * and COMMIT/ROLLBACK end it. Statements other flows send to the shared\n * handle wait until it ends instead of joining it, and transactions from\n * different flows take turns. Savepoints pass through as SQL, so\n * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on\n * any SQLite connection.\n *\n * Lease failures surface as TransactionExpiredError (`tx-expired`: the server\n * rolled the transaction back — idle past the lease, past the hard cap, or\n * the connection dropped) and TransactionBusyError (`tx-busy`: another\n * process's transaction kept this request waiting past the server's queue\n * timeout; nothing ran). A ROLLBACK of a transaction the server already\n * rolled back succeeds.\n *\n * With a protocol-3 client (`@noego/sqlego` >= 0.0.3) statements run through\n * `statement`, which tells rows from writes using SQLite's own column\n * metadata and returns 64-bit integers as `bigint` and blobs as\n * `Uint8Array`; parameterless multi-statement scripts run through `exec`.\n * Older clients fall back to `query`/`run` chosen from the SQL text.\n *\n * Pass a connected `SqlegoClient`, or a database file path (requires the\n * optional `@noego/sqlego` package).\n */\nexport async function createSqlegoDb(fileOrClient: string | SqlegoClientLike, options: SqlegoDbOptions = {}): Promise<Database> {\n let client: SqlegoClientLike;\n let owned = false;\n if (typeof fileOrClient === 'string') {\n let mod: any;\n try {\n const packageName = '@noego/sqlego';\n mod = await import(/* @vite-ignore */ packageName);\n } catch {\n throw new Error('createSqlegoDb(file) requires the @noego/sqlego package. Install it or pass a connected SqlegoClient.');\n }\n const SqlegoClient = mod.SqlegoClient ?? mod.default?.SqlegoClient;\n client = await SqlegoClient.connect(fileOrClient);\n owned = true;\n } else {\n client = fileOrClient;\n }\n\n // Settles when the transaction open on this client ends; null while none is\n // open. A sqlego connection holds at most one transaction at a time.\n let gate: Promise<void> | null = null;\n\n // Callers re-check `gate` and act in the same synchronous step after the\n // loop: an extra `await` in between would let another flow open a\n // transaction first.\n async function takeTurn(): Promise<() => void> {\n while (gate) await gate;\n let open!: () => void;\n gate = new Promise<void>((resolve) => {\n open = resolve;\n });\n let done = false;\n return () => {\n if (done) return;\n done = true;\n gate = null;\n open();\n };\n }\n\n /**\n * One connection-like handle: statements after its own BEGIN join that\n * transaction; without one open, its statements wait out any other\n * handle's transaction.\n */\n function handle(): Database {\n let tx: SqlegoTransactionLike | undefined;\n let endTurn: (() => void) | undefined;\n let failedCommit = false;\n\n const finish = () => {\n tx = undefined;\n const end = endTurn;\n endTurn = undefined;\n end?.();\n };\n\n return {\n dialect: 'sqlite',\n conn: client,\n close() {},\n async query(sql: string, params: unknown[]) {\n const control = transactionControl(sql);\n if (control?.kind === 'begin') {\n if (tx) throw new Error('cannot start a transaction within a transaction');\n const end = await takeTurn();\n try {\n tx = await client.begin({ mode: control.mode, leaseMs: options.leaseMs });\n } catch (err) {\n end();\n throw mapError(err);\n }\n endTurn = end;\n return { rowsAffected: 0 };\n }\n if (control) {\n const open = tx;\n if (!open) {\n // A failed COMMIT already ended the transaction on the server\n // (sqlego rolls it back); the caller's follow-up ROLLBACK is moot.\n if (control.kind === 'rollback' && failedCommit) {\n failedCommit = false;\n return { rowsAffected: 0 };\n }\n throw new Error(`cannot ${control.kind} - no transaction is active`);\n }\n failedCommit = false;\n try {\n if (control.kind === 'commit') {\n try {\n await open.commit();\n } catch (err) {\n failedCommit = true;\n throw err;\n }\n } else {\n try {\n await open.rollback();\n } catch (err) {\n // Already rolled back by the server (lease, cap, abort).\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-invalid') throw err;\n }\n }\n } catch (err) {\n throw mapError(err);\n } finally {\n finish();\n }\n return { rowsAffected: 0 };\n }\n try {\n if (tx) return await execute(tx, sql, params);\n // Wait out another flow's transaction, then send at once: requests\n // on one sqlego connection are served in order, so this statement\n // reaches the server before any BEGIN queued after it.\n while (gate) await gate;\n return await execute(client, sql, params);\n } catch (err) {\n throw mapError(err);\n }\n },\n } as Database;\n }\n\n const shared = handle();\n return {\n dialect: 'sqlite',\n conn: client,\n query: shared.query,\n transactionHandle: () => handle(),\n async close() {\n if (owned) await client.close();\n },\n } as Database;\n}\n"]}
1
+ {"version":3,"file":"sqlego.js","sourceRoot":"","sources":["../../../src/adapters/sqlego.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,wCAmJC;AAnSD,2CAA+E;AAC/E,qCAA8D;AA2D9D,6EAA6E;AAC7E,4DAA4D;AAC5D,SAAS,kBAAkB,CAAC,GAAW;IACrC,MAAM,IAAI,GAAG,IAAA,6BAAoB,EAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACrH,MAAM,KAAK,GAAG,8DAA8D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxF,IAAI,KAAK;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;IACxH,IAAI,mCAAmC,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC9E,IAAI,6BAA6B,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC;IAC1E,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,OAAQ,GAAiC,EAAE,IAA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AC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;gBAC5C,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACtB,CAAC;YACH,CAAC;SACU,CAAC;IAChB,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;IACxB,OAAO;QACL,OAAO,EAAE,QAAQ;QACjB,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,iBAAiB,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE;QACjC,KAAK,CAAC,KAAK;YACT,IAAI,KAAK;gBAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAClC,CAAC;KACU,CAAC;AAChB,CAAC","sourcesContent":["import type { Database, QueryResult } from '../registry';\nimport { TransactionBusyError, TransactionExpiredError } from '../core/errors';\nimport { producesRows, stripLeadingComments } from './sqlite';\n\ntype Row = Record<string, unknown>;\ntype RunInfo = { changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `statement`: rows and changes for one statement of any kind. */\ntype StatementInfo = { reader: boolean; rows: Row[]; changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `exec`: a whole script, no parameters. */\ntype ExecInfo = { statements: number; changes: number; lastInsertRowid: number | bigint };\n\n/** A value sqlego binds (mirrors `@noego/sqlego`'s `SqlValue`). */\nexport type SqlegoValue = string | number | bigint | boolean | null | Uint8Array;\n/**\n * Bound parameters as sqlego accepts them (mirrors `@noego/sqlego`'s\n * `SqlParams`). The client's methods take exactly this, so the interfaces\n * below must too: a wider parameter type such as `unknown[]` would reject a\n * real `SqlegoClient`, whose methods can't promise to accept arbitrary values.\n */\nexport type SqlegoParams = ReadonlyArray<SqlegoValue> | Readonly<Record<string, SqlegoValue>>;\n\n/**\n * What both a client and a transaction expose. `statement`/`exec` arrive with\n * protocol 3 (`@noego/sqlego` >= 0.0.3).\n */\nexport interface SqlegoTargetLike {\n query(sql: string, params?: SqlegoParams): Promise<Row[]>;\n run(sql: string, params?: SqlegoParams): Promise<RunInfo>;\n statement?(sql: string, params?: SqlegoParams): Promise<StatementInfo>;\n exec?(sql: string): Promise<ExecInfo>;\n}\n\n/**\n * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses, typed\n * structurally so sqlstack carries no runtime dependency on sqlego. A real\n * `SqlegoClient` satisfies it as is (see tests/sqlego.types.test.ts).\n */\nexport interface SqlegoClientLike extends SqlegoTargetLike {\n begin(options?: { mode?: 'deferred' | 'immediate'; leaseMs?: number }): Promise<SqlegoTransactionLike>;\n close(): Promise<void> | void;\n /** Optional for older clients/owners; capability alone does not enable it. */\n readonly server?: { readonly protocol?: number; readonly capabilities?: readonly string[] };\n enableDetachedPlain?(): Promise<boolean>;\n}\n\nexport interface SqlegoTransactionLike extends SqlegoTargetLike {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface SqlegoDbOptions {\n /**\n * Lease requested for each transaction: the server rolls it back when no\n * statement arrives for this long. The server caps it at its own lease\n * (sqlego default 10 000 ms), so it can only be shortened here.\n */\n leaseMs?: number;\n}\n\ntype Control = { kind: 'begin'; mode: 'deferred' | 'immediate' } | { kind: 'commit' } | { kind: 'rollback' };\n\n// Top-level transaction control only; `ROLLBACK TO [SAVEPOINT] x`, SAVEPOINT\n// and RELEASE are ordinary SQL inside a sqlego transaction.\nfunction transactionControl(sql: string): Control | null {\n const text = stripLeadingComments(String(sql)).trim().replace(/;\\s*$/, '').trim().toUpperCase().replace(/\\s+/g, ' ');\n const begin = /^BEGIN(?: (DEFERRED|IMMEDIATE|EXCLUSIVE))?(?: TRANSACTION)?$/.exec(text);\n if (begin) return { kind: 'begin', mode: begin[1] === undefined || begin[1] === 'DEFERRED' ? 'deferred' : 'immediate' };\n if (/^(?:COMMIT|END)(?: TRANSACTION)?$/.test(text)) return { kind: 'commit' };\n if (/^ROLLBACK(?: TRANSACTION)?$/.test(text)) return { kind: 'rollback' };\n return null;\n}\n\nfunction errorCode(err: unknown): unknown {\n return (err as { code?: unknown } | null)?.code;\n}\n\n/** sqlego's lease errors become typed sqlstack errors; anything else passes through. */\nfunction mapError(err: unknown): unknown {\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-busy') return err;\n const message = (err as { message?: unknown } | null)?.message;\n const text = typeof message === 'string' && message ? message : String(err);\n return code === 'tx-expired' ? new TransactionExpiredError(text, err) : new TransactionBusyError(text, err);\n}\n\n/** `statement` refuses text holding several statements, before running any of it. */\nfunction isSeveralStatementsRefusal(err: unknown): boolean {\n const message = (err as { message?: unknown } | null)?.message;\n return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);\n}\n\nasync function execute(target: SqlegoTargetLike, sql: string, rawParams: unknown[]): Promise<QueryResult> {\n // sqlstack binds positional values as unknown[]; the sqlego client checks\n // and encodes each value on send and rejects any it can't bind.\n const params = rawParams as ReadonlyArray<SqlegoValue>;\n if (typeof target.statement === 'function') {\n try {\n const out = await target.statement(sql, params);\n if (out.reader) return out.rows;\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n } catch (err) {\n // Parameterless multi-statement text (a schema or migration script)\n // runs through `exec`, which splits it the way SQLite does.\n if (params.length > 0 || typeof target.exec !== 'function' || !isSeveralStatementsRefusal(err)) throw err;\n const out = await target.exec(sql);\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n }\n }\n // Protocol-2 clients report no column metadata: decide from the SQL text.\n if (producesRows(sql)) return await target.query(sql, params);\n const info = await target.run(sql, params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n}\n\n/**\n * SQLite through a sqlego owner process.\n *\n * sqlego binds a transaction to the connection that opened it; legacy sockets\n * implicitly join plain statements to their own open transaction. Each\n * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens\n * a leased sqlego transaction there, its statements carry the transaction id,\n * and COMMIT/ROLLBACK end it. Statements other flows send to the shared\n * handle never join it. With negotiated detached-plain support they go to\n * the owner immediately: reads see committed data on its reader, writes queue.\n * Older owners keep the local gate. Transactions from different flows take\n * turns. Savepoints pass through as SQL, so\n * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on\n * any SQLite connection.\n *\n * Lease failures surface as TransactionExpiredError (`tx-expired`: the server\n * rolled the transaction back — idle past the lease, past the hard cap, or\n * the connection dropped) and TransactionBusyError (`tx-busy`: another\n * process's transaction kept this request waiting past the server's queue\n * timeout; nothing ran). A ROLLBACK of a transaction the server already\n * rolled back succeeds.\n *\n * With a protocol-3 client (`@noego/sqlego` >= 0.0.3) statements run through\n * `statement`, which tells rows from writes using SQLite's own column\n * metadata and returns 64-bit integers as `bigint` and blobs as\n * `Uint8Array`; parameterless multi-statement scripts run through `exec`.\n * Older clients fall back to `query`/`run` chosen from the SQL text.\n *\n * Pass a connected `SqlegoClient`, or a database file path (requires the\n * optional `@noego/sqlego` package).\n */\nexport async function createSqlegoDb(fileOrClient: string | SqlegoClientLike, options: SqlegoDbOptions = {}): Promise<Database> {\n let client: SqlegoClientLike;\n let owned = false;\n if (typeof fileOrClient === 'string') {\n let mod: any;\n try {\n const packageName = '@noego/sqlego';\n mod = await import(/* @vite-ignore */ packageName);\n } catch {\n throw new Error('createSqlegoDb(file) requires the @noego/sqlego package. Install it or pass a connected SqlegoClient.');\n }\n const SqlegoClient = mod.SqlegoClient ?? mod.default?.SqlegoClient;\n client = await SqlegoClient.connect(fileOrClient);\n owned = true;\n } else {\n client = fileOrClient;\n }\n\n // Negotiate on this socket before dropping the local plain-statement gate.\n // An older client/owner (or a non-WAL file) retains the original behavior.\n let detachedPlain = false;\n try {\n detachedPlain = client.server?.capabilities?.includes('detached-plain') === true\n && typeof client.enableDetachedPlain === 'function'\n && await client.enableDetachedPlain();\n } catch (error) {\n if (owned) await client.close();\n throw error;\n }\n\n // Settles when the transaction open on this client ends; null while none is\n // open. A sqlego connection holds at most one transaction at a time.\n let gate: Promise<void> | null = null;\n\n // Callers re-check `gate` and act in the same synchronous step after the\n // loop: an extra `await` in between would let another flow open a\n // transaction first.\n async function takeTurn(): Promise<() => void> {\n while (gate) await gate;\n let open!: () => void;\n gate = new Promise<void>((resolve) => {\n open = resolve;\n });\n let done = false;\n return () => {\n if (done) return;\n done = true;\n gate = null;\n open();\n };\n }\n\n /**\n * One connection-like handle: statements after its own BEGIN use its txId.\n * Without one open, statements go directly to a negotiated owner; otherwise\n * they wait out other handles' transactions in the legacy local gate.\n */\n function handle(): Database {\n let tx: SqlegoTransactionLike | undefined;\n let endTurn: (() => void) | undefined;\n let failedCommit = false;\n\n const finish = () => {\n tx = undefined;\n const end = endTurn;\n endTurn = undefined;\n end?.();\n };\n\n return {\n dialect: 'sqlite',\n conn: client,\n close() {},\n async query(sql: string, params: unknown[]) {\n const control = transactionControl(sql);\n if (control?.kind === 'begin') {\n if (tx) throw new Error('cannot start a transaction within a transaction');\n const end = await takeTurn();\n try {\n tx = await client.begin({ mode: control.mode, leaseMs: options.leaseMs });\n } catch (err) {\n end();\n throw mapError(err);\n }\n endTurn = end;\n return { rowsAffected: 0 };\n }\n if (control) {\n const open = tx;\n if (!open) {\n // A failed COMMIT already ended the transaction on the server\n // (sqlego rolls it back); the caller's follow-up ROLLBACK is moot.\n if (control.kind === 'rollback' && failedCommit) {\n failedCommit = false;\n return { rowsAffected: 0 };\n }\n throw new Error(`cannot ${control.kind} - no transaction is active`);\n }\n failedCommit = false;\n try {\n if (control.kind === 'commit') {\n try {\n await open.commit();\n } catch (err) {\n failedCommit = true;\n throw err;\n }\n } else {\n try {\n await open.rollback();\n } catch (err) {\n // Already rolled back by the server (lease, cap, abort).\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-invalid') throw err;\n }\n }\n } catch (err) {\n throw mapError(err);\n } finally {\n finish();\n }\n return { rowsAffected: 0 };\n }\n try {\n if (tx) return await execute(tx, sql, params);\n // Legacy owners implicitly join plain statements on this socket:\n // wait locally, then send without another await. Negotiated owners\n // isolate plain statements themselves, including same-socket writes.\n while (!detachedPlain && gate) await gate;\n return await execute(client, sql, params);\n } catch (err) {\n throw mapError(err);\n }\n },\n } as Database;\n }\n\n const shared = handle();\n return {\n dialect: 'sqlite',\n conn: client,\n query: shared.query,\n transactionHandle: () => handle(),\n async close() {\n if (owned) await client.close();\n },\n } as Database;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport type { SqlegoClientLike, SqlegoTransactionLike, SqlegoTargetLike, SqlegoDbOptions } from './sqlego';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport type {\n SqlegoClientLike,\n SqlegoTransactionLike,\n SqlegoTargetLike,\n SqlegoDbOptions,\n SqlegoParams,\n SqlegoValue,\n} from './sqlego';\n"]}
@@ -30,7 +30,10 @@ function isSeveralStatementsRefusal(err) {
30
30
  const message = err?.message;
31
31
  return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);
32
32
  }
33
- async function execute(target, sql, params) {
33
+ async function execute(target, sql, rawParams) {
34
+ // sqlstack binds positional values as unknown[]; the sqlego client checks
35
+ // and encodes each value on send and rejects any it can't bind.
36
+ const params = rawParams;
34
37
  if (typeof target.statement === 'function') {
35
38
  try {
36
39
  const out = await target.statement(sql, params);
@@ -56,13 +59,15 @@ async function execute(target, sql, params) {
56
59
  /**
57
60
  * SQLite through a sqlego owner process.
58
61
  *
59
- * sqlego binds a transaction to the connection that opened it, and every
60
- * statement that connection sends while it is open runs inside it. So each
62
+ * sqlego binds a transaction to the connection that opened it; legacy sockets
63
+ * implicitly join plain statements to their own open transaction. Each
61
64
  * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens
62
65
  * a leased sqlego transaction there, its statements carry the transaction id,
63
66
  * and COMMIT/ROLLBACK end it. Statements other flows send to the shared
64
- * handle wait until it ends instead of joining it, and transactions from
65
- * different flows take turns. Savepoints pass through as SQL, so
67
+ * handle never join it. With negotiated detached-plain support they go to
68
+ * the owner immediately: reads see committed data on its reader, writes queue.
69
+ * Older owners keep the local gate. Transactions from different flows take
70
+ * turns. Savepoints pass through as SQL, so
66
71
  * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on
67
72
  * any SQLite connection.
68
73
  *
@@ -101,6 +106,19 @@ export async function createSqlegoDb(fileOrClient, options = {}) {
101
106
  else {
102
107
  client = fileOrClient;
103
108
  }
109
+ // Negotiate on this socket before dropping the local plain-statement gate.
110
+ // An older client/owner (or a non-WAL file) retains the original behavior.
111
+ let detachedPlain = false;
112
+ try {
113
+ detachedPlain = client.server?.capabilities?.includes('detached-plain') === true
114
+ && typeof client.enableDetachedPlain === 'function'
115
+ && await client.enableDetachedPlain();
116
+ }
117
+ catch (error) {
118
+ if (owned)
119
+ await client.close();
120
+ throw error;
121
+ }
104
122
  // Settles when the transaction open on this client ends; null while none is
105
123
  // open. A sqlego connection holds at most one transaction at a time.
106
124
  let gate = null;
@@ -124,9 +142,9 @@ export async function createSqlegoDb(fileOrClient, options = {}) {
124
142
  };
125
143
  }
126
144
  /**
127
- * One connection-like handle: statements after its own BEGIN join that
128
- * transaction; without one open, its statements wait out any other
129
- * handle's transaction.
145
+ * One connection-like handle: statements after its own BEGIN use its txId.
146
+ * Without one open, statements go directly to a negotiated owner; otherwise
147
+ * they wait out other handles' transactions in the legacy local gate.
130
148
  */
131
149
  function handle() {
132
150
  let tx;
@@ -203,10 +221,10 @@ export async function createSqlegoDb(fileOrClient, options = {}) {
203
221
  try {
204
222
  if (tx)
205
223
  return await execute(tx, sql, params);
206
- // Wait out another flow's transaction, then send at once: requests
207
- // on one sqlego connection are served in order, so this statement
208
- // reaches the server before any BEGIN queued after it.
209
- while (gate)
224
+ // Legacy owners implicitly join plain statements on this socket:
225
+ // wait locally, then send without another await. Negotiated owners
226
+ // isolate plain statements themselves, including same-socket writes.
227
+ while (!detachedPlain && gate)
210
228
  await gate;
211
229
  return await execute(client, sql, params);
212
230
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sqlego.js","sourceRoot":"","sources":["../../../src/adapters/sqlego.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AA0C9D,6EAA6E;AAC7E,4DAA4D;AAC5D,SAAS,kBAAkB,CAAC,GAAW;IACrC,MAAM,IAAI,GAAG,oBAAoB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACrH,MAAM,KAAK,GAAG,8DAA8D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxF,IAAI,KAAK;QAAE,OAAO,EAA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AAO,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;gBAC5C,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACtB,CAAC;YACH,CAAC;SACU,CAAC;IAChB,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;IACxB,OAAO;QACL,OAAO,EAAE,QAAQ;QACjB,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,iBAAiB,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE;QACjC,KAAK,CAAC,KAAK;YACT,IAAI,KAAK;gBAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAClC,CAAC;KACU,CAAC;AAChB,CAAC","sourcesContent":["import type { Database, QueryResult } from '../registry';\nimport { TransactionBusyError, TransactionExpiredError } from '../core/errors';\nimport { producesRows, stripLeadingComments } from './sqlite';\n\ntype Row = Record<string, unknown>;\ntype RunInfo = { changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `statement`: rows and changes for one statement of any kind. */\ntype StatementInfo = { reader: boolean; rows: Row[]; changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `exec`: a whole script, no parameters. */\ntype ExecInfo = { statements: number; changes: number; lastInsertRowid: number | bigint };\n\n/** What both a client and a transaction expose. `statement`/`exec` arrive with protocol 3. */\nexport interface SqlegoTargetLike {\n query(sql: string, params?: readonly unknown[]): Promise<Row[]>;\n run(sql: string, params?: readonly unknown[]): Promise<RunInfo>;\n statement?(sql: string, params?: readonly unknown[]): Promise<StatementInfo>;\n exec?(sql: string): Promise<ExecInfo>;\n}\n\n/**\n * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses. Typed\n * structurally so sqlstack carries no hard dependency on sqlego.\n */\nexport interface SqlegoClientLike extends SqlegoTargetLike {\n begin(options?: { mode?: 'deferred' | 'immediate'; leaseMs?: number }): Promise<SqlegoTransactionLike>;\n close(): Promise<void> | void;\n}\n\nexport interface SqlegoTransactionLike extends SqlegoTargetLike {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface SqlegoDbOptions {\n /**\n * Lease requested for each transaction: the server rolls it back when no\n * statement arrives for this long. The server caps it at its own lease\n * (sqlego default 10 000 ms), so it can only be shortened here.\n */\n leaseMs?: number;\n}\n\ntype Control = { kind: 'begin'; mode: 'deferred' | 'immediate' } | { kind: 'commit' } | { kind: 'rollback' };\n\n// Top-level transaction control only; `ROLLBACK TO [SAVEPOINT] x`, SAVEPOINT\n// and RELEASE are ordinary SQL inside a sqlego transaction.\nfunction transactionControl(sql: string): Control | null {\n const text = stripLeadingComments(String(sql)).trim().replace(/;\\s*$/, '').trim().toUpperCase().replace(/\\s+/g, ' ');\n const begin = /^BEGIN(?: (DEFERRED|IMMEDIATE|EXCLUSIVE))?(?: TRANSACTION)?$/.exec(text);\n if (begin) return { kind: 'begin', mode: begin[1] === undefined || begin[1] === 'DEFERRED' ? 'deferred' : 'immediate' };\n if (/^(?:COMMIT|END)(?: TRANSACTION)?$/.test(text)) return { kind: 'commit' };\n if (/^ROLLBACK(?: TRANSACTION)?$/.test(text)) return { kind: 'rollback' };\n return null;\n}\n\nfunction errorCode(err: unknown): unknown {\n return (err as { code?: unknown } | null)?.code;\n}\n\n/** sqlego's lease errors become typed sqlstack errors; anything else passes through. */\nfunction mapError(err: unknown): unknown {\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-busy') return err;\n const message = (err as { message?: unknown } | null)?.message;\n const text = typeof message === 'string' && message ? message : String(err);\n return code === 'tx-expired' ? new TransactionExpiredError(text, err) : new TransactionBusyError(text, err);\n}\n\n/** `statement` refuses text holding several statements, before running any of it. */\nfunction isSeveralStatementsRefusal(err: unknown): boolean {\n const message = (err as { message?: unknown } | null)?.message;\n return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);\n}\n\nasync function execute(target: SqlegoTargetLike, sql: string, params: unknown[]): Promise<QueryResult> {\n if (typeof target.statement === 'function') {\n try {\n const out = await target.statement(sql, params);\n if (out.reader) return out.rows;\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n } catch (err) {\n // Parameterless multi-statement text (a schema or migration script)\n // runs through `exec`, which splits it the way SQLite does.\n if (params.length > 0 || typeof target.exec !== 'function' || !isSeveralStatementsRefusal(err)) throw err;\n const out = await target.exec(sql);\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n }\n }\n // Protocol-2 clients report no column metadata: decide from the SQL text.\n if (producesRows(sql)) return await target.query(sql, params);\n const info = await target.run(sql, params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n}\n\n/**\n * SQLite through a sqlego owner process.\n *\n * sqlego binds a transaction to the connection that opened it, and every\n * statement that connection sends while it is open runs inside it. So each\n * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens\n * a leased sqlego transaction there, its statements carry the transaction id,\n * and COMMIT/ROLLBACK end it. Statements other flows send to the shared\n * handle wait until it ends instead of joining it, and transactions from\n * different flows take turns. Savepoints pass through as SQL, so\n * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on\n * any SQLite connection.\n *\n * Lease failures surface as TransactionExpiredError (`tx-expired`: the server\n * rolled the transaction back — idle past the lease, past the hard cap, or\n * the connection dropped) and TransactionBusyError (`tx-busy`: another\n * process's transaction kept this request waiting past the server's queue\n * timeout; nothing ran). A ROLLBACK of a transaction the server already\n * rolled back succeeds.\n *\n * With a protocol-3 client (`@noego/sqlego` >= 0.0.3) statements run through\n * `statement`, which tells rows from writes using SQLite's own column\n * metadata and returns 64-bit integers as `bigint` and blobs as\n * `Uint8Array`; parameterless multi-statement scripts run through `exec`.\n * Older clients fall back to `query`/`run` chosen from the SQL text.\n *\n * Pass a connected `SqlegoClient`, or a database file path (requires the\n * optional `@noego/sqlego` package).\n */\nexport async function createSqlegoDb(fileOrClient: string | SqlegoClientLike, options: SqlegoDbOptions = {}): Promise<Database> {\n let client: SqlegoClientLike;\n let owned = false;\n if (typeof fileOrClient === 'string') {\n let mod: any;\n try {\n const packageName = '@noego/sqlego';\n mod = await import(/* @vite-ignore */ packageName);\n } catch {\n throw new Error('createSqlegoDb(file) requires the @noego/sqlego package. Install it or pass a connected SqlegoClient.');\n }\n const SqlegoClient = mod.SqlegoClient ?? mod.default?.SqlegoClient;\n client = await SqlegoClient.connect(fileOrClient);\n owned = true;\n } else {\n client = fileOrClient;\n }\n\n // Settles when the transaction open on this client ends; null while none is\n // open. A sqlego connection holds at most one transaction at a time.\n let gate: Promise<void> | null = null;\n\n // Callers re-check `gate` and act in the same synchronous step after the\n // loop: an extra `await` in between would let another flow open a\n // transaction first.\n async function takeTurn(): Promise<() => void> {\n while (gate) await gate;\n let open!: () => void;\n gate = new Promise<void>((resolve) => {\n open = resolve;\n });\n let done = false;\n return () => {\n if (done) return;\n done = true;\n gate = null;\n open();\n };\n }\n\n /**\n * One connection-like handle: statements after its own BEGIN join that\n * transaction; without one open, its statements wait out any other\n * handle's transaction.\n */\n function handle(): Database {\n let tx: SqlegoTransactionLike | undefined;\n let endTurn: (() => void) | undefined;\n let failedCommit = false;\n\n const finish = () => {\n tx = undefined;\n const end = endTurn;\n endTurn = undefined;\n end?.();\n };\n\n return {\n dialect: 'sqlite',\n conn: client,\n close() {},\n async query(sql: string, params: unknown[]) {\n const control = transactionControl(sql);\n if (control?.kind === 'begin') {\n if (tx) throw new Error('cannot start a transaction within a transaction');\n const end = await takeTurn();\n try {\n tx = await client.begin({ mode: control.mode, leaseMs: options.leaseMs });\n } catch (err) {\n end();\n throw mapError(err);\n }\n endTurn = end;\n return { rowsAffected: 0 };\n }\n if (control) {\n const open = tx;\n if (!open) {\n // A failed COMMIT already ended the transaction on the server\n // (sqlego rolls it back); the caller's follow-up ROLLBACK is moot.\n if (control.kind === 'rollback' && failedCommit) {\n failedCommit = false;\n return { rowsAffected: 0 };\n }\n throw new Error(`cannot ${control.kind} - no transaction is active`);\n }\n failedCommit = false;\n try {\n if (control.kind === 'commit') {\n try {\n await open.commit();\n } catch (err) {\n failedCommit = true;\n throw err;\n }\n } else {\n try {\n await open.rollback();\n } catch (err) {\n // Already rolled back by the server (lease, cap, abort).\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-invalid') throw err;\n }\n }\n } catch (err) {\n throw mapError(err);\n } finally {\n finish();\n }\n return { rowsAffected: 0 };\n }\n try {\n if (tx) return await execute(tx, sql, params);\n // Wait out another flow's transaction, then send at once: requests\n // on one sqlego connection are served in order, so this statement\n // reaches the server before any BEGIN queued after it.\n while (gate) await gate;\n return await execute(client, sql, params);\n } catch (err) {\n throw mapError(err);\n }\n },\n } as Database;\n }\n\n const shared = handle();\n return {\n dialect: 'sqlite',\n conn: client,\n query: shared.query,\n transactionHandle: () => handle(),\n async close() {\n if (owned) await client.close();\n },\n } as Database;\n}\n"]}
1
+ {"version":3,"file":"sqlego.js","sourceRoot":"","sources":["../../../src/adapters/sqlego.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AA2D9D,6EAA6E;AAC7E,4DAA4D;AAC5D,SAAS,kBAAkB,CAAC,GAAW;IACrC,MAAM,IAAI,GAAG,oBAAoB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACrH,MAAM,KAAK,GAAG,8DAA8D,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxF,IAAI,KAAK;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CA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OAAO,GAAG,EAAE,CAAC;wBACb,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC;oBACtB,CAAC;4BAAS,CAAC;wBACT,MAAM,EAAE,CAAC;oBACX,CAAC;oBACD,OAAO,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;gBAC7B,CAAC;gBACD,IAAI,CAAC;oBACH,IAAI,EAAE;wBAAE,OAAO,MAAM,OAAO,CAAC,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;oBAC9C,iEAAiE;oBACjE,mEAAmE;oBACnE,qEAAqE;oBACrE,OAAO,CAAC,aAAa,IAAI,IAAI;wBAAE,MAAM,IAAI,CAAC;oBAC1C,OAAO,MAAM,OAAO,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;gBAC5C,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACtB,CAAC;YACH,CAAC;SACU,CAAC;IAChB,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC;IACxB,OAAO;QACL,OAAO,EAAE,QAAQ;QACjB,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,iBAAiB,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE;QACjC,KAAK,CAAC,KAAK;YACT,IAAI,KAAK;gBAAE,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QAClC,CAAC;KACU,CAAC;AAChB,CAAC","sourcesContent":["import type { Database, QueryResult } from '../registry';\nimport { TransactionBusyError, TransactionExpiredError } from '../core/errors';\nimport { producesRows, stripLeadingComments } from './sqlite';\n\ntype Row = Record<string, unknown>;\ntype RunInfo = { changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `statement`: rows and changes for one statement of any kind. */\ntype StatementInfo = { reader: boolean; rows: Row[]; changes: number; lastInsertRowid: number | bigint };\n/** sqlego protocol 3 `exec`: a whole script, no parameters. */\ntype ExecInfo = { statements: number; changes: number; lastInsertRowid: number | bigint };\n\n/** A value sqlego binds (mirrors `@noego/sqlego`'s `SqlValue`). */\nexport type SqlegoValue = string | number | bigint | boolean | null | Uint8Array;\n/**\n * Bound parameters as sqlego accepts them (mirrors `@noego/sqlego`'s\n * `SqlParams`). The client's methods take exactly this, so the interfaces\n * below must too: a wider parameter type such as `unknown[]` would reject a\n * real `SqlegoClient`, whose methods can't promise to accept arbitrary values.\n */\nexport type SqlegoParams = ReadonlyArray<SqlegoValue> | Readonly<Record<string, SqlegoValue>>;\n\n/**\n * What both a client and a transaction expose. `statement`/`exec` arrive with\n * protocol 3 (`@noego/sqlego` >= 0.0.3).\n */\nexport interface SqlegoTargetLike {\n query(sql: string, params?: SqlegoParams): Promise<Row[]>;\n run(sql: string, params?: SqlegoParams): Promise<RunInfo>;\n statement?(sql: string, params?: SqlegoParams): Promise<StatementInfo>;\n exec?(sql: string): Promise<ExecInfo>;\n}\n\n/**\n * The subset of `@noego/sqlego`'s `SqlegoClient` this adapter uses, typed\n * structurally so sqlstack carries no runtime dependency on sqlego. A real\n * `SqlegoClient` satisfies it as is (see tests/sqlego.types.test.ts).\n */\nexport interface SqlegoClientLike extends SqlegoTargetLike {\n begin(options?: { mode?: 'deferred' | 'immediate'; leaseMs?: number }): Promise<SqlegoTransactionLike>;\n close(): Promise<void> | void;\n /** Optional for older clients/owners; capability alone does not enable it. */\n readonly server?: { readonly protocol?: number; readonly capabilities?: readonly string[] };\n enableDetachedPlain?(): Promise<boolean>;\n}\n\nexport interface SqlegoTransactionLike extends SqlegoTargetLike {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface SqlegoDbOptions {\n /**\n * Lease requested for each transaction: the server rolls it back when no\n * statement arrives for this long. The server caps it at its own lease\n * (sqlego default 10 000 ms), so it can only be shortened here.\n */\n leaseMs?: number;\n}\n\ntype Control = { kind: 'begin'; mode: 'deferred' | 'immediate' } | { kind: 'commit' } | { kind: 'rollback' };\n\n// Top-level transaction control only; `ROLLBACK TO [SAVEPOINT] x`, SAVEPOINT\n// and RELEASE are ordinary SQL inside a sqlego transaction.\nfunction transactionControl(sql: string): Control | null {\n const text = stripLeadingComments(String(sql)).trim().replace(/;\\s*$/, '').trim().toUpperCase().replace(/\\s+/g, ' ');\n const begin = /^BEGIN(?: (DEFERRED|IMMEDIATE|EXCLUSIVE))?(?: TRANSACTION)?$/.exec(text);\n if (begin) return { kind: 'begin', mode: begin[1] === undefined || begin[1] === 'DEFERRED' ? 'deferred' : 'immediate' };\n if (/^(?:COMMIT|END)(?: TRANSACTION)?$/.test(text)) return { kind: 'commit' };\n if (/^ROLLBACK(?: TRANSACTION)?$/.test(text)) return { kind: 'rollback' };\n return null;\n}\n\nfunction errorCode(err: unknown): unknown {\n return (err as { code?: unknown } | null)?.code;\n}\n\n/** sqlego's lease errors become typed sqlstack errors; anything else passes through. */\nfunction mapError(err: unknown): unknown {\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-busy') return err;\n const message = (err as { message?: unknown } | null)?.message;\n const text = typeof message === 'string' && message ? message : String(err);\n return code === 'tx-expired' ? new TransactionExpiredError(text, err) : new TransactionBusyError(text, err);\n}\n\n/** `statement` refuses text holding several statements, before running any of it. */\nfunction isSeveralStatementsRefusal(err: unknown): boolean {\n const message = (err as { message?: unknown } | null)?.message;\n return errorCode(err) === 'bad-request' && typeof message === 'string' && /use exec for several/.test(message);\n}\n\nasync function execute(target: SqlegoTargetLike, sql: string, rawParams: unknown[]): Promise<QueryResult> {\n // sqlstack binds positional values as unknown[]; the sqlego client checks\n // and encodes each value on send and rejects any it can't bind.\n const params = rawParams as ReadonlyArray<SqlegoValue>;\n if (typeof target.statement === 'function') {\n try {\n const out = await target.statement(sql, params);\n if (out.reader) return out.rows;\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n } catch (err) {\n // Parameterless multi-statement text (a schema or migration script)\n // runs through `exec`, which splits it the way SQLite does.\n if (params.length > 0 || typeof target.exec !== 'function' || !isSeveralStatementsRefusal(err)) throw err;\n const out = await target.exec(sql);\n return { rowsAffected: Number(out.changes ?? 0), lastInsertId: out.lastInsertRowid };\n }\n }\n // Protocol-2 clients report no column metadata: decide from the SQL text.\n if (producesRows(sql)) return await target.query(sql, params);\n const info = await target.run(sql, params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n}\n\n/**\n * SQLite through a sqlego owner process.\n *\n * sqlego binds a transaction to the connection that opened it; legacy sockets\n * implicitly join plain statements to their own open transaction. Each\n * sqlstack transaction gets its own handle (`transactionHandle`): BEGIN opens\n * a leased sqlego transaction there, its statements carry the transaction id,\n * and COMMIT/ROLLBACK end it. Statements other flows send to the shared\n * handle never join it. With negotiated detached-plain support they go to\n * the owner immediately: reads see committed data on its reader, writes queue.\n * Older owners keep the local gate. Transactions from different flows take\n * turns. Savepoints pass through as SQL, so\n * `@transaction`, nested scopes, `rollback()` and `afterCommit` work as on\n * any SQLite connection.\n *\n * Lease failures surface as TransactionExpiredError (`tx-expired`: the server\n * rolled the transaction back — idle past the lease, past the hard cap, or\n * the connection dropped) and TransactionBusyError (`tx-busy`: another\n * process's transaction kept this request waiting past the server's queue\n * timeout; nothing ran). A ROLLBACK of a transaction the server already\n * rolled back succeeds.\n *\n * With a protocol-3 client (`@noego/sqlego` >= 0.0.3) statements run through\n * `statement`, which tells rows from writes using SQLite's own column\n * metadata and returns 64-bit integers as `bigint` and blobs as\n * `Uint8Array`; parameterless multi-statement scripts run through `exec`.\n * Older clients fall back to `query`/`run` chosen from the SQL text.\n *\n * Pass a connected `SqlegoClient`, or a database file path (requires the\n * optional `@noego/sqlego` package).\n */\nexport async function createSqlegoDb(fileOrClient: string | SqlegoClientLike, options: SqlegoDbOptions = {}): Promise<Database> {\n let client: SqlegoClientLike;\n let owned = false;\n if (typeof fileOrClient === 'string') {\n let mod: any;\n try {\n const packageName = '@noego/sqlego';\n mod = await import(/* @vite-ignore */ packageName);\n } catch {\n throw new Error('createSqlegoDb(file) requires the @noego/sqlego package. Install it or pass a connected SqlegoClient.');\n }\n const SqlegoClient = mod.SqlegoClient ?? mod.default?.SqlegoClient;\n client = await SqlegoClient.connect(fileOrClient);\n owned = true;\n } else {\n client = fileOrClient;\n }\n\n // Negotiate on this socket before dropping the local plain-statement gate.\n // An older client/owner (or a non-WAL file) retains the original behavior.\n let detachedPlain = false;\n try {\n detachedPlain = client.server?.capabilities?.includes('detached-plain') === true\n && typeof client.enableDetachedPlain === 'function'\n && await client.enableDetachedPlain();\n } catch (error) {\n if (owned) await client.close();\n throw error;\n }\n\n // Settles when the transaction open on this client ends; null while none is\n // open. A sqlego connection holds at most one transaction at a time.\n let gate: Promise<void> | null = null;\n\n // Callers re-check `gate` and act in the same synchronous step after the\n // loop: an extra `await` in between would let another flow open a\n // transaction first.\n async function takeTurn(): Promise<() => void> {\n while (gate) await gate;\n let open!: () => void;\n gate = new Promise<void>((resolve) => {\n open = resolve;\n });\n let done = false;\n return () => {\n if (done) return;\n done = true;\n gate = null;\n open();\n };\n }\n\n /**\n * One connection-like handle: statements after its own BEGIN use its txId.\n * Without one open, statements go directly to a negotiated owner; otherwise\n * they wait out other handles' transactions in the legacy local gate.\n */\n function handle(): Database {\n let tx: SqlegoTransactionLike | undefined;\n let endTurn: (() => void) | undefined;\n let failedCommit = false;\n\n const finish = () => {\n tx = undefined;\n const end = endTurn;\n endTurn = undefined;\n end?.();\n };\n\n return {\n dialect: 'sqlite',\n conn: client,\n close() {},\n async query(sql: string, params: unknown[]) {\n const control = transactionControl(sql);\n if (control?.kind === 'begin') {\n if (tx) throw new Error('cannot start a transaction within a transaction');\n const end = await takeTurn();\n try {\n tx = await client.begin({ mode: control.mode, leaseMs: options.leaseMs });\n } catch (err) {\n end();\n throw mapError(err);\n }\n endTurn = end;\n return { rowsAffected: 0 };\n }\n if (control) {\n const open = tx;\n if (!open) {\n // A failed COMMIT already ended the transaction on the server\n // (sqlego rolls it back); the caller's follow-up ROLLBACK is moot.\n if (control.kind === 'rollback' && failedCommit) {\n failedCommit = false;\n return { rowsAffected: 0 };\n }\n throw new Error(`cannot ${control.kind} - no transaction is active`);\n }\n failedCommit = false;\n try {\n if (control.kind === 'commit') {\n try {\n await open.commit();\n } catch (err) {\n failedCommit = true;\n throw err;\n }\n } else {\n try {\n await open.rollback();\n } catch (err) {\n // Already rolled back by the server (lease, cap, abort).\n const code = errorCode(err);\n if (code !== 'tx-expired' && code !== 'tx-invalid') throw err;\n }\n }\n } catch (err) {\n throw mapError(err);\n } finally {\n finish();\n }\n return { rowsAffected: 0 };\n }\n try {\n if (tx) return await execute(tx, sql, params);\n // Legacy owners implicitly join plain statements on this socket:\n // wait locally, then send without another await. Negotiated owners\n // isolate plain statements themselves, including same-socket writes.\n while (!detachedPlain && gate) await gate;\n return await execute(client, sql, params);\n } catch (err) {\n throw mapError(err);\n }\n },\n } as Database;\n }\n\n const shared = handle();\n return {\n dialect: 'sqlite',\n conn: client,\n query: shared.query,\n transactionHandle: () => handle(),\n async close() {\n if (owned) await client.close();\n },\n } as Database;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sqlstack",
3
- "version": "3.7.0-dev.0",
3
+ "version": "3.7.0-dev.2",
4
4
  "description": "",
5
5
  "license": "ISC",
6
6
  "author": "",
@@ -72,6 +72,7 @@
72
72
  },
73
73
  "devDependencies": {
74
74
  "@noego/ioc": "^0.8.0",
75
+ "@noego/sqlego": "^0.1.2-dev.2",
75
76
  "@types/jest": "^29.5.13",
76
77
  "better-sqlite3": "^12.3.0",
77
78
  "jest": "^29.7.0",