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

query-collection.md

893 lines27.2 KB

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 })
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 }),
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 })
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 }
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 })
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 }
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 })
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 })
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 }
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 })
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 })
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​
474### Empty Array Behavior
475​
476When `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".
477​
478```typescript
479// This will delete all items in the collection
480queryFn: async () => []
481```
482​
483### Handling Partial/Incremental Fetches
484​
485Since the query collection expects `queryFn` to return the complete state, you can handle partial fetches by merging new data with existing data:
486​
487```typescript
488const todosCollection = createCollection(
489 queryCollectionOptions({
490 queryKey: ["todos"],
491 queryFn: async ({ queryKey }) => {
492 // Get existing data from cache
493 const existingData = queryClient.getQueryData(queryKey) || []
494​
495 // Fetch only new/updated items (e.g., changes since last sync)
496 const lastSyncTime = localStorage.getItem("todos-last-sync")
497 const newData = await fetch(`/api/todos?since=${lastSyncTime}`).then(
498 (r) => r.json()
499 )
500​
501 // Merge new data with existing data
502 const existingMap = new Map(existingData.map((item) => [item.id, item]))
503​
504 // Apply updates and additions
505 newData.forEach((item) => {
506 existingMap.set(item.id, item)
507 })
508​
509 // Handle deletions if your API provides them
510 if (newData.deletions) {
511 newData.deletions.forEach((id) => existingMap.delete(id))
512 }
513​
514 // Update sync time
515 localStorage.setItem("todos-last-sync", new Date().toISOString())
516​
517 // Return the complete merged state
518 return Array.from(existingMap.values())
519 },
520 queryClient,
521 getKey: (item) => item.id,
522 })
524```
525​
526This pattern allows you to:
527​
528- Fetch only incremental changes from your API
529- Merge those changes with existing data
530- Return the complete state that the collection expects
531- Avoid the performance overhead of fetching all data every time
532​
533### Direct Writes and Query Sync
534​
535Direct 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.
536​
537To handle this properly:
538​
5391. Use `{ refetch: false }` in your persistence handlers when using direct writes
5402. Set appropriate `staleTime` to prevent unnecessary refetches
5413. Design your `queryFn` to be aware of incremental updates (e.g., only fetch new data)
542​
543## Complete Direct Write API Reference
544​
545All direct write methods are available on `collection.utils`:
546​
547- `writeInsert(data)`: Insert one or more items directly
548- `writeUpdate(data)`: Update one or more items directly
549- `writeDelete(keys)`: Delete one or more items directly
550- `writeUpsert(data)`: Insert or update one or more items directly
551- `writeBatch(callback)`: Perform multiple operations atomically
552- `refetch(opts?)`: Manually trigger a refetch of the query
553​
554## QueryFn and Predicate Push-Down
555​
556When 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.
557​
558### How LoadSubsetOptions Are Passed
559​
560LoadSubsetOptions are passed to your `queryFn` via the query context's `meta` property:
561​
562```typescript
563queryFn: async (ctx) => {
564 // Extract LoadSubsetOptions from the context
565 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
566​
567 // Use these to fetch only the data you need
568 // - where: filter expression (AST)
569 // - orderBy: sort expression (AST)
570 // - limit: maximum number of rows
571 // - offset: number of rows to skip (for pagination)
572 // ...
574```
575​
576The `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.
577​
578### Expression Helpers
579​
580```typescript
581import {
582 parseWhereExpression,
583 parseOrderByExpression,
584 extractSimpleComparisons,
585 parseLoadSubsetOptions,
586} from '@tanstack/db'
587// Or from '@tanstack/query-db-collection' (re-exported for convenience)
588```
589​
590These helpers allow you to parse expression trees without manually traversing complex AST structures.
591​
592### Quick Start: Simple REST API
593​
594```typescript
595import { createCollection } from '@tanstack/react-db'
596import { queryCollectionOptions } from '@tanstack/query-db-collection'
597import { parseLoadSubsetOptions } from '@tanstack/db'
598import { QueryClient } from '@tanstack/query-core'
599​
600const queryClient = new QueryClient()
601​
602const productsCollection = createCollection(
603 queryCollectionOptions({
604 id: 'products',
605 queryKey: ['products'],
606 queryClient,
607 getKey: (item) => item.id,
608 syncMode: 'on-demand', // Enable predicate push-down
609​
610 queryFn: async (ctx) => {
611 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
612​
613 // Parse the expressions into simple format
614 const parsed = parseLoadSubsetOptions({ where, orderBy, limit })
615​
616 // Build query parameters from parsed filters
617 const params = new URLSearchParams()
618​
619 // Add filters
620 parsed.filters.forEach(({ field, operator, value }) => {
621 const fieldName = field.join('.')
622 if (operator === 'eq') {
623 params.set(fieldName, String(value))
624 } else if (operator === 'lt') {
625 params.set(`${fieldName}_lt`, String(value))
626 } else if (operator === 'gt') {
627 params.set(`${fieldName}_gt`, String(value))
628 }
629 })
630​
631 // Add sorting
632 if (parsed.sorts.length > 0) {
633 const sortParam = parsed.sorts
634 .map(s => `${s.field.join('.')}:${s.direction}`)
635 .join(',')
636 params.set('sort', sortParam)
637 }
638​
639 // Add limit
640 if (parsed.limit) {
641 params.set('limit', String(parsed.limit))
642 }
643​
644 // Add offset for pagination
645 if (offset) {
646 params.set('offset', String(offset))
647 }
648​
649 const response = await fetch(`/api/products?${params}`)
650 return response.json()
651 },
652 })
654​
655// Usage with live queries
656import { createLiveQueryCollection } from '@tanstack/react-db'
657import { eq, lt, and } from '@tanstack/db'
658​
659const affordableElectronics = createLiveQueryCollection({
660 query: (q) =>
661 q.from({ product: productsCollection })
662 .where(({ product }) => and(
663 eq(product.category, 'electronics'),
664 lt(product.price, 100)
665 ))
666 .orderBy(({ product }) => product.price, 'asc')
667 .limit(10)
668 .select(({ product }) => product)
669})
670​
671// This triggers a queryFn call with:
672// GET /api/products?category=electronics&price_lt=100&sort=price:asc&limit=10
673// When paginating, offset is included: &offset=20
674```
675​
676### Custom Handlers for Complex APIs
677​
678For APIs with specific formats, use custom handlers:
679​
680```typescript
681queryFn: async (ctx) => {
682 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
683​
684 // Use custom handlers to match your API's format
685 const filters = parseWhereExpression(where, {
686 handlers: {
687 eq: (field, value) => ({
688 field: field.join('.'),
689 op: 'equals',
690 value
691 }),
692 lt: (field, value) => ({
693 field: field.join('.'),
694 op: 'lessThan',
695 value
696 }),
697 and: (...conditions) => ({
698 operator: 'AND',
699 conditions
700 }),
701 or: (...conditions) => ({
702 operator: 'OR',
703 conditions
704 }),
705 }
706 })
707​
708 const sorts = parseOrderByExpression(orderBy)
709​
710 return api.query({
711 filters,
712 sort: sorts.map(s => ({
713 field: s.field.join('.'),
714 order: s.direction.toUpperCase()
715 })),
716 limit
717 })
719```
720​
721### GraphQL Example
722​
723```typescript
724queryFn: async (ctx) => {
725 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
726​
727 // Convert to a GraphQL where clause format
728 const whereClause = parseWhereExpression(where, {
729 handlers: {
730 eq: (field, value) => ({
731 [field.join('_')]: { _eq: value }
732 }),
733 lt: (field, value) => ({
734 [field.join('_')]: { _lt: value }
735 }),
736 and: (...conditions) => ({ _and: conditions }),
737 or: (...conditions) => ({ _or: conditions }),
738 }
739 })
740​
741 // Convert to a GraphQL order_by format
742 const sorts = parseOrderByExpression(orderBy)
743 const orderByClause = sorts.map(s => ({
744 [s.field.join('_')]: s.direction
745 }))
746​
747 const { data } = await graphqlClient.query({
748 query: gql`
749 query GetProducts($where: product_bool_exp, $orderBy: [product_order_by!], $limit: Int) {
750 product(where: $where, order_by: $orderBy, limit: $limit) {
751 id
752 name
753 category
754 price
755 }
756 }
757 `,
758 variables: {
759 where: whereClause,
760 orderBy: orderByClause,
761 limit
762 }
763 })
764​
765 return data.product
767```
768​
769### Expression Helper API Reference
770​
771#### `parseLoadSubsetOptions(options)`
772​
773Convenience function that parses all LoadSubsetOptions at once. Good for simple use cases.
774​
775```typescript
776const { filters, sorts, limit, offset } = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
777// filters: [{ field: ['category'], operator: 'eq', value: 'electronics' }]
778// sorts: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
779// limit: 10
780// offset: 20 (for pagination)
781```
782​
783#### `parseWhereExpression(expr, options)`
784​
785Parses a WHERE expression using custom handlers for each operator. Use this for complete control over the output format.
786​
787```typescript
788const filters = parseWhereExpression(where, {
789 handlers: {
790 eq: (field, value) => ({ [field.join('.')]: value }),
791 lt: (field, value) => ({ [`${field.join('.')}_lt`]: value }),
792 and: (...filters) => Object.assign({}, ...filters)
793 },
794 onUnknownOperator: (operator, args) => {
795 console.warn(`Unsupported operator: ${operator}`)
796 return null
797 }
798})
799```
800​
801#### `parseOrderByExpression(orderBy)`
802​
803Parses an ORDER BY expression into a simple array.
804​
805```typescript
806const sorts = parseOrderByExpression(orderBy)
807// Returns: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
808```
809​
810#### `extractSimpleComparisons(expr)`
811​
812Extracts simple AND-ed comparisons from a WHERE expression. Note: Only works for simple AND conditions.
813​
814```typescript
815const comparisons = extractSimpleComparisons(where)
816// Returns: [
817// { field: ['category'], operator: 'eq', value: 'electronics' },
818// { field: ['price'], operator: 'lt', value: 100 }
819// ]
820```
821​
822### Supported Operators
823​
824- `eq` - Equality (=)
825- `gt` - Greater than (>)
826- `gte` - Greater than or equal (>=)
827- `lt` - Less than (<)
828- `lte` - Less than or equal (<=)
829- `and` - Logical AND
830- `or` - Logical OR
831- `in` - IN clause
832​
833### Using Query Key Builders
834​
835Create different cache entries for different filter combinations:
836​
837```typescript
838const productsCollection = createCollection(
839 queryCollectionOptions({
840 id: 'products',
841 // Dynamic query key based on filters
842 queryKey: (opts) => {
843 const parsed = parseLoadSubsetOptions(opts)
844 const cacheKey = ['products']
845​
846 parsed.filters.forEach(f => {
847 cacheKey.push(`${f.field.join('.')}-${f.operator}-${f.value}`)
848 })
849​
850 if (parsed.limit) {
851 cacheKey.push(`limit-${parsed.limit}`)
852 }
853​
854 return cacheKey
855 },
856 queryClient,
857 getKey: (item) => item.id,
858 syncMode: 'on-demand',
859 queryFn: async (ctx) => { /* ... */ },
860 })
862```
863​
864#### Query Key Prefix Convention
865​
866When 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({})`).
867​
868TanStack 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.
869​
870```typescript
871// ✅ Correct: base key ['products'] is a prefix of all derived keys
872queryKey: (opts) => {
873 if (opts.where) {
874 return ['products', JSON.stringify(opts.where)]
875 }
876 return ['products']
878​
879// ❌ Wrong: base key ['products-all'] is NOT a prefix of ['products-filtered', ...]
880queryKey: (opts) => {
881 if (opts.where) {
882 return ['products-filtered', JSON.stringify(opts.where)]
883 }
884 return ['products-all']
886```
887​
888### Tips
889​
8901. **Start with `parseLoadSubsetOptions`** for simple use cases
8912. **Use custom handlers** via `parseWhereExpression` for APIs with specific formats
8923. **Handle unsupported operators** with the `onUnknownOperator` callback
8934. **Log parsed results** during development to verify correctness