The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { DurableObjectStorage, SqlStorage } from "@cloudflare/workers-types" |
| 2 | import { SqliteClient, SqliteMigrator } from "@effect/sql-sqlite-do" |
| 3 | import { assert, describe, it } from "@effect/vitest" |
| 4 | import { Deferred, Effect, Exit, Fiber, Schema, Stream } from "effect" |
| 5 | import * as Arr from "effect/Array" |
| 6 | import * as Reactivity from "effect/reactivity/Reactivity" |
| 7 | import * as SqlClient from "effect/sql/SqlClient" |
| 8 | import * as SqlResolver from "effect/sql/SqlResolver" |
| 9 | |
| 10 | class FakeCursor { |
| 11 | readonly columnNames: ReadonlyArray<string> |
| 12 | readonly rows: ReadonlyArray<ReadonlyArray<unknown>> |
| 13 | |
| 14 | constructor(rows: ReadonlyArray<Record<string, unknown>>, columns?: ReadonlyArray<string>) { |
| 15 | this.columnNames = columns ?? Object.keys(rows[0] ?? {}) |
| 16 | this.rows = rows.map((row) => this.columnNames.map((column) => row[column])) |
| 17 | } |
| 18 | |
| 19 | *raw() { |
| 20 | yield* this.rows.map((row) => [...row]) |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | class FakeSqlStorage { |
| 25 | readonly statements: Array<string> = [] |
| 26 | tables = new Map<string, Array<Record<string, unknown>>>() |
| 27 | columns = new Map<string, Array<string>>() |
| 28 | |
| 29 | snapshot() { |
| 30 | return { |
| 31 | tables: new Map(Array.from(this.tables, ([table, rows]) => [table, rows.map((row) => ({ ...row }))])), |
| 32 | columns: new Map(Array.from(this.columns, ([table, columns]) => [table, [...columns]])) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | restore(snapshot: ReturnType<FakeSqlStorage["snapshot"]>) { |
| 37 | this.tables = snapshot.tables |
| 38 | this.columns = snapshot.columns |
| 39 | } |
| 40 | |
| 41 | exec(sql: string, ...params: ReadonlyArray<unknown>) { |
| 42 | this.statements.push(sql) |
| 43 | const statement = normalizeSql(sql) |
| 44 | if (/^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT)\b/i.test(statement)) { |
| 45 | throw new Error(`Unsupported transaction SQL: ${statement}`) |
| 46 | } |
| 47 | |
| 48 | if (/^CREATE TABLE\b/i.test(statement)) { |
| 49 | const match = /^CREATE TABLE(?: IF NOT EXISTS)?\s+("[^"]+"|\w+)\s*\((.*)\)$/i.exec(statement) |
| 50 | if (match !== null) { |
| 51 | const table = unquote(match[1]) |
| 52 | if (!this.tables.has(table)) { |
| 53 | this.tables.set(table, []) |
| 54 | this.columns.set( |
| 55 | table, |
| 56 | match[2].split(",").map((part) => unquote(part.trim().split(/\s+/)[0])).filter((column) => |
| 57 | column.length > 0 && column.toUpperCase() !== "PRIMARY" |
| 58 | ) |
| 59 | ) |
| 60 | } |
| 61 | } |
| 62 | return new FakeCursor([]) |
| 63 | } |
| 64 | |
| 65 | if (/^INSERT INTO\b/i.test(statement)) { |
| 66 | const match = /^INSERT INTO\s+("[^"]+"|\w+)\s*\(([^)]+)\)\s+VALUES\s+(.+)$/i.exec(statement) |
| 67 | if (match !== null) { |
| 68 | const table = unquote(match[1]) |
| 69 | const columns = match[2].split(",").map((column) => unquote(column.trim())) |
| 70 | const rows = this.tables.get(table) ?? [] |
| 71 | const tableColumns = this.columns.get(table) ?? [...columns] |
| 72 | if (!this.tables.has(table)) { |
| 73 | this.tables.set(table, rows) |
| 74 | this.columns.set(table, tableColumns) |
| 75 | } |
| 76 | let paramIndex = 0 |
| 77 | for (const group of valueGroups(match[3])) { |
| 78 | const values = group.split(",").map((value) => parseValue(value.trim(), params, () => paramIndex++)) |
| 79 | const row: Record<string, unknown> = {} |
| 80 | if (tableColumns.includes("id") && !columns.includes("id")) { |
| 81 | row.id = rows.length + 1 |
| 82 | } |
| 83 | for (let i = 0; i < columns.length; i++) { |
| 84 | row[columns[i]] = values[i] |
| 85 | } |
| 86 | if (tableColumns.includes("created_at") && row.created_at === undefined) { |
| 87 | row.created_at = "current_timestamp" |
| 88 | } |
| 89 | rows.push(row) |
| 90 | } |
| 91 | } |
| 92 | return new FakeCursor([]) |
| 93 | } |
| 94 | |
| 95 | if (/^SELECT\b/i.test(statement)) { |
| 96 | const match = |
| 97 | /^SELECT\s+(.+)\s+FROM\s+("[^"]+"|\w+)(?:\s+WHERE\s+("[^"]+"|\w+)\s*=\s*(\?|('[^']*')|\d+))?(?:\s+ORDER BY\s+("[^"]+"|\w+)\s+DESC)?$/i |
| 98 | .exec(statement) |
| 99 | if (match !== null) { |
| 100 | const table = unquote(match[2]) |
| 101 | const selectedColumns = match[1].trim() === "*" |
| 102 | ? this.columns.get(table) ?? [] |
| 103 | : match[1].split(",").map((column) => unquote(column.trim())) |
| 104 | let rows = [...(this.tables.get(table) ?? [])] |
| 105 | if (match[3] !== undefined) { |
| 106 | const column = unquote(match[3]) |
| 107 | const value = match[4] === "?" ? params[0] : parseValue(match[4], [], () => 0) |
| 108 | rows = rows.filter((row) => row[column] === value) |
| 109 | } |
| 110 | if (match[6] !== undefined) { |
| 111 | const column = unquote(match[6]) |
| 112 | rows.sort((a, b) => Number(b[column]) - Number(a[column])) |
| 113 | } |
| 114 | return new FakeCursor(rows, selectedColumns) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | return new FakeCursor([]) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | class FakeDurableObjectStorage { |
| 123 | readonly sql = new FakeSqlStorage() |
| 124 | transactionCalls = 0 |
| 125 | rollbackCalls = 0 |
| 126 | readonly snapshots: Array<ReturnType<FakeSqlStorage["snapshot"]>> = [] |
| 127 | |
| 128 | transaction<T>(body: (txn: { rollback: () => void }) => Promise<T>): Promise<T> { |
| 129 | this.transactionCalls++ |
| 130 | const snapshot = this.sql.snapshot() |
| 131 | this.snapshots.push(snapshot) |
| 132 | let rolledBack = false |
| 133 | const txn = { |
| 134 | rollback: () => { |
| 135 | this.rollbackCalls++ |
| 136 | rolledBack = true |
| 137 | } |
| 138 | } |
| 139 | return Promise.resolve().then(() => body(txn)).then( |
| 140 | (value) => { |
| 141 | if (rolledBack) { |
| 142 | this.sql.restore(snapshot) |
| 143 | } |
| 144 | return value |
| 145 | }, |
| 146 | (error) => { |
| 147 | this.sql.restore(snapshot) |
| 148 | throw error |
| 149 | } |
| 150 | ).finally(() => { |
| 151 | assert.strictEqual(this.snapshots.pop(), snapshot) |
| 152 | }) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | const normalizeSql = (sql: string) => sql.replace(/;$/, "").replace(/\s+/g, " ").trim() |
| 157 | |
| 158 | const unquote = (value: string) => value.replace(/^"|"$/g, "") |
| 159 | |
| 160 | const valueGroups = (values: string): Array<string> => |
| 161 | values.match(/\(([^)]*)\)/g)?.map((group) => group.slice(1, -1)) ?? [] |
| 162 | |
| 163 | const parseValue = ( |
| 164 | value: string, |
| 165 | params: ReadonlyArray<unknown>, |
| 166 | nextParamIndex: () => number |
| 167 | ): unknown => { |
| 168 | if (value === "?") { |
| 169 | return params[nextParamIndex()] |
| 170 | } |
| 171 | if (/^'.*'$/.test(value)) { |
| 172 | return value.slice(1, -1) |
| 173 | } |
| 174 | const number = Number(value) |
| 175 | return Number.isNaN(number) ? value : number |
| 176 | } |
| 177 | |
| 178 | const makeClient = (config: SqliteClient.SqliteClientConfig) => |
| 179 | SqliteClient.make(config).pipe( |
| 180 | Effect.scoped, |
| 181 | Effect.provide(Reactivity.layer) |
| 182 | ) |
| 183 | |
| 184 | const hasForbiddenTransactionSql = (db: FakeSqlStorage) => |
| 185 | db.statements.some((statement) => /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT)\b/i.test(normalizeSql(statement))) |
| 186 | |
| 187 | describe("Client", () => { |
| 188 | it.effect("classifies native errors and releases the connection for the next statement", () => |
| 189 | Effect.gen(function*() { |
| 190 | const failingDb = { |
| 191 | exec: (statement: string) => { |
| 192 | if (statement === "SELECT broken") { |
| 193 | throw new Error("boom") |
| 194 | } |
| 195 | return new FakeCursor([{ value: 1 }]) |
| 196 | } |
| 197 | } as unknown as SqlStorage |
| 198 | |
| 199 | const client = yield* makeClient({ db: failingDb }) |
| 200 | const error = yield* Effect.flip(client`SELECT broken`) |
| 201 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 202 | assert.deepStrictEqual(yield* client`SELECT 1`, [{ value: 1 }]) |
| 203 | })) |
| 204 | |
| 205 | it.effect("classifies streaming native errors without stable sqlite codes as UnknownError", () => |
| 206 | Effect.gen(function*() { |
| 207 | const driverError = new Error("boom") |
| 208 | const failingDb = { |
| 209 | exec: () => { |
| 210 | throw driverError |
| 211 | } |
| 212 | } as unknown as SqlStorage |
| 213 | |
| 214 | const client = yield* makeClient({ db: failingDb }) |
| 215 | const error = yield* client`SELECT 1`.stream.pipe(Stream.runCollect, Effect.flip) |
| 216 | assert.strictEqual(error._tag, "SqlError") |
| 217 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 218 | assert.strictEqual(error.reason.cause, driverError) |
| 219 | })) |
| 220 | |
| 221 | it.effect("db-only clients support normal queries", () => |
| 222 | Effect.gen(function*() { |
| 223 | const db = new FakeSqlStorage() |
| 224 | const sql = yield* makeClient({ db: db as unknown as SqlStorage }) |
| 225 | |
| 226 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 227 | yield* sql`INSERT INTO test (name) VALUES (${"hello"})` |
| 228 | const rows = yield* sql`SELECT * FROM test` |
| 229 | |
| 230 | assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }]) |
| 231 | })) |
| 232 | |
| 233 | it.effect("statements wait for reservations and interrupted waiters do not leak the permit", () => |
| 234 | Effect.gen(function*() { |
| 235 | const db = new FakeSqlStorage() |
| 236 | const sql = yield* makeClient({ db: db as unknown as SqlStorage }) |
| 237 | const reserved = yield* Deferred.make<void>() |
| 238 | const release = yield* Deferred.make<void>() |
| 239 | |
| 240 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 241 | yield* sql`INSERT INTO test (name) VALUES (${"hello"})` |
| 242 | const reservation = yield* Effect.gen(function*() { |
| 243 | yield* sql.reserve |
| 244 | yield* Deferred.succeed(reserved, void 0) |
| 245 | yield* Deferred.await(release) |
| 246 | }).pipe(Effect.scoped, Effect.forkChild) |
| 247 | yield* Deferred.await(reserved) |
| 248 | |
| 249 | const interrupted = yield* sql`SELECT * FROM test`.pipe(Effect.forkChild({ startImmediately: true })) |
| 250 | assert.isUndefined(interrupted.pollUnsafe()) |
| 251 | yield* Fiber.interrupt(interrupted) |
| 252 | assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(interrupted))) |
| 253 | |
| 254 | const query = yield* sql`SELECT * FROM test`.pipe(Effect.forkChild({ startImmediately: true })) |
| 255 | assert.isUndefined(query.pollUnsafe()) |
| 256 | yield* Deferred.succeed(release, void 0) |
| 257 | yield* Fiber.join(reservation) |
| 258 | assert.deepStrictEqual(yield* Fiber.join(query), [{ id: 1, name: "hello" }]) |
| 259 | assert.deepStrictEqual(yield* sql`SELECT * FROM test`, [{ id: 1, name: "hello" }]) |
| 260 | })) |
| 261 | |
| 262 | it.effect("db-only transactions fail clearly without transaction SQL", () => |
| 263 | Effect.gen(function*() { |
| 264 | const db = new FakeSqlStorage() |
| 265 | const sql = yield* makeClient({ db: db as unknown as SqlStorage }) |
| 266 | |
| 267 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 268 | const error = yield* Effect.flip(sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`)) |
| 269 | const rows = yield* sql`SELECT * FROM test` |
| 270 | |
| 271 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 272 | assert.match(error.message, /Transactions require Durable Object storage/) |
| 273 | assert.deepStrictEqual(rows, []) |
| 274 | assert.strictEqual(hasForbiddenTransactionSql(db), false) |
| 275 | })) |
| 276 | |
| 277 | it.effect("storage-backed transactions use DurableObjectStorage.transaction", () => |
| 278 | Effect.gen(function*() { |
| 279 | const storage = new FakeDurableObjectStorage() |
| 280 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 281 | |
| 282 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 283 | yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('hello')`) |
| 284 | const rows = yield* sql`SELECT * FROM test` |
| 285 | |
| 286 | assert.strictEqual(storage.transactionCalls, 1) |
| 287 | assert.deepStrictEqual(rows, [{ id: 1, name: "hello" }]) |
| 288 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 289 | })) |
| 290 | |
| 291 | it.effect("storage-backed failed transactions roll back and re-emit the original failure", () => |
| 292 | Effect.gen(function*() { |
| 293 | const storage = new FakeDurableObjectStorage() |
| 294 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 295 | |
| 296 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 297 | const error = yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe( |
| 298 | Effect.andThen(Effect.fail("boom")), |
| 299 | sql.withTransaction, |
| 300 | Effect.flip |
| 301 | ) |
| 302 | const rows = yield* sql`SELECT * FROM test` |
| 303 | |
| 304 | assert.strictEqual(error, "boom") |
| 305 | assert.deepStrictEqual(rows, []) |
| 306 | assert.strictEqual(storage.rollbackCalls, 1) |
| 307 | })) |
| 308 | |
| 309 | it.effect("propagates native rejection after the body succeeds before releasing the connection", () => |
| 310 | Effect.gen(function*() { |
| 311 | const storage = new FakeDurableObjectStorage() |
| 312 | const commitError = new Error("native completion failed") |
| 313 | const bodyCompleted = yield* Deferred.make<void>() |
| 314 | let complete!: () => void |
| 315 | const completion = new Promise<void>((resolve) => { |
| 316 | complete = resolve |
| 317 | }) |
| 318 | const sql = yield* makeClient({ |
| 319 | storage: { |
| 320 | sql: storage.sql, |
| 321 | transaction: <T>(body: (txn: { rollback: () => void }) => Promise<T>) => |
| 322 | storage.transaction(async (txn) => { |
| 323 | await body(txn) |
| 324 | Deferred.doneUnsafe(bodyCompleted, Effect.void) |
| 325 | await completion |
| 326 | throw commitError |
| 327 | }) |
| 328 | } as unknown as DurableObjectStorage |
| 329 | }) |
| 330 | |
| 331 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 332 | const transaction = yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe( |
| 333 | sql.withTransaction, |
| 334 | Effect.flip, |
| 335 | Effect.forkChild |
| 336 | ) |
| 337 | yield* Deferred.await(bodyCompleted) |
| 338 | const query = yield* sql`SELECT * FROM test`.pipe(Effect.forkChild({ startImmediately: true })) |
| 339 | const transactionBeforeCompletion = transaction.pollUnsafe() |
| 340 | const queryBeforeCompletion = query.pollUnsafe() |
| 341 | complete() |
| 342 | |
| 343 | const error = yield* Fiber.join(transaction) |
| 344 | const rows = yield* Fiber.join(query) |
| 345 | assert.isUndefined(transactionBeforeCompletion) |
| 346 | assert.isUndefined(queryBeforeCompletion) |
| 347 | assert.strictEqual(error._tag, "SqlError") |
| 348 | assert.strictEqual(error.reason.cause, commitError) |
| 349 | assert.strictEqual(storage.rollbackCalls, 0) |
| 350 | assert.strictEqual(storage.transactionCalls, 1) |
| 351 | assert.deepStrictEqual(rows, []) |
| 352 | })) |
| 353 | |
| 354 | it.effect("storage-backed interrupted transactions roll back before release", () => |
| 355 | Effect.gen(function*() { |
| 356 | const storage = new FakeDurableObjectStorage() |
| 357 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 358 | const inserted = yield* Deferred.make<void>() |
| 359 | |
| 360 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 361 | const fiber = yield* sql`INSERT INTO test (name) VALUES ('hello')`.pipe( |
| 362 | Effect.tap(() => Deferred.succeed(inserted, void 0)), |
| 363 | Effect.andThen(Effect.never), |
| 364 | sql.withTransaction, |
| 365 | Effect.forkChild |
| 366 | ) |
| 367 | yield* Deferred.await(inserted) |
| 368 | yield* Fiber.interrupt(fiber) |
| 369 | const rows = yield* sql`SELECT * FROM test` |
| 370 | |
| 371 | assert.deepStrictEqual(rows, []) |
| 372 | assert.strictEqual(storage.rollbackCalls, 1) |
| 373 | })) |
| 374 | |
| 375 | it.effect("nested transactions commit inner and outer writes without transaction SQL", () => |
| 376 | Effect.gen(function*() { |
| 377 | const storage = new FakeDurableObjectStorage() |
| 378 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 379 | |
| 380 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 381 | yield* sql.withTransaction( |
| 382 | Effect.gen(function*() { |
| 383 | yield* sql`INSERT INTO test (name) VALUES ('outer')` |
| 384 | yield* sql.withTransaction(sql`INSERT INTO test (name) VALUES ('inner')`) |
| 385 | yield* sql`INSERT INTO test (name) VALUES ('after')` |
| 386 | }) |
| 387 | ) |
| 388 | const rows = yield* sql`SELECT * FROM test` |
| 389 | |
| 390 | assert.deepStrictEqual(rows, [ |
| 391 | { id: 1, name: "outer" }, |
| 392 | { id: 2, name: "inner" }, |
| 393 | { id: 3, name: "after" } |
| 394 | ]) |
| 395 | assert.strictEqual(storage.transactionCalls, 2) |
| 396 | assert.strictEqual(storage.rollbackCalls, 0) |
| 397 | assert.deepStrictEqual(storage.snapshots, []) |
| 398 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 399 | })) |
| 400 | |
| 401 | it.effect("cross-client nested transactions fail before opening storage or running the body", () => |
| 402 | Effect.gen(function*() { |
| 403 | const storageA = new FakeDurableObjectStorage() |
| 404 | const storageB = new FakeDurableObjectStorage() |
| 405 | const sqlA = yield* makeClient({ storage: storageA as unknown as DurableObjectStorage }) |
| 406 | const sqlB = yield* makeClient({ storage: storageB as unknown as DurableObjectStorage }) |
| 407 | let bodyRan = false |
| 408 | |
| 409 | const exit = yield* sqlA.withTransaction( |
| 410 | sqlB.withTransaction(Effect.sync(() => { |
| 411 | bodyRan = true |
| 412 | })) |
| 413 | ).pipe(Effect.exit) |
| 414 | |
| 415 | assert.strictEqual(storageA.transactionCalls, 1) |
| 416 | assert.strictEqual(storageB.transactionCalls, 0) |
| 417 | assert.strictEqual(bodyRan, false) |
| 418 | const error = yield* Effect.flip(exit) |
| 419 | assert.strictEqual(error.reason._tag, "UnknownError") |
| 420 | assert.match(error.message, /Transactions cannot use a connection from a different SQLite client/) |
| 421 | })) |
| 422 | |
| 423 | it.effect("caught nested failure rolls back only inner writes and lets the outer transaction commit", () => |
| 424 | Effect.gen(function*() { |
| 425 | const storage = new FakeDurableObjectStorage() |
| 426 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 427 | |
| 428 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 429 | yield* sql.withTransaction( |
| 430 | Effect.gen(function*() { |
| 431 | yield* sql`INSERT INTO test (name) VALUES ('outer')` |
| 432 | const error = yield* sql`INSERT INTO test (name) VALUES ('inner')`.pipe( |
| 433 | Effect.andThen(Effect.fail("inner failure")), |
| 434 | sql.withTransaction, |
| 435 | Effect.flip |
| 436 | ) |
| 437 | assert.strictEqual(error, "inner failure") |
| 438 | assert.deepStrictEqual(yield* sql`SELECT * FROM test`, [{ id: 1, name: "outer" }]) |
| 439 | yield* sql`INSERT INTO test (name) VALUES ('after')` |
| 440 | }) |
| 441 | ) |
| 442 | const rows = yield* sql`SELECT * FROM test` |
| 443 | |
| 444 | assert.deepStrictEqual(rows, [{ id: 1, name: "outer" }, { id: 2, name: "after" }]) |
| 445 | assert.strictEqual(storage.transactionCalls, 2) |
| 446 | assert.strictEqual(storage.rollbackCalls, 1) |
| 447 | assert.deepStrictEqual(storage.snapshots, []) |
| 448 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 449 | })) |
| 450 | |
| 451 | it.effect("uncaught nested failure rolls back the whole transaction", () => |
| 452 | Effect.gen(function*() { |
| 453 | const storage = new FakeDurableObjectStorage() |
| 454 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 455 | |
| 456 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 457 | const error = yield* sql.withTransaction( |
| 458 | Effect.gen(function*() { |
| 459 | yield* sql`INSERT INTO test (name) VALUES ('outer')` |
| 460 | return yield* sql`INSERT INTO test (name) VALUES ('inner')`.pipe( |
| 461 | Effect.andThen(Effect.fail("inner failure")), |
| 462 | sql.withTransaction |
| 463 | ) |
| 464 | }) |
| 465 | ).pipe(Effect.flip) |
| 466 | const rows = yield* sql`SELECT * FROM test` |
| 467 | |
| 468 | assert.strictEqual(error, "inner failure") |
| 469 | assert.deepStrictEqual(rows, []) |
| 470 | assert.strictEqual(storage.transactionCalls, 2) |
| 471 | assert.strictEqual(storage.rollbackCalls, 2) |
| 472 | assert.deepStrictEqual(storage.snapshots, []) |
| 473 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 474 | })) |
| 475 | |
| 476 | it.effect("interrupted nested transactions roll back only the child before the outer transaction continues", () => |
| 477 | Effect.gen(function*() { |
| 478 | const storage = new FakeDurableObjectStorage() |
| 479 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 480 | const inserted = yield* Deferred.make<void>() |
| 481 | |
| 482 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)` |
| 483 | yield* sql.withTransaction( |
| 484 | Effect.gen(function*() { |
| 485 | yield* sql`INSERT INTO test (name) VALUES ('outer')` |
| 486 | const fiber = yield* sql`INSERT INTO test (name) VALUES ('inner')`.pipe( |
| 487 | Effect.tap(() => Deferred.succeed(inserted, void 0)), |
| 488 | Effect.andThen(Effect.never), |
| 489 | sql.withTransaction, |
| 490 | Effect.forkChild |
| 491 | ) |
| 492 | // Surface an early transaction failure rather than waiting for an insert that never happens. |
| 493 | yield* Effect.raceFirst(Deferred.await(inserted), Fiber.join(fiber)) |
| 494 | yield* Fiber.interrupt(fiber) |
| 495 | assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(fiber))) |
| 496 | assert.strictEqual(storage.rollbackCalls, 1) |
| 497 | assert.deepStrictEqual(yield* sql`SELECT * FROM test`, [{ id: 1, name: "outer" }]) |
| 498 | yield* sql`INSERT INTO test (name) VALUES ('after')` |
| 499 | }) |
| 500 | ) |
| 501 | const rows = yield* sql`SELECT * FROM test` |
| 502 | |
| 503 | assert.deepStrictEqual(rows, [{ id: 1, name: "outer" }, { id: 2, name: "after" }]) |
| 504 | assert.strictEqual(storage.transactionCalls, 2) |
| 505 | assert.strictEqual(storage.rollbackCalls, 1) |
| 506 | assert.deepStrictEqual(storage.snapshots, []) |
| 507 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 508 | })) |
| 509 | |
| 510 | it.effect("SqlResolver keeps requests outside a storage-backed transaction out of its batch", () => |
| 511 | Effect.gen(function*() { |
| 512 | const storage = new FakeDurableObjectStorage() |
| 513 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 514 | const batches: Array<Array<number>> = [] |
| 515 | const insert = SqlResolver.request(SqlResolver.void({ |
| 516 | Request: Schema.Number, |
| 517 | execute: (ids) => { |
| 518 | batches.push(ids) |
| 519 | return sql`INSERT INTO test ${sql.insert(Arr.map(ids, (id) => ({ id })))}` |
| 520 | } |
| 521 | })) |
| 522 | |
| 523 | yield* sql`CREATE TABLE test (id INTEGER PRIMARY KEY)` |
| 524 | yield* Effect.all([ |
| 525 | Effect.exit(sql.withTransaction(Effect.andThen(insert(1), Effect.fail("rollback")))), |
| 526 | insert(2) |
| 527 | ], { concurrency: "unbounded" }) |
| 528 | const rows = yield* sql`SELECT * FROM test` |
| 529 | |
| 530 | assert.deepStrictEqual(batches, [[2], [1]]) |
| 531 | assert.deepStrictEqual(rows, [{ id: 2 }]) |
| 532 | })) |
| 533 | |
| 534 | it.effect("SqliteMigrator.run works with storage-backed transactions", () => |
| 535 | Effect.gen(function*() { |
| 536 | const storage = new FakeDurableObjectStorage() |
| 537 | const sql = yield* makeClient({ storage: storage as unknown as DurableObjectStorage }) |
| 538 | |
| 539 | const completed = yield* SqliteMigrator.run({ |
| 540 | loader: SqliteMigrator.fromRecord({ |
| 541 | "1_create": Effect.gen(function*() { |
| 542 | const sql = yield* SqlClient.SqlClient |
| 543 | yield* sql`CREATE TABLE migrated (id INTEGER PRIMARY KEY, name TEXT)` |
| 544 | yield* sql`INSERT INTO migrated (name) VALUES ('ok')` |
| 545 | }) |
| 546 | }) |
| 547 | }).pipe(Effect.provideService(SqlClient.SqlClient, sql)) |
| 548 | const rows = yield* sql`SELECT * FROM migrated` |
| 549 | const migrations = yield* sql`SELECT * FROM effect_sql_migrations` |
| 550 | |
| 551 | assert.deepStrictEqual(completed, [[1, "create"]]) |
| 552 | assert.deepStrictEqual(rows, [{ id: 1, name: "ok" }]) |
| 553 | assert.deepStrictEqual(migrations, [{ migration_id: 1, name: "create", created_at: "current_timestamp" }]) |
| 554 | assert.strictEqual(storage.transactionCalls, 1) |
| 555 | assert.strictEqual(hasForbiddenTransactionSql(storage.sql), false) |
| 556 | })) |
| 557 | }) |