@nitpicker/archive 0.25.1 → 0.25.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.
@@ -40,6 +40,15 @@ declare const Base: typeof BetterSqlite3Client;
40
40
  * A transaction that SQLite rolls back by itself (for example on a full disk)
41
41
  * rejects with the original error, not with the failure of the `ROLLBACK`
42
42
  * Knex sends afterwards.
43
+ *
44
+ * When the caller catches that error inside the callback and carries on, the
45
+ * transaction is already gone and what Knex sends at the end fails:
46
+ * `COMMIT` with `cannot commit - no transaction is active`, and
47
+ * `RELEASE SAVEPOINT` of a nested transaction with `no such savepoint`. That
48
+ * failure is replaced by an error that says SQLite rolled the transaction
49
+ * back, with the original error as `cause` and its `code`. It is not turned
50
+ * into a success: what the transaction wrote before the error was rolled
51
+ * back, and the caller has to know.
43
52
  * @example
44
53
  * ```ts
45
54
  * import knex from 'knex';
@@ -61,6 +70,19 @@ declare const Base: typeof BetterSqlite3Client;
61
70
  * // not `ROLLBACK - cannot rollback - no transaction is active`.
62
71
  * console.error((error as { code?: string }).code);
63
72
  * }
73
+ *
74
+ * try {
75
+ * await db.transaction(async (trx) => {
76
+ * try {
77
+ * await trx.raw('INSERT INTO t (v) VALUES (?)', ['...']);
78
+ * } catch {
79
+ * // Carrying on after the error does not keep the transaction alive.
80
+ * }
81
+ * });
82
+ * } catch (error) {
83
+ * // `code` is `SQLITE_FULL` again, and the original error is in `cause`.
84
+ * console.error((error as { code?: string }).code, (error as { cause?: unknown }).cause);
85
+ * }
64
86
  * ```
65
87
  */
66
88
  export declare class LibsqlDialect extends Base {
@@ -72,11 +94,12 @@ export declare class LibsqlDialect extends Base {
72
94
  */
73
95
  protected _driver(): unknown;
74
96
  /**
75
- * Skips a `ROLLBACK` for a transaction SQLite has already rolled back, and
76
- * delegates every other statement to the `better-sqlite3` implementation.
77
- * Knex calls it from outside the client (`executeQuery`), so it must stay
78
- * reachable at runtime; `protected` is only a compile-time marker, as for
79
- * `_driver`.
97
+ * Skips a `ROLLBACK` for a transaction SQLite has already rolled back,
98
+ * replaces the failure of a later `COMMIT` / `END` / `RELEASE SAVEPOINT`
99
+ * with an error that names the cause, and delegates every statement to the
100
+ * `better-sqlite3` implementation otherwise. Knex calls it from outside the
101
+ * client (`executeQuery`), so it must stay reachable at runtime; `protected`
102
+ * is only a compile-time marker, as for `_driver`.
80
103
  *
81
104
  * Why: SQLite rolls a transaction back by itself on some errors
82
105
  * (`SQLITE_FULL`, `SQLITE_IOERR`, `SQLITE_INTERRUPT`, `SQLITE_NOMEM` in the
@@ -103,6 +126,22 @@ export declare class LibsqlDialect extends Base {
103
126
  * outer one is then running in autocommit mode, because the outer
104
127
  * transaction no longer exists.
105
128
  *
129
+ * `COMMIT` and `RELEASE SAVEPOINT` are executed, not skipped: reporting
130
+ * them as done would show data that was never written as saved. The
131
+ * statement that left the connection outside its transaction is remembered
132
+ * per connection, and when a later `COMMIT` / `RELEASE SAVEPOINT` fails,
133
+ * its error is replaced by one that says SQLite rolled the transaction
134
+ * back, with the remembered error as `cause`. The memory is kept through
135
+ * the nested rollbacks and releases in between, even when a nested
136
+ * transaction opens a new transaction of its own with `SAVEPOINT`, because
137
+ * the outer transaction may still commit after them. It is dropped when
138
+ * the outermost transaction ends (`COMMIT`, `END` or `ROLLBACK`, whether
139
+ * executed, skipped or replaced) or the next one begins (`BEGIN`).
140
+ * Statements that succeed after the rollback ran outside any transaction
141
+ * and are written. If a nested transaction opened a new transaction of its
142
+ * own and the outer `COMMIT` then succeeds, nothing is reported: that
143
+ * `COMMIT` is a real one.
144
+ *
106
145
  * The result mirrors what the `better-sqlite3` dialect records for a
107
146
  * statement that returns no rows. Nothing ran, so there is no row id or
108
147
  * change count to report, and `0` is fine even when `safeIntegers` makes
@@ -19,6 +19,58 @@ const Base = Client_BetterSQLite3;
19
19
  * Knex.
20
20
  */
21
21
  const ROLLBACK_PATTERN = /^(ROLLBACK(?:\s+TO\s+SAVEPOINT)?)\b/i;
22
+ /**
23
+ * Matches the statements that end the outermost transaction successfully:
24
+ * `COMMIT`, and `END`, which SQLite treats as the same statement. Knex sends
25
+ * `COMMIT` after the callback of `transaction()` resolves.
26
+ */
27
+ const OUTERMOST_COMMIT_PATTERN = /^(?:COMMIT|END)\b/i;
28
+ /**
29
+ * Matches every statement that ends a transaction successfully: the outermost
30
+ * `COMMIT` / `END`, and `RELEASE SAVEPOINT` for a nested transaction.
31
+ */
32
+ const COMMIT_PATTERN = /^(?:COMMIT|END|RELEASE(?:\s+SAVEPOINT)?)\b/i;
33
+ /**
34
+ * Matches the statement Knex sends to start the outermost transaction. A new
35
+ * transaction on a connection drops what {@link rolledBackBy} holds for it.
36
+ */
37
+ const BEGIN_PATTERN = /^BEGIN\b/i;
38
+ /**
39
+ * Matches the rollback of the outermost transaction: `ROLLBACK` without
40
+ * `TO`. `ROLLBACK TO <savepoint>` rolls a nested transaction back and leaves
41
+ * the outer one open.
42
+ */
43
+ const OUTERMOST_ROLLBACK_PATTERN = /^ROLLBACK\b(?!\s+TO\b)/i;
44
+ /**
45
+ * The error that made SQLite roll a transaction back by itself, per
46
+ * connection. Set when a statement of a Knex transaction fails and leaves the
47
+ * connection outside any transaction; read when a later `COMMIT` / `END` /
48
+ * `RELEASE SAVEPOINT` fails while it is set; dropped when the outermost
49
+ * transaction ends (`COMMIT`, `END` or `ROLLBACK`, whether it was executed,
50
+ * skipped or replaced) or the next one begins (`BEGIN`). The error holds the
51
+ * SQL with its bound values, so it is not kept longer than that. A `WeakMap`
52
+ * so a closed connection takes its entry along.
53
+ */
54
+ const rolledBackBy = new WeakMap();
55
+ /**
56
+ * Builds the error that replaces the `COMMIT` / `RELEASE SAVEPOINT` failure
57
+ * after an automatic rollback. Carries the original error as `cause` and
58
+ * copies its `code`: a caller that did not catch the error gets the original
59
+ * error, one that did catches this one, and both can read the same `code`.
60
+ * The message names only the code: Knex appends the whole SQL, bound values
61
+ * included, to the original message, and repeating it here would repeat the
62
+ * stored data.
63
+ * @param cause - The error that made SQLite roll the transaction back
64
+ */
65
+ function rolledBackCommitError(cause) {
66
+ const code = cause?.code;
67
+ const error = new Error(`SQLite rolled the transaction back by itself after an earlier error${typeof code === 'string' ? ` (${code})` : ''}. ` +
68
+ 'Statements before that error were rolled back; statements after it may have run outside the transaction.', { cause });
69
+ if (typeof code === 'string') {
70
+ Object.assign(error, { code });
71
+ }
72
+ return error;
73
+ }
22
74
  /**
23
75
  * Knex dialect that reuses the `better-sqlite3` adapter logic but swaps the
24
76
  * underlying driver for `libsql`. `libsql` ships pre-compiled binaries via the
@@ -28,6 +80,15 @@ const ROLLBACK_PATTERN = /^(ROLLBACK(?:\s+TO\s+SAVEPOINT)?)\b/i;
28
80
  * A transaction that SQLite rolls back by itself (for example on a full disk)
29
81
  * rejects with the original error, not with the failure of the `ROLLBACK`
30
82
  * Knex sends afterwards.
83
+ *
84
+ * When the caller catches that error inside the callback and carries on, the
85
+ * transaction is already gone and what Knex sends at the end fails:
86
+ * `COMMIT` with `cannot commit - no transaction is active`, and
87
+ * `RELEASE SAVEPOINT` of a nested transaction with `no such savepoint`. That
88
+ * failure is replaced by an error that says SQLite rolled the transaction
89
+ * back, with the original error as `cause` and its `code`. It is not turned
90
+ * into a success: what the transaction wrote before the error was rolled
91
+ * back, and the caller has to know.
31
92
  * @example
32
93
  * ```ts
33
94
  * import knex from 'knex';
@@ -49,6 +110,19 @@ const ROLLBACK_PATTERN = /^(ROLLBACK(?:\s+TO\s+SAVEPOINT)?)\b/i;
49
110
  * // not `ROLLBACK - cannot rollback - no transaction is active`.
50
111
  * console.error((error as { code?: string }).code);
51
112
  * }
113
+ *
114
+ * try {
115
+ * await db.transaction(async (trx) => {
116
+ * try {
117
+ * await trx.raw('INSERT INTO t (v) VALUES (?)', ['...']);
118
+ * } catch {
119
+ * // Carrying on after the error does not keep the transaction alive.
120
+ * }
121
+ * });
122
+ * } catch (error) {
123
+ * // `code` is `SQLITE_FULL` again, and the original error is in `cause`.
124
+ * console.error((error as { code?: string }).code, (error as { cause?: unknown }).cause);
125
+ * }
52
126
  * ```
53
127
  */
54
128
  export class LibsqlDialect extends Base {
@@ -62,11 +136,12 @@ export class LibsqlDialect extends Base {
62
136
  return libsql;
63
137
  }
64
138
  /**
65
- * Skips a `ROLLBACK` for a transaction SQLite has already rolled back, and
66
- * delegates every other statement to the `better-sqlite3` implementation.
67
- * Knex calls it from outside the client (`executeQuery`), so it must stay
68
- * reachable at runtime; `protected` is only a compile-time marker, as for
69
- * `_driver`.
139
+ * Skips a `ROLLBACK` for a transaction SQLite has already rolled back,
140
+ * replaces the failure of a later `COMMIT` / `END` / `RELEASE SAVEPOINT`
141
+ * with an error that names the cause, and delegates every statement to the
142
+ * `better-sqlite3` implementation otherwise. Knex calls it from outside the
143
+ * client (`executeQuery`), so it must stay reachable at runtime; `protected`
144
+ * is only a compile-time marker, as for `_driver`.
70
145
  *
71
146
  * Why: SQLite rolls a transaction back by itself on some errors
72
147
  * (`SQLITE_FULL`, `SQLITE_IOERR`, `SQLITE_INTERRUPT`, `SQLITE_NOMEM` in the
@@ -93,6 +168,22 @@ export class LibsqlDialect extends Base {
93
168
  * outer one is then running in autocommit mode, because the outer
94
169
  * transaction no longer exists.
95
170
  *
171
+ * `COMMIT` and `RELEASE SAVEPOINT` are executed, not skipped: reporting
172
+ * them as done would show data that was never written as saved. The
173
+ * statement that left the connection outside its transaction is remembered
174
+ * per connection, and when a later `COMMIT` / `RELEASE SAVEPOINT` fails,
175
+ * its error is replaced by one that says SQLite rolled the transaction
176
+ * back, with the remembered error as `cause`. The memory is kept through
177
+ * the nested rollbacks and releases in between, even when a nested
178
+ * transaction opens a new transaction of its own with `SAVEPOINT`, because
179
+ * the outer transaction may still commit after them. It is dropped when
180
+ * the outermost transaction ends (`COMMIT`, `END` or `ROLLBACK`, whether
181
+ * executed, skipped or replaced) or the next one begins (`BEGIN`).
182
+ * Statements that succeed after the rollback ran outside any transaction
183
+ * and are written. If a nested transaction opened a new transaction of its
184
+ * own and the outer `COMMIT` then succeeds, nothing is reported: that
185
+ * `COMMIT` is a real one.
186
+ *
96
187
  * The result mirrors what the `better-sqlite3` dialect records for a
97
188
  * statement that returns no rows. Nothing ran, so there is no row id or
98
189
  * change count to report, and `0` is fine even when `safeIntegers` makes
@@ -104,13 +195,59 @@ export class LibsqlDialect extends Base {
104
195
  // `connection` may be undefined: `super._query` then reports `No connection provided`.
105
196
  const inTransaction = connection
106
197
  ?.inTransaction;
107
- const rollback = ROLLBACK_PATTERN.exec(query.sql ?? '');
108
- if (this.transacting === true && inTransaction === false && rollback) {
198
+ const sql = query.sql ?? '';
199
+ const rollback = ROLLBACK_PATTERN.exec(sql);
200
+ const transacting = this.transacting === true;
201
+ const tracked = typeof connection === 'object' && connection !== null;
202
+ // Only a statement that ends the outermost transaction: a nested one leaves it open.
203
+ const endsOutermost = OUTERMOST_COMMIT_PATTERN.test(sql) || OUTERMOST_ROLLBACK_PATTERN.test(sql);
204
+ if (transacting && inTransaction === false && rollback) {
109
205
  dbLog('Skipping %s: SQLite has already rolled the transaction back', rollback[1]);
206
+ if (tracked && endsOutermost) {
207
+ rolledBackBy.delete(connection);
208
+ }
110
209
  query.response = { changes: 0, lastInsertRowid: 0 };
111
210
  query.context = { lastID: 0, changes: 0 };
112
211
  return query;
113
212
  }
114
- return super._query(connection, query);
213
+ if (tracked && BEGIN_PATTERN.test(sql)) {
214
+ // A new transaction: whatever rolled back an earlier one no longer applies.
215
+ rolledBackBy.delete(connection);
216
+ }
217
+ try {
218
+ const result = await super._query(connection, query);
219
+ if (tracked && endsOutermost) {
220
+ rolledBackBy.delete(connection);
221
+ }
222
+ return result;
223
+ }
224
+ catch (error) {
225
+ if (transacting && tracked) {
226
+ // Only a statement that found no transaction to end is the one the memory explains;
227
+ // one that fails inside a live transaction (a deferred foreign key, say) keeps its error.
228
+ if (inTransaction === false &&
229
+ COMMIT_PATTERN.test(sql) &&
230
+ rolledBackBy.has(connection)) {
231
+ const cause = rolledBackBy.get(connection);
232
+ if (endsOutermost) {
233
+ rolledBackBy.delete(connection);
234
+ }
235
+ dbLog('Replacing the failure of %s: SQLite rolled the transaction back', sql);
236
+ throw rolledBackCommitError(cause);
237
+ }
238
+ const inTransactionAfter = connection
239
+ .inTransaction;
240
+ // A failing statement that ends the outermost transaction needs no memory:
241
+ // nothing commits after it. The first cause is kept: it is the one that
242
+ // discarded the writes of the outer transaction.
243
+ if (inTransaction === true &&
244
+ inTransactionAfter === false &&
245
+ !endsOutermost &&
246
+ !rolledBackBy.has(connection)) {
247
+ rolledBackBy.set(connection, error);
248
+ }
249
+ }
250
+ throw error;
251
+ }
115
252
  }
116
253
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nitpicker/archive",
3
- "version": "0.25.1",
3
+ "version": "0.25.2",
4
4
  "description": "Read/write layer for .nitpicker archives (SQLite schema, migration, cache, concat/split, template classification)",
5
5
  "author": "D-ZERO",
6
6
  "license": "Apache-2.0",
@@ -344,12 +344,12 @@
344
344
  "dependencies": {
345
345
  "@d-zero/fs": "0.2.8",
346
346
  "@d-zero/shared": "0.23.2",
347
- "@nitpicker/core": "0.25.1",
347
+ "@nitpicker/core": "0.25.2",
348
348
  "debug": "4.4.3",
349
349
  "fs-extra": "11.4.1",
350
350
  "knex": "3.3.0",
351
351
  "libsql": "0.5.29",
352
- "tar": "7.5.22"
352
+ "tar": "7.5.24"
353
353
  },
354
354
  "devDependencies": {
355
355
  "@types/debug": "4.1.13",
@@ -357,5 +357,5 @@
357
357
  "@types/tar": "7.0.87",
358
358
  "@types/unzipper": "0.10.11"
359
359
  },
360
- "gitHead": "fa839178ea8f40e92fc742e0480c6cfbbb8fb01f"
360
+ "gitHead": "3dc201cd82b0986c6f90a5d54e790f00d1503b96"
361
361
  }