@nextlyhq/adapter-sqlite 0.0.2-alpha.72 → 0.0.2-alpha.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -68,7 +68,7 @@ Most users do not need this.
68
68
 
69
69
  - **Single writer.** SQLite serializes writes; concurrent transactions queue. Fine for one user, painful for production traffic.
70
70
  - **No SSL or TLS.** Not applicable to a local file.
71
- - **Limited types.** No native arrays, no JSONB; JSON is stored as TEXT. ILIKE is emulated as `LOWER(...) LIKE LOWER(...)`.
71
+ - **Limited types.** No native arrays, no JSONB; JSON is stored as TEXT. ILIKE and case-insensitive `contains` fold both sides with `nextly_fold_case()`, a Unicode case fold the adapter registers on every connection it opens (SQLite's own `LOWER()` folds ASCII letters only), then compare with `LIKE`.
72
72
  - **Savepoints.** Supported.
73
73
  - **`RETURNING` clause.** Supported (SQLite 3.35+).
74
74
 
package/dist/index.cjs CHANGED
@@ -1,10 +1,26 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let node_async_hooks = require("node:async_hooks");
3
2
  let _nextlyhq_adapter_drizzle = require("@nextlyhq/adapter-drizzle");
4
3
  let _nextlyhq_adapter_drizzle_types = require("@nextlyhq/adapter-drizzle/types");
5
4
  let _nextlyhq_adapter_drizzle_version_check = require("@nextlyhq/adapter-drizzle/version-check");
6
5
  let drizzle_orm_better_sqlite3 = require("drizzle-orm/better-sqlite3");
7
6
  let drizzle_orm_sqlite_core = require("drizzle-orm/sqlite-core");
7
+ let _nextlyhq_adapter_drizzle_text_match = require("@nextlyhq/adapter-drizzle/text-match");
8
+ // src/sql-functions.ts
9
+ /**
10
+ * The SQL functions a SQLite connection needs before Nextly's statements run on it.
11
+ *
12
+ * @module sql-functions
13
+ */
14
+ /**
15
+ * Register the SQL functions Nextly's statements call on SQLite, on `db`: the Unicode case fold
16
+ * (`nextly_fold_case`), since SQLite's own `lower()` folds ASCII letters only.
17
+ *
18
+ * Every connection the adapter opens is handed here as it opens, before anything runs on it, so
19
+ * no statement can reach a connection without the function.
20
+ */
21
+ function registerSqliteFunctions(db) {
22
+ (0, _nextlyhq_adapter_drizzle_text_match.registerSqliteFoldCase)(db);
23
+ }
8
24
  // src/index.ts
9
25
  /**
10
26
  * @nextlyhq/adapter-sqlite
@@ -106,7 +122,8 @@ function sanitizeSqliteValue(v) {
106
122
  * - No connection pooling (single file/connection)
107
123
  * - RETURNING clause supported (SQLite 3.35+)
108
124
  * - Savepoints supported via nested transactions
109
- * - No native ILIKE (uses LOWER() LIKE workaround)
125
+ * - No native ILIKE (both sides case-folded, then LIKE; the fold is Nextly's own
126
+ * `nextly_fold_case`, registered on connect, since SQLite's `lower()` folds ASCII only)
110
127
  * - JSON support (not JSONB)
111
128
  * - No array types
112
129
  *
@@ -162,18 +179,6 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
162
179
  */
163
180
  transactionQueue = Promise.resolve();
164
181
  /**
165
- * The transaction the current async chain is running inside, if any.
166
- *
167
- * A `transaction()` call made from INSIDE a transaction's work — a store
168
- * writing on behalf of the caller, a plugin's write inside its own
169
- * `ctx.db.transaction` — used to queue behind the very transaction that
170
- * was waiting for it, and neither ever settled: that hung every later
171
- * transaction on the instance too. Such a call now runs as a SAVEPOINT of
172
- * the active transaction instead, so it commits or rolls back with it and
173
- * its own failure undoes only its own part.
174
- */
175
- transactionScope = new node_async_hooks.AsyncLocalStorage();
176
- /**
177
182
  * Creates a new SQLite adapter instance.
178
183
  *
179
184
  * @param config - Adapter configuration
@@ -210,6 +215,7 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
210
215
  readonly: this.config.readonly ?? false,
211
216
  timeout: this.config.busyTimeout ?? DEFAULT_CONFIG.busyTimeout
212
217
  });
218
+ registerSqliteFunctions(this.db);
213
219
  if ((this.config.wal ?? DEFAULT_CONFIG.wal) && dbPath !== ":memory:" && !this.config.readonly) this.db.pragma("journal_mode = WAL");
214
220
  if (this.config.foreignKeys ?? DEFAULT_CONFIG.foreignKeys) this.db.pragma("foreign_keys = ON");
215
221
  await (0, _nextlyhq_adapter_drizzle_version_check.checkDialectVersion)(this.db, "sqlite");
@@ -300,6 +306,10 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
300
306
  throw this.classifyError(error, sql);
301
307
  }
302
308
  }
309
+ /** How long a transaction waits for the connection: `pool.connectionTimeoutMs`. */
310
+ transactionWaitMs() {
311
+ return this.config.pool?.connectionTimeoutMs ?? DEFAULT_CONFIG.connectionTimeoutMs;
312
+ }
303
313
  /**
304
314
  * Execute work within a transaction.
305
315
  *
@@ -323,206 +333,94 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
323
333
  * Note: SQLite uses DEFERRED, IMMEDIATE, or EXCLUSIVE transaction modes
324
334
  * rather than isolation levels. This adapter uses IMMEDIATE.
325
335
  */
326
- /** How long a transaction waits for the connection: `pool.connectionTimeoutMs`. */
327
- transactionWaitMs() {
328
- return this.config.pool?.connectionTimeoutMs ?? DEFAULT_CONFIG.connectionTimeoutMs;
329
- }
330
- async transaction(work, _options) {
331
- const own = this.transactionScope.getStore();
332
- const parent = this.nestingScope();
333
- if (own && parent !== own) own.writesAfterClosing += 1;
334
- if (parent) return enqueueIn(parent, () => this.runSavepoint(work, parent));
335
- const run = async () => this.runTransaction(work);
336
- const previous = this.transactionQueue;
337
- const next = waitForTurn(previous, this.transactionWaitMs()).then(run);
338
- this.transactionQueue = previous.then(() => next).catch(() => void 0);
339
- const { result, effects } = await next;
340
- await this.runHeldEffects(effects);
341
- return result;
342
- }
343
- /**
344
- * Hold `effect` until the transaction enclosing this async context commits,
345
- * or run it now when none does.
346
- *
347
- * The effect belongs to the scope this async context runs in, even one
348
- * that has already released or rolled back: a service whose own
349
- * transaction nested as a savepoint registers from its caller's scope once
350
- * that savepoint has released, and the change is undoable for as long as
351
- * any scope around it is. The outermost transaction runs the effect once
352
- * its COMMIT succeeds, unless a scope between the effect's scope and the
353
- * outermost transaction rolled back, and drops every effect on ROLLBACK or
354
- * a failed COMMIT. A context whose outermost transaction has already
355
- * finished is outside any transaction, so its effect runs now, unless what
356
- * it announces was undone and it has run no transaction since.
357
- */
358
- async afterCommit(effect, onDeferredFailure) {
359
- const scope = this.transactionScope.getStore();
360
- if (!scope) {
361
- await effect();
362
- return;
363
- }
364
- const root = outermost(scope);
365
- if (!root.finished) {
366
- root.held.push({
367
- effect: this.inRegisteringContext(effect),
368
- onDeferredFailure,
369
- scope,
370
- writesBefore: scope.writesAfterClosing
371
- });
372
- return;
373
- }
374
- if (!undone(scope, scope.writesAfterClosing)) await effect();
336
+ transaction(work, options) {
337
+ return this.openOrJoin(work, options, {
338
+ run: () => this.takeTurn(() => this.runTransaction(work, options)),
339
+ retryable: () => false,
340
+ describe: () => ({
341
+ label: "a retryable error",
342
+ detail: {}
343
+ }),
344
+ logger: this.config.logger
345
+ });
375
346
  }
376
347
  /**
377
- * `effect`, bound to the async context it is registered from.
378
- *
379
- * A held effect runs after the outermost COMMIT, from the code that ran the
380
- * outermost transaction, so without this it sees that code's context rather
381
- * than its own: whatever its caller pinned around the write is gone. That
382
- * includes who is calling. A scope pinned for a scoped API key lost there
383
- * leaves a hook's nested call judged by the key's owner instead of the key,
384
- * and a person's frame lost there leaves the hook told of nobody.
348
+ * Runs `work` outside a transaction, each statement committing as it runs,
349
+ * once no other flow's transaction is open on the one connection.
385
350
  *
386
- * The adapter's own transaction scope is the one store it leaves: the
387
- * effect runs once that transaction has finished, outside it, as an effect
388
- * held to the outermost commit always has.
351
+ * @remarks
352
+ * Waits its turn in `transactionQueue` as a transaction does: a statement
353
+ * run while another flow's transaction is open would join it, and be undone
354
+ * if it rolled back. Transactions begun meanwhile wait behind the session in
355
+ * turn, so `work` must not open one of its own: it would wait behind the
356
+ * session that waits for it, until it fails as busy.
389
357
  */
390
- inRegisteringContext(effect) {
391
- return node_async_hooks.AsyncResource.bind(() => this.transactionScope.exit(effect));
358
+ async withSession(work, _options) {
359
+ this.refuseSessionInTransaction();
360
+ return this.takeTurn(() => work({ execute: (statement, params) => this.executeQuery(statement, params) }));
392
361
  }
393
362
  /**
394
- * Run the effects a committed transaction held, in order. A failure is
395
- * reported, never thrown: the change is durable, and reporting the
396
- * transaction as failed would invite a retry of something already done.
363
+ * Runs `run` once every turn queued before it in `transactionQueue` is
364
+ * done, and holds the queue until `run` is done too.
397
365
  */
398
- async runHeldEffects(effects) {
399
- for (const { effect, onDeferredFailure } of effects) try {
400
- await effect();
401
- } catch (error) {
402
- this.reportHeldEffectFailure(error, onDeferredFailure);
403
- }
366
+ takeTurn(run) {
367
+ const previous = this.transactionQueue;
368
+ const next = waitForTurn(previous, this.transactionWaitMs()).then(run);
369
+ this.transactionQueue = previous.then(() => next).catch(() => void 0);
370
+ return next;
404
371
  }
405
- /** Hand a held effect's failure to its reporter, or to the adapter's log. */
406
- reportHeldEffectFailure(error, onDeferredFailure) {
407
- try {
408
- if (onDeferredFailure) {
409
- onDeferredFailure(error);
410
- return;
411
- }
412
- } catch {}
413
- const failure = error instanceof Error ? error : new Error(String(error));
372
+ /** A held effect's failure that no reporter took goes to the adapter's logger. */
373
+ logHeldEffectFailure(failure) {
414
374
  if (this.config.logger?.error) this.config.logger.error(failure, { phase: "after-commit" });
415
- else console.error("An effect held until commit failed:", failure);
416
- }
417
- /**
418
- * Whether a `transaction()` call made here would join an open transaction
419
- * as a savepoint. On SQLite it would: the connection is the only one, so a
420
- * transaction open on it encloses whatever the async chain that opened it
421
- * starts.
422
- */
423
- inTransaction() {
424
- return this.nestingScope() !== void 0;
425
- }
426
- /**
427
- * Whether the calling async flow is inside a transaction that has not
428
- * finished, judged from the transaction this flow was started inside,
429
- * never from the connection: another request's open transaction answers
430
- * false here, where its own `transaction()` queues behind that one.
431
- *
432
- * A flow started inside a transaction, even inside a savepoint that has
433
- * since released, stays inside it until its outermost transaction has
434
- * committed or rolled back: until then whatever it writes on the one
435
- * connection lands in that transaction.
436
- */
437
- transactionOpenInFlow() {
438
- const own = this.transactionScope.getStore();
439
- return own !== void 0 && !outermost(own).finished;
440
- }
441
- /**
442
- * The scope a `transaction()` call made here nests in, or none when it
443
- * opens a transaction of its own.
444
- *
445
- * A call made later from inside a savepoint that has since released runs
446
- * inside the innermost scope open on the connection. Queued on an enclosing
447
- * scope, or on the instance, it would wait behind the scope running there,
448
- * which may be the one awaiting it. Savepoints on one connection form a
449
- * stack, so whatever opens now is inside that innermost scope anyway; when
450
- * none is open the call queues on the instance.
451
- *
452
- * The innermost open scope need not be related to the call. When it is a
453
- * sibling savepoint that later rolls back, the call's write rolls back with
454
- * it, although the call itself already resolved. Waiting for an unrelated
455
- * scope instead could wait on the very scope that awaits the call.
456
- */
457
- nestingScope() {
458
- const own = this.transactionScope.getStore();
459
- return own?.active ? own : own?.open.at(-1);
375
+ else super.logHeldEffectFailure(failure);
460
376
  }
461
377
  /**
462
- * Run `work` as a savepoint of the active transaction: released when it
463
- * resolves, rolled back to when it throws.
378
+ * The statements of a savepoint `depth` deep on the one connection:
379
+ * released when its work resolves, rolled back to when it throws.
464
380
  */
465
- async runSavepoint(work, parent) {
381
+ savepointSteps(depth) {
466
382
  const db = this.ensureDb();
467
- const name = `nextly_sp_${parent.depth + 1}`;
468
- try {
469
- const ctx = this.createTransactionContext(db);
470
- db.exec(`SAVEPOINT ${name}`);
471
- const scope = openScope(parent);
472
- try {
473
- const result = await this.transactionScope.run(scope, () => work(ctx));
474
- await settleNested(scope);
383
+ const name = `nextly_sp_${depth}`;
384
+ return {
385
+ context: this.createTransactionContext(db),
386
+ begin: () => {
387
+ db.exec(`SAVEPOINT ${name}`);
388
+ },
389
+ commit: () => {
390
+ db.exec(`RELEASE ${name}`);
391
+ },
392
+ rollback: () => {
393
+ db.exec(`ROLLBACK TO ${name}`);
475
394
  db.exec(`RELEASE ${name}`);
476
- return result;
477
- } catch (error) {
478
- await settleNested(scope);
479
- scope.rolledBack = true;
480
- try {
481
- db.exec(`ROLLBACK TO ${name}`);
482
- db.exec(`RELEASE ${name}`);
483
- } catch {}
484
- throw error;
485
395
  }
486
- } catch (error) {
487
- if ((0, _nextlyhq_adapter_drizzle_types.isApplicationError)(error)) throw error;
488
- throw this.classifyError(error);
489
- }
396
+ };
490
397
  }
491
398
  /**
492
- * Inner transaction body. Kept private so callers always go through
493
- * the serialized `transaction()` queue above and the BEGIN/COMMIT
494
- * pair is never invoked outside of it.
399
+ * One attempt's transaction body, settled rather than rejected for the
400
+ * transaction's own failure (`runOutermost`). Kept private so callers always
401
+ * go through the serialized `transaction()` queue above and the
402
+ * BEGIN/COMMIT pair is never invoked outside of it.
495
403
  */
496
- async runTransaction(work) {
404
+ async runTransaction(work, options) {
497
405
  const db = this.ensureDb();
498
- const startTime = Date.now();
499
406
  try {
500
- const ctx = this.createTransactionContext(db);
501
- db.exec("BEGIN IMMEDIATE");
502
- const scope = openScope();
503
- try {
504
- const result = await this.transactionScope.run(scope, () => work(ctx));
505
- await settleNested(scope);
506
- db.exec("COMMIT");
507
- scope.finished = true;
508
- if (this.config.logger?.debug) {
509
- const durationMs = Date.now() - startTime;
510
- this.config.logger.debug("Transaction committed", { durationMs });
407
+ return await this.settleOutermost({
408
+ context: this.createTransactionContext(db),
409
+ join: { adapter: (depth) => this.savepointSteps(depth) },
410
+ begin: () => {
411
+ db.exec("BEGIN IMMEDIATE");
412
+ },
413
+ commit: () => {
414
+ db.exec("COMMIT");
415
+ },
416
+ rollback: () => {
417
+ try {
418
+ db.exec("ROLLBACK");
419
+ } catch (error) {
420
+ if (db.inTransaction) throw error;
421
+ }
511
422
  }
512
- return {
513
- result,
514
- effects: scope.held.filter((held) => !undone(held.scope, held.writesBefore))
515
- };
516
- } catch (error) {
517
- await settleNested(scope);
518
- scope.rolledBack = true;
519
- scope.finished = true;
520
- scope.held.length = 0;
521
- try {
522
- db.exec("ROLLBACK");
523
- } catch {}
524
- throw error;
525
- }
423
+ }, work, options);
526
424
  } catch (error) {
527
425
  if ((0, _nextlyhq_adapter_drizzle_types.isApplicationError)(error)) throw error;
528
426
  throw this.classifyError(error);
@@ -566,6 +464,7 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
566
464
  if (data.length === 0) return [];
567
465
  const db = this.ensureDb();
568
466
  if (data.length === 1) return [await this.insert(table, data[0], options)];
467
+ const tableObj = this.resolvedTableObject(table);
569
468
  const columns = Object.keys(data[0]);
570
469
  const params = [];
571
470
  const valuesClauses = [];
@@ -584,9 +483,7 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
584
483
  sql += ` RETURNING ${returning}`;
585
484
  } else sql += " RETURNING *";
586
485
  try {
587
- const rows = db.prepare(sql).all(...params);
588
- const tableObj = this.getTableObject(table);
589
- return rows.map((r) => this.mapRowFromRawSql(tableObj, r));
486
+ return db.prepare(sql).all(...params).map((r) => this.mapRowFromRawSql(tableObj, r));
590
487
  } catch (error) {
591
488
  throw this.handleQueryError(error, "insertMany", table);
592
489
  }
@@ -673,7 +570,8 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
673
570
  }
674
571
  },
675
572
  insert: async (table, data, options) => {
676
- const mapped = this.mapKeysToSqlColumns(this.getTableObject(table), data);
573
+ const tableObj = this.resolvedTableObject(table);
574
+ const mapped = this.mapKeysToSqlColumns(tableObj, data);
677
575
  const columns = Object.keys(mapped);
678
576
  const values = Object.values(mapped).map(sanitizeSqliteValue);
679
577
  const placeholders = values.map(() => "?").join(", ");
@@ -681,7 +579,7 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
681
579
  const ret = options?.returning;
682
580
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
683
581
  if (!returningEmpty) {
684
- const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
582
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
685
583
  sql += ` RETURNING ${returning}`;
686
584
  }
687
585
  const stmt = db.prepare(sql);
@@ -690,11 +588,11 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
690
588
  return;
691
589
  }
692
590
  const rows = stmt.all(...values);
693
- return this.mapRowFromRawSql(this.getTableObject(table), rows[0]);
591
+ return this.mapRowFromRawSql(tableObj, rows[0]);
694
592
  },
695
593
  insertMany: async (table, data, options) => {
696
594
  if (data.length === 0) return [];
697
- const tableObj = this.getTableObject(table);
595
+ const tableObj = this.resolvedTableObject(table);
698
596
  const mappedRecords = data.map((r) => this.mapKeysToSqlColumns(tableObj, r));
699
597
  const columns = Object.keys(mappedRecords[0]);
700
598
  const allValues = [];
@@ -711,7 +609,7 @@ var SqliteAdapter = class extends _nextlyhq_adapter_drizzle.DrizzleAdapter {
711
609
  const ret = options?.returning;
712
610
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
713
611
  if (!returningEmpty) {
714
- const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
612
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
715
613
  sql += ` RETURNING ${returning}`;
716
614
  }
717
615
  const stmt = db.prepare(sql);
@@ -818,44 +716,6 @@ function isSqliteAdapter(value) {
818
716
  return value instanceof SqliteAdapter;
819
717
  }
820
718
  /**
821
- * Open the scope of a savepoint inside `parent`, or of an outermost
822
- * transaction when there is none, and record it among the connection's open
823
- * scopes.
824
- */
825
- function openScope(parent) {
826
- const scope = {
827
- active: true,
828
- depth: parent ? parent.depth + 1 : 0,
829
- parent,
830
- rolledBack: false,
831
- writesAfterClosing: 0,
832
- finished: false,
833
- held: [],
834
- queue: Promise.resolve(),
835
- open: parent ? parent.open : []
836
- };
837
- scope.open.push(scope);
838
- return scope;
839
- }
840
- /** The outermost transaction `scope` runs inside; itself for that one. */
841
- function outermost(scope) {
842
- let at = scope;
843
- while (at.parent) at = at.parent;
844
- return at;
845
- }
846
- /**
847
- * Whether an effect registered from `scope` describes a write that was
848
- * undone: `scope`, or a scope it runs inside, rolled back, and no
849
- * transaction had run from its context since it closed when the effect was
850
- * registered (`writesBefore`). An effect registered before such a write
851
- * still describes the undone one.
852
- */
853
- function undone(scope, writesBefore) {
854
- if (writesBefore > 0) return false;
855
- for (let at = scope; at; at = at.parent) if (at.rolledBack) return true;
856
- return false;
857
- }
858
- /**
859
719
  * Settles once `turn` does, or rejects with the pool-wait timeout error once
860
720
  * `boundMs` passes first. A bound of 0 waits without limit, as pg-pool reads a
861
721
  * `connectionTimeoutMillis` of 0.
@@ -871,23 +731,6 @@ function waitForTurn(turn, boundMs) {
871
731
  });
872
732
  });
873
733
  }
874
- /** Chain `run` onto a scope's queue, keeping the queue itself unrejected. */
875
- function enqueueIn(scope, run) {
876
- const next = scope.queue.then(run, run);
877
- scope.queue = next.catch(() => void 0);
878
- return next;
879
- }
880
- /**
881
- * Close a scope to new nested calls and wait for those already queued. A call
882
- * arriving after this joins the innermost scope still open on the connection,
883
- * or, when none is, goes to the instance queue behind the transaction.
884
- */
885
- async function settleNested(scope) {
886
- scope.active = false;
887
- const index = scope.open.indexOf(scope);
888
- if (index !== -1) scope.open.splice(index, 1);
889
- await scope.queue;
890
- }
891
734
  exports.SqliteAdapter = SqliteAdapter;
892
735
  exports.VERSION = VERSION;
893
736
  exports.createSqliteAdapter = createSqliteAdapter;