@nextlyhq/adapter-sqlite 0.0.2-alpha.73 → 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/dist/index.mjs CHANGED
@@ -1,9 +1,25 @@
1
- import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
2
1
  import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
3
2
  import { createDatabaseError, isApplicationError, isDatabaseError, poolWaitTimeoutError } from "@nextlyhq/adapter-drizzle/types";
4
3
  import { checkDialectVersion } from "@nextlyhq/adapter-drizzle/version-check";
5
4
  import { drizzle } from "drizzle-orm/better-sqlite3";
6
5
  import { getTableConfig } from "drizzle-orm/sqlite-core";
6
+ import { registerSqliteFoldCase } from "@nextlyhq/adapter-drizzle/text-match";
7
+ // src/sql-functions.ts
8
+ /**
9
+ * The SQL functions a SQLite connection needs before Nextly's statements run on it.
10
+ *
11
+ * @module sql-functions
12
+ */
13
+ /**
14
+ * Register the SQL functions Nextly's statements call on SQLite, on `db`: the Unicode case fold
15
+ * (`nextly_fold_case`), since SQLite's own `lower()` folds ASCII letters only.
16
+ *
17
+ * Every connection the adapter opens is handed here as it opens, before anything runs on it, so
18
+ * no statement can reach a connection without the function.
19
+ */
20
+ function registerSqliteFunctions(db) {
21
+ registerSqliteFoldCase(db);
22
+ }
7
23
  // src/index.ts
8
24
  /**
9
25
  * @nextlyhq/adapter-sqlite
@@ -105,7 +121,8 @@ function sanitizeSqliteValue(v) {
105
121
  * - No connection pooling (single file/connection)
106
122
  * - RETURNING clause supported (SQLite 3.35+)
107
123
  * - Savepoints supported via nested transactions
108
- * - No native ILIKE (uses LOWER() LIKE workaround)
124
+ * - No native ILIKE (both sides case-folded, then LIKE; the fold is Nextly's own
125
+ * `nextly_fold_case`, registered on connect, since SQLite's `lower()` folds ASCII only)
109
126
  * - JSON support (not JSONB)
110
127
  * - No array types
111
128
  *
@@ -161,18 +178,6 @@ var SqliteAdapter = class extends DrizzleAdapter {
161
178
  */
162
179
  transactionQueue = Promise.resolve();
163
180
  /**
164
- * The transaction the current async chain is running inside, if any.
165
- *
166
- * A `transaction()` call made from INSIDE a transaction's work — a store
167
- * writing on behalf of the caller, a plugin's write inside its own
168
- * `ctx.db.transaction` — used to queue behind the very transaction that
169
- * was waiting for it, and neither ever settled: that hung every later
170
- * transaction on the instance too. Such a call now runs as a SAVEPOINT of
171
- * the active transaction instead, so it commits or rolls back with it and
172
- * its own failure undoes only its own part.
173
- */
174
- transactionScope = new AsyncLocalStorage();
175
- /**
176
181
  * Creates a new SQLite adapter instance.
177
182
  *
178
183
  * @param config - Adapter configuration
@@ -209,6 +214,7 @@ var SqliteAdapter = class extends DrizzleAdapter {
209
214
  readonly: this.config.readonly ?? false,
210
215
  timeout: this.config.busyTimeout ?? DEFAULT_CONFIG.busyTimeout
211
216
  });
217
+ registerSqliteFunctions(this.db);
212
218
  if ((this.config.wal ?? DEFAULT_CONFIG.wal) && dbPath !== ":memory:" && !this.config.readonly) this.db.pragma("journal_mode = WAL");
213
219
  if (this.config.foreignKeys ?? DEFAULT_CONFIG.foreignKeys) this.db.pragma("foreign_keys = ON");
214
220
  await checkDialectVersion(this.db, "sqlite");
@@ -299,6 +305,10 @@ var SqliteAdapter = class extends DrizzleAdapter {
299
305
  throw this.classifyError(error, sql);
300
306
  }
301
307
  }
308
+ /** How long a transaction waits for the connection: `pool.connectionTimeoutMs`. */
309
+ transactionWaitMs() {
310
+ return this.config.pool?.connectionTimeoutMs ?? DEFAULT_CONFIG.connectionTimeoutMs;
311
+ }
302
312
  /**
303
313
  * Execute work within a transaction.
304
314
  *
@@ -322,18 +332,16 @@ var SqliteAdapter = class extends DrizzleAdapter {
322
332
  * Note: SQLite uses DEFERRED, IMMEDIATE, or EXCLUSIVE transaction modes
323
333
  * rather than isolation levels. This adapter uses IMMEDIATE.
324
334
  */
325
- /** How long a transaction waits for the connection: `pool.connectionTimeoutMs`. */
326
- transactionWaitMs() {
327
- return this.config.pool?.connectionTimeoutMs ?? DEFAULT_CONFIG.connectionTimeoutMs;
328
- }
329
- async transaction(work, _options) {
330
- const own = this.transactionScope.getStore();
331
- const parent = this.nestingScope();
332
- if (own && parent !== own) own.writesAfterClosing += 1;
333
- if (parent) return enqueueIn(parent, () => this.runSavepoint(work, parent));
334
- const { result, effects } = await this.takeTurn(() => this.runTransaction(work));
335
- await this.runHeldEffects(effects);
336
- return result;
335
+ transaction(work, options) {
336
+ return this.openOrJoin(work, options, {
337
+ run: () => this.takeTurn(() => this.runTransaction(work, options)),
338
+ retryable: () => false,
339
+ describe: () => ({
340
+ label: "a retryable error",
341
+ detail: {}
342
+ }),
343
+ logger: this.config.logger
344
+ });
337
345
  }
338
346
  /**
339
347
  * Runs `work` outside a transaction, each statement committing as it runs,
@@ -360,189 +368,58 @@ var SqliteAdapter = class extends DrizzleAdapter {
360
368
  this.transactionQueue = previous.then(() => next).catch(() => void 0);
361
369
  return next;
362
370
  }
363
- /**
364
- * Hold `effect` until the transaction enclosing this async context commits,
365
- * or run it now when none does.
366
- *
367
- * The effect belongs to the scope this async context runs in, even one
368
- * that has already released or rolled back: a service whose own
369
- * transaction nested as a savepoint registers from its caller's scope once
370
- * that savepoint has released, and the change is undoable for as long as
371
- * any scope around it is. The outermost transaction runs the effect once
372
- * its COMMIT succeeds, unless a scope between the effect's scope and the
373
- * outermost transaction rolled back, and drops every effect on ROLLBACK or
374
- * a failed COMMIT. A context whose outermost transaction has already
375
- * finished is outside any transaction, so its effect runs now, unless what
376
- * it announces was undone and it has run no transaction since.
377
- */
378
- async afterCommit(effect, onDeferredFailure) {
379
- const scope = this.transactionScope.getStore();
380
- if (!scope) {
381
- await effect();
382
- return;
383
- }
384
- const root = outermost(scope);
385
- if (!root.finished) {
386
- root.held.push({
387
- effect: this.inRegisteringContext(effect),
388
- onDeferredFailure,
389
- scope,
390
- writesBefore: scope.writesAfterClosing
391
- });
392
- return;
393
- }
394
- if (!undone(scope, scope.writesAfterClosing)) await effect();
395
- }
396
- /**
397
- * `effect`, bound to the async context it is registered from.
398
- *
399
- * A held effect runs after the outermost COMMIT, from the code that ran the
400
- * outermost transaction, so without this it sees that code's context rather
401
- * than its own: whatever its caller pinned around the write is gone. That
402
- * includes who is calling. A scope pinned for a scoped API key lost there
403
- * leaves a hook's nested call judged by the key's owner instead of the key,
404
- * and a person's frame lost there leaves the hook told of nobody.
405
- *
406
- * The adapter's own transaction scope is the one store it leaves: the
407
- * effect runs once that transaction has finished, outside it, as an effect
408
- * held to the outermost commit always has.
409
- */
410
- inRegisteringContext(effect) {
411
- return AsyncResource.bind(() => this.transactionScope.exit(effect));
412
- }
413
- /**
414
- * Run the effects a committed transaction held, in order. A failure is
415
- * reported, never thrown: the change is durable, and reporting the
416
- * transaction as failed would invite a retry of something already done.
417
- */
418
- async runHeldEffects(effects) {
419
- for (const { effect, onDeferredFailure } of effects) try {
420
- await effect();
421
- } catch (error) {
422
- this.reportHeldEffectFailure(error, onDeferredFailure);
423
- }
424
- }
425
- /** Hand a held effect's failure to its reporter, or to the adapter's log. */
426
- reportHeldEffectFailure(error, onDeferredFailure) {
427
- try {
428
- if (onDeferredFailure) {
429
- onDeferredFailure(error);
430
- return;
431
- }
432
- } catch {}
433
- const failure = error instanceof Error ? error : new Error(String(error));
371
+ /** A held effect's failure that no reporter took goes to the adapter's logger. */
372
+ logHeldEffectFailure(failure) {
434
373
  if (this.config.logger?.error) this.config.logger.error(failure, { phase: "after-commit" });
435
- else console.error("An effect held until commit failed:", failure);
436
- }
437
- /**
438
- * Whether a `transaction()` call made here would join an open transaction
439
- * as a savepoint. On SQLite it would: the connection is the only one, so a
440
- * transaction open on it encloses whatever the async chain that opened it
441
- * starts.
442
- */
443
- inTransaction() {
444
- return this.nestingScope() !== void 0;
445
- }
446
- /**
447
- * Whether the calling async flow is inside a transaction that has not
448
- * finished, judged from the transaction this flow was started inside,
449
- * never from the connection: another request's open transaction answers
450
- * false here, where its own `transaction()` queues behind that one.
451
- *
452
- * A flow started inside a transaction, even inside a savepoint that has
453
- * since released, stays inside it until its outermost transaction has
454
- * committed or rolled back: until then whatever it writes on the one
455
- * connection lands in that transaction.
456
- */
457
- transactionOpenInFlow() {
458
- const own = this.transactionScope.getStore();
459
- return own !== void 0 && !outermost(own).finished;
460
- }
461
- /**
462
- * The scope a `transaction()` call made here nests in, or none when it
463
- * opens a transaction of its own.
464
- *
465
- * A call made later from inside a savepoint that has since released runs
466
- * inside the innermost scope open on the connection. Queued on an enclosing
467
- * scope, or on the instance, it would wait behind the scope running there,
468
- * which may be the one awaiting it. Savepoints on one connection form a
469
- * stack, so whatever opens now is inside that innermost scope anyway; when
470
- * none is open the call queues on the instance.
471
- *
472
- * The innermost open scope need not be related to the call. When it is a
473
- * sibling savepoint that later rolls back, the call's write rolls back with
474
- * it, although the call itself already resolved. Waiting for an unrelated
475
- * scope instead could wait on the very scope that awaits the call.
476
- */
477
- nestingScope() {
478
- const own = this.transactionScope.getStore();
479
- return own?.active ? own : own?.open.at(-1);
374
+ else super.logHeldEffectFailure(failure);
480
375
  }
481
376
  /**
482
- * Run `work` as a savepoint of the active transaction: released when it
483
- * resolves, rolled back to when it throws.
377
+ * The statements of a savepoint `depth` deep on the one connection:
378
+ * released when its work resolves, rolled back to when it throws.
484
379
  */
485
- async runSavepoint(work, parent) {
380
+ savepointSteps(depth) {
486
381
  const db = this.ensureDb();
487
- const name = `nextly_sp_${parent.depth + 1}`;
488
- try {
489
- const ctx = this.createTransactionContext(db);
490
- db.exec(`SAVEPOINT ${name}`);
491
- const scope = openScope(parent);
492
- try {
493
- const result = await this.transactionScope.run(scope, () => work(ctx));
494
- await settleNested(scope);
382
+ const name = `nextly_sp_${depth}`;
383
+ return {
384
+ context: this.createTransactionContext(db),
385
+ begin: () => {
386
+ db.exec(`SAVEPOINT ${name}`);
387
+ },
388
+ commit: () => {
389
+ db.exec(`RELEASE ${name}`);
390
+ },
391
+ rollback: () => {
392
+ db.exec(`ROLLBACK TO ${name}`);
495
393
  db.exec(`RELEASE ${name}`);
496
- return result;
497
- } catch (error) {
498
- await settleNested(scope);
499
- scope.rolledBack = true;
500
- try {
501
- db.exec(`ROLLBACK TO ${name}`);
502
- db.exec(`RELEASE ${name}`);
503
- } catch {}
504
- throw error;
505
394
  }
506
- } catch (error) {
507
- if (isApplicationError(error)) throw error;
508
- throw this.classifyError(error);
509
- }
395
+ };
510
396
  }
511
397
  /**
512
- * Inner transaction body. Kept private so callers always go through
513
- * the serialized `transaction()` queue above and the BEGIN/COMMIT
514
- * pair is never invoked outside of it.
398
+ * One attempt's transaction body, settled rather than rejected for the
399
+ * transaction's own failure (`runOutermost`). Kept private so callers always
400
+ * go through the serialized `transaction()` queue above and the
401
+ * BEGIN/COMMIT pair is never invoked outside of it.
515
402
  */
516
- async runTransaction(work) {
403
+ async runTransaction(work, options) {
517
404
  const db = this.ensureDb();
518
- const startTime = Date.now();
519
405
  try {
520
- const ctx = this.createTransactionContext(db);
521
- db.exec("BEGIN IMMEDIATE");
522
- const scope = openScope();
523
- try {
524
- const result = await this.transactionScope.run(scope, () => work(ctx));
525
- await settleNested(scope);
526
- db.exec("COMMIT");
527
- scope.finished = true;
528
- if (this.config.logger?.debug) {
529
- const durationMs = Date.now() - startTime;
530
- this.config.logger.debug("Transaction committed", { durationMs });
406
+ return await this.settleOutermost({
407
+ context: this.createTransactionContext(db),
408
+ join: { adapter: (depth) => this.savepointSteps(depth) },
409
+ begin: () => {
410
+ db.exec("BEGIN IMMEDIATE");
411
+ },
412
+ commit: () => {
413
+ db.exec("COMMIT");
414
+ },
415
+ rollback: () => {
416
+ try {
417
+ db.exec("ROLLBACK");
418
+ } catch (error) {
419
+ if (db.inTransaction) throw error;
420
+ }
531
421
  }
532
- return {
533
- result,
534
- effects: scope.held.filter((held) => !undone(held.scope, held.writesBefore))
535
- };
536
- } catch (error) {
537
- await settleNested(scope);
538
- scope.rolledBack = true;
539
- scope.finished = true;
540
- scope.held.length = 0;
541
- try {
542
- db.exec("ROLLBACK");
543
- } catch {}
544
- throw error;
545
- }
422
+ }, work, options);
546
423
  } catch (error) {
547
424
  if (isApplicationError(error)) throw error;
548
425
  throw this.classifyError(error);
@@ -586,6 +463,7 @@ var SqliteAdapter = class extends DrizzleAdapter {
586
463
  if (data.length === 0) return [];
587
464
  const db = this.ensureDb();
588
465
  if (data.length === 1) return [await this.insert(table, data[0], options)];
466
+ const tableObj = this.resolvedTableObject(table);
589
467
  const columns = Object.keys(data[0]);
590
468
  const params = [];
591
469
  const valuesClauses = [];
@@ -604,9 +482,7 @@ var SqliteAdapter = class extends DrizzleAdapter {
604
482
  sql += ` RETURNING ${returning}`;
605
483
  } else sql += " RETURNING *";
606
484
  try {
607
- const rows = db.prepare(sql).all(...params);
608
- const tableObj = this.getTableObject(table);
609
- return rows.map((r) => this.mapRowFromRawSql(tableObj, r));
485
+ return db.prepare(sql).all(...params).map((r) => this.mapRowFromRawSql(tableObj, r));
610
486
  } catch (error) {
611
487
  throw this.handleQueryError(error, "insertMany", table);
612
488
  }
@@ -693,7 +569,8 @@ var SqliteAdapter = class extends DrizzleAdapter {
693
569
  }
694
570
  },
695
571
  insert: async (table, data, options) => {
696
- const mapped = this.mapKeysToSqlColumns(this.getTableObject(table), data);
572
+ const tableObj = this.resolvedTableObject(table);
573
+ const mapped = this.mapKeysToSqlColumns(tableObj, data);
697
574
  const columns = Object.keys(mapped);
698
575
  const values = Object.values(mapped).map(sanitizeSqliteValue);
699
576
  const placeholders = values.map(() => "?").join(", ");
@@ -701,7 +578,7 @@ var SqliteAdapter = class extends DrizzleAdapter {
701
578
  const ret = options?.returning;
702
579
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
703
580
  if (!returningEmpty) {
704
- const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
581
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
705
582
  sql += ` RETURNING ${returning}`;
706
583
  }
707
584
  const stmt = db.prepare(sql);
@@ -710,11 +587,11 @@ var SqliteAdapter = class extends DrizzleAdapter {
710
587
  return;
711
588
  }
712
589
  const rows = stmt.all(...values);
713
- return this.mapRowFromRawSql(this.getTableObject(table), rows[0]);
590
+ return this.mapRowFromRawSql(tableObj, rows[0]);
714
591
  },
715
592
  insertMany: async (table, data, options) => {
716
593
  if (data.length === 0) return [];
717
- const tableObj = this.getTableObject(table);
594
+ const tableObj = this.resolvedTableObject(table);
718
595
  const mappedRecords = data.map((r) => this.mapKeysToSqlColumns(tableObj, r));
719
596
  const columns = Object.keys(mappedRecords[0]);
720
597
  const allValues = [];
@@ -731,7 +608,7 @@ var SqliteAdapter = class extends DrizzleAdapter {
731
608
  const ret = options?.returning;
732
609
  const returningEmpty = Array.isArray(ret) && ret.length === 0;
733
610
  if (!returningEmpty) {
734
- const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(this.getTableObject(table), ret).map((col) => this.escapeIdentifier(col)).join(", ");
611
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
735
612
  sql += ` RETURNING ${returning}`;
736
613
  }
737
614
  const stmt = db.prepare(sql);
@@ -838,44 +715,6 @@ function isSqliteAdapter(value) {
838
715
  return value instanceof SqliteAdapter;
839
716
  }
840
717
  /**
841
- * Open the scope of a savepoint inside `parent`, or of an outermost
842
- * transaction when there is none, and record it among the connection's open
843
- * scopes.
844
- */
845
- function openScope(parent) {
846
- const scope = {
847
- active: true,
848
- depth: parent ? parent.depth + 1 : 0,
849
- parent,
850
- rolledBack: false,
851
- writesAfterClosing: 0,
852
- finished: false,
853
- held: [],
854
- queue: Promise.resolve(),
855
- open: parent ? parent.open : []
856
- };
857
- scope.open.push(scope);
858
- return scope;
859
- }
860
- /** The outermost transaction `scope` runs inside; itself for that one. */
861
- function outermost(scope) {
862
- let at = scope;
863
- while (at.parent) at = at.parent;
864
- return at;
865
- }
866
- /**
867
- * Whether an effect registered from `scope` describes a write that was
868
- * undone: `scope`, or a scope it runs inside, rolled back, and no
869
- * transaction had run from its context since it closed when the effect was
870
- * registered (`writesBefore`). An effect registered before such a write
871
- * still describes the undone one.
872
- */
873
- function undone(scope, writesBefore) {
874
- if (writesBefore > 0) return false;
875
- for (let at = scope; at; at = at.parent) if (at.rolledBack) return true;
876
- return false;
877
- }
878
- /**
879
718
  * Settles once `turn` does, or rejects with the pool-wait timeout error once
880
719
  * `boundMs` passes first. A bound of 0 waits without limit, as pg-pool reads a
881
720
  * `connectionTimeoutMillis` of 0.
@@ -891,23 +730,6 @@ function waitForTurn(turn, boundMs) {
891
730
  });
892
731
  });
893
732
  }
894
- /** Chain `run` onto a scope's queue, keeping the queue itself unrejected. */
895
- function enqueueIn(scope, run) {
896
- const next = scope.queue.then(run, run);
897
- scope.queue = next.catch(() => void 0);
898
- return next;
899
- }
900
- /**
901
- * Close a scope to new nested calls and wait for those already queued. A call
902
- * arriving after this joins the innermost scope still open on the connection,
903
- * or, when none is, goes to the instance queue behind the transaction.
904
- */
905
- async function settleNested(scope) {
906
- scope.active = false;
907
- const index = scope.open.indexOf(scope);
908
- if (index !== -1) scope.open.splice(index, 1);
909
- await scope.queue;
910
- }
911
733
  export { SqliteAdapter, VERSION, createSqliteAdapter, isSqliteAdapter };
912
734
 
913
735
  //# sourceMappingURL=index.mjs.map