Open History to see the last commit
1import {
2 batch,
3 createEffect,
4 createMemo,
5 createResource,
6 createSignal,
7 onCleanup,
8 untrack,
9} from 'solid-js'
10import { ReactiveMap } from '@solid-primitives/map'
11import {
12 BaseQueryBuilder,
13 createLiveQueryObserver,
14 getLiveQueryStatusFlags,
15 getPublicCollection,
16 isSingleResultCollection,
17 prepareLiveQueryValue,
18 resolveLiveQueryValue,
19 toBoundaryError,
20} from '@tanstack/db'
21import { createStore, reconcile } from 'solid-js/store'
22import { createRowStore, createStoreReadView } from './store-materialization'
23import type { Accessor } from 'solid-js'
24import type {
25 ChangeMessage,
26 Collection,
27 CollectionStatus,
28 Context,
29 GetResult,
30 HealthNode,
31 InferResultType,
32 InitialQueryBuilder,
33 LiveQueryHookConfig,
34 LiveQueryObserver,
35 LiveQueryStatusFlags,
36 NonSingleResult,
37 QueryBuilder,
38 SingleResult,
39} from '@tanstack/db'
40
41const DEFAULT_GC_TIME_MS = 1
42
43type InferConditionalResultType<TContext extends Context> =
44 TContext extends SingleResult
45 ? InferResultType<TContext> | []
46 : InferResultType<TContext>
47
48/**
49 * Create a live query using a query function
50 * @param queryFn - Query function that defines what data to fetch
51 * @returns Accessor that returns data with Suspense support, with state and status information as properties
52 * @example
53 * // Basic query with object syntax
54 * const todosQuery = useLiveQuery((q) =>
55 * q.from({ todos: todosCollection })
56 * .where(({ todos }) => eq(todos.completed, false))
57 * .select(({ todos }) => ({ id: todos.id, text: todos.text }))
58 * )
59 *
60 * @example
61 * // With dependencies that trigger re-execution
62 * const todosQuery = useLiveQuery(
63 * (q) => q.from({ todos: todosCollection })
64 * .where(({ todos }) => gt(todos.priority, minPriority())),
65 * )
66 *
67 * @example
68 * // Join pattern
69 * const personIssues = useLiveQuery((q) =>
70 * q.from({ issues: issueCollection })
71 * .join({ persons: personCollection }, ({ issues, persons }) =>
72 * eq(issues.userId, persons.id)
73 * )
74 * .select(({ issues, persons }) => ({
75 * id: issues.id,
76 * title: issues.title,
77 * userName: persons.name
78 * }))
79 * )
80 *
81 * @example
82 * // Handle loading and error states
83 * const todosQuery = useLiveQuery((q) =>
84 * q.from({ todos: todoCollection })
85 * )
86 *
87 * return (
88 * <Switch>
89 * <Match when={todosQuery.isLoading}>
90 * <div>Loading...</div>
91 * </Match>
92 * <Match when={todosQuery.isLoadingError}>
93 * <div>Error: {todosQuery.status}</div>
94 * </Match>
95 * <Match when={todosQuery.isReady}>
96 * <For each={todosQuery()}>
97 * {(todo) => <li key={todo.id}>{todo.text}</li>}
98 * </For>
99 * </Match>
100 * </Switch>
101 * )
102 *
103 * @example
104 * // Use Suspense boundaries
105 * const todosQuery = useLiveQuery((q) =>
106 * q.from({ todos: todoCollection })
107 * )
108 *
109 * return (
110 * <Suspense fallback={<div>Loading...</div>}>
111 * <For each={todosQuery()}>
112 * {(todo) => <li key={todo.id}>{todo.text}</li>}
113 * </For>
114 * </Suspense>
115 * )
116 */
117
118// Overload 1: Accept query function that always returns QueryBuilder
119export function useLiveQuery<TContext extends Context>(
120 queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,
121): Accessor<InferResultType<TContext>> & {
122 state: ReactiveMap<string | number, GetResult<TContext>>
123 collection: Collection<GetResult<TContext>, string | number, {}>
124 status: CollectionStatus
125} & LiveQueryStatusFlags
126
127// Overload 1b: Accept query function that can return undefined/null
128export function useLiveQuery<TContext extends Context>(
129 queryFn: (
130 q: InitialQueryBuilder,
131 ) => QueryBuilder<TContext> | undefined | null,
132): Accessor<InferConditionalResultType<TContext>> & {
133 state: ReactiveMap<string | number, GetResult<TContext>>
134 collection: Collection<GetResult<TContext>, string | number, {}> | null
135 status: CollectionStatus | `disabled`
136} & LiveQueryStatusFlags
137
138/**
139 * Create a live query using configuration object
140 * @param config - Configuration object with query and options
141 * @returns Accessor that returns data with Suspense support, with state and status information as properties
142 * @example
143 * // Basic config object usage
144 * const todosQuery = useLiveQuery(() => ({
145 * query: (q) => q.from({ todos: todosCollection }),
146 * gcTime: 60000
147 * }))
148 *
149 * @example
150 * // With query builder and options
151 * const queryBuilder = new Query()
152 * .from({ persons: collection })
153 * .where(({ persons }) => gt(persons.age, 30))
154 * .select(({ persons }) => ({ id: persons.id, name: persons.name }))
155 *
156 * const personsQuery = useLiveQuery(() => ({ query: queryBuilder }))
157 *
158 * @example
159 * // Handle all states uniformly
160 * const itemsQuery = useLiveQuery(() => ({
161 * query: (q) => q.from({ items: itemCollection })
162 * }))
163 *
164 * return (
165 * <Switch fallback={<div>{itemsQuery().length} items loaded</div>}>
166 * <Match when={itemsQuery.isLoading}>
167 * <div>Loading...</div>
168 * </Match>
169 * <Match when={itemsQuery.isLoadingError}>
170 * <div>Something went wrong</div>
171 * </Match>
172 * <Match when={!itemsQuery.isReady}>
173 * <div>Preparing...</div>
174 * </Match>
175 * </Switch>
176 * )
177 */
178// Overload 2: Accept config object
179export function useLiveQuery<TContext extends Context>(
180 config: Accessor<LiveQueryHookConfig<TContext>>,
181): Accessor<InferResultType<TContext>> & {
182 state: ReactiveMap<string | number, GetResult<TContext>>
183 collection: Collection<GetResult<TContext>, string | number, {}>
184 status: CollectionStatus
185} & LiveQueryStatusFlags
186
187/**
188 * Subscribe to an existing live query collection
189 * @param liveQueryCollection - Pre-created live query collection to subscribe to
190 * @returns Accessor that returns data with Suspense support, with state and status information as properties
191 * @example
192 * // Using pre-created live query collection
193 * const myLiveQuery = createLiveQueryCollection((q) =>
194 * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))
195 * )
196 * const todosQuery = useLiveQuery(() => myLiveQuery)
197 *
198 * @example
199 * // Access collection methods directly
200 * const existingQuery = useLiveQuery(() => existingCollection)
201 *
202 * // Use collection for mutations
203 * const handleToggle = (id) => {
204 * existingQuery.collection.update(id, draft => { draft.completed = !draft.completed })
205 * }
206 *
207 * @example
208 * // Handle states consistently
209 * const sharedQuery = useLiveQuery(() => sharedCollection)
210 *
211 * return (
212 * <Switch fallback={<div><For each={sharedQuery()}>{(item) => <Item key={item.id} {...item} />}</For></div>}>
213 * <Match when={sharedQuery.isLoading}>
214 * <div>Loading...</div>
215 * </Match>
216 * <Match when={sharedQuery.isLoadingError}>
217 * <div>Error loading data</div>
218 * </Match>
219 * </Switch>
220 * )
221 */
222// Overload 3: Accept pre-created live query collection (non-single result)
223export function useLiveQuery<
224 TResult extends object,
225 TKey extends string | number,
226 TUtils extends Record<string, any>,
227>(
228 liveQueryCollection: Accessor<
229 Collection<TResult, TKey, TUtils> & NonSingleResult
230 >,
231): Accessor<Array<TResult>> & {
232 state: ReactiveMap<TKey, TResult>
233 collection: Collection<TResult, TKey, TUtils>
234 status: CollectionStatus
235} & LiveQueryStatusFlags
236
237// Overload 3b: Accept pre-created live query collection with singleResult: true
238export function useLiveQuery<
239 TResult extends object,
240 TKey extends string | number,
241 TUtils extends Record<string, any>,
242>(
243 liveQueryCollection: Accessor<
244 Collection<TResult, TKey, TUtils> & SingleResult
245 >,
246): Accessor<TResult | undefined> & {
247 state: ReactiveMap<TKey, TResult>
248 collection: Collection<TResult, TKey, TUtils> & SingleResult
249 status: CollectionStatus
250} & LiveQueryStatusFlags
251
252// Implementation - use function overloads to infer the actual collection type
253export function useLiveQuery(
254 configOrQueryOrCollection: (queryFn?: any) => any,
255) {
256 const collection = createMemo(
257 () => {
258 const value =
259 configOrQueryOrCollection.length === 1
260 ? configOrQueryOrCollection(
261 new BaseQueryBuilder() as InitialQueryBuilder,
262 )
263 : configOrQueryOrCollection()
264 // Query-input reads define binding dependencies. Compilation can drain
265 // source rows synchronously; those reads belong to the result instead.
266 const prepared = prepareLiveQueryValue(value, undefined)
267 return untrack(() =>
268 resolveLiveQueryValue(prepared, { gcTime: DEFAULT_GC_TIME_MS }),
269 )
270 },
271 undefined,
272 { name: `TanstackDBCollectionMemo` },
273 )
274
275 // Reactive state that gets updated granularly through change events
276 const state = new ReactiveMap<string | number, any>()
277
278 // Keep the live Collection's result keys private while preserving one stable
279 // Solid store per logical row. A row's public $key can belong to an upstream
280 // Collection and is therefore not necessarily unique in this result.
281 const rowsByKey = new Map<
282 string | number,
283 { value: any; update: (value: any) => void }
284 >()
285 let rowsCollection: Collection<any, any, any> | undefined
286 const [data, setData] = createStore<Array<any>>([], {
287 name: `TanstackDBData`,
288 })
289
290 const readData = createStoreReadView(data)
291
292 // Track collection status reactively
293 const [status, setStatus] = createSignal(
294 collection() ? collection()!.status : (`disabled` as const),
295 {
296 name: `TanstackDBStatus`,
297 },
298 )
299 const [health, setHealth] = createSignal<HealthNode | undefined>(undefined)
300 // Every status flag comes from the shared rule; a disabled query is ready.
301 const flags = createMemo(() =>
302 getLiveQueryStatusFlags(status() as CollectionStatus, health()),
303 )
304
305 // Helper to sync data array from collection in correct order
306 const syncDataFromCollection = (
307 currentCollection: Collection<any, any, any>,
308 ) => {
309 const nextRows: Array<any> = []
310 const retainedKeys = new Set<string | number>()
311
312 for (const [key, value] of currentCollection.entries()) {
313 retainedKeys.add(key)
314
315 const existing = rowsByKey.get(key)
316 if (existing) {
317 existing.update(value)
318 nextRows.push(existing.value)
319 } else {
320 const row = createRowStore(value)
321 rowsByKey.set(key, row)
322 nextRows.push(row.value)
323 }
324 }
325
326 for (const key of rowsByKey.keys()) {
327 if (!retainedKeys.has(key)) rowsByKey.delete(key)
328 }
329
330 setData((previous) => reconcile(nextRows, { key: null })(previous))
331 }
332
333 // Generation guard for the resource's async continuations: Solid discards a
334 // superseded fetch's *return value*, but the writes below are side effects
335 // into hook-scoped state and would still run — resurrecting rows/status from
336 // a collection that has already been replaced.
337 let resourceGeneration = 0
338 let localWait:
339 | {
340 observer: LiveQueryObserver<any, any>
341 collection: Collection<any, any, any>
342 ready: boolean
343 }
344 | undefined
345 let subscribedCollection: Collection<any, any, any> | undefined
346 const releaseLocalWait = () => {
347 localWait?.observer.dispose()
348 localWait = undefined
349 }
350 onCleanup(() => {
351 resourceGeneration++
352 releaseLocalWait()
353 })
354
355 const [getDataResource] = createResource(
356 () => ({ currentCollection: collection() }),
357 async ({ currentCollection }) => {
358 const generation = ++resourceGeneration
359 releaseLocalWait()
360 if (!currentCollection) {
361 return []
362 }
363 setStatus(currentCollection.status)
364 setHealth(currentCollection.health)
365 try {
366 const observer = createLiveQueryObserver(currentCollection)
367 localWait = {
368 observer,
369 collection: currentCollection,
370 ready: false,
371 }
372 try {
373 await observer.preload()
374 } catch (error) {
375 if (generation === resourceGeneration) releaseLocalWait()
376 throw error
377 }
378 if (generation !== resourceGeneration) return data
379 localWait.ready = true
380 // `preload` waits for readiness but does not itself
381 // retain the Collection after it settles. Hold one observer
382 // subscription across Solid's ready-before-commit Suspense gap.
383 observer.subscribe(() => {})
384 // Solid disposes a provisional effect only after the resource settles
385 // and Suspense re-evaluates the branch. Check on the next turn: a real
386 // commit still owns the Collection, while a suspended branch keeps the
387 // preload observer until its later commit or root cleanup.
388 setTimeout(() => {
389 if (
390 localWait?.observer === observer &&
391 subscribedCollection === currentCollection
392 ) {
393 releaseLocalWait()
394 }
395 }, 0)
396 } catch (error) {
397 if (generation !== resourceGeneration) return data
398 // A crashed Collection also rejects preload; keep its crash visible.
399 setStatus(currentCollection.status === `crashed` ? `crashed` : `error`)
400 throw toBoundaryError(error)
401 }
402 if (generation !== resourceGeneration) {
403 return data
404 }
405 // Initialize state with current collection data
406 batch(() => {
407 state.clear()
408 for (const [key, value] of currentCollection.entries()) {
409 state.set(key, value)
410 }
411 syncDataFromCollection(currentCollection)
412 setStatus(currentCollection.status)
413 setHealth(currentCollection.health)
414 })
415 return data
416 },
417 {
418 name: `TanstackDBData`,
419 deferStream: false,
420 initialValue: data,
421 },
422 )
423
424 createEffect(() => {
425 const currentCollection = collection()
426 if (!currentCollection) {
427 setStatus(`disabled` as const)
428 setHealth(undefined)
429 state.clear()
430 rowsByKey.clear()
431 rowsCollection = undefined
432 setData([])
433 return
434 }
435
436 if (rowsCollection !== currentCollection) {
437 rowsByKey.clear()
438 rowsCollection = currentCollection
439 }
440
441 // The shared observer owns subscription, the ready-race, and status; Solid
442 // materializes into its keyed ReactiveMap (granular) + reconciled store.
443 const observer = createLiveQueryObserver(currentCollection)
444 // Clear any keys carried over from a previous collection before the new
445 // observer re-seeds via `includeInitialState` (which only inserts current
446 // rows, never deletes stale ones). Without this, switching collections
447 // leaves the dropped keys in `state` until the async resource reconciles.
448 state.clear()
449 const unsubscribe = observer.subscribe(
450 (changes: Array<ChangeMessage<any>> | undefined) => {
451 batch(() => {
452 if (changes) {
453 for (const change of changes) {
454 switch (change.type) {
455 case `insert`:
456 case `update`:
457 state.set(change.key, change.value)
458 break
459 case `delete`:
460 state.delete(change.key)
461 break
462 }
463 }
464 } else {
465 // Cleanup and other status-only publications carry no row deltas.
466 // Rebuild the keyed view so it cannot diverge from ordered data.
467 state.clear()
468 for (const [key, value] of observer.getSnapshot().state ?? []) {
469 state.set(key, value)
470 }
471 }
472 syncDataFromCollection(currentCollection)
473 const snapshot = observer.getSnapshot()
474 setStatus(snapshot.status)
475 setHealth(snapshot.health)
476 })
477 },
478 )
479 subscribedCollection = currentCollection
480 if (localWait?.ready && localWait.collection === currentCollection) {
481 releaseLocalWait()
482 }
483 // An already-ready empty collection produces no initial row batch. Bring
484 // ordered data and status in line synchronously instead of waiting for the
485 // resource continuation to correct the previous collection's rows.
486 batch(() => {
487 syncDataFromCollection(currentCollection)
488 const snapshot = observer.getSnapshot()
489 setStatus(snapshot.status)
490 setHealth(snapshot.health)
491 })
492
493 onCleanup(() => {
494 if (subscribedCollection === currentCollection) {
495 subscribedCollection = undefined
496 }
497 unsubscribe()
498 observer.dispose()
499 })
500 })
501
502 // We have to remove getters from the resource function so we wrap it
503 function getData() {
504 const currentCollection = collection()
505 if (currentCollection) {
506 if (isSingleResultCollection(currentCollection)) {
507 // Force resource tracking so Suspense works
508 getDataResource()
509 return readData[0]
510 }
511 }
512 const result = getDataResource()
513 return result === data ? readData : result
514 }
515
516 Object.defineProperties(getData, {
517 status: {
518 get() {
519 return status()
520 },
521 },
522 collection: {
523 get() {
524 return getPublicCollection(collection())
525 },
526 },
527 state: {
528 get() {
529 return state
530 },
531 },
532 isLoading: {
533 get() {
534 return flags().isLoading
535 },
536 },
537 isReady: {
538 get() {
539 return flags().isReady || status() === `disabled`
540 },
541 },
542 isIdle: {
543 get() {
544 return flags().isIdle
545 },
546 },
547 isLoadingError: {
548 get() {
549 return flags().isLoadingError
550 },
551 },
552 isCrashed: {
553 get() {
554 return flags().isCrashed
555 },
556 },
557 isCleanedUp: {
558 get() {
559 return flags().isCleanedUp
560 },
561 },
562 isSyncError: {
563 get() {
564 return flags().isSyncError
565 },
566 },
567 health: {
568 get() {
569 return health()
570 },
571 },
572 })
573 return getData
574}