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

node-persistence.ts

155 lines4.6 KB

1import {
2 SingleProcessCoordinator,
3 createSQLiteCorePersistenceAdapter,
4} from '@tanstack/db-sqlite-persistence-core'
5import { BetterSqlite3SQLiteDriver } from './node-driver'
6import type {
7 PersistedCollectionCoordinator,
8 PersistedCollectionMode,
9 PersistedCollectionPersistence,
10 SQLiteCoreAdapterOptions,
11 SQLiteDriver,
12} from '@tanstack/db-sqlite-persistence-core'
13import type { BetterSqlite3Database } from './node-driver'
14​
15export type { BetterSqlite3Database } from './node-driver'
16​
17type NodeSQLiteCoreSchemaMismatchPolicy =
18 | `sync-present-reset`
19 | `sync-absent-error`
20 | `reset`
21​
22export type NodeSQLiteSchemaMismatchPolicy =
23 | NodeSQLiteCoreSchemaMismatchPolicy
24 | `throw`
25​
26type NodeSQLitePersistenceBaseOptions = Omit<
27 SQLiteCoreAdapterOptions,
28 `driver` | `schemaVersion` | `schemaMismatchPolicy`
29> & {
30 database: BetterSqlite3Database
31 pragmas?: ReadonlyArray<string>
32 coordinator?: PersistedCollectionCoordinator
33 schemaMismatchPolicy?: NodeSQLiteSchemaMismatchPolicy
35​
36export type NodeSQLitePersistenceOptions = NodeSQLitePersistenceBaseOptions
37​
38function normalizeSchemaMismatchPolicy(
39 policy: NodeSQLiteSchemaMismatchPolicy,
40): NodeSQLiteCoreSchemaMismatchPolicy {
41 if (policy === `throw`) {
42 return `sync-absent-error`
43 }
44​
45 return policy
47​
48function resolveSchemaMismatchPolicy(
49 explicitPolicy: NodeSQLiteSchemaMismatchPolicy | undefined,
50 mode: PersistedCollectionMode,
51): NodeSQLiteCoreSchemaMismatchPolicy {
52 if (explicitPolicy) {
53 return normalizeSchemaMismatchPolicy(explicitPolicy)
54 }
55​
56 return mode === `sync-present` ? `sync-present-reset` : `sync-absent-error`
58​
59function createAdapterCacheKey(
60 schemaMismatchPolicy: NodeSQLiteCoreSchemaMismatchPolicy,
61 schemaVersion: number | undefined,
62): string {
63 const schemaVersionKey =
64 schemaVersion === undefined ? `schema:default` : `schema:${schemaVersion}`
65 return `${schemaMismatchPolicy}|${schemaVersionKey}`
67​
68function createInternalSQLiteDriver(
69 options: NodeSQLitePersistenceOptions,
70): SQLiteDriver {
71 return new BetterSqlite3SQLiteDriver({
72 database: options.database,
73 ...(options.pragmas ? { pragmas: options.pragmas } : {}),
74 })
76​
77function resolveAdapterBaseOptions(
78 options: NodeSQLitePersistenceOptions,
79): Omit<
80 SQLiteCoreAdapterOptions,
81 `driver` | `schemaVersion` | `schemaMismatchPolicy`
82> {
83 return {
84 appliedTxPruneMaxRows: options.appliedTxPruneMaxRows,
85 appliedTxPruneMaxAgeSeconds: options.appliedTxPruneMaxAgeSeconds,
86 pullSinceReloadThreshold: options.pullSinceReloadThreshold,
87 }
89​
90/**
91 * Creates a shared SQLite persistence instance that can be reused by many
92 * collections on the same database. Collection-specific schema versions are
93 * resolved by `persistedCollectionOptions` via `resolvePersistenceForCollection`.
94 */
95export function createNodeSQLitePersistence(
96 options: NodeSQLitePersistenceOptions,
97): PersistedCollectionPersistence {
98 const { coordinator, schemaMismatchPolicy } = options
99 const driver = createInternalSQLiteDriver(options)
100 const adapterBaseOptions = resolveAdapterBaseOptions(options)
101 const resolvedCoordinator = coordinator ?? new SingleProcessCoordinator()
102 const adapterCache = new Map<
103 string,
104 ReturnType<typeof createSQLiteCorePersistenceAdapter>
105 >()
106​
107 const getAdapterForCollection = (
108 mode: PersistedCollectionMode,
109 schemaVersion: number | undefined,
110 ) => {
111 const resolvedSchemaMismatchPolicy = resolveSchemaMismatchPolicy(
112 schemaMismatchPolicy,
113 mode,
114 )
115 const cacheKey = createAdapterCacheKey(
116 resolvedSchemaMismatchPolicy,
117 schemaVersion,
118 )
119 const cachedAdapter = adapterCache.get(cacheKey)
120 if (cachedAdapter) {
121 return cachedAdapter
122 }
123​
124 const adapter = createSQLiteCorePersistenceAdapter({
125 ...adapterBaseOptions,
126 driver,
127 schemaMismatchPolicy: resolvedSchemaMismatchPolicy,
128 ...(schemaVersion === undefined ? {} : { schemaVersion }),
129 })
130 adapterCache.set(cacheKey, adapter)
131 return adapter
132 }
133​
134 const createCollectionPersistence = (
135 mode: PersistedCollectionMode,
136 schemaVersion: number | undefined,
137 ): PersistedCollectionPersistence => ({
138 adapter: getAdapterForCollection(mode, schemaVersion),
139 coordinator: resolvedCoordinator,
140 })
141​
142 const defaultPersistence = createCollectionPersistence(
143 `sync-absent`,
144 undefined,
145 )
146​
147 return {
148 ...defaultPersistence,
149 resolvePersistenceForCollection: ({ mode, schemaVersion }) =>
150 createCollectionPersistence(mode, schemaVersion),
151 // Backward compatible fallback for older callers.
152 resolvePersistenceForMode: (mode) =>
153 createCollectionPersistence(mode, undefined),
154 }