Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Client.test.ts

172 lines6.8 KB

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 it.effect("withTransaction", () =>
67 Effect.gen(function*() {
68 const sql = yield* makeClient
69 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
70 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
71 const rows = yield* sql`SELECT * FROM test`
72 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
73 }))
74​
75 it.effect("withTransaction rollback", () =>
76 Effect.gen(function*() {
77 const sql = yield* makeClient
78 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
79 yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
80 Effect.andThen(Effect.fail("boom")),
81 sql.withTransaction,
82 Effect.ignore
83 )
84 const rows = yield* sql`SELECT * FROM test`
85 assert.deepStrictEqual(rows, [])
86 }))
87​
88 it.effect("uses a 5 second busy timeout", () =>
89 Effect.gen(function*() {
90 const sql = yield* makeClient
91 assert.deepStrictEqual(yield* sql`PRAGMA busy_timeout`, [{ timeout: 5000 }])
92​
93 const custom = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: "1 second" }).pipe(
94 Effect.provide(Reactivity.layer)
95 )
96 assert.deepStrictEqual(yield* custom`PRAGMA busy_timeout`, [{ timeout: 1000 }])
97​
98 const infinite = yield* SqliteClient.make({ filename: ":memory:", busyTimeout: Duration.infinity }).pipe(
99 Effect.provide(Reactivity.layer)
100 )
101 assert.deepStrictEqual(yield* infinite`PRAGMA busy_timeout`, [{ timeout: 2_147_483_647 }])
102 }))
103​
104 it.effect("starts transactions immediately", () =>
105 Effect.gen(function*() {
106 const { client, contender } = yield* makeClients
107 yield* contender`PRAGMA busy_timeout = 1`
108​
109 yield* client.withTransaction(
110 Effect.gen(function*() {
111 const error = yield* Effect.flip(contender`BEGIN IMMEDIATE`)
112 assert.strictEqual(error._tag, "SqlError")
113 assert(error.reason.cause instanceof Error)
114 assert.match(error.reason.cause.message, /database is locked/i)
115 })
116 )
117 }))
118​
119 it.effect("fails a contended transaction with a typed error", () =>
120 Effect.gen(function*() {
121 const { client, contender } = yield* makeClients
122 yield* contender`PRAGMA busy_timeout = 1`
123​
124 const exit = yield* client.withTransaction(
125 Effect.exit(contender.withTransaction(Effect.void))
126 )
127​
128 assert.isTrue(Exit.isFailure(exit))
129 if (!Exit.isFailure(exit)) {
130 return
131 }
132 // `BEGIN IMMEDIATE` cannot take the write lock, so it fails before a
133 // transaction exists. The failure has to stay a typed, retryable
134 // `SqlError` instead of being replaced by a rollback defect.
135 assert.isFalse(
136 Cause.hasDies(exit.cause),
137 `expected a typed failure but the cause contains a defect:\n${Cause.pretty(exit.cause)}`
138 )
139 const error = Option.getOrThrow(Cause.findErrorOption(exit.cause))
140 assert.strictEqual(error._tag, "SqlError")
141 assert(error.reason.cause instanceof Error)
142 assert.match(error.reason.cause.message, /database is locked/i)
143 }))
144​
145 it.effect("supports transactions on readonly clients", () =>
146 Effect.gen(function*() {
147 const fs = yield* FileSystem.FileSystem
148 const dir = yield* fs.makeTempDirectoryScoped()
149 const filename = dir + "/test.db"
150​
151 yield* Effect.scoped(
152 Effect.gen(function*() {
153 const sql = yield* SqliteClient.make({ filename })
154 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)`
155 })
156 )
157​
158 const sql = yield* SqliteClient.make({ filename, readonly: true })
159 assert.deepStrictEqual(yield* sql.withTransaction(sql`SELECT * FROM test`), [])
160 }).pipe(Effect.provide([NodeFileSystem.layer, Reactivity.layer])))
161​
162 it.effect("supports backup and export", () =>
163 Effect.gen(function*() {
164 const sql = yield* makeClient
165 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
166 yield* sql`INSERT INTO test (name) VALUES ('hello')`
167​
168 const metadata = yield* sql.backup(sql.config.filename + ".backup")
169 assert(metadata.totalPages > 0)
170 assert.strictEqual(metadata.remainingPages, 0)
171 }))
172})