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, Duration, Effect, Exit, FileSystem, Option } from "effect"
5import { Reactivity } from "effect/unstable/reactivity"
6
7const makeClient = Effect.gen(function*() {
8 const fs = yield* FileSystem.FileSystem
9 const dir = yield* fs.makeTempDirectoryScoped()
10 return yield* SqliteClient.make({
11 filename: dir + "/test.db"
12 })
13}).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer]))
14
15const makeClients = Effect.gen(function*() {
16 const fs = yield* FileSystem.FileSystem
17 const dir = yield* fs.makeTempDirectoryScoped()
18 const filename = dir + "/test.db"
19 return {
20 client: yield* SqliteClient.make({ filename }),
21 contender: yield* SqliteClient.make({ filename })
22 }
23}).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer]))
24
25describe("Client", () => {
26 it.effect("should work", () =>
27 Effect.gen(function*() {
28 const sql = yield* makeClient
29 let response
30 response = yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
31 assert.deepStrictEqual(response, [])
32 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`
33 assert.deepStrictEqual(response, [])
34 response = yield* sql`SELECT * FROM test`
35 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
36 response = yield* sql`SELECT * FROM test`.valuesUnprepared
37 assert.deepStrictEqual(response, [[1, "hello"]])
38 response = yield* sql`INSERT INTO test (name) VALUES ('world')`.pipe(sql.withTransaction)
39 assert.deepStrictEqual(response, [])
40 response = yield* sql`SELECT * FROM test`
41 assert.deepStrictEqual(response, [
42 { id: 1, name: "hello" },
43 { id: 2, name: "world" }
44 ])
45 }))
46
47 it.effect("should work with raw", () =>
48 Effect.gen(function*() {
49 const sql = yield* makeClient
50 let response
51 response = yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`.raw
52 assert.deepStrictEqual(response, { changes: 0, lastInsertRowid: 0 })
53 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`.raw
54 assert.deepStrictEqual(response, { changes: 1, lastInsertRowid: 1 })
55 response = yield* sql`SELECT * FROM test`.raw
56 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
57 response = yield* sql`INSERT INTO test (name) VALUES ('world')`.raw.pipe(sql.withTransaction)
58 assert.deepStrictEqual(response, { changes: 1, lastInsertRowid: 2 })
59 response = yield* sql`SELECT * FROM test`
60 assert.deepStrictEqual(response, [
61 { id: 1, name: "hello" },
62 { id: 2, name: "world" }
63 ])
64 }))
65
66 for (const mode of ["unprepared", "valuesUnprepared"] as const) {
67 it.effect(`captures ${mode} preparation errors`, () =>
68 Effect.gen(function*() {
69 const sql = yield* makeClient
70 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
71
72 const statement = sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
73 const execution = mode === "unprepared"
74 ? Effect.as(statement.unprepared, false)
75 : Effect.as(statement.valuesUnprepared, false)
76 const recovered = yield* execution.pipe(Effect.catchTag("SqlError", () => Effect.succeed(true)))
77
78 assert.isTrue(recovered)
79 }))
80 }
81
82 it.effect("withTransaction", () =>
83 Effect.gen(function*() {
84 const sql = yield* makeClient
85 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
86 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
87 const rows = yield* sql`SELECT * FROM test`
88 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
89 }))
90
91 it.effect("withTransaction rollback", () =>
92 Effect.gen(function*() {
93 const sql = yield* makeClient
94 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
95 yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
96 Effect.andThen(Effect.fail("boom")),
97 sql.withTransaction,
98 Effect.ignore
99 )
100 const rows = yield* sql`SELECT * FROM test`
101 assert.deepStrictEqual(rows, [])
102 }))
103
104 it.effect("uses a 5 second busy timeout", () =>
105 Effect.gen(function*() {
106 const sql = yield* makeClient
107 assert.deepStrictEqual(yield* sql`PRAGMA busy_timeout`, [{ timeout: 5000 }])
108
109 const custom = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: "1 second" }).pipe(
110 Effect.provide(Reactivity.layer)
111 )
112 assert.deepStrictEqual(yield* custom`PRAGMA busy_timeout`, [{ timeout: 1000 }])
113
114 const infinite = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: Duration.infinity }).pipe(
115 Effect.provide(Reactivity.layer)
116 )
117 assert.deepStrictEqual(yield* infinite`PRAGMA busy_timeout`, [{ timeout: 2_147_483_647 }])
118 }))
119
120 it.effect("starts transactions immediately", () =>
121 Effect.gen(function*() {
122 const { client, contender } = yield* makeClients
123 yield* contender`PRAGMA busy_timeout = 1`
124
125 yield* client.withTransaction(
126 Effect.gen(function*() {
127 const error = yield* Effect.flip(contender`BEGIN IMMEDIATE`)
128 assert.strictEqual(error._tag, "SqlError")
129 assert(error.reason.cause instanceof Error)
130 assert.match(error.reason.cause.message, /database is locked/i)
131 })
132 )
133 }))
134
135 it.effect("fails a contended transaction with a typed error", () =>
136 Effect.gen(function*() {
137 const { client, contender } = yield* makeClients
138 yield* contender`PRAGMA busy_timeout = 1`
139
140 const exit = yield* client.withTransaction(
141 Effect.exit(contender.withTransaction(Effect.void))
142 )
143
144 assert.isTrue(Exit.isFailure(exit))
145 if (!Exit.isFailure(exit)) {
146 return
147 }
148 // `BEGIN IMMEDIATE` cannot take the write lock, so it fails before a
149 // transaction exists. The failure has to stay a typed, retryable
150 // `SqlError` instead of being replaced by a rollback defect.
151 assert.isFalse(
152 Cause.hasDies(exit.cause),
153 `expected a typed failure but the cause contains a defect:\n${Cause.pretty(exit.cause)}`
154 )
155 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause))
156 assert.strictEqual(error._tag, "SqlError")
157 assert(error.reason.cause instanceof Error)
158 assert.match(error.reason.cause.message, /database is locked/i)
159 }))
160
161 it.effect("supports transactions on readonly clients", () =>
162 Effect.gen(function*() {
163 const fs = yield* FileSystem.FileSystem
164 const dir = yield* fs.makeTempDirectoryScoped()
165 const filename = dir + "/test.db"
166
167 yield* Effect.scoped(
168 Effect.gen(function*() {
169 const sql = yield* SqliteClient.make({ filename })
170 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
171 })
172 )
173
174 const sql = yield* SqliteClient.make({ filename, readonly: true })
175 yield* sql`PRAGMA query_only = ON`
176 assert.deepStrictEqual(yield* sql.withTransaction(sql`SELECT * FROM test`), [])
177 }).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer])))
178
179 it.effect("supports backup and export", () =>
180 Effect.gen(function*() {
181 const sql = yield* makeClient
182 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
183 yield* sql`INSERT INTO test (name) VALUES ('hello')`
184
185 const metadata = yield* sql.backup(sql.config.filename + ".backup")
186 assert(metadata.totalPages > 0)
187 assert.strictEqual(metadata.remainingPages, 0)
188 }))
189})