The best way to control Claude Code, Codex and more from any computer or phone

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