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

README.md

158 lines6.1 KB

1# @tanstack/electron-db-sqlite-persistence
2​
3Thin Electron bridge for TanStack DB SQLite persistence.
4​
5Start with the [SQLite Persistence guide](../../docs/guides/sqlite-persistence.md) for Collection setup and lifecycle behavior.
6​
7## Public API
8​
9- `exposeElectronSQLitePersistence(...)` (main process)
10- `createElectronSQLitePersistence(...)` (renderer process)
11- `ElectronCollectionCoordinator`
12- `persistedCollectionOptions(...)` (re-exported from core)
13​
14Use `@tanstack/electron-db-sqlite-persistence/main` and
15`@tanstack/electron-db-sqlite-persistence/renderer` if you prefer
16explicit process-specific entrypoints.
17​
18## Main process
19​
20```ts
21import { ipcMain } from 'electron'
22import { createNodeSQLitePersistence } from '@tanstack/node-db-sqlite-persistence'
23import { exposeElectronSQLitePersistence } from '@tanstack/electron-db-sqlite-persistence/main'
24import Database from 'better-sqlite3'
25​
26const database = new Database(`./tanstack-db.sqlite`)
27​
28const persistence = createNodeSQLitePersistence({
29 database,
30})
31​
32const dispose = exposeElectronSQLitePersistence({
33 ipcMain,
34 persistence,
35})
36​
37// Call dispose() and database.close() during shutdown.
38```
39​
40## Renderer process
41​
42```ts
43import { createCollection } from '@tanstack/db'
44import { ipcRenderer } from 'electron'
45import {
46 createElectronSQLitePersistence,
47 persistedCollectionOptions,
48} from '@tanstack/electron-db-sqlite-persistence'
49​
50type Todo = {
51 id: string
52 title: string
53 completed: boolean
55​
56const persistence = createElectronSQLitePersistence<Todo, string>({
57 ipcRenderer,
58})
59​
60export const todosCollection = createCollection(
61 persistedCollectionOptions<Todo, string>({
62 id: `todos`,
63 getKey: (todo) => todo.id,
64 persistence,
65 schemaVersion: 1, // Per-collection schema version
66 }),
68```
69​
70## Multi-renderer ownership
71​
72Pass an `ElectronCollectionCoordinator` when multiple renderers share the same
73database. Coordinators using the same `dbName` elect a writer independently for
74each collection.
75​
76```ts
77import {
78 ElectronCollectionCoordinator,
79 createElectronSQLitePersistence,
80} from '@tanstack/electron-db-sqlite-persistence'
81​
82const coordinator = new ElectronCollectionCoordinator({
83 dbName: `tanstack-db`,
84})
85​
86const persistence = createElectronSQLitePersistence({
87 ipcRenderer,
88 coordinator,
89})
90​
91// On teardown:
92// coordinator.dispose()
93```
94​
95The persisted sync wrapper routes every source transaction with durable effects
96through the coordinator's required
97`requestApplyCommittedTx(collectionId, tx)` method. The elected renderer applies
98the complete `PersistedTx` through its resolved per-collection renderer adapter,
99which forwards it over IPC to the main-process persistence owner. Resolution
100remains specific to the collection id, mode, and `schemaVersion`.
101​
102Truncation, row changes, row metadata, collection metadata, and stream position
103stay in the same transaction. Electron does not feature-detect a partial route
104or fall back to row-only mutation RPC. A custom coordinator that omits
105`requestApplyCommittedTx` is rejected while the collection is configured,
106before its sync source can publish rows. An effect-free source commit neither
107publishes nor consumes a coordinator sequence.
108​
109If a mutating RPC loses its response, Electron coordination replays it only
110while the requester still knows the same non-null leader id and term. An
111unknown initial route or any leader/term change rejects the direct RPC with
112`IndeterminateCommitError`. For a source-backed persisted Collection, the sync
113wrapper can certify the original transaction ID through the replacement leader
114and the main-process SQLite adapter. Application-issued mutations still need
115caller reconciliation. Main and renderer must use matching persistence protocol
116v5 peers for this IPC operation. A main-process adapter used by an
117`ElectronCollectionCoordinator` must implement `reserveLeadershipTerm` so each
118election reserves a durable term before publishing a route. An adapter without
119that capability can still serve single-renderer persistence through
120`SingleProcessCoordinator`; a coordinated election rejects it before route
121publication.
122​
123Remote-subset requests use the same crash-only boundary. The coordinator
124projects a live `LoadSubsetOptions` input to the exported
125`TransportedLoadSubsetOptions` type before either local completion or renderer
126transport. Live `signal` and `subscription` fields do not cross the boundary.
127Unsupported nested values throw `RemoteSubsetWireValueError` with the exact
128value path before publication; Electron does not add codecs, coercion, or a
129fallback representation.
130​
131Electron uses the same explicit lease lifecycle as Browser coordination. The
132same request object reuses one acquisition identity, distinct equal objects
133remain independent, and release unloads the exact transported options once.
134Leadership loss unloads the retiring renderer's leases; still-live requester
135leases replay against the next leader. A second owner registration for one
136collection throws `DuplicateRemoteSubsetOwnerError`, and there is no adapter
137fallback for a missing owner. Remote follower transport/admission failures
138reject and retain demand for its normal retry without entering the follower's
139local owner lifecycle. Terminal release identities expire after the existing
140RPC dedupe horizon while delayed duplicates inside that horizon remain
141idempotent.
142​
143## Notes
144​
145- The renderer API mirrors other runtimes: one shared `create...Persistence`.
146- IPC protocol v6 forwards explicit eager or managed storage targets,
147 on-demand cache claims, rotation, renewal, release, claim checks on SQLite
148 reads and writes, exact transaction-ID
149 reconciliation, and claim-scoped leadership-term reservation. Upgrade main
150 and renderer together.
151 If a custom main-process adapter does not implement these operations, pass
152 `managedCacheGenerations: false` to `createElectronSQLitePersistence` to keep
153 the full-shape recovery fallback.
154- Collection mode (`sync-present` vs `sync-absent`) and `schemaVersion` are
155 resolved per collection and forwarded across IPC automatically.
156- Without an `ElectronCollectionCoordinator`, single-renderer mode uses
157 `SingleProcessCoordinator`: it is always leader, but still routes complete
158 transactions to the collection's resolved IPC adapter.