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