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