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

sqlite-persistence.md

419 lines23.9 KB

1---
2title: SQLite Persistence
3id: sqlite-persistence
4---
5​
6SQLite persistence stores Collection rows in a SQLite database supplied by the runtime. A new Collection can load those rows when it uses the same database. The wrapper can also save sync metadata so a supported sync adapter can resume safely.
7​
8Choose a package for your runtime. Each runtime package supplies a SQLite driver and re-exports `persistedCollectionOptions` from `@tanstack/db-sqlite-persistence-core`.
9​
10SQLite persistence stores Collection data. To retain mutations that still need a server response, use [offline transactions](./offline-transactions.md). The [combined React Native recipe](./offline-transactions.md#use-sqlite-persistence-with-the-outbox) shows both stores together.
11​
12## Choose a runtime package
13​
14Each package connects through its runtime's database, storage, or IPC interface. Follow its README for setup and required native plugins.
15​
16| Runtime | Package and setup | Factory |
17| --- | --- | --- |
18| Browser with OPFS | [`@tanstack/browser-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/browser-db-sqlite-persistence#readme) | `createBrowserWASQLitePersistence` |
19| Node.js | [`@tanstack/node-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#readme) | `createNodeSQLitePersistence` |
20| React Native with OP-SQLite | [`@tanstack/react-native-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/react-native-db-sqlite-persistence#readme) | `createReactNativeSQLitePersistence` |
21| Expo with `expo-sqlite` | [`@tanstack/expo-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/expo-db-sqlite-persistence#readme) | `createExpoSQLitePersistence` |
22| Capacitor | [`@tanstack/capacitor-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/capacitor-db-sqlite-persistence#readme) | `createCapacitorSQLitePersistence` |
23| Tauri | [`@tanstack/tauri-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/tauri-db-sqlite-persistence#readme) | `createTauriSQLitePersistence` |
24| Electron | [`@tanstack/electron-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/electron-db-sqlite-persistence#readme) | `createElectronSQLitePersistence` in a renderer |
25| Cloudflare Durable Objects (server) | [`@tanstack/cloudflare-durable-objects-db-sqlite-persistence`](https://github.com/TanStack/db/tree/main/packages/cloudflare-durable-objects-db-sqlite-persistence#readme) | `createCloudflareDOSQLitePersistence` |
26​
27The core package has no SQLite engine binding. Use a runtime package unless you are implementing a new driver.
28​
29## Start in the browser
30​
31Install the browser wrapper and its SQLite engine:
32​
33```sh
34npm install @tanstack/db @tanstack/browser-db-sqlite-persistence @journeyapps/wa-sqlite
35```
36​
37This example uses one browser tab. Open an OPFS database, then create one persistence instance for it. Give every persisted Collection a stable `id` and a `getKey` function. Set `schemaVersion` to track the stored row format. Increase it when that format changes.
38​
39```ts
40import { createCollection } from '@tanstack/db'
41import {
42 createBrowserWASQLitePersistence,
43 openBrowserWASQLiteOPFSDatabase,
44 persistedCollectionOptions,
45} from '@tanstack/browser-db-sqlite-persistence'
46​
47type Todo = {
48 id: string
49 title: string
50 completed: boolean
52​
53const database = await openBrowserWASQLiteOPFSDatabase({
54 databaseName: 'app.sqlite',
55})
56const persistence = createBrowserWASQLitePersistence({ database })
57​
58const todos = createCollection(
59 persistedCollectionOptions<Todo, string>({
60 id: 'todos',
61 getKey: (todo) => todo.id,
62 persistence,
63 schemaVersion: 1,
64 }),
66​
67await todos.preload()
68const transaction = todos.insert({
69 id: '1',
70 title: 'Buy milk',
71 completed: false,
72})
73await transaction.when('settled')
74```
75​
76This Collection has no `sync` option. Its normal insert, update, and delete handlers save local mutations to SQLite. It does not contact a server. The browser must support OPFS and run in a secure context. If multiple tabs can open the same database, use the [multi-tab setup](#browser-tabs-and-electron-renderers).
77​
78### Manual transactions on a local Collection
79​
80Local persistence reserves the utility names `acceptMutations`,
81`getLeadershipState`, and `forceReloadSubset`. If caller-supplied `utils`
82contains one of these properties, `persistedCollectionOptions` throws
83`InvalidPersistedCollectionConfigError` before it resolves persistence.
84This also applies to inherited properties and properties whose value is
85`undefined`. Other custom utility names remain available. Collections with a
86`sync` option retain their adapter utilities without this local-only restriction.
87​
88For a Collection without a `sync` option, normal Collection mutations persist automatically. A manual transaction must call `acceptMutations` in its mutation function:
89​
90```ts
91import { createTransaction } from '@tanstack/db'
92​
93const manualTransaction = createTransaction({
94 autoCommit: false,
95 mutationFn: async ({ transaction }) => {
96 await todos.utils.acceptMutations(transaction)
97 },
98})
99​
100manualTransaction.mutate(() => {
101 todos.insert({ id: '2', title: 'Call home', completed: false })
102})
103​
104await manualTransaction.commit()
105```
106​
107### Load rows after reopening the database
108​
109Keep the database open while its Collections run. To simulate a page restart, clean up the Collection and close the database:
110​
111```ts
112await todos.cleanup()
113await database.close?.()
114```
115​
116Open the same OPFS database and create a Collection with the same `id` and `schemaVersion`. Load its rows before you read them:
117​
118```ts
119const reopenedDatabase = await openBrowserWASQLiteOPFSDatabase({
120 databaseName: 'app.sqlite',
121})
122const reopenedPersistence = createBrowserWASQLitePersistence({
123 database: reopenedDatabase,
124})
125const reopenedTodos = createCollection(
126 persistedCollectionOptions<Todo, string>({
127 id: 'todos',
128 getKey: (todo) => todo.id,
129 persistence: reopenedPersistence,
130 schemaVersion: 1,
131 }),
133​
134await reopenedTodos.preload()
135console.log(reopenedTodos.get('1')?.title) // 'Buy milk'
136​
137await reopenedTodos.cleanup()
138await reopenedDatabase.close?.()
139```
140​
141## Temporal values
142​
143SQLite persistence preserves `Temporal.Instant` and `Temporal.PlainDate` as
144native values, including nested fields, metadata and replay. Register the same
145Temporal implementation globally before writing or reopening persisted data.
146On a runtime without native Temporal, for example:
147​
148```ts
149import 'temporal-polyfill/global'
150```
151​
152Missing constructors and other Temporal kinds reject explicitly. Strings remain
153strings. Equality retains the Temporal kind and canonical text, including a
154PlainDate's calendar; ordering follows Temporal comparison. Supported native
155predicates and persisted expression indexes use the existing SQL filtering and
156in-memory cleanup pipeline without reducing nanosecond precision.
157​
158This support applies to the shared SQLite adapter and local persisted wrapper.
159The remote-subset coordinator wire domain does not include Temporal literals;
160those requests reject before remote retry admission. If retained local demand
161becomes remote after an ownership change, fallback sequence-gap recovery fails
162the current Collection sync run before retrying that invalid request. This is a
163terminal Collection error: later active subsets are not recovered, subsequent
164loads reject with the same error, and later coordinator messages do not resume
165the failed run. Existing acquisitions can still be released. Multiprocess
166transport of native Temporal rows is not covered by this support claim.
167​
168Values already stored as `{}` cannot be recovered. If an older version damaged
169a synced cache, replace it through the existing `schemaVersion` and schema-reset
170policy, then refetch. Updating the library does not automatically erase data.
171Also rebuild an older cache if ordinary objects used the reserved
172`__tanstack_db_persisted_type__` marker with a newly recognized type name. Older
173writes did not escape those objects, so their original meaning is ambiguous.
174New writes escape the marker and preserve the ordinary object.
175Older library versions cannot interpret the new Temporal encoding. Changed
176expression indexes rebuild when first ensured after upgrade. Later startups reuse
177those indexes. A changed native-literal or escaped-record signature can leave an
178obsolete registry entry and index until an explicit schema reset; this release
179does not reclaim those entries automatically. Increment the affected synced
180Collection's `schemaVersion` and retain its reset policy to rebuild that cache.
181The reset removes its old values and indexes before reading the new schema;
182other Collections with unchanged schema versions retain their caches. Refetch
183from the upstream source after reset.
184​
185## Add persistence to a synced Collection
186​
187Pass the options from a sync adapter into `persistedCollectionOptions`. The wrapper keeps that adapter's sync behavior and stores its applied data in SQLite.
188​
189For example, you can wrap a Query Collection. This separate example uses the imports and `Todo` type from the browser example above:
190​
191```ts
192import { QueryClient } from '@tanstack/query-core'
193import { queryCollectionOptions } from '@tanstack/query-db-collection'
194​
195const syncedDatabase = await openBrowserWASQLiteOPFSDatabase({
196 databaseName: 'synced.sqlite',
197})
198const syncedPersistence = createBrowserWASQLitePersistence({
199 database: syncedDatabase,
200})
201const queryClient = new QueryClient()
202​
203const syncedTodos = createCollection(
204 persistedCollectionOptions<Todo, string>({
205 ...queryCollectionOptions<Todo, string>({
206 id: 'synced-todos',
207 queryClient,
208 queryKey: ['todos'],
209 queryFn: async () => {
210 const response = await fetch('http://localhost:3000/api/todos')
211 if (!response.ok) throw new Error('Could not load todos')
212 return (await response.json()) as Array<Todo>
213 },
214 getKey: (todo) => todo.id,
215 }),
216 persistence: syncedPersistence,
217 schemaVersion: 1,
218 initialRender: {
219 strategy: 'network-first',
220 networkTimeoutMs: 3_000,
221 },
222 }),
224```
225​
226Install `@tanstack/query-core` and `@tanstack/query-db-collection` to use this example. Change the URL to your server. You can wrap another Collection sync adapter in the same way.
227​
228The `initialRender` option is optional. It lets the Collection become ready from restored SQLite rows when the network is slow or unavailable. See [Render after SQLite restore](#render-after-sqlite-restore).
229​
230Keep `syncedDatabase` open while `syncedTodos` runs. During normal shutdown, await `syncedTodos.cleanup()` and then `syncedDatabase.close?.()`.
231​
232The `sync` option determines which mode the wrapper uses:
233​
234| Collection options | SQLite behavior |
235| --- | --- |
236| `sync` present | Load persisted rows, then apply source sync transactions. The source remains responsible for current data. |
237| `sync` absent | Load and save local rows through a loopback sync adapter. The Collection has no remote source. |
238​
239The wrapper also supports `syncMode: 'on-demand'`. In that mode, it loads rows for active query demand rather than loading every stored row into the Collection. When no query needs rows, a peer reload or schema reset checks rows already visible in the Collection but does not add unrelated stored rows.
240​
241Built-in SQLite adapters use managed generations for on-demand caches. If a cache claim expires, the wrapper retires the old source callbacks, cleans up that source session, rotates the cache, and calls a custom source's `sync` function again. A custom source does not need a restart hook. Query and Electric provide `restartAfterScopedRecovery` to control their own restart; their hooks must retire old callbacks immediately and start replacement loads after `cacheRotated` resolves.
242​
243An on-demand cache is not yet a certified offline snapshot. The first managed generation does not import legacy cache tables, and a private replacement created after claim expiry is not the next run's shared cache. A later launch must refetch those subsets from the source.
244​
245## Render after SQLite restore
246​
247Without `initialRender`, a persisted Collection becomes `ready` when its sync adapter calls `markReady()`, like any other Collection. The restored rows are in the Collection while it loads, but `status` stays `loading`. Eager and on-demand Collections both support `initialRender`; [on-demand Collections](#on-demand-collections-offline) apply it to each query demand.
248​
249With `initialRender: { strategy: 'network-first', networkTimeoutMs }`, the Collection prefers the network for `networkTimeoutMs` (default 3 seconds). It becomes `ready` from the restored rows when both of these are true:
250​
251- the SQLite restore completed and installed at least one row, and
252- the deadline passed, or the sync adapter failed its first load.
253​
254To render cached rows as soon as the restore completes, set `networkTimeoutMs: 0`. Use this when a fast first render is more important than fresh data:
255​
256```ts
257persistedCollectionOptions({
258 ...todoSyncOptions,
259 persistence: syncedPersistence,
260 schemaVersion: 1,
261 initialRender: { strategy: 'network-first', networkTimeoutMs: 0 },
262})
263```
264​
265A Collection with restored rows then becomes `ready` from them immediately. Network sync continues, and its changes apply over the restored rows when they arrive. An empty restore still waits for the network, so the Collection never shows an empty list that the network did not confirm. An on-demand Collection applies this to each query demand, as [On-demand Collections offline](#on-demand-collections-offline) describes.
266​
267The status is the only signal. Every hook, Suspense, and `preload()` follow it, so you do not need a separate persisted flag:
268​
269```tsx
270import { useLiveQuery } from '@tanstack/react-db'
271​
272function TodosView() {
273 const { data, isLoading, isLoadingError, isSyncError } = useLiveQuery((q) =>
274 q.from({ syncedTodos }),
275 )
276 if (isLoading) return <p>Loading todos...</p>
277 if (isLoadingError) return <p>Could not load todos.</p>
278 return (
279 <>
280 {isSyncError && <p>Showing saved todos. Sync is having trouble.</p>}
281 <ul>{data.map((todo: Todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
282 </>
283 )
285```
286​
287These rules keep `ready` meaningful:
288​
289- **An empty restore waits for the network.** The Collection stays `loading` until the sync adapter answers, so an empty list always means "no rows". A Collection that last synced to zero rows also waits, because the restore cannot tell the two cases apart.
290- **The restore comes first.** If the sync adapter answers before the restore completes, the answer waits for the restore. A remote failure then opens the Collection from restored rows and shows the failure as a sync error (`isSyncError`, `collection.health.error`). Without restored rows, the first load fails (`status: 'error'`).
291- **A failed restore is a crash.** The Collection becomes `crashed`, because local storage cannot serve reads.
292- **The deadline does not stop network sync.** Network changes apply over the restored rows when they arrive.
293​
294These rules apply to an eager Collection. An on-demand Collection applies `initialRender` to each query demand. See [On-demand Collections offline](#on-demand-collections-offline).
295​
296Suspense uses the same status. This React component uses the `syncedTodos` Collection configured above:
297​
298```tsx
299import { Suspense } from 'react'
300import { useLiveSuspenseQuery } from '@tanstack/react-db'
301​
302function TodosList() {
303 const { data } = useLiveSuspenseQuery((q) => q.from({ syncedTodos }))
304 return <ul>{data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
306​
307function TodosScreen() {
308 return (
309 <Suspense fallback={<p>Loading todos...</p>}>
310 <TodosList />
311 </Suspense>
312 )
314```
315​
316Place `TodosScreen` inside an [Error Boundary](./error-handling.md#using-suspense-and-error-boundaries-react) to handle a failed first load or a crash.
317​
318Restored rows do not prove current authorization. Isolate SQLite data by user or tenant. If an authorization failure must hide cached rows, block the view separately: a remote failure can open the Collection from restored rows.
319​
320### On-demand Collections offline
321​
322An on-demand Collection loads rows for each query demand: the filter, order, and limit that a query asks the source for. With `initialRender`, a demand can settle on its rows from SQLite when the network does not answer. This includes Electric's `syncMode: 'progressive'`, which loads query subsets on demand until its full sync completes.
323​
324```ts
325type Issue = { id: string; title: string }
326​
327const issues = createCollection(
328 persistedCollectionOptions({
329 ...electricCollectionOptions<Issue>({
330 id: 'issues',
331 shapeOptions: { url: 'http://localhost:3000/v1/shape', params: { table: 'issues' } },
332 syncMode: 'progressive',
333 getKey: (issue) => issue.id,
334 }),
335 persistence: syncedPersistence,
336 initialRender: { strategy: 'network-first', networkTimeoutMs: 3_000 },
337 }),
339```
340​
341The rule applies to each demand separately:
342​
343- A demand is covered after a load of that exact demand settles online and its rows are saved in SQLite. Another filter, order, or limit is a different demand, even when its rows overlap.
344- A later load of a covered demand first shows its rows from SQLite. If the network does not answer within `networkTimeoutMs`, or it fails, the load settles on those rows. `isReady`, `preload()`, and Suspense then proceed as they do after a network load. Only the load settles from SQLite; the on-demand Collection's own status does not change.
345- The network load keeps running. Its rows replace the restored rows when they arrive. If it fails after the load settled, the query stays ready on the rows it shows.
346- A demand that never settled online is not covered. Offline, it waits for the network. A query that has never run therefore stays loading offline unless a completed progressive full sync already holds every row.
347- A source truncate, such as an Electric must-refetch, ends coverage for every demand, and so does a snapshot transaction (`begin({ snapshot: true })`), which replaces every row. A new cache generation starts without coverage.
348- Scoped recovery also ends coverage. For the rest of that sync run, no load settles from SQLite and no load records coverage.
349- A load that is released before it settles records no coverage, even if its source finishes it afterward.
350- Coverage also ends when SQLite holds fewer rows for the demand than it held when the demand settled. A row that the source deletes, or that Query DB retention removes after `gcTime`, therefore ends coverage until the demand loads online again, unless another row of the demand reached SQLite meanwhile, for example through another query. Coverage counts the rows of an unordered demand; it does not record which rows they were.
351- An ordered window with a `limit` stays covered only while SQLite holds the same rows for it, in any order. A row that leaves, joins, or replaces a row of the window ends its coverage.
352- A load with `refetch: true` always waits for the network.
353- Only the default single-process coordinator supports this. If you pass a multi-tab coordinator, such as `BrowserCollectionCoordinator`, on-demand loads do not settle from SQLite. They wait for the network, as they did before this option.
354​
355Coverage proves that the rows were complete when the earlier load settled. It does not prove that they are current. The wait changes when readiness arrives, not which rows the source has. A cursor page or a demand built from other rows' values is covered only if the restored rows produce the same demand again.
356​
357For a query that joins eager and on-demand sources, the query becomes ready when every eager source is ready, which network-first allows from its restored rows after the deadline, and every demand that the query reaches on an on-demand source has settled. A network failure alone does not settle an on-demand demand that is not covered.
358​
359## Browser tabs and Electron renderers
360​
361The browser package uses single-tab coordination by default. If tabs share one OPFS database, give the persistence instance a `BrowserCollectionCoordinator`. It elects an owner for each Collection and routes writes between tabs. Replace the initial database and persistence setup with this code in each tab:
362​
363```ts
364import { BrowserCollectionCoordinator } from '@tanstack/browser-db-sqlite-persistence'
365​
366const database = await openBrowserWASQLiteOPFSDatabase({
367 databaseName: 'app.sqlite',
368})
369const coordinator = new BrowserCollectionCoordinator({ dbName: 'app' })
370const persistence = createBrowserWASQLitePersistence({
371 database,
372 coordinator,
373})
374```
375​
376Pass this persistence instance to `persistedCollectionOptions`. During normal shutdown, clean up the Collections, dispose the coordinator, and close the database.
377​
378The Electron package uses a main-process SQLite owner and a renderer bridge. Add `ElectronCollectionCoordinator` when multiple renderers share the database.
379​
380These coordinators belong to SQLite persistence. The offline transaction executor has separate leader election for its outbox. Configure each system for the storage it owns.
381​
382The browser database uses a worker. Its OPFS setup needs a secure context and browser support for OPFS. Close the database during normal shutdown. After a page returns from the back/forward cache, create fresh database and Collection instances.
383​
384## Node.js alternative
385​
386For a Node.js process, install `@tanstack/node-db-sqlite-persistence` and `better-sqlite3` in place of the browser packages. Open a file with `better-sqlite3` and pass it to the Node factory:
387​
388```ts
389import Database from 'better-sqlite3'
390import {
391 createNodeSQLitePersistence,
392 persistedCollectionOptions,
393} from '@tanstack/node-db-sqlite-persistence'
394​
395const nodeDatabase = new Database('./app.sqlite')
396const nodePersistence = createNodeSQLitePersistence({
397 database: nodeDatabase,
398})
399```
400​
401Use `nodePersistence` in the Collection options shown above. Clean up each Collection before you call `nodeDatabase.close()`. The [Node package README](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#readme) has a complete example.
402​
403## Schema versions and recovery
404​
405By default, a synced Collection resets its persisted data after a schema mismatch. Its sync adapter must then load current data. A Collection without `sync` reports an error instead. It has no source that can restore deleted local rows.
406​
407All runtime factories listed above except the Electron renderer factory accept `schemaMismatchPolicy`. An explicit `reset` policy can delete local data, so use it only when your application can restore that data.
408​
409The Node package prunes its applied transaction log by default. Its [README](https://github.com/TanStack/db/tree/main/packages/node-db-sqlite-persistence#applied-transaction-pruning) lists the limits and options. If a resume position is older than the retained log, persistence loads a full snapshot.
410​
411## Errors and limits
412​
413An unavailable browser storage capability raises `PersistenceUnavailableError`. A durable write failure raises `PersistedCollectionDurabilityError` and crashes the Collection: it moves to `crashed` even after it was ready, and so does every live query and Effect over it. `reload()` rejects; recover with `cleanup({ dependents: true })` and `preload()` (see [When a Collection crashes](./error-handling.md#when-a-collection-crashes)).
414​
415Failures from the wrapped sync adapter keep their usual meaning. Before the Collection is ready, the adapter's `fail` fails the first load (see [Render after SQLite restore](#render-after-sqlite-restore) for `initialRender`). After it, the adapter's `reportError`, `reportHealthy`, and `fail` appear in `collection.health` and in each live query's `health` tree, and the persisted rows stay. A failure of persistence itself crashes the Collection. In a follower tab, a failed request routed to the leader appears as a request error on the query that asked for the data.
416​
417If a coordinated write loses its response, the result can be uncertain. `IndeterminateCommitError` means the application must check the durable state before it retries that write.
418​
419Persistence retains source data and metadata. It does not define how an application sends local changes to a server. Use a mutation handler or the [offline transactions guide](./offline-transactions.md) for that work.