@beignet/provider-db-drizzle 0.0.9

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +1046 -0
  3. package/dist/mysql/index.d.ts +254 -0
  4. package/dist/mysql/index.d.ts.map +1 -0
  5. package/dist/mysql/index.js +348 -0
  6. package/dist/mysql/index.js.map +1 -0
  7. package/dist/postgres/index.d.ts +240 -0
  8. package/dist/postgres/index.d.ts.map +1 -0
  9. package/dist/postgres/index.js +296 -0
  10. package/dist/postgres/index.js.map +1 -0
  11. package/dist/shared/idempotency-core.d.ts +71 -0
  12. package/dist/shared/idempotency-core.d.ts.map +1 -0
  13. package/dist/shared/idempotency-core.js +169 -0
  14. package/dist/shared/idempotency-core.js.map +1 -0
  15. package/dist/shared/identifiers.d.ts +20 -0
  16. package/dist/shared/identifiers.d.ts.map +1 -0
  17. package/dist/shared/identifiers.js +27 -0
  18. package/dist/shared/identifiers.js.map +1 -0
  19. package/dist/shared/instrumentation.d.ts +19 -0
  20. package/dist/shared/instrumentation.d.ts.map +1 -0
  21. package/dist/shared/instrumentation.js +41 -0
  22. package/dist/shared/instrumentation.js.map +1 -0
  23. package/dist/shared/outbox-core.d.ts +76 -0
  24. package/dist/shared/outbox-core.d.ts.map +1 -0
  25. package/dist/shared/outbox-core.js +193 -0
  26. package/dist/shared/outbox-core.js.map +1 -0
  27. package/dist/shared/rows.d.ts +84 -0
  28. package/dist/shared/rows.d.ts.map +1 -0
  29. package/dist/shared/rows.js +128 -0
  30. package/dist/shared/rows.js.map +1 -0
  31. package/dist/sqlite/index.d.ts +235 -0
  32. package/dist/sqlite/index.d.ts.map +1 -0
  33. package/dist/sqlite/index.js +293 -0
  34. package/dist/sqlite/index.js.map +1 -0
  35. package/package.json +173 -0
  36. package/src/mysql/index.ts +627 -0
  37. package/src/postgres/index.ts +572 -0
  38. package/src/shared/idempotency-core.ts +280 -0
  39. package/src/shared/identifiers.ts +28 -0
  40. package/src/shared/instrumentation.ts +49 -0
  41. package/src/shared/outbox-core.ts +322 -0
  42. package/src/shared/rows.ts +197 -0
  43. package/src/sqlite/index.ts +547 -0
@@ -0,0 +1,547 @@
1
+ /**
2
+ * @beignet/provider-db-drizzle/sqlite
3
+ *
4
+ * Drizzle ORM SQLite provider, backed by libSQL, that creates a typed
5
+ * database port. Works with local `file:` SQLite databases and with Turso's
6
+ * hosted libSQL service.
7
+ *
8
+ * Configuration:
9
+ * - SQLITE_DB_URL: libSQL database URL (required)
10
+ * - SQLITE_DB_AUTH_TOKEN: auth token for remote connections such as Turso
11
+ * (optional for local dev)
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import * as schema from "@/db/schema";
16
+ * import { createDrizzleSqliteProvider } from "@beignet/provider-db-drizzle/sqlite";
17
+ *
18
+ * export const drizzleSqliteProvider = createDrizzleSqliteProvider({ schema });
19
+ *
20
+ * // In createNextServer:
21
+ * const server = await createNextServer({
22
+ * ports: basePorts,
23
+ * providers: [drizzleSqliteProvider],
24
+ * // ...
25
+ * });
26
+ *
27
+ * // In infra:
28
+ * const todos = createDrizzleTodoRepository(ctx.ports.db.db);
29
+ * ```
30
+ */
31
+
32
+ import type { IdempotencyPort } from "@beignet/core/idempotency";
33
+ import type { OutboxPort } from "@beignet/core/outbox";
34
+ import {
35
+ type BufferedDomainEventRecorder,
36
+ createDomainEventRecorder,
37
+ type EventBusPort,
38
+ type UnitOfWorkCallback,
39
+ type UnitOfWorkPort,
40
+ } from "@beignet/core/ports";
41
+ import {
42
+ createProvider,
43
+ createProviderInstrumentation,
44
+ } from "@beignet/core/providers";
45
+ import { type Client, createClient } from "@libsql/client";
46
+ import { type ExtractTablesWithRelations, type SQL, sql } from "drizzle-orm";
47
+ import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";
48
+ import type { LibSQLTransaction } from "drizzle-orm/libsql/session";
49
+ import type { SQLiteTransactionConfig } from "drizzle-orm/sqlite-core";
50
+ import { z } from "zod";
51
+ import {
52
+ createIdempotencyPortCore,
53
+ formatIdempotencyMutationErrorMessage,
54
+ type IdempotencySqlExecutor,
55
+ } from "../shared/idempotency-core.js";
56
+ import { quoteIdentifier } from "../shared/identifiers.js";
57
+ import { createDbQueryLogger } from "../shared/instrumentation.js";
58
+ import {
59
+ createOutboxPortCore,
60
+ type OutboxSqlExecutor,
61
+ type SqlExecutorBase,
62
+ } from "../shared/outbox-core.js";
63
+
64
+ /**
65
+ * Typed database port interface.
66
+ * Exposes a typed Drizzle database instance for your schema.
67
+ *
68
+ * @template TSchema - The Drizzle schema type (e.g., `typeof schema`)
69
+ */
70
+ export interface DbPort<
71
+ TSchema extends Record<string, unknown> = Record<string, unknown>,
72
+ > {
73
+ /**
74
+ * The typed Drizzle database instance.
75
+ * Use this to query your database with full type safety.
76
+ */
77
+ db: LibSQLDatabase<TSchema>;
78
+
79
+ /**
80
+ * The underlying libSQL client instance.
81
+ * Use this for advanced operations not covered by Drizzle ORM.
82
+ */
83
+ client: Client;
84
+ }
85
+
86
+ /**
87
+ * Drizzle database or transaction client accepted by repository factories.
88
+ */
89
+ export type DrizzleSqliteDatabase<
90
+ TSchema extends Record<string, unknown> = Record<string, unknown>,
91
+ > =
92
+ | LibSQLDatabase<TSchema>
93
+ | LibSQLTransaction<TSchema, ExtractTablesWithRelations<TSchema>>;
94
+
95
+ /**
96
+ * Drizzle transaction client passed to Unit of Work repository factories.
97
+ */
98
+ export type DrizzleSqliteTransaction<
99
+ TSchema extends Record<string, unknown> = Record<string, unknown>,
100
+ > = LibSQLTransaction<TSchema, ExtractTablesWithRelations<TSchema>>;
101
+
102
+ /**
103
+ * Options for creating a Drizzle SQLite-backed Unit of Work port.
104
+ */
105
+ export interface DrizzleSqliteUnitOfWorkOptions<
106
+ TSchema extends Record<string, unknown>,
107
+ TxPorts,
108
+ > {
109
+ /**
110
+ * The root Drizzle database instance from `ctx.ports.db.db`.
111
+ */
112
+ db: LibSQLDatabase<TSchema>;
113
+
114
+ /**
115
+ * Create transaction-scoped ports from the Drizzle transaction client.
116
+ *
117
+ * The event recorder is transaction-local. Record domain events inside the
118
+ * callback and pass `eventBus` to publish them after the database commit.
119
+ */
120
+ createTransactionPorts: (
121
+ db: DrizzleSqliteTransaction<TSchema>,
122
+ events: BufferedDomainEventRecorder,
123
+ ) => TxPorts;
124
+
125
+ /**
126
+ * Optional event bus used to flush recorded domain events after commit.
127
+ */
128
+ eventBus?: EventBusPort;
129
+
130
+ /**
131
+ * Optional Drizzle transaction configuration.
132
+ */
133
+ transactionConfig?: SQLiteTransactionConfig;
134
+ }
135
+
136
+ /**
137
+ * Create a Unit of Work port backed by Drizzle's libSQL transaction API.
138
+ *
139
+ * Beignet does not own your repository interfaces. This helper only
140
+ * provides the transaction boundary and post-commit event flushing; your app
141
+ * decides which transaction-scoped ports to create.
142
+ */
143
+ export function createDrizzleSqliteUnitOfWork<
144
+ TSchema extends Record<string, unknown>,
145
+ TxPorts,
146
+ >(
147
+ options: DrizzleSqliteUnitOfWorkOptions<TSchema, TxPorts>,
148
+ ): UnitOfWorkPort<TxPorts> {
149
+ return {
150
+ async transaction<Result>(
151
+ work: UnitOfWorkCallback<TxPorts, Result>,
152
+ ): Promise<Result> {
153
+ const events = createDomainEventRecorder();
154
+
155
+ const result = await options.db.transaction(async (tx) => {
156
+ const txPorts = options.createTransactionPorts(
157
+ tx as DrizzleSqliteTransaction<TSchema>,
158
+ events,
159
+ );
160
+ return work(txPorts);
161
+ }, options.transactionConfig);
162
+
163
+ if (options.eventBus) {
164
+ await events.flush(options.eventBus);
165
+ }
166
+
167
+ return result;
168
+ },
169
+ };
170
+ }
171
+
172
+ /**
173
+ * Options for a Drizzle SQLite-backed outbox port.
174
+ */
175
+ export interface DrizzleSqliteOutboxOptions {
176
+ /**
177
+ * Table that stores outbox messages.
178
+ *
179
+ * Default: "outbox_messages".
180
+ */
181
+ tableName?: string;
182
+
183
+ /**
184
+ * Clock used by tests and deterministic environments.
185
+ */
186
+ now?: () => Date;
187
+ }
188
+
189
+ function readRowsAffected(result: unknown): number | undefined {
190
+ const rowsAffected = (result as { rowsAffected?: unknown }).rowsAffected;
191
+ return typeof rowsAffected === "number" ? rowsAffected : undefined;
192
+ }
193
+
194
+ /**
195
+ * SQLite executor implementing both the outbox and idempotency seams of the
196
+ * shared database cores.
197
+ */
198
+ interface DrizzleSqliteSqlExecutor
199
+ extends SqlExecutorBase<DrizzleSqliteSqlExecutor> {
200
+ claimLockSuffix: SQL;
201
+ insertPrefix: SQL;
202
+ insertConflictSuffix: SQL;
203
+ }
204
+
205
+ function createSqliteExecutor<TSchema extends Record<string, unknown>>(
206
+ db: DrizzleSqliteDatabase<TSchema>,
207
+ table: SQL,
208
+ ): DrizzleSqliteSqlExecutor {
209
+ return {
210
+ table,
211
+ // SQLite serializes writers; no row-locking clause exists or is needed.
212
+ claimLockSuffix: sql.raw(""),
213
+ insertPrefix: sql.raw("insert or ignore into"),
214
+ insertConflictSuffix: sql.raw(""),
215
+
216
+ async rows(query) {
217
+ return db.all<Record<string, unknown>>(query);
218
+ },
219
+
220
+ async row(query) {
221
+ return db.get<Record<string, unknown> | undefined>(query);
222
+ },
223
+
224
+ async run(query) {
225
+ return readRowsAffected(await db.run(query));
226
+ },
227
+
228
+ withTransaction(fn) {
229
+ if ("transaction" in db && typeof db.transaction === "function") {
230
+ return db.transaction((tx) =>
231
+ fn(createSqliteExecutor(tx as DrizzleSqliteDatabase<TSchema>, table)),
232
+ );
233
+ }
234
+
235
+ return undefined;
236
+ },
237
+ };
238
+ }
239
+
240
+ /**
241
+ * Create idempotent SQL statements for the Drizzle SQLite outbox table.
242
+ *
243
+ * Run these during migrations or local setup before using
244
+ * `createDrizzleSqliteOutboxPort(...)`.
245
+ */
246
+ export function createDrizzleSqliteOutboxSetupStatements(
247
+ options: DrizzleSqliteOutboxOptions = {},
248
+ ): readonly string[] {
249
+ const tableName = options.tableName ?? "outbox_messages";
250
+ const table = quoteIdentifier(tableName, '"');
251
+ const indexPrefix = tableName.replaceAll(/[^A-Za-z0-9_]/g, "_");
252
+
253
+ return [
254
+ `CREATE TABLE IF NOT EXISTS ${table} (
255
+ id text PRIMARY KEY NOT NULL,
256
+ kind text NOT NULL,
257
+ name text NOT NULL,
258
+ payload_json text NOT NULL,
259
+ status text NOT NULL,
260
+ attempts integer DEFAULT 0 NOT NULL,
261
+ max_attempts integer DEFAULT 3 NOT NULL,
262
+ available_at text NOT NULL,
263
+ claimed_at text,
264
+ locked_until text,
265
+ claim_token text,
266
+ delivered_at text,
267
+ last_error_json text,
268
+ created_at text NOT NULL,
269
+ updated_at text NOT NULL
270
+ )`,
271
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${indexPrefix}_available_idx`, '"')} ON ${table} (status, available_at)`,
272
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${indexPrefix}_locked_idx`, '"')} ON ${table} (status, locked_until)`,
273
+ ];
274
+ }
275
+
276
+ /**
277
+ * Create a Beignet outbox port backed by a Drizzle SQLite database.
278
+ *
279
+ * Claiming uses a claim-token lease so concurrent workers can safely compete
280
+ * for eligible messages.
281
+ */
282
+ export function createDrizzleSqliteOutboxPort<
283
+ TSchema extends Record<string, unknown>,
284
+ >(
285
+ db: DrizzleSqliteDatabase<TSchema>,
286
+ adapterOptions: DrizzleSqliteOutboxOptions = {},
287
+ ): OutboxPort {
288
+ const table = sql.raw(
289
+ quoteIdentifier(adapterOptions.tableName ?? "outbox_messages", '"'),
290
+ );
291
+ const executor: OutboxSqlExecutor = createSqliteExecutor(db, table);
292
+
293
+ return createOutboxPortCore(executor, { now: adapterOptions.now });
294
+ }
295
+
296
+ /**
297
+ * Options for a Drizzle SQLite-backed idempotency port.
298
+ */
299
+ export interface DrizzleSqliteIdempotencyOptions {
300
+ /**
301
+ * Table that stores idempotency records.
302
+ *
303
+ * Default: "idempotency_records".
304
+ */
305
+ tableName?: string;
306
+
307
+ /**
308
+ * Clock used by tests and deterministic environments.
309
+ */
310
+ now?: () => Date;
311
+ }
312
+
313
+ /**
314
+ * Error thrown when `complete(...)` or `fail(...)` does not match an
315
+ * in-progress idempotency reservation with the provided fingerprint.
316
+ *
317
+ * This usually signals a workflow bug: the reservation was never made, was
318
+ * already completed or released, expired and was cleaned up, or the caller
319
+ * passed a different fingerprint than the one used to reserve.
320
+ */
321
+ export class DrizzleSqliteIdempotencyMutationError extends Error {
322
+ readonly action: "complete" | "fail";
323
+ readonly namespace: string;
324
+ readonly key: string;
325
+ readonly scopeKey: string;
326
+
327
+ constructor(args: {
328
+ action: "complete" | "fail";
329
+ namespace: string;
330
+ key: string;
331
+ scopeKey: string;
332
+ }) {
333
+ super(formatIdempotencyMutationErrorMessage(args));
334
+ this.name = "DrizzleSqliteIdempotencyMutationError";
335
+ this.action = args.action;
336
+ this.namespace = args.namespace;
337
+ this.key = args.key;
338
+ this.scopeKey = args.scopeKey;
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Create idempotent SQL statements for the Drizzle SQLite idempotency table.
344
+ *
345
+ * Run these during migrations or local setup before using
346
+ * `createDrizzleSqliteIdempotencyPort(...)`.
347
+ */
348
+ export function createDrizzleSqliteIdempotencySetupStatements(
349
+ options: DrizzleSqliteIdempotencyOptions = {},
350
+ ): readonly string[] {
351
+ const tableName = options.tableName ?? "idempotency_records";
352
+ const table = quoteIdentifier(tableName, '"');
353
+ const indexPrefix = tableName.replaceAll(/[^A-Za-z0-9_]/g, "_");
354
+
355
+ return [
356
+ `CREATE TABLE IF NOT EXISTS ${table} (
357
+ storage_key text PRIMARY KEY NOT NULL,
358
+ namespace text NOT NULL,
359
+ idempotency_key text NOT NULL,
360
+ scope_key text NOT NULL,
361
+ fingerprint text NOT NULL,
362
+ status text NOT NULL,
363
+ result_json text,
364
+ reserved_at text NOT NULL,
365
+ completed_at text,
366
+ expires_at text,
367
+ updated_at text NOT NULL
368
+ )`,
369
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${indexPrefix}_lookup_idx`, '"')} ON ${table} (namespace, scope_key, idempotency_key)`,
370
+ `CREATE INDEX IF NOT EXISTS ${quoteIdentifier(`${indexPrefix}_expires_idx`, '"')} ON ${table} (expires_at)`,
371
+ ];
372
+ }
373
+
374
+ /**
375
+ * Create a Beignet idempotency port backed by a Drizzle SQLite database.
376
+ *
377
+ * The port accepts both the root Drizzle database and transaction clients, so
378
+ * applications can expose root idempotency for ordinary retry-safe commands and
379
+ * transaction-scoped idempotency from Unit of Work.
380
+ */
381
+ export function createDrizzleSqliteIdempotencyPort<
382
+ TSchema extends Record<string, unknown>,
383
+ >(
384
+ db: DrizzleSqliteDatabase<TSchema>,
385
+ adapterOptions: DrizzleSqliteIdempotencyOptions = {},
386
+ ): IdempotencyPort {
387
+ const table = sql.raw(
388
+ quoteIdentifier(adapterOptions.tableName ?? "idempotency_records", '"'),
389
+ );
390
+ const executor: IdempotencySqlExecutor = createSqliteExecutor(db, table);
391
+
392
+ return createIdempotencyPortCore(
393
+ executor,
394
+ { now: adapterOptions.now },
395
+ DrizzleSqliteIdempotencyMutationError,
396
+ );
397
+ }
398
+
399
+ const SQLITE_DB_URL_PREFIXES = [
400
+ "libsql://",
401
+ "file:",
402
+ "http://",
403
+ "https://",
404
+ "ws://",
405
+ "wss://",
406
+ ] as const;
407
+
408
+ /**
409
+ * Configuration schema for the Drizzle SQLite provider.
410
+ * Validates environment variables with SQLITE_ prefix.
411
+ */
412
+ const SqliteConfigSchema = z.object({
413
+ /**
414
+ * libSQL database URL.
415
+ * Accepts every URL scheme @libsql/client accepts: "libsql://" and "file:"
416
+ * plus "http(s)://" and "ws(s)://" for local sqld instances.
417
+ * Example: "libsql://<org>-<db>.turso.io" or "file:local.db"
418
+ */
419
+ DB_URL: z
420
+ .string()
421
+ .min(1)
422
+ .refine(
423
+ (val) => SQLITE_DB_URL_PREFIXES.some((prefix) => val.startsWith(prefix)),
424
+ {
425
+ message:
426
+ 'DB_URL must start with "libsql://", "file:", "http://", "https://", "ws://", or "wss://" (e.g., "libsql://<org>-<db>.turso.io", "file:local.db", or "http://127.0.0.1:8080")',
427
+ },
428
+ ),
429
+
430
+ /**
431
+ * Auth token for remote libSQL connections (optional for local dev).
432
+ * Required when connecting to Turso's hosted libSQL service.
433
+ */
434
+ DB_AUTH_TOKEN: z.string().optional(),
435
+ });
436
+
437
+ /**
438
+ * SQLite provider config loaded from `SQLITE_*` env vars.
439
+ */
440
+ export type SqliteConfig = z.infer<typeof SqliteConfigSchema>;
441
+
442
+ /**
443
+ * Options for creating a Drizzle SQLite provider.
444
+ *
445
+ * @template TSchema - The Drizzle schema type
446
+ */
447
+ export interface DrizzleSqliteProviderOptions<
448
+ TSchema extends Record<string, unknown>,
449
+ PortName extends string = "db",
450
+ > {
451
+ /**
452
+ * The Drizzle schema object (e.g. `import * as schema from '@/db/schema'`).
453
+ * This schema is used to create a typed Drizzle database instance.
454
+ */
455
+ schema: TSchema;
456
+
457
+ /**
458
+ * Optional port name. Defaults to "db".
459
+ * Renames the contributed port. The provider always reads its connection
460
+ * from `SQLITE_DB_URL`; for a second database, wire an app-owned provider
461
+ * with its own env prefix instead.
462
+ */
463
+ portName?: PortName;
464
+ }
465
+
466
+ /**
467
+ * Create a Drizzle SQLite provider factory.
468
+ *
469
+ * This factory creates a service provider that:
470
+ * - Uses libSQL via @libsql/client, for local `file:` SQLite databases and
471
+ * Turso's hosted libSQL service
472
+ * - Uses Drizzle ORM via drizzle-orm/libsql
473
+ * - Exposes a typed DbPort<TSchema> on ports
474
+ * - Uses SQLITE_-prefixed env vars for connection config
475
+ *
476
+ * @template TSchema - The Drizzle schema type (inferred from the schema parameter)
477
+ * @param options - Configuration options including the schema
478
+ * @returns A service provider that can be used with createNextServer
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * import * as schema from "@/db/schema";
483
+ * import { createDrizzleSqliteProvider } from "@beignet/provider-db-drizzle/sqlite";
484
+ *
485
+ * export const drizzleSqliteProvider = createDrizzleSqliteProvider({ schema });
486
+ * ```
487
+ */
488
+ export function createDrizzleSqliteProvider<
489
+ TSchema extends Record<string, unknown>,
490
+ PortName extends string = "db",
491
+ >(options: DrizzleSqliteProviderOptions<TSchema, PortName>) {
492
+ const { schema, portName = "db" } = options;
493
+
494
+ return createProvider({
495
+ name: "drizzle-sqlite",
496
+
497
+ config: {
498
+ schema: SqliteConfigSchema,
499
+ envPrefix: "SQLITE_",
500
+ },
501
+
502
+ async setup({ ports, config }) {
503
+ if (!config) {
504
+ throw new Error(
505
+ "[drizzleSqliteProvider] Missing config. Set SQLITE_DB_URL (and optional SQLITE_DB_AUTH_TOKEN).",
506
+ );
507
+ }
508
+
509
+ // 1. Create libSQL client
510
+ const client: Client = createClient({
511
+ url: config.DB_URL,
512
+ authToken: config.DB_AUTH_TOKEN,
513
+ });
514
+
515
+ const instrumentation = createProviderInstrumentation(ports, {
516
+ providerName: "drizzle-sqlite",
517
+ watcher: "db",
518
+ });
519
+
520
+ const logger = createDbQueryLogger(instrumentation, portName);
521
+
522
+ // 2. Create typed Drizzle instance
523
+ const db: LibSQLDatabase<TSchema> = logger
524
+ ? drizzle(client, { schema, logger })
525
+ : drizzle(client, { schema });
526
+
527
+ // 3. Build a typed DbPort
528
+ const dbPort: DbPort<TSchema> = { db, client };
529
+
530
+ return {
531
+ ports: { [portName]: dbPort } as Record<PortName, DbPort<TSchema>>,
532
+ async stop() {
533
+ // Gracefully close the database connection
534
+ try {
535
+ await dbPort.client.close();
536
+ } catch (error) {
537
+ // Log error but don't throw - we're shutting down anyway
538
+ console.error(
539
+ "[drizzleSqliteProvider] Error closing database connection:",
540
+ error,
541
+ );
542
+ }
543
+ },
544
+ };
545
+ },
546
+ });
547
+ }