Open History to see the last commit
1/**
2 * Shared helpers for the op-sqlite driver tests: temporary databases, columnar
3 * test harnesses, and the exact-row checkers. The ordinary driver tests in
4 * op-sqlite-driver.test.ts and the alias owner in op-sqlite-driver-oracle.test.ts
5 * import them. The checkers compare with the rows their caller supplies, so
6 * they state no expectation of their own.
7 */
8import { mkdtempSync, rmSync } from 'node:fs'
9import { tmpdir } from 'node:os'
10import { join } from 'node:path'
11import { expect } from 'vitest'
12import { oracleRuns } from '../../db/tests/oracle-config.js'
13import { OpSQLiteDriver } from '../src/op-sqlite-driver'
14import { createOpSQLiteTestDatabase } from './helpers/op-sqlite-test-db'
15import type { SQLiteDriverContractHarnessFactory } from '../../db-sqlite-persistence-core/tests/contracts/sqlite-driver-contract'
16
17export const activeCleanupFns: Array<() => void | Promise<void>> = []
18
19export async function runActiveCleanupFns(): Promise<void> {
20 const cleanupErrors: Array<unknown> = []
21 while (activeCleanupFns.length > 0) {
22 const cleanupFn = activeCleanupFns.pop()
23 try {
24 await Promise.resolve(cleanupFn?.())
25 } catch (error) {
26 cleanupErrors.push(error)
27 }
28 }
29 if (cleanupErrors.length === 1) {
30 throw cleanupErrors[0]
31 }
32 if (cleanupErrors.length > 1) {
33 throw new AggregateError(cleanupErrors, `op-sqlite test cleanup failed`, {
34 cause: cleanupErrors[0],
35 })
36 }
37}
38
39export function createTempSqlitePath(): string {
40 const tempDirectory = mkdtempSync(join(tmpdir(), `db-rn-op-sqlite-test-`))
41 const dbPath = join(tempDirectory, `state.sqlite`)
42 activeCleanupFns.push(() => {
43 rmSync(tempDirectory, { recursive: true, force: true })
44 })
45 return dbPath
46}
47
48export type ColumnarDriverHarness = {
49 driver: OpSQLiteDriver
50 queryExecutions: () => number
51}
52
53export async function withColumnarDriver<T>(
54 fn: (harness: ColumnarDriverHarness) => Promise<T>,
55): Promise<T> {
56 const tempDirectory = mkdtempSync(
57 join(tmpdir(), `db-rn-op-sqlite-alias-contract-`),
58 )
59 let database: ReturnType<typeof createOpSQLiteTestDatabase> | undefined
60 let outcome: { ok: true; value: T } | { ok: false; error: unknown }
61 try {
62 database = createOpSQLiteTestDatabase({
63 filename: join(tempDirectory, `state.sqlite`),
64 resultShape: `execute-async-columnar`,
65 })
66 const queryExecutions = trackQueryExecutions(database)
67 const driver = new OpSQLiteDriver({ database })
68 outcome = {
69 ok: true,
70 value: await fn({ driver, queryExecutions }),
71 }
72 } catch (error) {
73 outcome = { ok: false, error }
74 }
75
76 const cleanupErrors: Array<unknown> = []
77 if (database) {
78 try {
79 await Promise.resolve(database.close())
80 } catch (error) {
81 cleanupErrors.push(error)
82 }
83 }
84 try {
85 rmSync(tempDirectory, { recursive: true, force: true })
86 } catch (error) {
87 cleanupErrors.push(error)
88 }
89
90 if (!outcome.ok) {
91 if (cleanupErrors.length > 0) {
92 throw new AggregateError(
93 [outcome.error, ...cleanupErrors],
94 `op-sqlite alias law and cleanup failed`,
95 { cause: outcome.error },
96 )
97 }
98 throw outcome.error
99 }
100 if (cleanupErrors.length === 1) throw cleanupErrors[0]
101 if (cleanupErrors.length > 1) {
102 throw new AggregateError(cleanupErrors, `op-sqlite alias cleanup failed`, {
103 cause: cleanupErrors[0],
104 })
105 }
106 return outcome.value
107}
108
109export async function queryInjectedResult<T = unknown>(
110 result: unknown,
111 arrayResultMode?: `rows` | `statement-results`,
112): Promise<ReadonlyArray<T>> {
113 return new OpSQLiteDriver({
114 database: {
115 executeAsync: () => Promise.resolve(result),
116 },
117 ...(arrayResultMode ? { arrayResultMode } : {}),
118 }).query<T>(`SELECT * FROM injected_result`)
119}
120
121export function expectExactRows<T>(
122 actual: ReadonlyArray<T>,
123 expected: ReadonlyArray<T>,
124): void {
125 expect(actual).toHaveLength(expected.length)
126 expected.forEach((row, rowIndex) => {
127 if (isRecord(row)) {
128 const actualRow = actual[rowIndex]
129 expect(Object.keys(isRecord(actualRow) ? actualRow : {})).toEqual(
130 Object.keys(row),
131 )
132 }
133 expect(actual[rowIndex]).toEqual(row)
134 })
135}
136
137export function isRecord(value: unknown): value is Record<string, unknown> {
138 return typeof value === `object` && value !== null && !Array.isArray(value)
139}
140
141export function expectExactAliasRows(
142 actual: ReadonlyArray<Record<string, unknown>>,
143 expected: ReadonlyArray<Record<string, unknown>>,
144): void {
145 try {
146 expect(actual).toHaveLength(expected.length)
147 expected.forEach((row, rowIndex) => {
148 expect(Object.keys(actual[rowIndex] ?? {})).toEqual(Object.keys(row))
149 expect(actual[rowIndex]).toEqual(row)
150 })
151 } catch (cause) {
152 throw new Error(`op-sqlite reserved-alias exact-row law violated`, {
153 cause,
154 })
155 }
156}
157
158export const statementResultFieldNames = [
159 `rows`,
160 `resultRows`,
161 `rawRows`,
162 `columnNames`,
163 `results`,
164 `rowsAffected`,
165 `changes`,
166 `insertId`,
167 `lastInsertRowId`,
168 `res`,
169] as const
170
171export const statementResultAliasNames = [
172 ...statementResultFieldNames,
173 `ordinary_name`,
174 `another_value`,
175] as const
176
177export const writeResultFieldNames = [
178 `rowsAffected`,
179 `changes`,
180 `insertId`,
181 `lastInsertRowId`,
182] as const
183
184export type AliasOracleEnvironment = Record<string, string | undefined>
185
186export function readAliasOracleRuns(
187 environment: AliasOracleEnvironment = process.env,
188): number {
189 // A run-count control, not a replay coordinate. Its default is the shared
190 // base count, so TANSTACK_DB_ORACLE_RUNS_MULTIPLIER still scales it.
191 const runsText =
192 environment.TANSTACK_DB_OP_SQLITE_ORACLE_RUNS ?? String(oracleRuns(50))
193 const runs = Number(runsText)
194 if (runsText.trim() === `` || !Number.isSafeInteger(runs) || runs < 1) {
195 throw new Error(
196 `TANSTACK_DB_OP_SQLITE_ORACLE_RUNS must be a positive integer`,
197 )
198 }
199 return runs
200}
201
202export function trackQueryExecutions(
203 database: ReturnType<typeof createOpSQLiteTestDatabase>,
204): () => number {
205 const executeAsync = database.executeAsync
206 if (!executeAsync) {
207 throw new Error(`columnar fixture must expose executeAsync`)
208 }
209 let queryExecutions = 0
210 database.executeAsync = (sql, params) => {
211 if (/^\s*SELECT\b/i.test(sql)) queryExecutions++
212 return executeAsync.call(database, sql, params)
213 }
214 return () => queryExecutions
215}
216
217export function createColumnarDriverHarness(
218 createDatabase: typeof createOpSQLiteTestDatabase = createOpSQLiteTestDatabase,
219): ReturnType<SQLiteDriverContractHarnessFactory> {
220 const tempDirectory = mkdtempSync(join(tmpdir(), `db-rn-op-sqlite-contract-`))
221 let database: ReturnType<typeof createOpSQLiteTestDatabase> | undefined
222 try {
223 const createdDatabase = createDatabase({
224 filename: join(tempDirectory, `state.sqlite`),
225 resultShape: `execute-async-columnar`,
226 })
227 database = createdDatabase
228 const driver = new OpSQLiteDriver({ database: createdDatabase })
229
230 return {
231 driver,
232 cleanup: async () => {
233 const cleanupErrors: Array<unknown> = []
234 try {
235 await Promise.resolve(createdDatabase.close())
236 } catch (error) {
237 cleanupErrors.push(error)
238 }
239 try {
240 rmSync(tempDirectory, { recursive: true, force: true })
241 } catch (error) {
242 cleanupErrors.push(error)
243 }
244 if (cleanupErrors.length === 1) throw cleanupErrors[0]
245 if (cleanupErrors.length > 1) {
246 throw new AggregateError(
247 cleanupErrors,
248 `op-sqlite contract cleanup failed`,
249 { cause: cleanupErrors[0] },
250 )
251 }
252 },
253 }
254 } catch (error) {
255 const cleanupErrors: Array<unknown> = []
256 try {
257 database?.close()
258 } catch (cleanupError) {
259 cleanupErrors.push(cleanupError)
260 }
261 try {
262 rmSync(tempDirectory, { recursive: true, force: true })
263 } catch (cleanupError) {
264 cleanupErrors.push(cleanupError)
265 }
266 if (cleanupErrors.length > 0) {
267 throw new AggregateError(
268 [error, ...cleanupErrors],
269 `op-sqlite contract construction and cleanup failed`,
270 { cause: error },
271 )
272 }
273 throw error
274 }
275}