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

conformance.test.tsx

227 lines6.1 KB

1/**
2 * Solid driver for the shared live-query conformance suite.
3 *
4 * Each mount runs inside a `createRoot` so `unmount` disposes via the captured
5 * dispose fn; the root stays alive between mount and reads so Solid's reactive
6 * getters stay current. Solid auto-tracks signals, so controllable inputs use a
7 * signal read inside the query fn (no deps array). Collection/config inputs are
8 * passed as accessors, per Solid's arity-based input detection.
9 *
10 * `knownGaps` is populated empirically from the run below.
11 */
12import {
13 coalesce,
14 count,
15 createCollection,
16 createLiveQueryCollection,
17 createOptimisticAction,
18 eq,
19 gt,
20 sum,
21} from '@tanstack/db'
22import { createRoot, createSignal } from 'solid-js'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import type {
30 ConformanceResult,
31 ControllableHandle,
32 DeferredSourceHandle,
33 LiveQueryDriver,
34 LiveQueryHandle,
35 QueryBuild,
36 SourceHandle,
37} from '../../db/tests/conformance/contract'
38​
39let sourceSeq = 0
40​
41function writer<T extends { id: string }>(collection: any) {
42 return (type: `insert` | `update` | `delete`, value: T) => {
43 collection.utils.begin()
44 collection.utils.write({ type, value })
45 collection.utils.commit()
46 }
48​
49function makeSource<T extends { id: string }>(
50 initialData: ReadonlyArray<T>,
51): SourceHandle<T> {
52 const collection = createCollection(
53 mockSyncCollectionOptions<T>({
54 id: `conformance-solid-${sourceSeq++}`,
55 getKey: (r) => r.id,
56 initialData: [...initialData],
57 }),
58 )
59 const write = writer<T>(collection)
60 return {
61 collection,
62 insert: (row) => write(`insert`, row),
63 update: (row) => write(`update`, row),
64 remove: (row) => write(`delete`, row),
65 }
67​
68function makeDeferredSource<
69 T extends { id: string },
70>(): DeferredSourceHandle<T> {
71 const collection = createCollection(
72 mockSyncCollectionOptionsNoInitialState<T>({
73 id: `conformance-solid-${sourceSeq++}`,
74 getKey: (r) => r.id,
75 }),
76 )
77 collection.startSyncImmediate()
78 const write = writer<T>(collection)
79 return {
80 collection,
81 insert: (row) => write(`insert`, row),
82 update: (row) => write(`update`, row),
83 remove: (row) => write(`delete`, row),
84 emit: (rows) => {
85 collection.utils.begin()
86 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
87 collection.utils.commit()
88 },
89 markReady: () => collection.utils.markReady(),
90 }
92​
93function makePrecreated(build: QueryBuild, opts?: { startSync?: boolean }) {
94 const collection = createLiveQueryCollection({
95 query: build as any,
96 startSync: opts?.startSync ?? true,
97 })
98 return { collection }
100​
101function makeErrorSource() {
102 const collection = createCollection<{ id: string }>({
103 id: `conformance-solid-err-${sourceSeq++}`,
104 getKey: (r) => r.id,
105 startSync: false,
106 sync: {
107 sync: () => {
108 throw new Error(`conformance: sync failure`)
109 },
110 },
111 })
112 try {
113 collection.startSyncImmediate()
114 } catch {
115 // expected: engine catches the sync error and sets status to `error`
116 }
117 return { collection }
119​
120async function settle() {
121 await new Promise((resolve) => setTimeout(resolve, 10))
123​
124function makeHandle(
125 getResult: () => any,
126 dispose: () => void,
127): LiveQueryHandle {
128 return {
129 current(): ConformanceResult {
130 const result = getResult()
131 return {
132 data: result?.data,
133 state: result?.state,
134 status: result?.status ?? `idle`,
135 isReady: Boolean(result?.isReady),
136 isError: Boolean(result?.isError),
137 // solid-db exposes no `isEnabled`; derive it from status (status-derived).
138 isEnabled: result?.status !== `disabled`,
139 }
140 },
141 flush: settle,
142 async apply(fn: () => void) {
143 fn()
144 await settle()
145 },
146 unmount() {
147 dispose()
148 },
149 }
151​
152function inRoot(fn: () => any): { getResult: () => any; dispose: () => void } {
153 let result: any
154 let dispose!: () => void
155 createRoot((d) => {
156 dispose = d
157 result = fn()
158 })
159 return { getResult: () => result, dispose }
161​
162function mount(build: QueryBuild) {
163 const { getResult, dispose } = inRoot(() => useLiveQuery(build as any))
164 return makeHandle(getResult, dispose)
166​
167function mountCollection(collection: any) {
168 // Solid accepts a pre-created collection via an accessor.
169 const { getResult, dispose } = inRoot(() => useLiveQuery(() => collection))
170 return makeHandle(getResult, dispose)
172​
173function mountConfig(build: QueryBuild) {
174 // Solid accepts the config-object form via an accessor.
175 const { getResult, dispose } = inRoot(() =>
176 useLiveQuery(() => ({ query: build })),
177 )
178 return makeHandle(getResult, dispose)
180​
181function mountDisabled() {
182 // Disabled: an accessor returning null.
183 const { getResult, dispose } = inRoot(() => useLiveQuery(() => null))
184 return makeHandle(getResult, dispose)
186​
187function mountControllable<P>(
188 build: (q: any, param: P) => any,
189 initial: P,
190): ControllableHandle<P> {
191 const [param, setParam] = createSignal<P>(initial)
192 const { getResult, dispose } = inRoot(() =>
193 // Reading param() inside the query fn makes Solid recompute on change.
194 useLiveQuery((q: any) => build(q, param())),
195 )
196 const handle = makeHandle(getResult, dispose)
197 return {
198 ...handle,
199 async setParam(next: P) {
200 setParam(() => next)
201 await settle()
202 },
203 }
205​
206const solidDriver: LiveQueryDriver = {
207 name: `solid`,
208 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
209 makeSource,
210 makeDeferredSource,
211 makePrecreated,
212 makeErrorSource,
213 mount,
214 mountControllable,
215 mountCollection,
216 mountConfig,
217 mountDisabled,
218 // solid-db routes errors through its createResource/Suspense path: reading an
219 // errored query throws (CollectionStateError) for an <ErrorBoundary> to catch,
220 // rather than exposing a readable isError flag. That's a framework idiom, not a
221 // gap — the error-status scenario is parametrized to assert it via the boundary.
222 errorSurface: `throw`,
223 knownGaps: [],
224 features: { serverSnapshot: false, suspense: true },
226​
227runSuite(solidDriver)