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

powersync-collection.md

1,102 lines36.5 KB

1---
2title: PowerSync Collection
3---
4​
5# PowerSync Collection
6​
7PowerSync collections provide seamless integration between TanStack DB and [PowerSync](https://powersync.com), enabling automatic synchronization between your in-memory TanStack DB collections and PowerSync's SQLite database. This gives you offline-ready persistence, real-time sync capabilities, and powerful conflict resolution.
8​
9## Overview
10​
11The `@tanstack/powersync-db-collection` package allows you to create collections that:
12​
13- Automatically mirror the state of an underlying PowerSync SQLite database
14- Reactively update when PowerSync records change
15- Support query-driven sync, loading only the data relevant to active live queries
16- Support optimistic mutations with rollback on error
17- Provide persistence handlers to keep PowerSync in sync with TanStack DB transactions
18- Use PowerSync's efficient SQLite-based storage engine
19- Work with PowerSync's real-time sync features for offline-first scenarios
20- Leverage PowerSync's built-in conflict resolution and data consistency guarantees
21- Enable real-time synchronization with PostgreSQL, MongoDB and MySQL backends
22​
23## 1. Installation
24​
25Install the PowerSync collection package along with your preferred framework integration.
26PowerSync currently works with Web, React Native and Node.js. The examples below use the Web SDK.
27See the PowerSync quickstart [docs](https://docs.powersync.com/installation/quickstart-guide) for more details.
28​
29```bash
30npm install @tanstack/powersync-db-collection @powersync/web @journeyapps/wa-sqlite
31```
32​
33### 2. Create a PowerSync Database and Schema
34​
35```ts
36import { Schema, Table, column } from "@powersync/web"
37​
38// Define your schema
39const APP_SCHEMA = new Schema({
40 documents: new Table({
41 name: column.text,
42 author: column.text,
43 created_at: column.text,
44 archived: column.integer,
45 }),
46})
47​
48// Initialize PowerSync database
49const db = new PowerSyncDatabase({
50 database: {
51 dbFilename: "app.sqlite",
52 },
53 schema: APP_SCHEMA,
54})
55```
56​
57### 3. (optional) Configure Sync with a Backend
58​
59```ts
60import {
61 AbstractPowerSyncDatabase,
62 PowerSyncBackendConnector,
63 PowerSyncCredentials,
64} from "@powersync/web"
65​
66// TODO implement your logic here
67class Connector implements PowerSyncBackendConnector {
68 fetchCredentials: () => Promise<PowerSyncCredentials | null>
69​
70 /** Upload local changes to the app backend.
71 *
72 * Use {@link AbstractPowerSyncDatabase.getCrudBatch} to get a batch of changes to upload.
73 *
74 * Any thrown errors will result in a retry after the configured wait period (default: 5 seconds).
75 */
76 uploadData: (database: AbstractPowerSyncDatabase) => Promise<void>
78​
79// Configure the client to connect to a PowerSync service and your backend
80db.connect(new Connector())
81```
82​
83### 4. Create a TanStack DB Collection
84​
85There are two main ways to create a collection: using type inference or using schema validation. Type inference will infer collection types from the underlying PowerSync SQLite tables. Schema validation can be used for additional input/output validations and type transforms.
86​
87#### Option 1: Using Table Type Inference
88​
89The collection types are automatically inferred from the PowerSync schema table definition. The table is used to construct a default standard schema validator which is used internally to validate collection operations.
90​
91Collection mutations accept SQLite types and queries report data with SQLite types.
92​
93```ts
94import { createCollection } from "@tanstack/react-db"
95import { powerSyncCollectionOptions } from "@tanstack/powersync-db-collection"
96​
97const documentsCollection = createCollection(
98 powerSyncCollectionOptions({
99 database: db,
100 table: APP_SCHEMA.props.documents,
101 })
103​
104/** Note: The types for input and output are defined as this */
105// Used for mutations like `insert` or `update`
106type DocumentCollectionInput = {
107 id: string
108 name: string | null
109 author: string | null
110 created_at: string | null // SQLite TEXT
111 archived: number | null // SQLite integer
113// The type of query/data results
114type DocumentCollectionOutput = DocumentCollectionInput
115```
116​
117The standard PowerSync SQLite types map to these TypeScript types:
118​
119| PowerSync Column Type | TypeScript Type | Description |
120| --------------------- | ---------------- | -------------------------------------------------------------------- |
121| `column.text` | `string \| null` | Text values, commonly used for strings, JSON, dates (as ISO strings) |
122| `column.integer` | `number \| null` | Integer values, also used for booleans (0/1) |
123| `column.real` | `number \| null` | Floating point numbers |
124​
125Note: All PowerSync column types are nullable by default.
126​
127#### Option 2: SQLite Types with Schema Validation
128​
129Additional validations for collection mutations can be performed with a custom schema. The Schema below asserts that
130the `name`, `author` and `created_at` fields are required as input. `name` also has an additional string length check.
131​
132Note: The input and output types specified in this example still satisfy the underlying SQLite types. An additional `deserializationSchema` is required if the typing differs. See the examples below for more details.
133​
134The application logic (including the backend) should enforce that all incoming synced data passes validation with the `schema`. Failing to validate data will result in inconsistency of the collection data. This is a fatal error! An `onDeserializationError` handler must be provided to react to this case.
135​
136```ts
137import { createCollection } from "@tanstack/react-db"
138import { powerSyncCollectionOptions } from "@tanstack/powersync-db-collection"
139import { z } from "zod"
140​
141// Schema validates SQLite types but adds constraints
142const schema = z.object({
143 id: z.string(),
144 name: z.string().min(3, { message: "Should be at least 3 characters" }),
145 author: z.string(),
146 created_at: z.string(), // SQLite TEXT for dates
147 archived: z.number(),
148})
149​
150const documentsCollection = createCollection(
151 powerSyncCollectionOptions({
152 database: db,
153 table: APP_SCHEMA.props.documents,
154 schema,
155 onDeserializationError: (error) => {
156 // Present fatal error
157 },
158 })
160​
161/** Note: The types for input and output are defined as this */
162// Used for mutations like `insert` or `update`
163type DocumentCollectionInput = {
164 id: string
165 name: string
166 author: string
167 created_at: string // SQLite TEXT
168 archived: number // SQLite integer
170// The type of query/data results
171type DocumentCollectionOutput = DocumentCollectionInput
172```
173​
174#### Option 3: Transform SQLite Input Types to Rich Output Types
175​
176You can transform SQLite types to richer types (like Date objects) while keeping SQLite-compatible input types:
177​
178Note: The Transformed types are provided by TanStack DB to the PowerSync SQLite persister. These types need to be serialized in
179order to be persisted to SQLite. Most types are converted by default. For custom types, override the serialization by providing a
180`serializer` param.
181​
182The example below uses `nullable` columns, this is not a requirement.
183​
184The application logic (including the backend) should enforce that all incoming synced data passes validation with the `schema`. Failing to validate data will result in inconsistency of the collection data. This is a fatal error! An `onDeserializationError` handler must be provided to react to this case.
185​
186```ts
187const schema = z.object({
188 id: z.string(),
189 name: z.string().nullable(),
190 created_at: z
191 .string()
192 .nullable()
193 .transform((val) => (val ? new Date(val) : null)), // Transform SQLite TEXT to Date
194 archived: z
195 .number()
196 .nullable()
197 .transform((val) => (val != null ? val > 0 : null)), // Transform SQLite INTEGER to boolean
198})
199​
200const documentsCollection = createCollection(
201 powerSyncCollectionOptions({
202 database: db,
203 table: APP_SCHEMA.props.documents,
204 schema,
205 onDeserializationError: (error) => {
206 // Present fatal error
207 },
208 // Optional: custom column serialization
209 serializer: {
210 // Dates are serialized by default, this is just an example
211 created_at: (value) => (value ? value.toISOString() : null),
212 },
213 })
215​
216/** Note: The types for input and output are defined as this */
217// Used for mutations like `insert` or `update`
218type DocumentCollectionInput = {
219 id: string
220 name: string | null
221 author: string | null
222 created_at: string | null // SQLite TEXT
223 archived: number | null
225// The type of query/data results
226type DocumentCollectionOutput = {
227 id: string
228 name: string | null
229 author: string | null
230 created_at: Date | null // JS Date instance
231 archived: boolean | null // JS boolean
233```
234​
235#### Option 4: Custom Input/Output Types with Deserialization
236​
237The input and output types can be completely decoupled from the internal SQLite types. This can be used to accept rich values for input mutations.
238We require an additional `deserializationSchema` in order to validate and transform incoming synced (SQLite) updates. This schema should convert the incoming SQLite update to the output type.
239​
240The application logic (including the backend) should enforce that all incoming synced data passes validation with the `deserializationSchema`. Failing to validate data will result in inconsistency of the collection data. This is a fatal error! An `onDeserializationError` handler must be provided to react to this case.
241​
242```ts
243// Our input/output types use Date and boolean
244const schema = z.object({
245 id: z.string(),
246 name: z.string(),
247 author: z.string(),
248 created_at: z.date(), // Accept Date objects as input
249 archived: z.boolean(), // Accept Booleans as input
250})
251​
252// Schema to transform from SQLite types to our output types
253const deserializationSchema = z.object({
254 id: z.string(),
255 name: z.string(),
256 author: z.string(),
257 created_at: z
258 .string()
259 .transform((val) => (new Date(val))), // SQLite TEXT to Date
260 archived: z
261 .number()
262 .transform((val) => (val > 0), // SQLite INTEGER to Boolean
263})
264​
265const documentsCollection = createCollection(
266 powerSyncCollectionOptions({
267 database: db,
268 table: APP_SCHEMA.props.documents,
269 schema,
270 deserializationSchema,
271 onDeserializationError: (error) => {
272 // Present fatal error
273 },
274 })
276​
277/** Note: The types for input and output are defined as this */
278// Used for mutations like `insert` or `update`
279type DocumentCollectionInput = {
280 id: string
281 name: string
282 author: string
283 created_at: Date
284 archived: boolean
286// The type of query/data results
287type DocumentCollectionOutput = DocumentCollectionInput
288```
289​
290## Features
291​
292### Offline-First
293​
294PowerSync collections are offline-first by default. All data is stored locally in a SQLite database, allowing your app to work without an internet connection. Changes are automatically synced when connectivity is restored.
295​
296### Real-Time Sync
297​
298When connected to a PowerSync backend, changes are automatically synchronized in real-time across all connected clients. The sync process handles:
299​
300- Bi-directional sync with the server
301- Conflict resolution
302- Queue management for offline changes
303- Automatic retries on connection loss
304​
305### Query-Driven Sync
306Collections support an optional `on-demand` sync mode that loads only the rows your active live queries need, rather than syncing the full table into memory upfront. Useful for large datasets where most rows won't be accessed at a given time.
307​
308### Working with Rich JavaScript Types
309​
310PowerSync collections support rich JavaScript types like `Date`, `Boolean`, and custom objects while maintaining SQLite compatibility. The collection handles serialization and deserialization automatically:
311​
312```typescript
313import { z } from "zod"
314import { Schema, Table, column } from "@powersync/web"
315import { createCollection } from "@tanstack/react-db"
316import { powerSyncCollectionOptions } from "@tanstack/powersync-db-collection"
317​
318// Define PowerSync SQLite schema
319const APP_SCHEMA = new Schema({
320 tasks: new Table({
321 title: column.text,
322 due_date: column.text, // Stored as ISO string in SQLite
323 completed: column.integer, // Stored as 0/1 in SQLite
324 metadata: column.text, // Stored as JSON string in SQLite
325 }),
326})
327​
328// Define rich types schema
329const taskSchema = z.object({
330 id: z.string(),
331 title: z.string().nullable(),
332 due_date: z
333 .string()
334 .nullable()
335 .transform((val) => (val ? new Date(val) : null)), // Convert to Date
336 completed: z
337 .number()
338 .nullable()
339 .transform((val) => (val != null ? val > 0 : null)), // Convert to boolean
340 metadata: z
341 .string()
342 .nullable()
343 .transform((val) => (val ? JSON.parse(val) : null)), // Parse JSON
344})
345​
346// Create collection with rich types
347const tasksCollection = createCollection(
348 powerSyncCollectionOptions({
349 database: db,
350 table: APP_SCHEMA.props.tasks,
351 schema: taskSchema,
352 })
354​
355// Work with rich types in your code
356await tasksCollection.insert({
357 id: crypto.randomUUID(),
358 title: "Review PR",
359 due_date: "2025-10-30T10:00:00Z", // String input is automatically converted to Date
360 completed: 0, // Number input is automatically converted to boolean
361 metadata: JSON.stringify({ priority: "high" }),
362})
363​
364// Query returns rich types
365const task = tasksCollection.get("task-1")
366console.log(task.due_date instanceof Date) // true
367console.log(typeof task.completed) // "boolean"
368console.log(task.metadata.priority) // "high"
369```
370​
371### Type Safety with Rich Types
372​
373The collection maintains type safety throughout:
374​
375```typescript
376type TaskInput = {
377 id: string
378 title: string | null
379 due_date: string | null // Accept ISO string for mutations
380 completed: number | null // Accept 0/1 for mutations
381 metadata: string | null // Accept JSON string for mutations
383​
384type TaskOutput = {
385 id: string
386 title: string | null
387 due_date: Date | null // Get Date object in queries
388 completed: boolean | null // Get boolean in queries
389 metadata: {
390 priority: string
391 [key: string]: any
392 } | null
394​
395// TypeScript enforces correct types:
396tasksCollection.insert({
397 due_date: new Date(), // Error: Type 'Date' is not assignable to type 'string'
398})
399​
400const task = tasksCollection.get("task-1")
401task.due_date.getTime() // OK - TypeScript knows this is a Date
402```
403​
404### Optimistic Updates
405​
406Updates to the collection are applied optimistically to the local state first, then synchronized with PowerSync and the backend. If an error occurs during sync, the changes are automatically rolled back.
407​
408### Metadata Tracking
409​
410Metadata tracking allows attaching custom metadata to collection operations (insert, update, delete). This metadata is persisted alongside the operation and available in PowerSync `CrudEntry` records during upload processing. This is useful for passing additional context about mutations to the backend, such as audit information, operation sources, or custom processing hints.
411​
412#### Enabling Metadata Tracking
413​
414Metadata tracking must be enabled on the PowerSync table:
415​
416```typescript
417const APP_SCHEMA = new Schema({
418 documents: new Table(
419 {
420 name: column.text,
421 author: column.text,
422 },
423 {
424 // Enable metadata tracking on this table
425 trackMetadata: true,
426 }
427 ),
428})
429```
430​
431#### Using Metadata in Operations
432​
433Once enabled, metadata can be passed to any collection operation:
434​
435```typescript
436const documents = createCollection(
437 powerSyncCollectionOptions({
438 database: db,
439 table: APP_SCHEMA.props.documents,
440 })
442​
443// Insert with metadata
444await documents.insert(
445 {
446 id: crypto.randomUUID(),
447 name: "Report Q4",
448 author: "Jane Smith",
449 },
450 {
451 metadata: {
452 source: "web-app",
453 userId: "user-123",
454 timestamp: Date.now(),
455 },
456 }
457).isPersisted.promise
458​
459// Update with metadata
460await documents.update(
461 docId,
462 { metadata: { reason: "typo-fix", editor: "user-456" } },
463 (doc) => {
464 doc.name = "Report Q4 (Updated)"
465 }
466).isPersisted.promise
467​
468// Delete with metadata
469await documents.delete(docId, {
470 metadata: { deletedBy: "user-789", reason: "duplicate" },
471}).isPersisted.promise
472```
473​
474#### Accessing Metadata During Upload
475​
476The metadata is available in PowerSync `CrudEntry` records when processing uploads in the connector:
477​
478```typescript
479import { CrudEntry } from "@powersync/web"
480​
481class Connector implements PowerSyncBackendConnector {
482 // ...
483​
484 async uploadData(database: AbstractPowerSyncDatabase) {
485 const batch = await database.getCrudBatch()
486 if (!batch) return
487​
488 for (const entry of batch.crud) {
489 console.log("Operation:", entry.op) // PUT, PATCH, DELETE
490 console.log("Table:", entry.table)
491 console.log("Data:", entry.opData)
492 console.log("Metadata:", entry.metadata) // Custom metadata (stringified)
493​
494 // Parse metadata if needed
495 if (entry.metadata) {
496 const meta = JSON.parse(entry.metadata)
497 console.log("Source:", meta.source)
498 console.log("User ID:", meta.userId)
499 }
500​
501 // Process the operation with the backend...
502 }
503​
504 await batch.complete()
505 }
507```
508​
509**Note**: If metadata is provided to an operation but the table doesn't have `trackMetadata: true`, a warning will be logged and the metadata will be ignored.
510​
511## Configuration Options
512​
513The `powerSyncCollectionOptions` function accepts the following options:
514​
515```ts
516interface PowerSyncCollectionConfig<TTable extends Table, TSchema> {
517 // Required options
518 database: PowerSyncDatabase
519 table: Table
520​
521 // Schema validation and type transformation
522 schema?: StandardSchemaV1
523 deserializationSchema?: StandardSchemaV1 // Required for custom input types
524 onDeserializationError?: (error: StandardSchemaV1.FailureResult) => void // Required for custom input types
525​
526 // Optional Custom serialization
527 serializer?: {
528 [Key in keyof TOutput]?: (value: TOutput[Key]) => SQLiteCompatibleType
529 }
530​
531 // Performance tuning
532 syncBatchSize?: number // Control batch size for initial sync, defaults to 1000
534```
535​
536## Advanced Transactions
537​
538When you need more control over transaction handling, such as batching multiple operations or handling complex transaction scenarios, you can use PowerSync's transaction system directly with TanStack DB transactions.
539​
540```ts
541import { createTransaction } from "@tanstack/react-db"
542import { PowerSyncTransactor } from "@tanstack/powersync-db-collection"
543​
544// Create a transaction that won't auto-commit
545const batchTx = createTransaction({
546 autoCommit: false,
547 mutationFn: async ({ transaction }) => {
548 // Use PowerSyncTransactor to apply the transaction to PowerSync
549 await new PowerSyncTransactor({ database: db }).applyTransaction(
550 transaction
551 )
552 },
553})
554​
555// Perform multiple operations in the transaction
556batchTx.mutate(() => {
557 // Add multiple documents in a single transaction
558 for (let i = 0; i < 5; i++) {
559 documentsCollection.insert({
560 id: crypto.randomUUID(),
561 name: `Document ${i}`,
562 content: `Content ${i}`,
563 created_at: new Date().toISOString(),
564 updated_at: new Date().toISOString(),
565 })
566 }
567})
568​
569// Commit the transaction
570await batchTx.commit()
571​
572// Wait for the changes to be persisted
573await batchTx.isPersisted.promise
574```
575​
576This approach allows you to:
577​
578- Batch multiple operations into a single transaction
579- Control when the transaction is committed
580- Ensure all operations are atomic
581- Wait for persistence confirmation
582- Handle complex transaction scenarios
583​
584## On-demand Sync Mode (Query-Driven Sync)
585​
586By default the PowerSync collection uses the `eager` sync mode, but you can opt to use `on-demand` sync mode instead. In on-demand mode, the collection is query-driven - it only loads data from SQLite that satisfies the predicates of your active live queries, rather than syncing everything and filtering afterwards.
587​
588To understand how data flows under the hood, it helps to know that there are two independent dimensions at play:
589​
590- **Sync mode** (`eager` vs `on-demand`) - controls how data moves from SQLite into the TanStack DB collection
591- **Sync Streams** (optional) - controls how data moves from the PowerSync Service into SQLite, using the `onLoad` or `onLoadSubset` hooks
592​
593These dimensions compose independently, giving you six combinations covered below:
594​
595| Example | Sync mode | Sync Streams | Parameters |
596|---|---|---|---|
597| 1 | Eager | No | - |
598| 2 | On-demand | No | - |
599| 3 | Eager | Yes | Hardcoded |
600| 4 | On-demand | Yes | Hardcoded |
601| 5 | On-demand | Yes | Dynamic - `extractSimpleComparisons` |
602| 6 | On-demand | Yes | Dynamic - `parseWhereExpression` |
603​
604Examples 1 and 2 assume SQLite is already fully populated by PowerSync's sync mechanism. Examples 3–6 add Sync Streams, which let you control which data from the PowerSync Service reaches SQLite in the first place - useful when you only want a subset of data on-device.
605​
606In examples 3 and 4, Sync Stream subscription parameters are hardcoded. Examples 5 and 6 show how to derive those parameters dynamically from the live query's predicates, so the subscription automatically adjusts as the query changes.
607​
608​
609### 1. Eager Mode
610​
611In `eager` mode, all data from the SQLite database is synced into the TanStack DB collection. The live query then filters this full dataset to produce the final result. This means the collection holds all rows regardless of whether they match any active query.
612​
613**SQLite**
614​
615| id | list_id | completed |
616|:--:|:-------:|:---------:|
617| 1 | list_1 | 0 |
618| 2 | list_1 | 1 |
619| 3 | list_2 | 0 |
620| 4 | list_2 | 1 |
621​
622*Eager mode syncs all SQLite data to TanStack DB Collection*
623​
624**Collection**
625​
626| id | list_id | completed |
627|:--:|:-------:|:---------:|
628| 1 | list_1 | 0 |
629| 2 | list_1 | 1 |
630| 3 | list_2 | 0 |
631| 4 | list_2 | 1 |
632​
633*TanStack DB Query filters for list_id = 'list_1'*
634​
635**Result**
636​
637| id | list_id | completed |
638|:--:|:-------:|:---------:|
639| 1 | list_1 | 0 |
640| 2 | list_1 | 1 |
641​
642```typescript
643const collection = createCollection(
644 powerSyncCollectionOptions({
645 database: db,
646 table: AppSchema.props.todos,
647 syncMode: 'eager'
648 }),
650​
651const liveQuery = createLiveQueryCollection({
652 query: (q) =>
653 q
654 .from({ todo: collection })
655 .where(
656 ({ todo }) => eq(todo.list_id, 'list_id'),
657 )
658 .select(({ todo }) => ({
659 id: todo.id,
660 completed: todo.completed,
661 })),
662})
663```
664​
665### 2. On-Demand Mode
666​
667In `on-demand` mode, only data from the SQLite database that satisfies the predicates of active TanStack DB live queries is synced into the TanStack DB collection. This reduces the amount of data held in memory, since the collection only contains rows that are relevant to the queries currently registered against it.
668​
669**SQLite**
670​
671| id | list_id | completed |
672|:--:|:-------:|:---------:|
673| 1 | list_1 | 0 |
674| 2 | list_1 | 1 |
675| 3 | list_2 | 0 |
676| 4 | list_2 | 1 |
677​
678*On-demand mode only syncs data from SQLite to the TanStack DB collection if they satisfy any of the live queries: list_id = 'list_1'*
679​
680**Collection**
681​
682| id | list_id | completed |
683|:--:|:-------:|:---------:|
684| 1 | list_1 | 0 |
685| 2 | list_1 | 1 |
686​
687*TanStack DB Query filters for list_id = 'list_1'*
688​
689**Result**
690​
691| id | list_id | completed |
692|:--:|:-------:|:---------:|
693| 1 | list_1 | 0 |
694| 2 | list_1 | 1 |
695​
696```typescript
697const collection = createCollection(
698 powerSyncCollectionOptions({
699 database: db,
700 table: AppSchema.props.todos,
701 syncMode: 'on-demand'
702 }),
704​
705// live query that tells the collection what the data domain is
706const liveQuery = createLiveQueryCollection({
707 query: (q) =>
708 q
709 .from({ todo: collection })
710 .where(
711 ({ todo }) => eq(todo.list_id, 'list_id'),
712 )
713 .select(({ todo }) => ({
714 id: todo.id,
715 completed: todo.completed,
716 })),
717})
718```
719​
720## Incorporating Sync Streams With OnLoad/OnLoadSubset Hooks
721Sync Streams can be used through the data loading hooks for both `eager` and `on-demand` sync modes that allow a user to call Sync Streams when a collection is defined (eager mode) or when a collection's data boundary changes based on the live queries predicates (on-demand).
722​
723These examples assume the following Sync Stream definition exists:
724```
725config:
726 edition: 3
727​
728streams:
729 lists:
730 query: SELECT * FROM lists WHERE owner_id = auth.user_id()
731 auto_subscribe: true
732 todos:
733 query: SELECT * FROM todos WHERE list_id = subscription.parameter('list') AND list_id IN (SELECT id FROM lists WHERE owner_id = auth.user_id())
734```
735​
736### 3. Eager Mode with Sync Streams
737​
738Use the `onLoad` hook to subscribe to a Sync Stream when the collection first loads, so SQLite is populated before the collection starts serving queries. In `eager` mode, all rows in SQLite are synced into the TanStack DB collection; live query filtering then runs against that full dataset.
739The hook can optionally return a cleanup function where you can unsubscribe from the Sync Stream.
740​
741This example starts with 4 todos in the PowerSync Service, only 2 of which get synced via the Sync Stream to the SQLite database. Because it's eager mode, both get synced from the SQLite database to the collection. Finally the TanStack DB query only returns the single todo that matches the live query predicate.
742​
743**PS Service**
744​
745| id | list_id | completed |
746|:--:|:-------:|:---------:|
747| 1 | list_1 | 0 |
748| 2 | list_1 | 1 |
749| 3 | list_2 | 0 |
750| 4 | list_2 | 1 |
751​
752*Subscribe to Sync Stream, only sync where list_id = 'list_1'*
753​
754**SQLite**
755​
756| id | list_id | completed |
757|:--:|:-------:|:---------:|
758| 1 | list_1 | 0 |
759| 2 | list_1 | 1 |
760​
761*Eager mode syncs all SQLite data to TanStack DB Collection*
762​
763**Collection**
764​
765| id | list_id | completed |
766|:--:|:-------:|:---------:|
767| 1 | list_1 | 0 |
768| 2 | list_1 | 1 |
769​
770*TanStack DB Query filters for completed = 1*
771​
772**Result**
773​
774| id | list_id | completed |
775|:--:|:-------:|:---------:|
776| 2 | list_1 | 1 |
777​
778```typescript
779const collection = createCollection(
780 powerSyncCollectionOptions({
781 database: db,
782 table: AppSchema.props.todos,
783 syncMode: 'eager',
784 onLoad: async () => {
785 console.log('onLoad')
786 const subscription = await db
787 .syncStream('todos', { list: 'list_1' })
788 .subscribe()
789​
790 await subscription.waitForFirstSync()
791​
792 return () => {
793 console.log('onUnload')
794 subscription.unsubscribe()
795 }
796 },
797 }),
798)
799​
800// A live query that filters by the `completed` state.
801const liveQuery = createLiveQueryCollection({
802 query: (q) =>
803 q
804 .from({ todo: collection })
805 .where(({ todo }) => eq(todo.completed, 1))
806 .select(({ todo }) => ({
807 id: todo.id,
808 completed: todo.completed,
809 })),
810})
811```
812​
813### 4. On-Demand Mode with Sync Streams
814​
815Use the `onLoadSubset` hook to subscribe to a Sync Stream whenever the collection's data boundary changes (i.e. when the set of active live queries changes). In `on-demand` mode, only rows that satisfy the active live query predicates are synced from SQLite into the TanStack DB collection.
816The hook can optionally return a cleanup function where you can unsubscribe from the Sync Stream when that subset is no longer needed.
817​
818This example starts with 4 todos in the PowerSync Service, only 2 of which get synced via the Sync Stream to the SQLite database. Because it's on-demand mode, only 1 todo matches gets synced from the SQLite database to the collection. Finally the TanStack DB query only returns the single todo that matches the live query predicate.
819​
820**PS Service**
821​
822| id | list_id | completed |
823|:--:|:-------:|:---------:|
824| 1 | list_1 | 0 |
825| 2 | list_1 | 1 |
826| 3 | list_2 | 0 |
827| 4 | list_2 | 1 |
828​
829*Subscribe to Sync Stream, only sync where list_id = 'list_1'*
830​
831**SQLite**
832​
833| id | list_id | completed |
834|:--:|:-------:|:---------:|
835| 1 | list_1 | 0 |
836| 2 | list_1 | 1 |
837​
838*On-demand mode only syncs data from SQLite to the TanStack DB collection if they satisfy any of the live queries: completed = 1*
839​
840**Collection**
841​
842| id | list_id | completed |
843|:--:|:-------:|:---------:|
844| 2 | list_1 | 1 |
845​
846*TanStack DB Query filters for completed = 1*
847​
848**Result**
849​
850| id | list_id | completed |
851|:--:|:-------:|:---------:|
852| 2 | list_1 | 1 |
853​
854```typescript
855const collection = createCollection(
856 powerSyncCollectionOptions({
857 database: db,
858 table: AppSchema.props.todos,
859 syncMode: 'on-demand',
860 onLoadSubset: async (options) => {
861 console.log('onLoadSubset')
862 const subscription = await db
863 .syncStream('todos', { list: 'list_1' })
864 .subscribe()
865​
866 await subscription.waitForFirstSync()
867​
868 return () => {
869 console.log('onUnloadSubset')
870 subscription.unsubscribe()
871 }
872 },
873 }),
875​
876// A live query that filters by the `completed` state.
877const liveQuery = createLiveQueryCollection({
878 query: (q) =>
879 q
880 .from({ todo: collection })
881 .where(({ todo }) => eq(todo.completed, 1))
882 .select(({ todo }) => ({
883 id: todo.id,
884 completed: todo.completed,
885 })),
886})
887```
888​
889### 5. On-Demand Mode with Simple Predicates
890​
891In the previous example, the Sync Stream subscription parameters were hardcoded. In practice, you'll often want to derive those parameters dynamically from the live query's where clause. That way, changing the query automatically adjusts which data is synced from the PowerSync Service. `extractSimpleComparisons` is a convenience helper that parses the expression tree from `onLoadSubset` into a flat list of `{ field, operator, value }` objects.
892​
893Given a live query like:
894​
895```
896.where(({ todo }) => eq(todo.list_id, selectedListId))
897```
898​
899`onLoadSubset` receives options.where as an expression tree `for eq(list_id, '<uuid>')`.
900The `list_id` value is parsed from the expression tree and passed to `syncStream()`.
901​
902Note: This example slightly differs from the previous two as it aims to illustrate `extractSimpleComparisons` usage.
903​
904This example starts with 4 todos in the PowerSync Service, the Sync Stream subscription criteria (`list_id = "list_1"`) is derived from the live query registered against the collection. Only 2 todos get synced via the Sync Stream to the SQLite database. Two todos get synced from the SQLite database to the collection. Finally the TanStack DB query returns both todos as they both match `eq(todo.list_id, 'list_id')`.
905​
906**PS Service**
907​
908| id | list_id | completed |
909|:--:|:-------:|:---------:|
910| 1 | list_1 | 0 |
911| 2 | list_1 | 1 |
912| 3 | list_2 | 0 |
913| 4 | list_2 | 1 |
914​
915*Derive the list_id criteria from live query, subscribe to Sync Stream, only sync where list = 'list_1'*
916​
917**SQLite**
918​
919| id | list_id | completed |
920|:--:|:-------:|:---------:|
921| 1 | list_1 | 0 |
922| 2 | list_1 | 1 |
923​
924*On-demand mode only syncs data from SQLite to the TanStack DB collection if they satisfy any of the live queries: list_id = 'list_1'*
925​
926**Collection**
927​
928| id | list_id | completed |
929|:--:|:-------:|:---------:|
930| 1 | list_1 | 0 |
931| 2 | list_1 | 1 |
932​
933*TanStack DB Query filters for list_id = 'list_1'*
934​
935**Result**
936​
937| id | list_id | completed |
938|:--:|:-------:|:---------:|
939| 1 | list_1 | 0 |
940| 2 | list_1 | 1 |
941​
942```typescript
943const collection = createCollection(
944 powerSyncCollectionOptions({
945 database: db,
946 table: AppSchema.props.todos,
947 syncMode: 'on-demand',
948 onLoadSubset: async (options) => {
949 // Extract simple comparisons from the where expression
950 const comparisons = extractSimpleComparisons(options.where)
951 // comparisons = [{ field: ['todo', 'list_id'], operator: 'eq', value: '<uuid>' }]
952​
953 // Find the list_id filter
954 const listIdFilter = comparisons.find(
955 (c) => c.field.includes('list_id') && c.operator === 'eq',
956 )
957​
958 if (!listIdFilter) {
959 console.warn('No list_id filter found, skipping Sync Stream')
960 return
961 }
962​
963 console.log(`Subscribing to todos for list: ${listIdFilter.value}`)
964​
965 const subscription = await db
966 .syncStream('todos', { list: listIdFilter.value })
967 .subscribe()
968​
969 await subscription.waitForFirstSync()
970​
971 return () => {
972 console.log(`Unsubscribing from todos for list: ${listIdFilter.value}`)
973 subscription.unsubscribe()
974 }
975 },
976 }),
978​
979// Simple filter -> triggers `onLoadSubset` with `eq(list_id, '...')`
980const liveQuery = createLiveQueryCollection({
981 query: (q) =>
982 q
983 .from({ todo: collection })
984 .where(
985 ({ todo }) => eq(todo.list_id, 'list_id'), // or some listId variable
986 )
987 .select(({ todo }) => ({
988 id: todo.id,
989 completed: todo.completed,
990 })),
991})
992```
993​
994### 6. On-Demand Mode with Complex Predicates
995​
996While `extractSimpleComparisons` works well for simple, single-condition filters, live queries often combine multiple conditions using `and`, `or`, or other nested expressions. `parseWhereExpression` lets you provide custom handler functions for each operator (`eq`, `and`, etc.). This gives you full control over how a compound expression tree is unpacked and transformed into the parameters object passed to `syncStream()`. It's useful when your Sync Stream accepts multiple parameters and you need to extract all of them from a single composite where clause - for example, filtering by both `list_id` and `completed` status simultaneously.
997​
998Assume a small adjustment to the Sync Stream definition of todos (adding the `completed` subscription parameter):
999```
1000todos:
1001 query: SELECT * FROM todos WHERE list_id = subscription.parameter('list') AND completed = subscription.parameter("completed") AND list_id IN (SELECT id FROM lists WHERE owner_id = auth.user_id())
1002```
1003​
1004The `list` parameter name is kept as-is (consistent with most examples), but must be mapped to `list_id` to work with the following example. Alternatively, it can be named `list_id` in the Sync Stream definition to skip the programmatic mapping step.
1005​
1006This example starts with 4 todos in the PowerSync Service, the Sync Stream subscription criteria (`list_id = "list_1" and completed = 1`) is derived from the live query registered against the collection. Only 1 todo gets synced via the Sync Stream to the SQLite database. One todo gets synced from the SQLite database to the collection. Finally the TanStack DB query returns 1 todo that matches `eq(todo.list_id, 'list_id') and eq(todo.completed, 1)`.
1007​
1008**PS Service**
1009​
1010| id | list_id | completed |
1011|:--:|:-------:|:---------:|
1012| 1 | list_1 | 0 |
1013| 2 | list_1 | 1 |
1014| 3 | list_2 | 0 |
1015| 4 | list_2 | 1 |
1016​
1017*Derive the list_id and completed criteria from live query, subscribe to Sync Stream where list = 'list_1' AND completed = 1*
1018​
1019**SQLite**
1020​
1021| id | list_id | completed |
1022|:--:|:-------:|:---------:|
1023| 2 | list_1 | 1 |
1024​
1025*On-demand mode only syncs data from SQLite to the TanStack DB collection if they satisfy any of the live queries: list = 'list_1' AND completed = 1*
1026​
1027**Collection**
1028​
1029| id | list_id | completed |
1030|:--:|:-------:|:---------:|
1031| 2 | list_1 | 1 |
1032​
1033*TanStack DB Query filters for list = 'list_1' AND completed = 1*
1034​
1035**Result**
1036​
1037| id | list_id | completed |
1038|:--:|:-------:|:---------:|
1039| 2 | list_1 | 1 |
1040​
1041```typescript
1042const collection = createCollection(
1043 powerSyncCollectionOptions({
1044 database: db,
1045 table: AppSchema.props.todos,
1046 syncMode: 'on-demand',
1047 onLoadSubset: async (options) => {
1048 // Parse the where into a flat params record using custom handlers
1049 const streamParams = parseWhereExpression(options.where, {
1050 handlers: {
1051 eq: (field: Array<string>, value: unknown) => {
1052 const mappedField = mapFields(field[field.length - 1]!)
1053​
1054 return {
1055 [mappedField]: value,
1057 },
1058 and: (...filters: Array<Record<string, unknown>>) =>
1059 Object.assign({}, ...filters),
1060 },
1061 onUnknownOperator: (op, _args) => {
1062 console.warn(`Ignoring unsupported operator in stream params: ${op}`)
1063 return {}
1064 },
1065 })
1066 // For a query like: where(({ todo }) => and(eq(todo.list_id, 'abc'), eq(todo.completed, 0)))
1067 // streamParams = { list: 'abc', completed: 0 }
1068​
1069 if (!streamParams || Object.keys(streamParams).length === 0) {
1070 console.warn('No stream params extracted, skipping Sync Stream')
1071 return
1073​
1074 console.log(
1075 `Subscribing to todos with params: ${JSON.stringify(streamParams)}`,
1077​
1078 const subscription = await db
1079 .syncStream('todos', streamParams)
1080 .subscribe()
1081​
1082 await subscription.waitForFirstSync()
1083​
1084 return () => subscription.unsubscribe()
1085 },
1086 }),
1088​
1089// Compound filter -> triggers `onLoadSubset` with `and(eq(list_id, '...'), eq(completed, 1))`
1090const liveQuery = createLiveQueryCollection({
1091 query: (q) =>
1093 .from({ todo: collection })
1094 .where(({ todo }) =>
1095 and(eq(todo.list_id, 'list_1'), eq(todo.completed, 1)),
1097 .select(({ todo }) => ({
1098 id: todo.id,
1099 completed: todo.completed,
1100 })),
1102```