@nextlyhq/adapter-sqlite 0.0.2-alpha.7 → 0.0.2-alpha.71

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.d.cts CHANGED
@@ -1,48 +1,11 @@
1
- import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
- import { SqliteAdapterConfig, PoolStats, SqlParam, TransactionContext, TransactionOptions, DatabaseCapabilities, InsertOptions, DatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
- export { AdapterLogger, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, SelectOptions, SqlParam, SqliteAdapterConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from '@nextlyhq/adapter-drizzle/types';
4
- import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
5
-
6
- /**
7
- * @nextlyhq/adapter-sqlite
8
- *
9
- * SQLite database adapter for Nextly.
10
- * Extends DrizzleAdapter from @nextlyhq/adapter-drizzle to provide SQLite-specific functionality.
11
- *
12
- * @remarks
13
- * This adapter uses the better-sqlite3 package for database connectivity and provides:
14
- * - Synchronous API wrapped for async interface compatibility
15
- * - Full transaction support with savepoints (via better-sqlite3's native transaction handling)
16
- * - CRUD operations with RETURNING clause support (SQLite 3.35+)
17
- * - WAL mode for better concurrent read performance
18
- * - In-memory and file-based database support
19
- *
20
- * @example
21
- * ```typescript
22
- * import { createSqliteAdapter } from '@nextlyhq/adapter-sqlite';
23
- *
24
- * const adapter = createSqliteAdapter({
25
- * url: 'file:./data/app.db',
26
- * });
27
- *
28
- * await adapter.connect();
29
- *
30
- * // Query data
31
- * const users = await adapter.select('users', {
32
- * where: { and: [{ column: 'status', op: '=', value: 'active' }] },
33
- * limit: 10,
34
- * });
35
- *
36
- * await adapter.disconnect();
37
- * ```
38
- *
39
- * @packageDocumentation
40
- */
41
-
1
+ import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
2
+ import { AdapterLogger, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, SelectOptions, SqlParam, SqliteAdapterConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from "@nextlyhq/adapter-drizzle/types";
3
+ import { AnyRelations } from "drizzle-orm";
4
+ import { BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
42
5
  /**
43
6
  * Package version
44
7
  */
45
- declare const VERSION = "0.1.0";
8
+ export declare const VERSION = "0.1.0";
46
9
  /**
47
10
  * SQLite database adapter for Nextly.
48
11
  *
@@ -68,173 +31,274 @@ declare const VERSION = "0.1.0";
68
31
  * await adapter.connect();
69
32
  * ```
70
33
  */
71
- declare class SqliteAdapter extends DrizzleAdapter {
72
- /**
73
- * The database dialect - always 'sqlite' for this adapter.
74
- */
75
- readonly dialect: "sqlite";
76
- /**
77
- * Adapter configuration.
78
- */
79
- protected readonly config: SqliteAdapterConfig;
80
- /**
81
- * better-sqlite3 Database instance.
82
- */
83
- private db;
84
- /**
85
- * Connection state flag.
86
- */
87
- private connected;
88
- /**
89
- * Serialization queue for concurrent `transaction()` calls.
90
- *
91
- * better-sqlite3 is synchronous, single-connection, and rejects nested
92
- * `BEGIN` with "cannot start a transaction within a transaction".
93
- * When two `await adapter.transaction(...)` calls overlap (e.g. a bulk
94
- * mutation calling `Promise.allSettled` with N per-row updates), the
95
- * second one tries to BEGIN while the first is still open and the
96
- * driver throws.
97
- *
98
- * Postgres/MySQL avoid this by allocating a fresh client/connection
99
- * per transaction from a pool — there is no equivalent for
100
- * better-sqlite3, so we serialize at the JS layer instead. Every
101
- * `transaction()` invocation chains onto this promise; only one
102
- * BEGIN→COMMIT/ROLLBACK section runs at any moment, preserving
103
- * write-isolation semantics that callers expect from a transactional
104
- * adapter.
105
- *
106
- * Performance impact is the natural floor: SQLite already serializes
107
- * writers at the file-lock level, so the queue removes failed-call
108
- * surface area without changing the achievable concurrency.
109
- */
110
- private transactionQueue;
111
- /**
112
- * Creates a new SQLite adapter instance.
113
- *
114
- * @param config - Adapter configuration
115
- */
116
- constructor(config: SqliteAdapterConfig);
117
- /**
118
- * Connect to the SQLite database.
119
- *
120
- * @remarks
121
- * This method initializes the database connection. For SQLite, this
122
- * opens the database file or creates an in-memory database.
123
- * Also configures WAL mode and foreign keys based on config.
124
- *
125
- * @throws {DatabaseError} If connection fails
126
- */
127
- connect(): Promise<void>;
128
- /**
129
- * Disconnect from the SQLite database.
130
- *
131
- * @remarks
132
- * This method closes the database connection and releases resources.
133
- */
134
- disconnect(): Promise<void>;
135
- /**
136
- * Check if connected to the database.
137
- */
138
- isConnected(): boolean;
139
- /**
140
- * Get connection pool statistics.
141
- *
142
- * @remarks
143
- * SQLite doesn't use connection pooling, so this returns null.
144
- * The database is single-file with a single connection.
145
- */
146
- getPoolStats(): PoolStats | null;
147
- /**
148
- * Execute a raw SQL query.
149
- *
150
- * @param sql - SQL query string with $1, $2 placeholders (converted to ? for SQLite)
151
- * @param params - Query parameters
152
- * @returns Query results
153
- *
154
- * @throws {DatabaseError} If query execution fails
155
- */
156
- executeQuery<T = unknown>(sql: string, params?: SqlParam[]): Promise<T[]>;
157
- /**
158
- * Execute work within a transaction.
159
- *
160
- * @param work - Function containing transactional operations
161
- * @param options - Transaction options (isolation level not fully supported in SQLite)
162
- * @returns Result of the work function
163
- *
164
- * @remarks
165
- * Uses better-sqlite3's native transaction handling which:
166
- * - Automatically commits on success
167
- * - Automatically rolls back on error
168
- * - Converts nested transactions to savepoints
169
- *
170
- * Note: SQLite uses DEFERRED, IMMEDIATE, or EXCLUSIVE transaction modes
171
- * rather than isolation levels. This adapter uses IMMEDIATE by default.
172
- */
173
- transaction<T>(work: (tx: TransactionContext) => Promise<T>, _options?: TransactionOptions): Promise<T>;
174
- /**
175
- * Inner transaction body. Kept private so callers always go through
176
- * the serialized `transaction()` queue above and the BEGIN/COMMIT
177
- * pair is never invoked outside of it.
178
- */
179
- private runTransaction;
180
- /**
181
- * Get SQLite database capabilities.
182
- *
183
- * @remarks
184
- * SQLite capabilities:
185
- * - JSON support (not JSONB)
186
- * - No arrays
187
- * - No native ILIKE
188
- * - RETURNING clause (3.35+)
189
- * - Savepoints supported
190
- * - ON CONFLICT supported
191
- */
192
- getCapabilities(): DatabaseCapabilities;
193
- /**
194
- * Override insertMany for bulk insert optimization.
195
- *
196
- * @remarks
197
- * Uses a single multi-row INSERT statement for better performance.
198
- */
199
- insertMany<T = unknown>(table: string, data: Record<string, unknown>[], options?: InsertOptions): Promise<T[]>;
200
- /**
201
- * Ensures database is connected and returns it.
202
- *
203
- * @throws {DatabaseError} If not connected
204
- */
205
- private ensureDb;
206
- /**
207
- * Return the typed Drizzle instance for SQLite.
208
- * Guarded for server-only usage and requires an active connection.
209
- *
210
- * @param schema - Optional schema for relational queries (db.query.*)
211
- * @returns Drizzle ORM instance wrapping the better-sqlite3 connection
212
- * @throws {Error} If called in browser or not connected
213
- */
214
- getDrizzle<T = BetterSQLite3Database<any>>(schema?: Record<string, unknown>): T;
215
- /**
216
- * Convert $1, $2 placeholders to ? for better-sqlite3.
217
- *
218
- * @param sql - SQL with PostgreSQL-style placeholders
219
- * @returns SQL with ? placeholders
220
- */
221
- private convertPlaceholders;
222
- /**
223
- * Creates a TransactionContext for the given database connection.
224
- */
225
- private createTransactionContext;
226
- /**
227
- * Classifies a SQLite error into a DatabaseError.
228
- *
229
- * @param error - Original error from better-sqlite3
230
- * @param sql - SQL statement that caused the error (optional)
231
- * @returns DatabaseError with proper classification
232
- */
233
- private classifyError;
234
- /**
235
- * Override handleQueryError to use SQLite-specific classification.
236
- */
237
- protected handleQueryError(error: unknown, operation: string, table: string): DatabaseError;
34
+ export declare class SqliteAdapter extends DrizzleAdapter {
35
+ private drizzleByRelations;
36
+ private drizzleBare;
37
+ /**
38
+ * The database dialect - always 'sqlite' for this adapter.
39
+ */
40
+ readonly dialect: "sqlite";
41
+ /**
42
+ * Adapter configuration.
43
+ */
44
+ protected readonly config: SqliteAdapterConfig;
45
+ /**
46
+ * better-sqlite3 Database instance.
47
+ */
48
+ private db;
49
+ /**
50
+ * Connection state flag.
51
+ */
52
+ private connected;
53
+ /**
54
+ * Serialization queue for concurrent `transaction()` calls.
55
+ *
56
+ * better-sqlite3 is synchronous, single-connection, and rejects nested
57
+ * `BEGIN` with "cannot start a transaction within a transaction".
58
+ * When two `await adapter.transaction(...)` calls overlap (e.g. a bulk
59
+ * mutation calling `Promise.allSettled` with N per-row updates), the
60
+ * second one tries to BEGIN while the first is still open and the
61
+ * driver throws.
62
+ *
63
+ * Postgres/MySQL avoid this by allocating a fresh client/connection
64
+ * per transaction from a pool — there is no equivalent for
65
+ * better-sqlite3, so we serialize at the JS layer instead. Every
66
+ * `transaction()` invocation chains onto this promise; only one
67
+ * BEGIN→COMMIT/ROLLBACK section runs at any moment, preserving
68
+ * write-isolation semantics that callers expect from a transactional
69
+ * adapter.
70
+ *
71
+ * Performance impact is the natural floor: SQLite already serializes
72
+ * writers at the file-lock level, so the queue removes failed-call
73
+ * surface area without changing the achievable concurrency.
74
+ */
75
+ private transactionQueue;
76
+ /**
77
+ * The transaction the current async chain is running inside, if any.
78
+ *
79
+ * A `transaction()` call made from INSIDE a transaction's work — a store
80
+ * writing on behalf of the caller, a plugin's write inside its own
81
+ * `ctx.db.transaction` — used to queue behind the very transaction that
82
+ * was waiting for it, and neither ever settled: that hung every later
83
+ * transaction on the instance too. Such a call now runs as a SAVEPOINT of
84
+ * the active transaction instead, so it commits or rolls back with it and
85
+ * its own failure undoes only its own part.
86
+ */
87
+ private readonly transactionScope;
88
+ /**
89
+ * Creates a new SQLite adapter instance.
90
+ *
91
+ * @param config - Adapter configuration
92
+ */
93
+ constructor(config: SqliteAdapterConfig);
94
+ /**
95
+ * Connect to the SQLite database.
96
+ *
97
+ * @remarks
98
+ * This method initializes the database connection. For SQLite, this
99
+ * opens the database file or creates an in-memory database.
100
+ * Also configures WAL mode and foreign keys based on config.
101
+ *
102
+ * @throws {DatabaseError} If connection fails
103
+ */
104
+ connect(): Promise<void>;
105
+ /**
106
+ * Disconnect from the SQLite database.
107
+ *
108
+ * @remarks
109
+ * This method closes the database connection and releases resources.
110
+ */
111
+ disconnect(): Promise<void>;
112
+ /**
113
+ * Check if connected to the database.
114
+ */
115
+ isConnected(): boolean;
116
+ /**
117
+ * Get connection pool statistics.
118
+ *
119
+ * @remarks
120
+ * SQLite doesn't use connection pooling, so this returns null.
121
+ * The database is single-file with a single connection.
122
+ */
123
+ getPoolStats(): PoolStats | null;
124
+ /**
125
+ * Execute a raw SQL query.
126
+ *
127
+ * @param sql - SQL query string with $1, $2 placeholders (converted to ? for SQLite)
128
+ * @param params - Query parameters
129
+ * @returns Query results
130
+ *
131
+ * @throws {DatabaseError} If query execution fails
132
+ */
133
+ executeQuery<T = unknown>(sql: string, params?: SqlParam[]): Promise<T[]>;
134
+ /**
135
+ * Execute work within a transaction.
136
+ *
137
+ * @param work - Function containing transactional operations
138
+ * @param options - Transaction options (isolation level not fully supported in SQLite)
139
+ * @returns Result of the work function
140
+ *
141
+ * @remarks
142
+ * The adapter manages the transaction itself, because better-sqlite3's
143
+ * `db.transaction()` does not take async work: it runs `BEGIN IMMEDIATE`,
144
+ * then `COMMIT` when `work` resolves or `ROLLBACK` when it throws.
145
+ * - Top-level calls run one at a time.
146
+ * - A call made inside an open transaction's work joins it as a savepoint
147
+ * (`SAVEPOINT` / `RELEASE` / `ROLLBACK TO`).
148
+ * - Nested calls of one scope run one at a time.
149
+ * - A call made later from a savepoint that has already released joins the
150
+ * innermost scope still open.
151
+ * - Nested work started and not awaited finishes before the enclosing scope
152
+ * commits or rolls back.
153
+ *
154
+ * Note: SQLite uses DEFERRED, IMMEDIATE, or EXCLUSIVE transaction modes
155
+ * rather than isolation levels. This adapter uses IMMEDIATE.
156
+ */
157
+ /** How long a transaction waits for the connection: `pool.connectionTimeoutMs`. */
158
+ private transactionWaitMs;
159
+ transaction<T>(work: (tx: TransactionContext) => Promise<T>, _options?: TransactionOptions): Promise<T>;
160
+ /**
161
+ * Hold `effect` until the transaction enclosing this async context commits,
162
+ * or run it now when none does.
163
+ *
164
+ * The effect belongs to the scope this async context runs in, even one
165
+ * that has already released or rolled back: a service whose own
166
+ * transaction nested as a savepoint registers from its caller's scope once
167
+ * that savepoint has released, and the change is undoable for as long as
168
+ * any scope around it is. The outermost transaction runs the effect once
169
+ * its COMMIT succeeds, unless a scope between the effect's scope and the
170
+ * outermost transaction rolled back, and drops every effect on ROLLBACK or
171
+ * a failed COMMIT. A context whose outermost transaction has already
172
+ * finished is outside any transaction, so its effect runs now, unless what
173
+ * it announces was undone and it has run no transaction since.
174
+ */
175
+ override afterCommit(effect: () => unknown, onDeferredFailure?: (error: unknown) => void): Promise<void>;
176
+ /**
177
+ * `effect`, bound to the async context it is registered from.
178
+ *
179
+ * A held effect runs after the outermost COMMIT, from the code that ran the
180
+ * outermost transaction, so without this it sees that code's context rather
181
+ * than its own: whatever its caller pinned around the write is gone. That
182
+ * includes who is calling. A scope pinned for a scoped API key lost there
183
+ * leaves a hook's nested call judged by the key's owner instead of the key,
184
+ * and a person's frame lost there leaves the hook told of nobody.
185
+ *
186
+ * The adapter's own transaction scope is the one store it leaves: the
187
+ * effect runs once that transaction has finished, outside it, as an effect
188
+ * held to the outermost commit always has.
189
+ */
190
+ private inRegisteringContext;
191
+ /**
192
+ * Run the effects a committed transaction held, in order. A failure is
193
+ * reported, never thrown: the change is durable, and reporting the
194
+ * transaction as failed would invite a retry of something already done.
195
+ */
196
+ private runHeldEffects;
197
+ /** Hand a held effect's failure to its reporter, or to the adapter's log. */
198
+ private reportHeldEffectFailure;
199
+ /**
200
+ * Whether a `transaction()` call made here would join an open transaction
201
+ * as a savepoint. On SQLite it would: the connection is the only one, so a
202
+ * transaction open on it encloses whatever the async chain that opened it
203
+ * starts.
204
+ */
205
+ override inTransaction(): boolean;
206
+ /**
207
+ * Whether the calling async flow is inside a transaction that has not
208
+ * finished, judged from the transaction this flow was started inside,
209
+ * never from the connection: another request's open transaction answers
210
+ * false here, where its own `transaction()` queues behind that one.
211
+ *
212
+ * A flow started inside a transaction, even inside a savepoint that has
213
+ * since released, stays inside it until its outermost transaction has
214
+ * committed or rolled back: until then whatever it writes on the one
215
+ * connection lands in that transaction.
216
+ */
217
+ override transactionOpenInFlow(): boolean;
218
+ /**
219
+ * The scope a `transaction()` call made here nests in, or none when it
220
+ * opens a transaction of its own.
221
+ *
222
+ * A call made later from inside a savepoint that has since released runs
223
+ * inside the innermost scope open on the connection. Queued on an enclosing
224
+ * scope, or on the instance, it would wait behind the scope running there,
225
+ * which may be the one awaiting it. Savepoints on one connection form a
226
+ * stack, so whatever opens now is inside that innermost scope anyway; when
227
+ * none is open the call queues on the instance.
228
+ *
229
+ * The innermost open scope need not be related to the call. When it is a
230
+ * sibling savepoint that later rolls back, the call's write rolls back with
231
+ * it, although the call itself already resolved. Waiting for an unrelated
232
+ * scope instead could wait on the very scope that awaits the call.
233
+ */
234
+ private nestingScope;
235
+ /**
236
+ * Run `work` as a savepoint of the active transaction: released when it
237
+ * resolves, rolled back to when it throws.
238
+ */
239
+ private runSavepoint;
240
+ /**
241
+ * Inner transaction body. Kept private so callers always go through
242
+ * the serialized `transaction()` queue above and the BEGIN/COMMIT
243
+ * pair is never invoked outside of it.
244
+ */
245
+ private runTransaction;
246
+ /**
247
+ * Get SQLite database capabilities.
248
+ *
249
+ * @remarks
250
+ * SQLite capabilities:
251
+ * - JSON support (not JSONB)
252
+ * - No arrays
253
+ * - No native ILIKE
254
+ * - RETURNING clause (3.35+)
255
+ * - Savepoints supported
256
+ * - ON CONFLICT supported
257
+ */
258
+ getCapabilities(): DatabaseCapabilities;
259
+ /**
260
+ * Override insertMany for bulk insert optimization.
261
+ *
262
+ * @remarks
263
+ * Uses a single multi-row INSERT statement for better performance.
264
+ */
265
+ override insertMany<T = unknown>(table: string, data: Record<string, unknown>[], options?: InsertOptions): Promise<T[]>;
266
+ /**
267
+ * Ensures database is connected and returns it.
268
+ *
269
+ * @throws {DatabaseError} If not connected
270
+ */
271
+ private ensureDb;
272
+ /**
273
+ * Return the typed Drizzle instance for SQLite.
274
+ * Guarded for server-only usage and requires an active connection.
275
+ *
276
+ * @param schema - Optional schema for relational queries (db.query.*)
277
+ * @returns Drizzle ORM instance wrapping the better-sqlite3 connection
278
+ * @throws {Error} If called in browser or not connected
279
+ */
280
+ getDrizzle<T = BetterSQLite3Database<AnyRelations>>(relations?: AnyRelations): T;
281
+ /**
282
+ * Convert $1, $2 placeholders to ? for better-sqlite3.
283
+ *
284
+ * @param sql - SQL with PostgreSQL-style placeholders
285
+ * @returns SQL with ? placeholders
286
+ */
287
+ private convertPlaceholders;
288
+ /**
289
+ * Creates a TransactionContext for the given database connection.
290
+ */
291
+ /** A table-level `primaryKey({ columns })`, read through the SQLite table config. */
292
+ protected override compositePrimaryKey(tableObj: Record<string, unknown>): object[];
293
+ private createTransactionContext;
294
+ /**
295
+ * Classifies a SQLite error into a DatabaseError.
296
+ *
297
+ * @param error - Original error from better-sqlite3
298
+ * @param sql - SQL statement that caused the error (optional)
299
+ * @returns DatabaseError with proper classification
300
+ */
301
+ protected override classifyError(error: unknown, sql?: string): DatabaseError;
238
302
  }
239
303
  /**
240
304
  * Create a SQLite database adapter.
@@ -268,7 +332,7 @@ declare class SqliteAdapter extends DrizzleAdapter {
268
332
  * await adapter.connect();
269
333
  * ```
270
334
  */
271
- declare function createSqliteAdapter(config: SqliteAdapterConfig): SqliteAdapter;
335
+ export declare function createSqliteAdapter(config: SqliteAdapterConfig): SqliteAdapter;
272
336
  /**
273
337
  * Type guard to check if a value is a SqliteAdapter.
274
338
  *
@@ -283,6 +347,6 @@ declare function createSqliteAdapter(config: SqliteAdapterConfig): SqliteAdapter
283
347
  * }
284
348
  * ```
285
349
  */
286
- declare function isSqliteAdapter(value: unknown): value is SqliteAdapter;
287
-
288
- export { SqliteAdapter, VERSION, createSqliteAdapter, isSqliteAdapter };
350
+ export declare function isSqliteAdapter(value: unknown): value is SqliteAdapter;
351
+ export type { AdapterLogger, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, SelectOptions, SqlParam, SqliteAdapterConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator };
352
+ //# sourceMappingURL=index.d.cts.map