Open History to see the last commit
1import type { DurableObjectStorage, SqlStorage } from "@cloudflare/workers-types"
2import { SqliteClient, SqliteMigrator } from "@effect/sql-sqlite-do"
3import { assert, describe, it } from "@effect/vitest"
4import { Deferred, Effect, Fiber } from "effect"
5import * as Reactivity from "effect/unstable/reactivity/Reactivity"
6import * as SqlClient from "effect/unstable/sql/SqlClient"
7
8class FakeCursor {
9 readonly columnNames: ReadonlyArray<string>
10 readonly rows: ReadonlyArray<ReadonlyArray<unknown>>
11
12 constructor(rows: ReadonlyArray<Record<string, unknown>>, columns?: ReadonlyArray<string>) {
13 this.columnNames = columns ?? Object.keys(rows[0] ?? {})
14 this.rows = rows.map((row) => this.columnNames.map((column) => row[column]))
15 }
16
17 *raw() {
18 yield* this.rows.map((row) => [...row])
19 }
20}
21
22class FakeSqlStorage {
23 readonly statements: Array<string> = []
24 tables = new Map<string, Array<Record<string, unknown>>>()
25 columns = new Map<string, Array<string>>()
26
27 snapshot() {
28 return {
29 tables: new Map(Array.from(this.tables, ([table, rows]) => [table, rows.map((row) => ({ ...row }))])),
30 columns: new Map(Array.from(this.columns, ([table, columns]) => [table, [...columns]]))
31 }
32 }
33
34 restore(snapshot: ReturnType<FakeSqlStorage["snapshot"]>) {
35 this.tables = snapshot.tables
36 this.columns = snapshot.columns
37 }
38
39 exec(sql: string, ...params: ReadonlyArray<unknown>) {
40 this.statements.push(sql)
41 const statement = normalizeSql(sql)
42 if (/^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT)\b/i.test(statement)) {
43 throw new Error(`Unsupported transaction SQL: ${statement}`)
44 }
45
46 if (/^CREATE TABLE\b/i.test(statement)) {
47 const match = /^CREATE TABLE(?: IF NOT EXISTS)?\s+("[^"]+"|\w+)\s*\((.*)\)$/i.exec(statement)
48 if (match !== null) {
49 const table = unquote(match[1])
50 if (!this.tables.has(table)) {
51 this.tables.set(table, [])
52 this.columns.set(
53 table,
54 match[2].split(",").map((part) => unquote(part.trim().split(/\s+/)[0])).filter((column) =>
55 column.length > 0 && column.toUpperCase() !== "PRIMARY"
56 )
57 )
58 }
59 }
60 return new FakeCursor([])
61 }
62
63 if (/^INSERT INTO\b/i.test(statement)) {
64 const match = /^INSERT INTO\s+("[^"]+"|\w+)\s*\(([^)]+)\)\s+VALUES\s+(.+)$/i.exec(statement)
65 if (match !== null) {
66 const table = unquote(match[1])
67 const columns = match[2].split(",").map((column) => unquote(column.trim()))
68 const rows = this.tables.get(table) ?? []
69 const tableColumns = this.columns.get(table) ?? [...columns]
70 if (!this.tables.has(table)) {
71 this.tables.set(table, rows)
72 this.columns.set(table, tableColumns)
73 }
74 let paramIndex = 0
75 for (const group of valueGroups(match[3])) {
76 const values = group.split(",").map((value) => parseValue(value.trim(), params, () => paramIndex++))
77 const row: Record<string, unknown> = {}
78 if (tableColumns.includes("id") && !columns.includes("id")) {
79 row.id = rows.length + 1
80 }
81 for (let i = 0; i < columns.length; i++) {
82 row[columns[i]] = values[i]
83 }
84 if (tableColumns.includes("created_at") && row.created_at === undefined) {
85 row.created_at = "current_timestamp"
86 }
87 rows.push(row)
88 }
89 }
90 return new FakeCursor([])
91 }
92
93 if (/^SELECT\b/i.test(statement)) {
94 const match =
95 /^SELECT\s+(.+)\s+FROM\s+("[^"]+"|\w+)(?:\s+WHERE\s+("[^"]+"|\w+)\s*=\s*(\?|('[^']*')|\d+))?(?:\s+ORDER BY\s+("[^"]+"|\w+)\s+DESC)?$/i
96 .exec(statement)
97 if (match !== null) {
98 const table = unquote(match[2])
99 const selectedColumns = match[1].trim() === "*"
100 ? this.columns.get(table) ?? []
101 : match[1].split(",").map((column) => unquote(column.trim()))
102 let rows = [...(this.tables.get(table) ?? [])]
103 if (match[3] !== undefined) {
104 const column = unquote(match[3])
105 const value = match[4] === "?" ? params[0] : parseValue(match[4], [], () => 0)
106 rows = rows.filter((row) => row[column] === value)
107 }
108 if (match[6] !== undefined) {
109 const column = unquote(match[6])
110 rows.sort((a, b) => Number(b[column]) - Number(a[column]))
111 }
112 return new FakeCursor(rows, selectedColumns)
113 }
114 }
115
116 return new FakeCursor([])
117 }
118}
119
120class FakeDurableObjectStorage {
121 readonly sql = new FakeSqlStorage()
122 transactionCalls = 0
123 rollbackCalls = 0
124
125 transaction<T>(body: (txn: { rollback: () => void }) => Promise<T>): Promise<T> {
126 this.transactionCalls++
127 const snapshot = this.sql.snapshot()
128 let rolledBack = false
129 const txn = {
130 rollback: () => {
131 this.rollbackCalls++
132 rolledBack = true
133 }
134 }
135 return Promise.resolve().then(() => body(txn)).then(
136 (value) => {
137 if (rolledBack) {
138 this.sql.restore(snapshot)
139 }
140 return value
141 },
142 (error) => {
143 this.sql.restore(snapshot)
144 throw error
145 }
146 )
147 }
148}
149
150const normalizeSql = (sql: string) => sql.replace(/;$/, "").replace(/\s+/g, " ").trim()
151
152const unquote = (value: string) => value.replace(/^"|"$/g, "")
153
154const valueGroups = (values: string): Array<string> =>
155 values.match(/\(([^)]*)\)/g)?.map((group) => group.slice(1, -1)) ?? []
156
157const parseValue = (
158 value: string,
159 params: ReadonlyArray<unknown>,
160 nextParamIndex: () => number
161): unknown => {
162 if (value === "?") {
163 return params[nextParamIndex()]
164 }
165 if (/^'.*'$/.test(value)) {
166 return value.slice(1, -1)
167 }
168 const number = Number(value)
169 return Number.isNaN(number) ? value : number
170}
171
172const makeClient = (config: SqliteClient.SqliteClientConfig) =>
173 SqliteClient.make(config).pipe(
174 Effect.scoped,
175 Effect.provide(Reactivity.layer)
176 )
177
178const hasForbiddenTransactionSql = (db: FakeSqlStorage) =>
179 db.statements.some((statement) => /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT)\b/i.test(normalizeSql(statement)))
180
181describe("Client", () => {
182 it.effect("classifies native errors without stable sqlite codes as UnknownError", () =>
183 Effect.gen(function*() {
184 const failingDb = {
185 exec: () => {
186 throw new Error("boom")
187 }
188 } as unknown as SqlStorage
189
190 const client = yield* makeClient({ db: failingDb })
191 const error = yield* Effect.flip(client`SELECT 1`)
192 assert.strictEqual(error.reason._tag, "UnknownError")
193 }))
194
195 it.effect("db-only clients support normal queries", () =>
196 Effect.gen(function*() {
197 const db = new FakeSqlStorage()
198 const sql = yield* makeClient({ db: db as unknown as SqlStorage })
199
200 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
201 yield* sql`INSERT INTO test (name) VALUES (${"hello"})`
202 const rows = yield* sql`SELECT * FROM test`
203
204 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
205 }))
206
207 it.effect("db-only transactions fail clearly without transaction SQL", () =>
208 Effect.gen(function*() {
209 const db = new FakeSqlStorage()
210 const sql = yield* makeClient({ db: db as unknown as SqlStorage })
211
212 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
213 const error = yield* Effect.flip(sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`))
214 const rows = yield* sql`SELECT * FROM test`
215
216 assert.strictEqual(error.reason._tag, "UnknownError")
217 assert.match(error.message, /Transactions require Durable Object storage/)
218 assert.deepStrictEqual(rows, [])
219 assert.strictEqual(hasForbiddenTransactionSql(db), false)
220 }))
221
222 it.effect("storage-backed transactions use DurableObjectStorage.transaction", () =>
223 Effect.gen(function*() {
224 const storage = new FakeDurableObjectStorage()
225 const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage })
226
227 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
228 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)
229 const rows = yield* sql`SELECT * FROM test`
230
231 assert.strictEqual(storage.transactionCalls, 1)
232 assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }])
233 assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false)
234 }))
235
236 it.effect("storage-backed failed transactions roll back and re-emit the original failure", () =>
237 Effect.gen(function*() {
238 const storage = new FakeDurableObjectStorage()
239 const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage })
240
241 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
242 const error = yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
243 Effect.andThen(Effect.fail("boom")),
244 sql.withTransaction,
245 Effect.flip
246 )
247 const rows = yield* sql`SELECT * FROM test`
248
249 assert.strictEqual(error, "boom")
250 assert.deepStrictEqual(rows, [])
251 assert.strictEqual(storage.rollbackCalls, 1)
252 }))
253
254 it.effect("storage-backed interrupted transactions roll back before release", () =>
255 Effect.gen(function*() {
256 const storage = new FakeDurableObjectStorage()
257 const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage })
258 const inserted = yield* Deferred.make<void>()
259
260 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
261 const fiber = yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe(
262 Effect.tap(() => Deferred.succeed(inserted, void 0)),
263 Effect.andThen(Effect.never),
264 sql.withTransaction,
265 Effect.forkChild
266 )
267 yield* Deferred.await(inserted)
268 yield* Fiber.interrupt(fiber)
269 const rows = yield* sql`SELECT * FROM test`
270
271 assert.deepStrictEqual(rows, [])
272 assert.strictEqual(storage.rollbackCalls, 1)
273 }))
274
275 it.effect("nested transactions fail clearly without savepoint SQL", () =>
276 Effect.gen(function*() {
277 const storage = new FakeDurableObjectStorage()
278 const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage })
279
280 yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`
281 const error = yield* sql.withTransaction(
282 Effect.gen(function*() {
283 yield* sql`INSERT INTO test (name) VALUES ('outer')`
284 yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('inner')`)
285 })
286 ).pipe(Effect.flip)
287 const rows = yield* sql`SELECT * FROM test`
288
289 assert.strictEqual(error.reason._tag, "UnknownError")
290 assert.match(error.message, /Nested transactions are not supported/)
291 assert.deepStrictEqual(rows, [])
292 assert.strictEqual(storage.rollbackCalls, 1)
293 assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false)
294 }))
295
296 it.effect("SqliteMigrator.run works with storage-backed transactions", () =>
297 Effect.gen(function*() {
298 const storage = new FakeDurableObjectStorage()
299 const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage })
300
301 const completed = yield* SqliteMigrator.run({
302 loader: SqliteMigrator.fromRecord({
303 "1_create": Effect.gen(function*() {
304 const sql = yield* SqlClient.SqlClient
305 yield* sql`CREATE TABLE migrated (id INTEGER PRIMARY KEY, name TEXT)`
306 yield* sql`INSERT INTO migrated (name) VALUES ('ok')`
307 })
308 })
309 }).pipe(Effect.provideService(SqlClient.SqlClient, sql))
310 const rows = yield* sql`SELECT * FROM migrated`
311 const migrations = yield* sql`SELECT * FROM effect_sql_migrations`
312
313 assert.deepStrictEqual(completed, [[1, "create"]])
314 assert.deepStrictEqual(rows, [{ id: 1, name: "ok" }])
315 assert.deepStrictEqual(migrations, [{ migration_id: 1, name: "create", created_at: "current_timestamp" }])
316 assert.strictEqual(storage.transactionCalls, 1)
317 assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false)
318 }))
319})