Open History to see the last commit
1import { NodeFileSystem } from "@effect/platform-node"
2import { SqliteClient } from "@effect/sql-sqlite-node"
3import { assert, describe, it } from "@effect/vitest"
4import { Cause, Deferred, Duration, Effect, Exit, Fiber, FileSystem, Option, References } from "effect"
5import { Reactivity } from "effect/reactivity"
6import { ConnectionError, SqlError } from "effect/sql/SqlError"
7import { TestClock } from "effect/testing"
8import { DatabaseSync } from "node:sqlite"
9
10const makeClient = Effect.gen(function*() {
11 const fs = yield* FileSystem.FileSystem
12 const dir = yield* fs.makeTempDirectoryScoped()
13 return yield* SqliteClient.make({
14 filename: dir + "/test.db"
15 })
16}).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer]))
17
18const makeClients = Effect.gen(function*() {
19 const fs = yield* FileSystem.FileSystem
20 const dir = yield* fs.makeTempDirectoryScoped()
21 const filename = dir + "/test.db"
22 return {
23 client: yield* SqliteClient.make({ filename }),
24 contender: yield* SqliteClient.make({ filename })
25 }
26}).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer]))
27
28const makeLockedDatabase = Effect.gen(function*() {
29 const fs = yield* FileSystem.FileSystem
30 const dir = yield* fs.makeTempDirectoryScoped()
31 const filename = dir + "/test.db"
32 const lock = yield* Effect.acquireRelease(
33 Effect.sync(() => new DatabaseSync(filename)),
34 (db) => Effect.sync(() => db.close())
35 )
36 lock.exec("BEGIN IMMEDIATE")
37 return { filename, unlock: () => lock.exec("ROLLBACK") }
38}).pipe(Effect.provide(NodeFileSystem.layer))
39
40// node:sqlite blocks the Vitest worker; concurrent tests would share a running
41// timeout while waiting for each other's queries.
42describe("Client", { concurrent: false }, () => {
43 it.effect("should disable query-only transforms", () =>
44 Effect.gen(function*() {
45 const sql = yield* SqliteClient.make({
46 filename: ":memory:",
47 transformQueryNames: (name) => name === "firstName" ? "first_name" : name
48 }).pipe(Effect.provide(Reactivity.layer))
49 const withoutTransforms = sql.withoutTransforms()
50 yield* sql`CREATE TABLE test (first_name TEXT, "firstName" TEXT)`
51 yield* sql`INSERT INTO test (first_name, "firstName") VALUES ('John', 'Jane')`
52
53 const select = withoutTransforms`SELECT ${withoutTransforms("firstName")} FROM test`
54 assert.deepStrictEqual(yield* select, [{ firstName: "Jane" }])
55 }))
56
57 it.effect("releases completed nested savepoints", () =>
58 Effect.gen(function*() {
59 const sql = yield* makeClient
60 yield* sql`CREATE TABLE savepoint_release (value INTEGER)`
61 yield* sql.withTransaction(Effect.gen(function*() {
62 for (const rollback of [false, true]) {
63 yield* sql.withTransaction(
64 sql`INSERT INTO savepoint_release VALUES (1)`.pipe(
65 Effect.andThen(rollback ? Effect.fail("rollback") : Effect.void)
66 )
67 ).pipe(Effect.ignore)
68 const error = yield* sql`RELEASE SAVEPOINT effect_sql_1`.unprepared.pipe(Effect.flip)
69 assert.strictEqual(error._tag, "SqlError")
70 }
71 }))
72 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
73 const error = yield* sql.withTransaction(
74 sql.withTransaction(sql`INSERT INTO savepoint_release VALUES (2)`).pipe(
75 Effect.andThen(Effect.fail("outer rollback"))
76 )
77 ).pipe(Effect.flip)
78 assert.strictEqual(error, "outer rollback")
79 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
80 }))
81
82 it.effect("should work", () =>
83 Effect.gen(function*() {
84 const sql = yield* makeClient
85 let response
86 response = yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
87 assert.deepStrictEqual(response, [])
88 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`
89 assert.deepStrictEqual(response, [])
90 response = yield* sql`SELECT * FROM test`
91 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
92 response = yield* sql`SELECT * FROM test`.valuesUnprepared
93 assert.deepStrictEqual(response, [[1, "hello"]])
94 response = yield* sql`INSERT INTO test (name) VALUES ('world')`.pipe(sql.withTransaction)
95 assert.deepStrictEqual(response, [])
96 response = yield* sql`SELECT * FROM test`
97 assert.deepStrictEqual(response, [
98 { id: 1, name: "hello" },
99 { id: 2, name: "world" }
100 ])
101 response = yield* sql`INSERT INTO test (name) VALUES ('unprepared')`.valuesUnprepared
102 assert.deepStrictEqual(response, [])
103 assert.deepStrictEqual(yield* sql`SELECT * FROM test WHERE id = 3`, [{ id: 3, name: "unprepared" }])
104 }))
105
106 it.effect.each(["rows", "values"] as const)(
107 "returns cached INSERT %s across count_changes OFF → ON → OFF",
108 (mode) =>
109 Effect.gen(function*() {
110 const sql = yield* makeClient
111 yield* sql`CREATE TABLE count_changes (value INTEGER)`
112 yield* sql`PRAGMA count_changes = OFF`
113 const insert = sql`INSERT INTO count_changes VALUES (1)`
114 const execute = mode === "values" ? insert.values : insert
115
116 assert.deepStrictEqual(yield* execute, [])
117 yield* sql`PRAGMA count_changes = ON`
118 // Node may omit fields after recompilation; check only the row count.
119 assert.lengthOf(yield* execute, 1)
120 yield* sql`PRAGMA count_changes = OFF`
121 assert.deepStrictEqual(yield* execute, [])
122 assert.deepStrictEqual(yield* sql`SELECT COUNT(*) AS count FROM count_changes`, [{ count: 3 }])
123 })
124 )
125
126 it.effect.each(["rows", "values"] as const)(
127 "retries %s queries after a missing table is created",
128 (mode) =>
129 Effect.gen(function*() {
130 const sql = yield* makeClient
131 const select = sql`SELECT value FROM created_later`
132 const execute: Effect.Effect<ReadonlyArray<unknown>, SqlError> = mode === "values" ? select.values : select
133
134 const error = yield* Effect.flip(execute)
135 assert.strictEqual(error._tag, "SqlError")
136 yield* sql`CREATE TABLE created_later (value INTEGER)`
137 yield* sql`INSERT INTO created_later VALUES (1)`
138
139 assert.deepStrictEqual(yield* execute, mode === "values" ? [[1]] : [{ value: 1 }])
140 })
141 )
142
143 it.effect("should work with raw", () =>
144 Effect.gen(function*() {
145 const sql = yield* makeClient
146 let response
147 response = yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`.raw
148 assert.deepStrictEqual(response, { changes: 0, lastInsertRowid: 0 })
149 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`.raw
150 assert.deepStrictEqual(response, { changes: 1, lastInsertRowid: 1 })
151 response = yield* sql`SELECT * FROM test`.raw
152 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
153 response = yield* sql`INSERT INTO test (name) VALUES ('world')`.raw.pipe(sql.withTransaction)
154 assert.deepStrictEqual(response, { changes: 1, lastInsertRowid: 2 })
155 response = yield* sql`SELECT * FROM test`
156 assert.deepStrictEqual(response, [
157 { id: 1, name: "hello" },
158 { id: 2, name: "world" }
159 ])
160 }))
161
162 for (const mode of ["unprepared", "valuesUnprepared"] as const) {
163 it.effect(`captures ${mode} preparation errors`, () =>
164 Effect.gen(function*() {
165 const sql = yield* makeClient
166 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
167
168 const statement = sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
169 const execution = mode === "unprepared"
170 ? Effect.as(statement.unprepared, false)
171 : Effect.as(statement.valuesUnprepared, false)
172 const recovered = yield* execution.pipe(Effect.catchTag("SqlError", () => Effect.succeed(true)))
173
174 assert.isTrue(recovered)
175 }))
176 }
177
178 it.effect("withTransaction", () =>
179 Effect.gen(function*() {
180 const sql = yield* makeClient
181 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
182 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
183 const rows = yield* sql`SELECT * FROM test`
184 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
185 }))
186
187 it.effect("keeps a fiber that outlives its transaction out of another transaction", () =>
188 Effect.gen(function*() {
189 const sql = yield* makeClient
190 yield* sql`CREATE TABLE t (who TEXT)`
191 const go = yield* Deferred.make<void>()
192 const done = yield* Deferred.make<void>()
193 const idle = yield* Deferred.make<void>()
194
195 const stale = yield* sql.withTransaction(Effect.forkChild(
196 Effect.all([
197 Effect.andThen(Deferred.await(go), Effect.flip(sql`INSERT INTO t VALUES ('stale fiber')`)).pipe(
198 Effect.ensuring(Deferred.succeed(done, undefined))
199 ),
200 // On an idle connection, a stale SAVEPOINT would start a transaction and block the next BEGIN.
201 Effect.andThen(Deferred.await(idle), Effect.flip(sql.withTransaction(Effect.void)))
202 ])
203 ))
204 const other = yield* Effect.forkChild(Effect.exit(sql.withTransaction(Effect.gen(function*() {
205 yield* sql`INSERT INTO t VALUES ('other transaction')`
206 yield* Deferred.succeed(go, undefined)
207 yield* Deferred.await(done)
208 return yield* Effect.fail("rollback")
209 }))))
210
211 yield* Fiber.join(other)
212 yield* Deferred.succeed(idle, undefined)
213 const errors = yield* Fiber.join(stale)
214 for (const error of errors) {
215 assert.deepStrictEqual(
216 [error.reason._tag, error.reason.message, error.isRetryable],
217 ["UnknownError", "SqlClient: the transaction has already ended", false]
218 )
219 }
220 assert.deepStrictEqual(yield* sql`SELECT who FROM t`, [])
221 // The connection is still usable for new transactions.
222 yield* sql.withTransaction(sql`INSERT INTO t VALUES ('after')`)
223 assert.deepStrictEqual(yield* sql`SELECT who FROM t`, [{ who: "after" }])
224 }))
225
226 it.effect.each(["ABORT", "ROLLBACK", "nested ROLLBACK"] as const)(
227 "preserves a typed constraint failure and reuses the connection after %s",
228 (mode) =>
229 Effect.gen(function*() {
230 const sql = yield* SqliteClient.make({ filename: ":memory:" }).pipe(Effect.provide(Reactivity.layer))
231 yield* sql`CREATE TABLE items (id INTEGER PRIMARY KEY)`
232 yield* sql`INSERT INTO items VALUES (1)`
233
234 const insert = mode === "ABORT"
235 ? sql`INSERT INTO items VALUES (1)`
236 : sql`INSERT OR ROLLBACK INTO items VALUES (1)`
237 const transaction = sql.withTransaction(
238 mode === "nested ROLLBACK" ? sql.withTransaction(insert) : insert
239 )
240 const exit = yield* Effect.exit(transaction)
241 assert.isTrue(Exit.isFailure(exit))
242 if (!Exit.isFailure(exit)) return
243 assert.isFalse(
244 Cause.hasDies(exit.cause),
245 `expected only a typed constraint failure:\n${Cause.pretty(exit.cause)}`
246 )
247 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause))
248 assert.strictEqual(error._tag, "SqlError")
249 assert.strictEqual(error.reason._tag, "ConstraintError")
250
251 const recovered = yield* transaction.pipe(
252 Effect.as(false),
253 Effect.catchTag("SqlError", () => Effect.succeed(true))
254 )
255 assert.isTrue(recovered)
256 yield* sql.withTransaction(sql`INSERT INTO items VALUES (2)`)
257 assert.deepStrictEqual(yield* sql`SELECT id FROM items ORDER BY id`, [{ id: 1 }, { id: 2 }])
258 })
259 )
260
261 it.effect.each(["missing savepoint", "unrelated cleanup error"] as const)(
262 "keeps a %s as a defect and rolls back the outer transaction",
263 (mode) =>
264 Effect.gen(function*() {
265 const sql = yield* SqliteClient.make({ filename: ":memory:" }).pipe(Effect.provide(Reactivity.layer))
266 yield* sql`CREATE TABLE items (id INTEGER PRIMARY KEY)`
267 const error = new SqlError({
268 reason: new ConnectionError({
269 message: "injected cleanup failure",
270 operation: "rollback",
271 cause: new Error("injected cleanup failure")
272 })
273 })
274 if (mode === "unrelated cleanup error") {
275 const conn = yield* Effect.scoped(sql.reserve)
276 const executeUnprepared = conn.executeUnprepared
277 Object.defineProperty(conn, "executeUnprepared", {
278 configurable: true,
279 value: (...args: Parameters<typeof executeUnprepared>) =>
280 args[0].startsWith("ROLLBACK TO SAVEPOINT")
281 ? Effect.fail(error)
282 : executeUnprepared(...args)
283 })
284 }
285
286 const exit = yield* Effect.exit(sql.withTransaction(
287 sql.withTransaction(Effect.gen(function*() {
288 yield* sql`INSERT INTO items VALUES (1)`
289 if (mode === "missing savepoint") {
290 yield* sql`RELEASE SAVEPOINT effect_sql_1`.unprepared
291 }
292 return yield* Effect.fail(error)
293 })).pipe(Effect.catchTag("SqlError", () => Effect.void))
294 ))
295
296 assert.deepStrictEqual(yield* sql`SELECT id FROM items`, [])
297 assert.isTrue(Exit.isFailure(exit))
298 if (!Exit.isFailure(exit)) return
299 assert.isTrue(Cause.hasDies(exit.cause))
300 assert.match(
301 Cause.pretty(exit.cause),
302 mode === "missing savepoint" ? /no such savepoint/i : /injected cleanup failure/i
303 )
304 })
305 )
306
307 it.effect("recovers a failed deferred commit without losing an in-memory database", () =>
308 Effect.gen(function*() {
309 const sql = yield* SqliteClient.make({ filename: ":memory:" }).pipe(Effect.provide(Reactivity.layer))
310 yield* sql`PRAGMA foreign_keys = ON`
311 yield* sql`CREATE TABLE parent (id INTEGER PRIMARY KEY)`
312 yield* sql`CREATE TABLE child (parent_id INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED)`
313 yield* sql`INSERT INTO parent VALUES (1)`
314
315 const failedCommit = yield* Effect.exit(sql.withTransaction(sql`INSERT INTO child VALUES (999)`))
316 assert.isTrue(Exit.isFailure(failedCommit))
317 if (!Exit.isFailure(failedCommit)) return
318 assert.match(Cause.pretty(failedCommit.cause), /foreign key constraint failed/i)
319
320 assert.deepStrictEqual(yield* sql`SELECT * FROM parent`, [{ id: 1 }])
321 assert.deepStrictEqual(yield* sql`SELECT * FROM child`, [])
322 yield* sql.withTransaction(sql`INSERT INTO child VALUES (1)`)
323 assert.deepStrictEqual(yield* sql`SELECT * FROM child`, [{ parent_id: 1 }])
324 }))
325
326 it.effect("poisons the connection when failed-commit cleanup fails", () =>
327 Effect.gen(function*() {
328 const sql = yield* makeClient
329 yield* sql`PRAGMA foreign_keys = ON`
330 yield* sql`CREATE TABLE parent (id INTEGER PRIMARY KEY)`
331 yield* sql`CREATE TABLE child (parent_id INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED)`
332 yield* sql`INSERT INTO parent VALUES (1)`
333
334 // Reserve lends the same SQLite connection used by transactions. Fail only
335 // the cleanup ROLLBACK, leaving the deferred constraint failure real.
336 const conn = yield* Effect.scoped(sql.reserve)
337 const executeUnprepared = conn.executeUnprepared
338 let failRollback = true
339 Object.defineProperty(conn, "executeUnprepared", {
340 configurable: true,
341 value: (...args: Parameters<typeof executeUnprepared>) => {
342 if (args[0] === "ROLLBACK" && failRollback) {
343 return Effect.fail(
344 new SqlError({
345 reason: new ConnectionError({
346 message: "injected rollback failure",
347 operation: "rollback",
348 cause: new Error("injected rollback failure")
349 })
350 })
351 )
352 }
353 return executeUnprepared(...args)
354 }
355 })
356
357 const failedCommit = yield* Effect.exit(sql.withTransaction(sql`INSERT INTO child VALUES (999)`))
358 assert.isTrue(Exit.isFailure(failedCommit))
359 if (!Exit.isFailure(failedCommit)) return
360 const cause = Cause.pretty(failedCommit.cause)
361 assert.match(cause, /foreign key constraint failed/i)
362 assert.match(cause, /injected rollback failure/i)
363
364 const query = yield* Effect.exit(sql`SELECT * FROM parent`)
365 assert.isTrue(Exit.isFailure(query))
366 if (Exit.isFailure(query)) {
367 assert.match(Cause.pretty(query.cause), /cannot be reused after failed COMMIT cleanup/i)
368 }
369 const transaction = yield* Effect.exit(sql.withTransaction(Effect.die("transaction body ran")))
370 assert.isTrue(Exit.isFailure(transaction))
371 const queryAfterTransaction = yield* Effect.exit(sql`SELECT * FROM parent`)
372 assert.isTrue(Exit.isFailure(queryAfterTransaction))
373 // Retry cleanup after the transient failure clears, without replacing the database.
374 failRollback = false
375 assert.deepStrictEqual(yield* sql`SELECT * FROM parent`, [{ id: 1 }])
376 assert.deepStrictEqual(yield* sql`SELECT * FROM child`, [])
377 yield* sql`INSERT INTO child VALUES (1)`
378 assert.deepStrictEqual(yield* sql`SELECT * FROM child`, [{ parent_id: 1 }])
379 }))
380
381 it.effect("does not poison a connection already rolled back before failed commit cleanup", () =>
382 Effect.gen(function*() {
383 const sql = yield* makeClient
384 yield* sql`CREATE TABLE items (id INTEGER PRIMARY KEY)`
385
386 const failedCommit = yield* Effect.exit(sql.withTransaction(Effect.gen(function*() {
387 yield* sql`INSERT INTO items VALUES (1)`
388 const insert = yield* Effect.exit(sql`INSERT OR ROLLBACK INTO items VALUES (1)`)
389 assert.isTrue(Exit.isFailure(insert))
390 })))
391 assert.isTrue(Exit.isFailure(failedCommit))
392 if (Exit.isFailure(failedCommit)) {
393 assert.match(Cause.pretty(failedCommit.cause), /no transaction is active/i)
394 }
395
396 assert.deepStrictEqual(yield* sql`SELECT * FROM items`, [])
397 }))
398
399 it.effect("withTransaction rollback", () =>
400 Effect.gen(function*() {
401 const sql = yield* makeClient
402 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
403 yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
404 Effect.andThen(Effect.fail("boom")),
405 sql.withTransaction,
406 Effect.ignore
407 )
408 const rows = yield* sql`SELECT * FROM test`
409 assert.deepStrictEqual(rows, [])
410 }))
411
412 it.effect("keeps a plain write out of another fiber's rolled back transaction", () =>
413 Effect.gen(function*() {
414 // Sweep the acquisition/execution gap without relying on one scheduler offset.
415 for (let delay = 0; delay < 31; delay++) {
416 yield* Effect.scoped(Effect.gen(function*() {
417 const sql = yield* makeClient
418 yield* sql`CREATE TABLE race (kind TEXT NOT NULL)`
419 const plain = yield* sql`INSERT INTO race VALUES ('plain')`.pipe(
420 Effect.provideService(References.MaxOpsBeforeYield, 3),
421 Effect.forkChild
422 )
423 for (let i = 0; i < delay; i++) yield* Effect.yieldNow
424 const transaction = yield* sql.withTransaction(Effect.gen(function*() {
425 yield* sql`INSERT INTO race VALUES ('rolled back')`
426 for (let i = 0; i < 1000; i++) yield* Effect.yieldNow
427 return yield* Effect.fail("rollback")
428 })).pipe(Effect.ignore, Effect.forkChild)
429 yield* Fiber.join(plain)
430 yield* Fiber.join(transaction)
431 assert.deepStrictEqual(yield* sql`SELECT kind FROM race`, [{ kind: "plain" }])
432 }))
433 }
434 }), { timeout: 30_000 })
435
436 it.effect("releases the connection when a queued transaction is interrupted", () =>
437 Effect.gen(function*() {
438 // Sweep the interrupt across the gap between taking the connection and registering its release.
439 for (let delay = 0; delay < 31; delay++) {
440 yield* Effect.scoped(Effect.gen(function*() {
441 const sql = yield* SqliteClient.make({ filename: ":memory:" }).pipe(Effect.provide(Reactivity.layer))
442 const holder = yield* Effect.forkChild(sql`SELECT 1`)
443 const queued = yield* sql.withTransaction(sql`SELECT 2`).pipe(
444 Effect.provideService(References.MaxOpsBeforeYield, 3),
445 Effect.forkChild
446 )
447 for (let i = 0; i < delay; i++) yield* Effect.yieldNow
448 yield* Fiber.interrupt(queued)
449 yield* Fiber.join(holder)
450 const next = yield* Effect.forkChild(sql`SELECT 3`, { startImmediately: true })
451 assert.isDefined(next.pollUnsafe(), `connection leaked at delay ${delay}`)
452 }))
453 }
454 }))
455
456 it.effect("uses a 5 second busy timeout", () =>
457 Effect.gen(function*() {
458 const sql = yield* makeClient
459 assert.deepStrictEqual(yield* sql`PRAGMA busy_timeout`, [{ timeout: 5000 }])
460
461 const custom = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: "1 second" }).pipe(
462 Effect.provide(Reactivity.layer)
463 )
464 assert.deepStrictEqual(yield* custom`PRAGMA busy_timeout`, [{ timeout: 1000 }])
465
466 const infinite = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: Duration.infinity }).pipe(
467 Effect.provide(Reactivity.layer)
468 )
469 assert.deepStrictEqual(yield* infinite`PRAGMA busy_timeout`, [{ timeout: 2_147_483_647 }])
470 }))
471
472 it.effect("starts transactions immediately", () =>
473 Effect.gen(function*() {
474 const { client, contender } = yield* makeClients
475 yield* contender`PRAGMA busy_timeout = 1`
476
477 yield* client.withTransaction(
478 Effect.gen(function*() {
479 const error = yield* Effect.flip(contender`BEGIN IMMEDIATE`)
480 assert.strictEqual(error._tag, "SqlError")
481 assert(error.reason.cause instanceof Error)
482 assert.match(error.reason.cause.message, /database is locked/i)
483 })
484 )
485 }))
486
487 it.effect("fails a contended transaction with a typed error", () =>
488 Effect.gen(function*() {
489 const { client, contender } = yield* makeClients
490 yield* contender`PRAGMA busy_timeout = 1`
491
492 const exit = yield* client.withTransaction(
493 Effect.exit(contender.withTransaction(Effect.void))
494 )
495
496 assert.isTrue(Exit.isFailure(exit))
497 if (!Exit.isFailure(exit)) {
498 return
499 }
500 // `BEGIN IMMEDIATE` cannot take the write lock, so it fails before a
501 // transaction exists. The failure has to stay a typed, retryable
502 // `SqlError` instead of being replaced by a rollback defect.
503 assert.isFalse(
504 Cause.hasDies(exit.cause),
505 `expected a typed failure but the cause contains a defect:\n${Cause.pretty(exit.cause)}`
506 )
507 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause))
508 assert.strictEqual(error._tag, "SqlError")
509 assert(error.reason.cause instanceof Error)
510 assert.match(error.reason.cause.message, /database is locked/i)
511 }))
512
513 it.effect("supports transactions on readonly clients", () =>
514 Effect.gen(function*() {
515 const fs = yield* FileSystem.FileSystem
516 const dir = yield* fs.makeTempDirectoryScoped()
517 const filename = dir + "/test.db"
518
519 yield* Effect.scoped(
520 Effect.gen(function*() {
521 const sql = yield* SqliteClient.make({ filename })
522 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
523 })
524 )
525
526 const sql = yield* SqliteClient.make({ filename, readonly: true })
527 yield* sql`PRAGMA query_only = ON`
528 assert.deepStrictEqual(yield* sql.withTransaction(sql`SELECT * FROM test`), [])
529 }).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer])))
530
531 it.effect("supports backup and export", () =>
532 Effect.gen(function*() {
533 const sql = yield* makeClient
534 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
535 yield* sql`INSERT INTO test (name) VALUES ('hello')`
536
537 const metadata = yield* sql.backup(sql.config.filename + ".backup")
538 assert(metadata.totalPages > 0)
539 assert.strictEqual(metadata.remainingPages, 0)
540 }))
541
542 it.effect("retries enabling WAL while the database is locked", () =>
543 Effect.gen(function*() {
544 const { filename, unlock } = yield* makeLockedDatabase
545 const fiber = yield* SqliteClient.make({ filename }).pipe(Effect.forkChild({ startImmediately: true }))
546 unlock()
547 yield* TestClock.adjust("10 millis")
548 const sql = yield* Fiber.join(fiber)
549 assert.deepStrictEqual(yield* sql`PRAGMA journal_mode`, [{ journal_mode: "wal" }])
550 }).pipe(Effect.provide(Reactivity.layer)))
551
552 it.effect("fails to enable WAL with a typed error after busyTimeout", () =>
553 Effect.gen(function*() {
554 const { filename } = yield* makeLockedDatabase
555 const fiber = yield* SqliteClient.make({ filename, busyTimeout: "1 second" }).pipe(
556 Effect.forkChild({ startImmediately: true })
557 )
558 yield* TestClock.adjust("2 seconds")
559 const error = yield* Effect.flip(Fiber.join(fiber))
560 assert.strictEqual(error.reason._tag, "LockTimeoutError")
561 }).pipe(Effect.provide(Reactivity.layer)))
562
563 it.effect("does not enable WAL on readonly clients", () =>
564 Effect.gen(function*() {
565 const fs = yield* FileSystem.FileSystem
566 const dir = yield* fs.makeTempDirectoryScoped()
567 const filename = dir + "/test.db"
568
569 yield* Effect.scoped(
570 Effect.gen(function*() {
571 const sql = yield* SqliteClient.make({ filename, disableWAL: true })
572 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
573 })
574 )
575
576 const sql = yield* SqliteClient.make({ filename, readonly: true })
577 assert.deepStrictEqual(yield* sql`PRAGMA journal_mode`, [{ journal_mode: "delete" }])
578 }).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer])))
579
580 it.effect("works when node:sqlite does not provide enableLoadExtension", () =>
581 Effect.gen(function*() {
582 const prototype: Partial<Pick<DatabaseSync, "enableLoadExtension">> = DatabaseSync.prototype
583 const descriptor = Object.getOwnPropertyDescriptor(prototype, "enableLoadExtension")
584 yield* Effect.acquireRelease(
585 Effect.sync(() => delete prototype.enableLoadExtension),
586 () =>
587 Effect.sync(() => {
588 if (descriptor) Object.defineProperty(prototype, "enableLoadExtension", descriptor)
589 })
590 )
591
592 const sql = yield* makeClient
593 assert.deepStrictEqual(yield* sql`SELECT 1 AS value`, [{ value: 1 }])
594 const error = yield* Effect.flip(sql.loadExtension(sql.config.filename + ".missing-extension"))
595 assert.strictEqual(error._tag, "SqlError")
596 }), { concurrent: false })
597})