Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

do-replacement-batching.test.ts

77 lines2.5 KB

1import { DatabaseSync } from 'node:sqlite'
2import { describe, expect, it } from 'vitest'
3import { SQLiteCorePersistenceAdapter } from '../../db-sqlite-persistence-core/src'
4import { createCloudflareDOSQLiteDriver } from '../src/do-driver'
5​
6// Cloudflare caps each Durable Object SQL query at 100 bound parameters.
7const MAX_BOUND_PARAMETERS = 100
8​
9function toSqliteBinding(value: unknown): string | number | bigint | null {
10 if (value === null || value === undefined) return null
11 if (typeof value === `boolean`) return value ? 1 : 0
12 if (
13 typeof value === `string` ||
14 typeof value === `number` ||
15 typeof value === `bigint`
16 ) {
17 return value
18 }
19 return String(value)
21​
22describe(`Cloudflare Durable Object replacement batching`, () => {
23 it.each([25, 26, 205])(
24 `persists %i replacement rows within the host parameter limit`,
25 async (rowCount) => {
26 const database = new DatabaseSync(`:memory:`)
27 const boundParameterCounts: Array<number> = []
28 const driver = createCloudflareDOSQLiteDriver({
29 sql: {
30 exec: (sql, ...params) => {
31 boundParameterCounts.push(params.length)
32 if (params.length > MAX_BOUND_PARAMETERS) {
33 throw new Error(`host parameter limit exceeded`)
34 }
35 const statement = database.prepare(sql)
36 const bindings = params.map(toSqliteBinding)
37 if (statement.columns().length > 0) {
38 return statement.all(...bindings).map((row) => ({ ...row }))
39 }
40 statement.run(...bindings)
41 return []
42 },
43 },
44 })
45 const adapter = new SQLiteCorePersistenceAdapter({ driver })
46 const collectionId = `cloudflare-batch-${rowCount}`
47 const keys = Array.from(
48 { length: rowCount },
49 (_, index) => `row-${index}`,
50 )
51​
52 try {
53 await adapter.applyCommittedTx(collectionId, {
54 txId: `replacement`,
55 term: 1,
56 seq: 1,
57 rowVersion: 1,
58 truncate: true,
59 mutations: keys.map((key) => ({
60 type: `insert` as const,
61 key,
62 value: { id: key },
63 })),
64 })
65​
66 const snapshot = await adapter.loadResumeSnapshot(collectionId)
67 expect(snapshot.rows.map(({ key }) => key).sort()).toEqual(
68 [...keys].sort(),
69 )
70 expect(snapshot.keySet).toEqual({ status: `consistent` })
71 expect(Math.max(...boundParameterCounts)).toBe(MAX_BOUND_PARAMETERS)
72 } finally {
73 database.close()
74 }
75 },
76 )
77})