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

Client.integration.test.ts

352 lines14.0 KB

1import { LibsqlClient } from "@effect/sql-libsql"
2import { assert, describe, it, layer } from "@effect/vitest"
3import { Cause, Deferred, Effect, Exit, Fiber, Layer, Option } from "effect"
4import * as Reactivity from "effect/reactivity/Reactivity"
5import { SqlError } from "effect/sql/SqlError"
6import { LibsqlContainer } from "./util.ts"
7​
8const Migrations = Layer.effectDiscard(
9 LibsqlClient.LibsqlClient.pipe(
10 Effect.andThen((sql) =>
11 Effect.acquireRelease(
12 sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`,
13 () => sql`DROP TABLE test;`.pipe(Effect.ignore)
14 )
15 )
16 )
18​
19describe("Client", () => {
20 it.effect("exposes the active transaction service for each client", () =>
21 Effect.gen(function*() {
22 const a = yield* LibsqlClient.make({ url: ":memory:" })
23 const b = yield* LibsqlClient.make({ url: ":memory:" })
24 const active = Effect.all([
25 Effect.map(Effect.serviceOption(a.transactionService), Option.isSome),
26 Effect.map(Effect.serviceOption(b.transactionService), Option.isSome)
27 ])
28​
29 assert.deepStrictEqual(yield* active, [false, false])
30 yield* a.withTransaction(Effect.gen(function*() {
31 assert.deepStrictEqual(yield* active, [true, false])
32 assert.deepStrictEqual(yield* b.withTransaction(active), [true, true])
33 assert.deepStrictEqual(yield* active, [true, false])
34 }))
35 assert.deepStrictEqual(yield* active, [false, false])
36 }).pipe(Effect.provide(Reactivity.layer)))
37​
38 it.effect.each(["transaction", "savepoint"] as const)(
39 "fails reserve from a fiber that outlives its %s",
40 (level) =>
41 Effect.gen(function*() {
42 const sql = yield* LibsqlClient.make({ url: ":memory:" })
43 yield* sql`CREATE TABLE stale_reserve (value INTEGER)`
44 const attempt = Effect.gen(function*() {
45 const go = yield* Deferred.make<void>()
46 const stale = yield* sql.withTransaction(
47 Effect.forkChild(Effect.andThen(
48 Deferred.await(go),
49 Effect.scoped(
50 Effect.flatMap(sql.reserve, (conn) => conn.executeRaw("INSERT INTO stale_reserve VALUES (1)", []))
51 )
52 ))
53 )
54 yield* Deferred.succeed(go, undefined)
55 // Keep the outer transaction alive until the stale attempt finishes, even if it succeeds.
56 yield* Fiber.await(stale)
57 return stale
58 })
59 const stale = yield* level === "savepoint" ? sql.withTransaction(attempt) : attempt
60 assert.deepStrictEqual(yield* sql`SELECT value FROM stale_reserve`, [])
61 const error = yield* Effect.flip(Fiber.join(stale))
62 assert.instanceOf(error, SqlError)
63 assert.deepStrictEqual(
64 [error.reason._tag, error.reason.message, error.isRetryable],
65 ["UnknownError", "SqlClient: the transaction has already ended", false]
66 )
67 }).pipe(Effect.provide(Reactivity.layer))
68 )
69​
70 it.effect("releases completed nested savepoints", () =>
71 Effect.gen(function*() {
72 const sql = yield* LibsqlClient.make({ url: ":memory:" })
73 yield* sql`CREATE TABLE savepoint_release (value INTEGER)`
74 yield* sql.withTransaction(Effect.gen(function*() {
75 for (const rollback of [false, true]) {
76 yield* sql.withTransaction(
77 sql`INSERT INTO savepoint_release VALUES (1)`.pipe(
78 Effect.andThen(rollback ? Effect.fail("rollback") : Effect.void)
79 )
80 ).pipe(Effect.ignore)
81 const error = yield* sql`RELEASE SAVEPOINT effect_sql_1`.unprepared.pipe(Effect.flip)
82 assert.strictEqual(error._tag, "SqlError")
83 }
84 }))
85 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
86 const error = yield* sql.withTransaction(
87 sql.withTransaction(sql`INSERT INTO savepoint_release VALUES (2)`).pipe(
88 Effect.andThen(Effect.fail("outer rollback"))
89 )
90 ).pipe(Effect.flip)
91 assert.strictEqual(error, "outer rollback")
92 assert.deepStrictEqual(yield* sql`SELECT value FROM savepoint_release`, [{ value: 1 }])
93 }).pipe(Effect.provide(Reactivity.layer)))
94​
95 it.effect("keeps transactions isolated between clients", () =>
96 Effect.gen(function*() {
97 const a = yield* LibsqlClient.make({ url: ":memory:" })
98 const b = yield* LibsqlClient.make({ url: ":memory:" })
99​
100 yield* a`CREATE TABLE marker (owner TEXT NOT NULL)`
101 yield* b`CREATE TABLE marker (owner TEXT NOT NULL)`
102 yield* a`INSERT INTO marker VALUES ('A')`
103 yield* b`INSERT INTO marker VALUES ('B')`
104​
105 const rows = yield* a.withTransaction(b`SELECT owner FROM marker`)
106 assert.deepStrictEqual(rows, [{ owner: "B" }])
107 }).pipe(
108 Effect.scoped,
109 Effect.provide(Reactivity.layer)
110 ))
111​
112 it.effect("releases transaction serialization after begin fails", () => {
113 let transactionCalls = 0
114 const transaction = {
115 execute: () => Promise.resolve({ rows: [] }),
116 commit: () => Promise.resolve(),
117 rollback: () => Promise.resolve()
118 }
119 const liveClient = {
120 execute: () => Promise.resolve({ rows: [] }),
121 transaction: () => {
122 transactionCalls++
123 return transactionCalls === 1
124 ? Promise.reject(new Error("transient begin failure"))
125 : Promise.resolve(transaction)
126 }
127 }
128​
129 return Effect.gen(function*() {
130 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
131 const first = yield* Effect.exit(client.withTransaction(Effect.void))
132 assert.isTrue(Exit.isFailure(first))
133​
134 yield* Effect.forkChild(client.withTransaction(Effect.void))
135 yield* Effect.yieldNow
136​
137 assert.strictEqual(transactionCalls, 2)
138 }).pipe(
139 Effect.scoped,
140 Effect.provide(Reactivity.layer)
141 )
142 })
143​
144 for (const rollbackFails of [false, true]) {
145 it.effect(`rolls back an interrupted pending begin (rollback ${rollbackFails ? "rejects" : "succeeds"})`, () =>
146 Effect.gen(function*() {
147 const calls: Array<string> = []
148 const rollbackError = new Error("rollback failed")
149 const transaction = {
150 execute: () => Promise.resolve({ rows: [] }),
151 commit: () => {
152 calls.push("commit")
153 return Promise.resolve()
154 },
155 rollback: () => {
156 calls.push("rollback")
157 return rollbackFails ? Promise.reject(rollbackError) : Promise.resolve()
158 }
159 }
160 const started = Promise.withResolvers<void>()
161 const begin = Promise.withResolvers<typeof transaction>()
162 let transactionCalls = 0
163 const liveClient = {
164 transaction: () => {
165 if (++transactionCalls === 1) {
166 started.resolve()
167 return begin.promise
168 }
169 return Promise.resolve(transaction)
170 }
171 }
172 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
173 const fiber = yield* Effect.forkChild(client.withTransaction(Effect.sync(() => {
174 calls.push("cancelled body")
175 })))
176 yield* Effect.promise(() => started.promise)
177 // Request interruption while the SDK still owns the pending BEGIN.
178 fiber.interruptUnsafe()
179 begin.resolve(transaction)
180 const exit = yield* Fiber.await(fiber)
181​
182 assert.isTrue(Exit.isFailure(exit))
183 if (Exit.isFailure(exit)) {
184 assert.isTrue(Cause.hasInterrupts(exit.cause))
185 const defects = exit.cause.reasons.filter(Cause.isDieReason).map((reason) => reason.defect)
186 assert.strictEqual(defects.length, rollbackFails ? 1 : 0)
187 if (rollbackFails) {
188 assert.instanceOf(defects[0], SqlError)
189 assert.strictEqual((defects[0] as SqlError).reason.cause, rollbackError)
190 }
191 }
192 assert.deepStrictEqual(calls, ["rollback"])
193​
194 yield* client.withTransaction(Effect.sync(() => {
195 calls.push("next body")
196 }))
197 assert.deepStrictEqual(calls, ["rollback", "next body", "commit"])
198 }).pipe(Effect.provide(Reactivity.layer)))
199 }
200​
201 it.effect("overlaps remote statements with each other and open transactions", () =>
202 Effect.gen(function*() {
203 const calls: Array<string> = []
204 const statement = Promise.withResolvers<{ rows: Array<unknown> }>()
205 const transaction = {
206 execute: () => {
207 calls.push("transaction execute")
208 return Promise.resolve({ rows: [] })
209 },
210 commit: () => Promise.resolve(),
211 rollback: () => Promise.resolve()
212 }
213 const liveClient = {
214 protocol: "http",
215 execute: () => {
216 calls.push("execute")
217 return statement.promise
218 },
219 transaction: () => Promise.resolve(transaction)
220 }
221 const client = yield* LibsqlClient.make({ liveClient: liveClient as any })
222 const open = yield* Deferred.make<void>()
223 const release = yield* Deferred.make<void>()
224 const tx = yield* Effect.forkChild(client.withTransaction(
225 Deferred.succeed(open, undefined).pipe(Effect.andThen(Deferred.await(release)))
226 ))
227 yield* Deferred.await(open)
228​
229 const statements = yield* Effect.forkChild(
230 Effect.all([client`SELECT 1`, client`SELECT 2`], { concurrency: "unbounded" })
231 )
232 yield* Effect.yieldNow
233 assert.deepStrictEqual(calls, ["execute", "execute"])
234​
235 statement.resolve({ rows: [] })
236 yield* Fiber.join(statements)
237 yield* Deferred.succeed(release, undefined)
238 yield* Fiber.join(tx)
239 }).pipe(Effect.provide(Reactivity.layer)))
240​
241 it.effect("serializes local statements behind open transactions", () =>
242 Effect.gen(function*() {
243 const sql = yield* LibsqlClient.make({ url: ":memory:" })
244 yield* sql`CREATE TABLE serialized (value INTEGER)`
245 const open = yield* Deferred.make<void>()
246 const release = yield* Deferred.make<void>()
247 const tx = yield* Effect.forkChild(sql.withTransaction(
248 sql`INSERT INTO serialized VALUES (1)`.pipe(
249 Effect.andThen(Deferred.succeed(open, undefined)),
250 Effect.andThen(Deferred.await(release))
251 )
252 ))
253 yield* Deferred.await(open)
254​
255 const read = yield* Effect.forkChild(sql`SELECT value FROM serialized`)
256 yield* Effect.yieldNow
257 yield* Deferred.succeed(release, undefined)
258 yield* Fiber.join(tx)
259​
260 assert.deepStrictEqual(yield* Fiber.join(read), [{ value: 1 }])
261 }).pipe(Effect.provide(Reactivity.layer)))
262​
263 // Each test recreates the same tables.
264 layer(LibsqlContainer.layerClient, { timeout: "30 seconds", concurrent: false })("shared tables", (it) => {
265 it.effect("should work", () =>
266 Effect.gen(function*() {
267 const sql = yield* LibsqlClient.LibsqlClient
268 let response = yield* sql`INSERT INTO test (name) VALUES ('hello')`
269 assert.deepStrictEqual(response, [])
270 response = yield* sql`SELECT * FROM test`
271 assert.deepStrictEqual(response, [{ id: 1, name: "hello" }])
272 response = yield* sql`SELECT * FROM test`
273 assert.deepStrictEqual(yield* sql`select * from test`.values, [
274 [1, "hello"]
275 ])
276 }).pipe(Effect.provide(Migrations)))
277​
278 it.effect("should work with raw", () =>
279 Effect.gen(function*() {
280 const sql = yield* LibsqlClient.LibsqlClient
281 let response: any
282 response = yield* sql`CREATE TABLE test2 (id INTEGER PRIMARY KEY, name TEXT)`.raw
283 yield* Effect.addFinalizer(() => sql`DROP TABLE test2;`.pipe(Effect.ignore))
284 assert.deepStrictEqual(response.toJSON(), {
285 columnTypes: [],
286 columns: [],
287 lastInsertRowid: null,
288 rows: [],
289 rowsAffected: 0
290 })
291 response = yield* sql`INSERT INTO test (name) VALUES ('hello')`.raw
292 assert.deepStrictEqual(response.toJSON(), {
293 columnTypes: [],
294 columns: [],
295 lastInsertRowid: "1",
296 rows: [],
297 rowsAffected: 1
298 })
299 response = yield* sql`SELECT * FROM test`.raw
300 assert.deepStrictEqual(response.toJSON(), {
301 columnTypes: ["INTEGER", "TEXT"],
302 columns: ["id", "name"],
303 lastInsertRowid: null,
304 rows: [[1, "hello"]],
305 rowsAffected: 0
306 })
307 }).pipe(Effect.provide(Migrations)))
308​
309 it.effect("withTransaction", () =>
310 Effect.gen(function*() {
311 const sql = yield* LibsqlClient.LibsqlClient
312 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
313 const rows = yield* sql`SELECT * FROM test`
314 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
315 }).pipe(Effect.provide(Migrations)))
316​
317 it.effect("withTransaction rollback", () =>
318 Effect.gen(function*() {
319 const sql = yield* LibsqlClient.LibsqlClient
320 yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
321 Effect.andThen(Effect.fail("boom")),
322 sql.withTransaction,
323 Effect.ignore
324 )
325 const rows = yield* sql`SELECT * FROM test`
326 assert.deepStrictEqual(rows, [])
327 }).pipe(Effect.provide(Migrations)))
328​
329 it.effect("withTransaction nested", () =>
330 Effect.gen(function*() {
331 const sql = yield* LibsqlClient.LibsqlClient
332 const stmt = sql`INSERT INTO test (name) VALUES ('hello')`
333​
334 yield* stmt.pipe(Effect.andThen(() => stmt.pipe(sql.withTransaction)), sql.withTransaction)
335 const rows = yield* sql<{ total_rows: number }>`select count(*) as total_rows FROM test`
336 assert.deepStrictEqual(rows.at(0)?.total_rows, 2)
337 }).pipe(Effect.provide(Migrations)))
338​
339 it.effect("withTransaction nested rollback", () =>
340 Effect.gen(function*() {
341 const sql = yield* LibsqlClient.LibsqlClient
342 const stmt = sql`INSERT INTO test (name) VALUES ('hello')`
343​
344 yield* stmt.pipe(
345 Effect.andThen(() => stmt.pipe(Effect.andThen(Effect.fail("boom")), sql.withTransaction, Effect.ignore)),
346 sql.withTransaction
347 )
348 const rows = yield* sql<{ total_rows: number }>`select count(*) as total_rows FROM test`
349 assert.deepStrictEqual(rows.at(0)?.total_rows, 1)
350 }).pipe(Effect.provide(Migrations)))
351 })
352})