Open History to see the last commit
1---
2title: Query Collection
3---
4
5# Query Collection
6
7Query collections provide seamless integration between TanStack DB and TanStack Query, enabling automatic synchronization between your local database and remote data sources.
8
9## Overview
10
11The `@tanstack/query-db-collection` package allows you to create collections that:
12
13- Automatically fetch remote data via TanStack Query
14- Support optimistic updates with automatic rollback on errors
15- Handle persistence through customizable mutation handlers
16- Provide direct write capabilities for directly writing to the sync store
17
18## Installation
19
20```bash
21npm install @tanstack/query-db-collection @tanstack/query-core @tanstack/db
22```
23
24## Basic Usage
25
26```typescript
27import { QueryClient } from "@tanstack/query-core"
28import { createCollection } from "@tanstack/db"
29import { queryCollectionOptions } from "@tanstack/query-db-collection"
30
31const queryClient = new QueryClient()
32
33const todosCollection = createCollection(
34 queryCollectionOptions({
35 queryKey: ["todos"],
36 queryFn: async () => {
37 const response = await fetch("/api/todos")
38 return response.json()
39 },
40 queryClient,
41 getKey: (item) => item.id,
42 })
43)
44```
45
46## Configuration Options
47
48The `queryCollectionOptions` function accepts the following options:
49
50### Required Options
51
52- `queryKey`: The query key for TanStack Query. Can be a static array or a function that receives `LoadSubsetOptions` and returns a key. When using a function, all returned keys must share the base key (`queryKey({})`) as a prefix — see [Query Key Prefix Convention](#query-key-prefix-convention).
53- `queryFn`: Function that fetches data from the server
54- `queryClient`: TanStack Query client instance
55- `getKey`: Function to extract the unique key from an item
56
57### Query Options
58
59- `select`: Function that lets extract array items when they're wrapped with metadata
60- `enabled`: Whether the query should automatically run (default: `true`)
61- `refetchInterval`: Refetch interval in milliseconds (default: 0 — set an interval to enable polling refetching)
62- `retry`: Retry configuration for failed queries
63- `retryDelay`: Delay between retries
64- `staleTime`: How long data is considered fresh
65- `meta`: Optional metadata that will be passed to the query function context
66
67### Using with `queryOptions(...)`
68
69If your app already uses TanStack Query's `queryOptions` helper (e.g. from `@tanstack/react-query`), you can spread those options into `queryCollectionOptions`. Note that `queryFn` must be explicitly provided since query collections require it both in types and at runtime:
70
71```typescript
72import { QueryClient } from "@tanstack/query-core"
73import { createCollection } from "@tanstack/db"
74import { queryCollectionOptions } from "@tanstack/query-db-collection"
75import { queryOptions } from "@tanstack/react-query"
76
77const queryClient = new QueryClient()
78
79const listOptions = queryOptions({
80 queryKey: ["todos"],
81 queryFn: async () => {
82 const response = await fetch("/api/todos")
83 return response.json() as Promise<Array<{ id: string; title: string }>>
84 },
85})
86
87const todosCollection = createCollection(
88 queryCollectionOptions({
89 ...listOptions,
90 queryFn: (context) => listOptions.queryFn!(context),
91 queryClient,
92 getKey: (item) => item.id,
93 }),
94)
95```
96
97If `queryFn` is missing at runtime, `queryCollectionOptions` throws `QueryFnRequiredError`.
98
99### Collection Options
100
101- `id`: Unique identifier for the collection
102- `schema`: Schema for validating items
103- `sync`: Custom sync configuration
104- `startSync`: Whether to start syncing immediately (default: `true`)
105
106### Persistence Handlers
107
108- `onInsert`: Handler called before insert operations
109- `onUpdate`: Handler called before update operations
110- `onDelete`: Handler called before delete operations
111
112## Extending Meta with Custom Properties
113
114The `meta` option allows you to pass additional metadata to your query function. By default, Query Collections automatically include `loadSubsetOptions` in the meta object, which contains filtering, sorting, and pagination options for on-demand queries.
115
116### Type-Safe Meta Access
117
118The `ctx.meta.loadSubsetOptions` property is automatically typed as `LoadSubsetOptions` without requiring any additional imports or type assertions:
119
120```typescript
121import { parseLoadSubsetOptions } from "@tanstack/query-db-collection"
122
123const collection = createCollection(
124 queryCollectionOptions({
125 queryKey: ["products"],
126 syncMode: "on-demand",
127 queryFn: async (ctx) => {
128 // ✅ Type-safe access - no @ts-ignore needed!
129 const options = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
130
131 // Use the parsed options to fetch only what you need
132 return api.getProducts(options)
133 },
134 queryClient,
135 getKey: (item) => item.id,
136 })
137)
138```
139
140### Adding Custom Meta Properties
141
142You can extend the meta type to include your own custom properties using TypeScript's module augmentation:
143
144```typescript
145// In a global type definition file (e.g., types.d.ts or global.d.ts)
146declare module "@tanstack/query-db-collection" {
147 interface QueryCollectionMeta {
148 // Add your custom properties here
149 userId?: string
150 includeDeleted?: boolean
151 cacheTTL?: number
152 }
153}
154```
155
156Once you've extended the interface, your custom properties are fully typed throughout your application:
157
158```typescript
159const collection = createCollection(
160 queryCollectionOptions({
161 queryKey: ["todos"],
162 queryFn: async (ctx) => {
163 // ✅ Both loadSubsetOptions and custom properties are typed
164 const { loadSubsetOptions, userId, includeDeleted } = ctx.meta
165
166 return api.getTodos({
167 ...parseLoadSubsetOptions(loadSubsetOptions),
168 userId,
169 includeDeleted,
170 })
171 },
172 queryClient,
173 getKey: (item) => item.id,
174 // Pass custom meta alongside Query Collection defaults
175 meta: {
176 userId: "user-123",
177 includeDeleted: false,
178 },
179 })
180)
181```
182
183### Important Notes
184
185- The module augmentation pattern follows TanStack Query's official approach for typing meta
186- `QueryCollectionMeta` is an interface (not a type alias), enabling proper TypeScript declaration merging
187- Your custom properties are merged with the base `loadSubsetOptions` property
188- All meta properties must be compatible with `Record<string, unknown>`
189- The augmentation should be done in a file that's included in your TypeScript compilation
190
191### Example: API Request Context
192
193A common use case is passing request context to your query function:
194
195```typescript
196// types.d.ts
197declare module "@tanstack/query-db-collection" {
198 interface QueryCollectionMeta {
199 authToken?: string
200 locale?: string
201 version?: string
202 }
203}
204
205// collections.ts
206const productsCollection = createCollection(
207 queryCollectionOptions({
208 queryKey: ["products"],
209 queryFn: async (ctx) => {
210 const { loadSubsetOptions, authToken, locale, version } = ctx.meta
211
212 return api.getProducts({
213 ...parseLoadSubsetOptions(loadSubsetOptions),
214 headers: {
215 Authorization: `Bearer ${authToken}`,
216 "Accept-Language": locale,
217 "API-Version": version,
218 },
219 })
220 },
221 queryClient,
222 getKey: (item) => item.id,
223 meta: {
224 authToken: session.token,
225 locale: "en-US",
226 version: "v1",
227 },
228 })
229)
230```
231
232## Persistence Handlers
233
234You can define handlers that are called when mutations occur. These handlers can persist changes to your backend and control whether the query should refetch after the operation:
235
236```typescript
237const todosCollection = createCollection(
238 queryCollectionOptions({
239 queryKey: ["todos"],
240 queryFn: fetchTodos,
241 queryClient,
242 getKey: (item) => item.id,
243
244 onInsert: async ({ transaction }) => {
245 const newItems = transaction.mutations.map((m) => m.modified)
246 await api.createTodos(newItems)
247 // Returning nothing or { refetch: true } will trigger a refetch
248 // Return { refetch: false } to skip automatic refetch
249 },
250
251 onUpdate: async ({ transaction }) => {
252 const updates = transaction.mutations.map((m) => ({
253 id: m.key,
254 changes: m.changes,
255 }))
256 await api.updateTodos(updates)
257 },
258
259 onDelete: async ({ transaction }) => {
260 const ids = transaction.mutations.map((m) => m.key)
261 await api.deleteTodos(ids)
262 },
263 })
264)
265```
266
267### Controlling Refetch Behavior
268
269By default, after any persistence handler (`onInsert`, `onUpdate`, or `onDelete`) completes successfully, the query will automatically refetch to ensure the local state matches the server state.
270
271You can control this behavior by returning an object with a `refetch` property:
272
273```typescript
274onInsert: async ({ transaction }) => {
275 await api.createTodos(transaction.mutations.map((m) => m.modified))
276
277 // Skip the automatic refetch
278 return { refetch: false }
279}
280```
281
282This is useful when:
283
284- You're confident the server state matches what you sent
285- You want to avoid unnecessary network requests
286- You're handling state updates through other mechanisms (like WebSockets)
287
288## Utility Methods
289
290The collection provides these utility methods via `collection.utils`:
291
292- `refetch(opts?)`: Manually trigger a refetch of the query
293 - `opts.throwOnError`: Whether to throw an error if the refetch fails (default: `false`)
294 - Bypasses `enabled: false` to support imperative/manual refetching patterns (similar to hook `refetch()` behavior)
295 - Returns `QueryObserverResult` for inspecting the result
296
297## Direct Writes
298
299Direct writes are intended for scenarios where the normal query/mutation flow doesn't fit your needs. They allow you to write directly to the synced data store, bypassing the optimistic update system and query refetch mechanism.
300
301### Understanding the Data Stores
302
303Query Collections maintain two data stores:
304
3051. **Synced Data Store** - The authoritative state synchronized with the server via `queryFn`
3062. **Optimistic Mutations Store** - Temporary changes that are applied optimistically before server confirmation
307
308Normal collection operations (insert, update, delete) create optimistic mutations that are:
309
310- Applied immediately to the UI
311- Sent to the server via persistence handlers
312- Rolled back automatically if the server request fails
313- Replaced with server data when the query refetches
314
315Direct writes bypass this system entirely and write directly to the synced data store, making them ideal for handling real-time updates from alternative sources.
316
317### When to Use Direct Writes
318
319Direct writes should be used when:
320
321- You need to sync real-time updates from WebSockets or server-sent events
322- You're dealing with large datasets where refetching everything is too expensive
323- You receive incremental updates or server-computed field updates
324- You need to implement complex pagination or partial data loading scenarios
325
326### Individual Write Operations
327
328```typescript
329// Insert a new item directly to the synced data store
330todosCollection.utils.writeInsert({
331 id: "1",
332 text: "Buy milk",
333 completed: false,
334})
335
336// Update an existing item in the synced data store
337todosCollection.utils.writeUpdate({ id: "1", completed: true })
338
339// Delete an item from the synced data store
340todosCollection.utils.writeDelete("1")
341
342// Upsert (insert or update) in the synced data store
343todosCollection.utils.writeUpsert({
344 id: "1",
345 text: "Buy milk",
346 completed: false,
347})
348```
349
350These operations:
351
352- Write directly to the synced data store
353- Do NOT create optimistic mutations
354- Do NOT trigger automatic query refetches
355- Update the TanStack Query cache immediately
356- Are immediately visible in the UI
357
358### Batch Operations
359
360The `writeBatch` method allows you to perform multiple operations atomically. Any write operations called within the callback will be collected and executed as a single transaction:
361
362```typescript
363todosCollection.utils.writeBatch(() => {
364 todosCollection.utils.writeInsert({ id: "1", text: "Buy milk" })
365 todosCollection.utils.writeInsert({ id: "2", text: "Walk dog" })
366 todosCollection.utils.writeUpdate({ id: "3", completed: true })
367 todosCollection.utils.writeDelete("4")
368})
369```
370
371### Real-World Example: WebSocket Integration
372
373```typescript
374// Handle real-time updates from WebSocket without triggering full refetches
375ws.on("todos:update", (changes) => {
376 todosCollection.utils.writeBatch(() => {
377 changes.forEach((change) => {
378 switch (change.type) {
379 case "insert":
380 todosCollection.utils.writeInsert(change.data)
381 break
382 case "update":
383 todosCollection.utils.writeUpdate(change.data)
384 break
385 case "delete":
386 todosCollection.utils.writeDelete(change.id)
387 break
388 }
389 })
390 })
391})
392```
393
394### Example: Incremental Updates
395
396When the server returns computed fields (like server-generated IDs or timestamps), you can use the `onInsert` handler with `{ refetch: false }` to avoid unnecessary refetches while still syncing the server response:
397
398```typescript
399const todosCollection = createCollection(
400 queryCollectionOptions({
401 queryKey: ["todos"],
402 queryFn: fetchTodos,
403 queryClient,
404 getKey: (item) => item.id,
405
406 onInsert: async ({ transaction }) => {
407 const newItems = transaction.mutations.map((m) => m.modified)
408
409 // Send to server and get back items with server-computed fields
410 const serverItems = await api.createTodos(newItems)
411
412 // Sync server-computed fields (like server-generated IDs, timestamps, etc.)
413 // to the collection's synced data store
414 todosCollection.utils.writeBatch(() => {
415 serverItems.forEach((serverItem) => {
416 todosCollection.utils.writeInsert(serverItem)
417 })
418 })
419
420 // Skip automatic refetch since we've already synced the server response
421 // (optimistic state is automatically replaced when handler completes)
422 return { refetch: false }
423 },
424
425 onUpdate: async ({ transaction }) => {
426 const updates = transaction.mutations.map((m) => ({
427 id: m.key,
428 changes: m.changes,
429 }))
430 const serverItems = await api.updateTodos(updates)
431
432 // Sync server-computed fields from the update response
433 todosCollection.utils.writeBatch(() => {
434 serverItems.forEach((serverItem) => {
435 todosCollection.utils.writeUpdate(serverItem)
436 })
437 })
438
439 return { refetch: false }
440 },
441 })
442)
443
444// Usage is just like a regular collection
445todosCollection.insert({ text: "Buy milk", completed: false })
446```
447
448### Example: Large Dataset Pagination
449
450```typescript
451// Load additional pages without refetching existing data
452const loadMoreTodos = async (page) => {
453 const newTodos = await api.getTodos({ page, limit: 50 })
454
455 // Add new items without affecting existing ones
456 todosCollection.utils.writeBatch(() => {
457 newTodos.forEach((todo) => {
458 todosCollection.utils.writeInsert(todo)
459 })
460 })
461}
462```
463
464## Important Behaviors
465
466### Full State Sync
467
468The query collection treats the `queryFn` result as the **complete state** of the collection. This means:
469
470- Items present in the collection but not in the query result will be deleted
471- Items in the query result but not in the collection will be inserted
472- Items present in both will be updated if they differ
473
474This is important when the same entity type can be loaded from multiple REST
475endpoints. For example, do not point the same Query Collection at
476`/api/documents/preview` for one load and `/api/documents/deleted` for another
477unless each result represents the complete state for that collection
478scope. A narrower endpoint can otherwise remove rows that were loaded from a
479different endpoint.
480
481For multiple endpoint or subset-loading use cases, choose the pattern that
482matches your API semantics:
483
484- Use `syncMode: 'on-demand'` when one logical collection can serve different
485 subsets of data. In this mode, query predicates (`where`, `orderBy`, `limit`,
486 and `offset`) are passed to your `queryFn` via `ctx.meta.loadSubsetOptions`,
487 letting you translate them into API parameters.
488- Use separate Query Collections when endpoints represent distinct server scopes
489 whose results should not replace each other. Use `unionAll` to combine them
490 into a single query when you need a unified view across endpoints.
491- Use direct writes such as `writeUpsert`/`writeBatch` for lower-level
492 incremental loading when you intentionally want to merge server responses into
493 the synced store yourself.
494
495### Empty Array Behavior
496
497When `queryFn` returns an empty array, **all items in the collection will be deleted**. This is because the collection interprets an empty array as "the server has no items".
498
499```typescript
500// This will delete all items in the collection
501queryFn: async () => []
502```
503
504### Handling Partial/Incremental Fetches
505
506Since the query collection expects `queryFn` to return the complete state, you can handle partial fetches by merging new data with existing data:
507
508```typescript
509const todosCollection = createCollection(
510 queryCollectionOptions({
511 queryKey: ["todos"],
512 queryFn: async ({ queryKey }) => {
513 // Get existing data from cache
514 const existingData = queryClient.getQueryData(queryKey) || []
515
516 // Fetch only new/updated items (e.g., changes since last sync)
517 const lastSyncTime = localStorage.getItem("todos-last-sync")
518 const newData = await fetch(`/api/todos?since=${lastSyncTime}`).then(
519 (r) => r.json()
520 )
521
522 // Merge new data with existing data
523 const existingMap = new Map(existingData.map((item) => [item.id, item]))
524
525 // Apply updates and additions
526 newData.forEach((item) => {
527 existingMap.set(item.id, item)
528 })
529
530 // Handle deletions if your API provides them
531 if (newData.deletions) {
532 newData.deletions.forEach((id) => existingMap.delete(id))
533 }
534
535 // Update sync time
536 localStorage.setItem("todos-last-sync", new Date().toISOString())
537
538 // Return the complete merged state
539 return Array.from(existingMap.values())
540 },
541 queryClient,
542 getKey: (item) => item.id,
543 })
544)
545```
546
547This pattern allows you to:
548
549- Fetch only incremental changes from your API
550- Merge those changes with existing data
551- Return the complete state that the collection expects
552- Avoid the performance overhead of fetching all data every time
553
554### Direct Writes and Query Sync
555
556Direct writes update the collection immediately and also update the TanStack Query cache. However, they do not prevent the normal query sync behavior. If your `queryFn` returns data that conflicts with your direct writes, the query data will take precedence.
557
558To handle this properly:
559
5601. Use `{ refetch: false }` in your persistence handlers when using direct writes
5612. Set appropriate `staleTime` to prevent unnecessary refetches
5623. Design your `queryFn` to be aware of incremental updates (e.g., only fetch new data)
563
564## Complete Direct Write API Reference
565
566All direct write methods are available on `collection.utils`:
567
568- `writeInsert(data)`: Insert one or more items directly
569- `writeUpdate(data)`: Update one or more items directly
570- `writeDelete(keys)`: Delete one or more items directly
571- `writeUpsert(data)`: Insert or update one or more items directly
572- `writeBatch(callback)`: Perform multiple operations atomically
573- `refetch(opts?)`: Manually trigger a refetch of the query
574
575## QueryFn and Predicate Push-Down
576
577When using `syncMode: 'on-demand'`, the collection automatically pushes down query predicates (where clauses, orderBy, limit, and offset) to your `queryFn`. This allows you to fetch only the data needed for each specific query, rather than fetching the entire dataset.
578
579### How LoadSubsetOptions Are Passed
580
581LoadSubsetOptions are passed to your `queryFn` via the query context's `meta` property:
582
583```typescript
584queryFn: async (ctx) => {
585 // Extract LoadSubsetOptions from the context
586 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
587
588 // Use these to fetch only the data you need
589 // - where: filter expression (AST)
590 // - orderBy: sort expression (AST)
591 // - limit: maximum number of rows
592 // - offset: number of rows to skip (for pagination)
593 // ...
594}
595```
596
597The `where` and `orderBy` fields are expression trees (AST - Abstract Syntax Tree) that need to be parsed. TanStack DB provides helper functions to make this easy.
598
599### Expression Helpers
600
601```typescript
602import {
603 parseWhereExpression,
604 parseOrderByExpression,
605 extractSimpleComparisons,
606 parseLoadSubsetOptions,
607} from '@tanstack/db'
608// Or from '@tanstack/query-db-collection' (re-exported for convenience)
609```
610
611These helpers allow you to parse expression trees without manually traversing complex AST structures.
612
613### Quick Start: Simple REST API
614
615```typescript
616import { createCollection } from '@tanstack/react-db'
617import { queryCollectionOptions } from '@tanstack/query-db-collection'
618import { parseLoadSubsetOptions } from '@tanstack/db'
619import { QueryClient } from '@tanstack/query-core'
620
621const queryClient = new QueryClient()
622
623const productsCollection = createCollection(
624 queryCollectionOptions({
625 id: 'products',
626 queryKey: ['products'],
627 queryClient,
628 getKey: (item) => item.id,
629 syncMode: 'on-demand', // Enable predicate push-down
630
631 queryFn: async (ctx) => {
632 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
633
634 // Parse the expressions into simple format
635 const parsed = parseLoadSubsetOptions({ where, orderBy, limit })
636
637 // Build query parameters from parsed filters
638 const params = new URLSearchParams()
639
640 // Add filters
641 parsed.filters.forEach(({ field, operator, value }) => {
642 const fieldName = field.join('.')
643 if (operator === 'eq') {
644 params.set(fieldName, String(value))
645 } else if (operator === 'lt') {
646 params.set(`${fieldName}_lt`, String(value))
647 } else if (operator === 'gt') {
648 params.set(`${fieldName}_gt`, String(value))
649 }
650 })
651
652 // Add sorting
653 if (parsed.sorts.length > 0) {
654 const sortParam = parsed.sorts
655 .map(s => `${s.field.join('.')}:${s.direction}`)
656 .join(',')
657 params.set('sort', sortParam)
658 }
659
660 // Add limit
661 if (parsed.limit) {
662 params.set('limit', String(parsed.limit))
663 }
664
665 // Add offset for pagination
666 if (offset) {
667 params.set('offset', String(offset))
668 }
669
670 const response = await fetch(`/api/products?${params}`)
671 return response.json()
672 },
673 })
674)
675
676// Usage with live queries
677import { createLiveQueryCollection } from '@tanstack/react-db'
678import { eq, lt, and } from '@tanstack/db'
679
680const affordableElectronics = createLiveQueryCollection({
681 query: (q) =>
682 q.from({ product: productsCollection })
683 .where(({ product }) => and(
684 eq(product.category, 'electronics'),
685 lt(product.price, 100)
686 ))
687 .orderBy(({ product }) => product.price, 'asc')
688 .limit(10)
689 .select(({ product }) => product)
690})
691
692// This triggers a queryFn call with:
693// GET /api/products?category=electronics&price_lt=100&sort=price:asc&limit=10
694// When paginating, offset is included: &offset=20
695```
696
697### Custom Handlers for Complex APIs
698
699For APIs with specific formats, use custom handlers:
700
701```typescript
702queryFn: async (ctx) => {
703 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
704
705 // Use custom handlers to match your API's format
706 const filters = parseWhereExpression(where, {
707 handlers: {
708 eq: (field, value) => ({
709 field: field.join('.'),
710 op: 'equals',
711 value
712 }),
713 lt: (field, value) => ({
714 field: field.join('.'),
715 op: 'lessThan',
716 value
717 }),
718 and: (...conditions) => ({
719 operator: 'AND',
720 conditions
721 }),
722 or: (...conditions) => ({
723 operator: 'OR',
724 conditions
725 }),
726 }
727 })
728
729 const sorts = parseOrderByExpression(orderBy)
730
731 return api.query({
732 filters,
733 sort: sorts.map(s => ({
734 field: s.field.join('.'),
735 order: s.direction.toUpperCase()
736 })),
737 limit
738 })
739}
740```
741
742### GraphQL Example
743
744```typescript
745queryFn: async (ctx) => {
746 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
747
748 // Convert to a GraphQL where clause format
749 const whereClause = parseWhereExpression(where, {
750 handlers: {
751 eq: (field, value) => ({
752 [field.join('_')]: { _eq: value }
753 }),
754 lt: (field, value) => ({
755 [field.join('_')]: { _lt: value }
756 }),
757 and: (...conditions) => ({ _and: conditions }),
758 or: (...conditions) => ({ _or: conditions }),
759 }
760 })
761
762 // Convert to a GraphQL order_by format
763 const sorts = parseOrderByExpression(orderBy)
764 const orderByClause = sorts.map(s => ({
765 [s.field.join('_')]: s.direction
766 }))
767
768 const { data } = await graphqlClient.query({
769 query: gql`
770 query GetProducts($where: product_bool_exp, $orderBy: [product_order_by!], $limit: Int) {
771 product(where: $where, order_by: $orderBy, limit: $limit) {
772 id
773 name
774 category
775 price
776 }
777 }
778 `,
779 variables: {
780 where: whereClause,
781 orderBy: orderByClause,
782 limit
783 }
784 })
785
786 return data.product
787}
788```
789
790### Expression Helper API Reference
791
792#### `parseLoadSubsetOptions(options)`
793
794Convenience function that parses all LoadSubsetOptions at once. Good for simple use cases.
795
796```typescript
797const { filters, sorts, limit, offset } = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
798// filters: [{ field: ['category'], operator: 'eq', value: 'electronics' }]
799// sorts: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
800// limit: 10
801// offset: 20 (for pagination)
802```
803
804#### `parseWhereExpression(expr, options)`
805
806Parses a WHERE expression using custom handlers for each operator. Use this for complete control over the output format.
807
808```typescript
809const filters = parseWhereExpression(where, {
810 handlers: {
811 eq: (field, value) => ({ [field.join('.')]: value }),
812 lt: (field, value) => ({ [`${field.join('.')}_lt`]: value }),
813 and: (...filters) => Object.assign({}, ...filters)
814 },
815 onUnknownOperator: (operator, args) => {
816 console.warn(`Unsupported operator: ${operator}`)
817 return null
818 }
819})
820```
821
822#### `parseOrderByExpression(orderBy)`
823
824Parses an ORDER BY expression into a simple array.
825
826```typescript
827const sorts = parseOrderByExpression(orderBy)
828// Returns: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
829```
830
831#### `extractSimpleComparisons(expr)`
832
833Extracts simple AND-ed comparisons from a WHERE expression. Note: Only works for simple AND conditions.
834
835```typescript
836const comparisons = extractSimpleComparisons(where)
837// Returns: [
838// { field: ['category'], operator: 'eq', value: 'electronics' },
839// { field: ['price'], operator: 'lt', value: 100 }
840// ]
841```
842
843### Supported Operators
844
845- `eq` - Equality (=)
846- `gt` - Greater than (>)
847- `gte` - Greater than or equal (>=)
848- `lt` - Less than (<)
849- `lte` - Less than or equal (<=)
850- `and` - Logical AND
851- `or` - Logical OR
852- `in` - IN clause
853
854### Using Query Key Builders
855
856Create different cache entries for different filter combinations:
857
858```typescript
859const productsCollection = createCollection(
860 queryCollectionOptions({
861 id: 'products',
862 // Dynamic query key based on filters
863 queryKey: (opts) => {
864 const parsed = parseLoadSubsetOptions(opts)
865 const cacheKey = ['products']
866
867 parsed.filters.forEach(f => {
868 cacheKey.push(`${f.field.join('.')}-${f.operator}-${f.value}`)
869 })
870
871 if (parsed.limit) {
872 cacheKey.push(`limit-${parsed.limit}`)
873 }
874
875 return cacheKey
876 },
877 queryClient,
878 getKey: (item) => item.id,
879 syncMode: 'on-demand',
880 queryFn: async (ctx) => { /* ... */ },
881 })
882)
883```
884
885#### Query Key Prefix Convention
886
887When using a function-based `queryKey`, all derived keys **must extend the base key as a prefix**. The base key is what your function returns when called with no options (`queryKey({})`).
888
889TanStack Query uses prefix matching for cache operations internally. The query collection relies on this to find all cache entries belonging to a collection — including stale entries from destroyed query observers that are still held in cache due to `gcTime`. If derived keys don't share the base prefix, cache updates may silently miss entries, leading to stale data.
890
891```typescript
892// ✅ Correct: base key ['products'] is a prefix of all derived keys
893queryKey: (opts) => {
894 if (opts.where) {
895 return ['products', JSON.stringify(opts.where)]
896 }
897 return ['products']
898}
899
900// ❌ Wrong: base key ['products-all'] is NOT a prefix of ['products-filtered', ...]
901queryKey: (opts) => {
902 if (opts.where) {
903 return ['products-filtered', JSON.stringify(opts.where)]
904 }
905 return ['products-all']
906}
907```
908
909### Tips
910
9111. **Start with `parseLoadSubsetOptions`** for simple use cases
9122. **Use custom handlers** via `parseWhereExpression` for APIs with specific formats
9133. **Handle unsupported operators** with the `onUnknownOperator` callback
9144. **Log parsed results** during development to verify correctness