@powersync/shared-internals 0.0.0-tmp.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +5 -0
- package/dist/bundle.cjs +11787 -0
- package/dist/bundle.cjs.map +1 -0
- package/dist/bundle.mjs +11757 -0
- package/dist/bundle.mjs.map +1 -0
- package/dist/bundle.node.cjs +9418 -0
- package/dist/bundle.node.cjs.map +1 -0
- package/dist/bundle.node.mjs +9388 -0
- package/dist/bundle.node.mjs.map +1 -0
- package/dist/index.d.cts +1159 -0
- package/dist/websockets.mjs +7558 -0
- package/dist/websockets.mjs.map +1 -0
- package/dist/websockets.node.mjs +5189 -0
- package/dist/websockets.node.mjs.map +1 -0
- package/legacy/sync_protocol.d.ts +103 -0
- package/lib/client/BasePowerSyncDatabase.d.ts +147 -0
- package/lib/client/BasePowerSyncDatabase.js +622 -0
- package/lib/client/BasePowerSyncDatabase.js.map +1 -0
- package/lib/client/ConnectionManager.d.ts +116 -0
- package/lib/client/ConnectionManager.js +306 -0
- package/lib/client/ConnectionManager.js.map +1 -0
- package/lib/client/CustomQuery.d.ts +21 -0
- package/lib/client/CustomQuery.js +43 -0
- package/lib/client/CustomQuery.js.map +1 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +42 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js +23 -0
- package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
- package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
- package/lib/client/sync/bucket/CrudEntry.js +60 -0
- package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +33 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js +166 -0
- package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
- package/lib/client/sync/options.d.ts +9 -0
- package/lib/client/sync/options.js +16 -0
- package/lib/client/sync/options.js.map +1 -0
- package/lib/client/sync/stream/AbstractRemote.d.ts +125 -0
- package/lib/client/sync/stream/AbstractRemote.js +265 -0
- package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +138 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +611 -0
- package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
- package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
- package/lib/client/sync/stream/WebSocketSupport.js +198 -0
- package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
- package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
- package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
- package/lib/client/sync/stream/core-instruction.d.ts +75 -0
- package/lib/client/sync/stream/core-instruction.js +4 -0
- package/lib/client/sync/stream/core-instruction.js.map +1 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
- package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
- package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
- package/lib/client/triggers/TriggerManagerImpl.js +415 -0
- package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
- package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
- package/lib/client/watched/AbstractQueryProcessor.js +155 -0
- package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
- package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
- package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
- package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
- package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
- package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
- package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
- package/lib/client/watched/WatchedQuery.d.ts +9 -0
- package/lib/client/watched/WatchedQuery.js +12 -0
- package/lib/client/watched/WatchedQuery.js.map +1 -0
- package/lib/constants.d.ts +5 -0
- package/lib/constants.js +6 -0
- package/lib/constants.js.map +1 -0
- package/lib/db/ConnectionClosedError.d.ts +12 -0
- package/lib/db/ConnectionClosedError.js +23 -0
- package/lib/db/ConnectionClosedError.js.map +1 -0
- package/lib/db/crud/SyncProgress.d.ts +10 -0
- package/lib/db/crud/SyncProgress.js +33 -0
- package/lib/db/crud/SyncProgress.js.map +1 -0
- package/lib/db/crud/SyncStatus.d.ts +48 -0
- package/lib/db/crud/SyncStatus.js +178 -0
- package/lib/db/crud/SyncStatus.js.map +1 -0
- package/lib/db/openDatabase.d.ts +7 -0
- package/lib/db/openDatabase.js +22 -0
- package/lib/db/openDatabase.js.map +1 -0
- package/lib/index.d.ts +22 -0
- package/lib/index.js +22 -0
- package/lib/index.js.map +1 -0
- package/lib/utils/AbortOperation.d.ts +11 -0
- package/lib/utils/AbortOperation.js +21 -0
- package/lib/utils/AbortOperation.js.map +1 -0
- package/lib/utils/ControlledExecutor.d.ts +31 -0
- package/lib/utils/ControlledExecutor.js +54 -0
- package/lib/utils/ControlledExecutor.js.map +1 -0
- package/lib/utils/MetaBaseObserver.d.ts +11 -0
- package/lib/utils/MetaBaseObserver.js +51 -0
- package/lib/utils/MetaBaseObserver.js.map +1 -0
- package/lib/utils/async.d.ts +46 -0
- package/lib/utils/async.js +147 -0
- package/lib/utils/async.js.map +1 -0
- package/lib/utils/compatibility.d.ts +8 -0
- package/lib/utils/compatibility.js +9 -0
- package/lib/utils/compatibility.js.map +1 -0
- package/lib/utils/mutex.d.ts +42 -0
- package/lib/utils/mutex.js +150 -0
- package/lib/utils/mutex.js.map +1 -0
- package/lib/utils/parseQuery.d.ts +12 -0
- package/lib/utils/parseQuery.js +20 -0
- package/lib/utils/parseQuery.js.map +1 -0
- package/lib/utils/queue.d.ts +16 -0
- package/lib/utils/queue.js +42 -0
- package/lib/utils/queue.js.map +1 -0
- package/lib/utils/stream_transform.d.ts +41 -0
- package/lib/utils/stream_transform.js +211 -0
- package/lib/utils/stream_transform.js.map +1 -0
- package/lib/version.d.ts +1 -0
- package/lib/version.js +4 -0
- package/lib/version.js.map +1 -0
- package/package.json +65 -0
- package/src/client/BasePowerSyncDatabase.ts +853 -0
- package/src/client/ConnectionManager.ts +419 -0
- package/src/client/CustomQuery.ts +60 -0
- package/src/client/sync/bucket/BucketStorageAdapter.ts +51 -0
- package/src/client/sync/bucket/CrudEntry.ts +116 -0
- package/src/client/sync/bucket/SqliteBucketStorage.ts +213 -0
- package/src/client/sync/options.ts +24 -0
- package/src/client/sync/stream/AbstractRemote.ts +369 -0
- package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +795 -0
- package/src/client/sync/stream/WebSocketSupport.ts +259 -0
- package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
- package/src/client/sync/stream/core-instruction.ts +78 -0
- package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
- package/src/client/triggers/TriggerManagerImpl.ts +538 -0
- package/src/client/watched/AbstractQueryProcessor.ts +231 -0
- package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
- package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
- package/src/client/watched/WatchedQuery.ts +14 -0
- package/src/constants.ts +6 -0
- package/src/db/ConnectionClosedError.ts +25 -0
- package/src/db/crud/SyncProgress.ts +39 -0
- package/src/db/crud/SyncStatus.ts +234 -0
- package/src/db/openDatabase.ts +23 -0
- package/src/index.ts +24 -0
- package/src/utils/AbortOperation.ts +19 -0
- package/src/utils/ControlledExecutor.ts +78 -0
- package/src/utils/MetaBaseObserver.ts +65 -0
- package/src/utils/async.ts +185 -0
- package/src/utils/compatibility.ts +9 -0
- package/src/utils/mutex.ts +186 -0
- package/src/utils/parseQuery.ts +31 -0
- package/src/utils/queue.ts +48 -0
- package/src/utils/stream_transform.ts +260 -0
- package/src/version.ts +3 -0
|
@@ -0,0 +1,853 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ArrayQueryDefinition,
|
|
3
|
+
BasePowerSyncDatabaseOptions,
|
|
4
|
+
BatchedUpdateNotification,
|
|
5
|
+
CommonPowerSyncDatabase,
|
|
6
|
+
createConsoleLogger,
|
|
7
|
+
CrudBatch,
|
|
8
|
+
CrudEntry,
|
|
9
|
+
CrudTransaction,
|
|
10
|
+
DBAdapter,
|
|
11
|
+
DisconnectAndClearOptions,
|
|
12
|
+
LockContext,
|
|
13
|
+
LogLevels,
|
|
14
|
+
PowerSyncBackendConnector,
|
|
15
|
+
PowerSyncCloseOptions,
|
|
16
|
+
PowerSyncDBListener,
|
|
17
|
+
PowerSyncLogger,
|
|
18
|
+
Query,
|
|
19
|
+
QueryResult,
|
|
20
|
+
Schema,
|
|
21
|
+
SQLOnChangeOptions,
|
|
22
|
+
SQLWatchOptions,
|
|
23
|
+
SyncOptions,
|
|
24
|
+
SyncStatus,
|
|
25
|
+
SyncStream,
|
|
26
|
+
Transaction,
|
|
27
|
+
TriggerManager,
|
|
28
|
+
UploadQueueStats,
|
|
29
|
+
WatchCompatibleQuery,
|
|
30
|
+
WatchHandler,
|
|
31
|
+
WatchOnChangeEvent,
|
|
32
|
+
WatchOnChangeHandler,
|
|
33
|
+
BaseObserver,
|
|
34
|
+
SqliteRecord,
|
|
35
|
+
SyncStreamConnectionMethod
|
|
36
|
+
} from '@powersync/common';
|
|
37
|
+
import { BucketStorageAdapter, PSInternalTable } from './sync/bucket/BucketStorageAdapter.js';
|
|
38
|
+
import { SyncStatusSnapshot } from '../db/crud/SyncStatus.js';
|
|
39
|
+
import {
|
|
40
|
+
ConnectionManager,
|
|
41
|
+
CreateSyncImplementationOptions,
|
|
42
|
+
InternalSubscriptionAdapter
|
|
43
|
+
} from './ConnectionManager.js';
|
|
44
|
+
import { Mutex } from '../utils/mutex.js';
|
|
45
|
+
import { TriggerManagerConfig, TriggerManagerImpl } from './triggers/TriggerManagerImpl.js';
|
|
46
|
+
import { StreamingSyncImplementation } from './sync/stream/AbstractStreamingSyncImplementation.js';
|
|
47
|
+
import { CoreSyncStatus } from './sync/stream/core-instruction.js';
|
|
48
|
+
import { CrudEntryImpl, CrudEntryJSON } from './sync/bucket/CrudEntry.js';
|
|
49
|
+
import { OnChangeQueryProcessor } from './watched/OnChangeQueryProcessor.js';
|
|
50
|
+
import { EventQueue, throttleTrailing } from '../utils/async.js';
|
|
51
|
+
import { ControlledExecutor } from '../utils/ControlledExecutor.js';
|
|
52
|
+
import { DEFAULT_WATCH_THROTTLE_MS } from './watched/WatchedQuery.js';
|
|
53
|
+
import { CustomQuery } from './CustomQuery.js';
|
|
54
|
+
import { MEMORY_TRIGGER_CLAIM_MANAGER } from './triggers/MemoryTriggerClaimManager.js';
|
|
55
|
+
import { symbolAsyncIterator } from '../utils/compatibility.js';
|
|
56
|
+
|
|
57
|
+
const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
|
|
58
|
+
|
|
59
|
+
const DEFAULT_DISCONNECT_CLEAR_OPTIONS: DisconnectAndClearOptions = {
|
|
60
|
+
clearLocal: true
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @internal
|
|
65
|
+
*/
|
|
66
|
+
export const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions = {
|
|
67
|
+
disconnect: true
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const DEFAULT_CRUD_BATCH_LIMIT = 100;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Requesting nested or recursive locks can block the application in some circumstances.
|
|
74
|
+
* This default lock timeout will act as a failsafe to throw an error if a lock cannot
|
|
75
|
+
* be obtained.
|
|
76
|
+
*
|
|
77
|
+
* @internal
|
|
78
|
+
*/
|
|
79
|
+
export const DEFAULT_LOCK_TIMEOUT_MS = 120_000; // 2 mins
|
|
80
|
+
|
|
81
|
+
export abstract class BasePowerSyncDatabase<Options extends BasePowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions>
|
|
82
|
+
extends BaseObserver<PowerSyncDBListener>
|
|
83
|
+
implements CommonPowerSyncDatabase
|
|
84
|
+
{
|
|
85
|
+
closed: boolean;
|
|
86
|
+
ready: boolean;
|
|
87
|
+
|
|
88
|
+
currentStatus: SyncStatusSnapshot;
|
|
89
|
+
|
|
90
|
+
sdkVersion: string;
|
|
91
|
+
|
|
92
|
+
protected bucketStorageAdapter: BucketStorageAdapter;
|
|
93
|
+
protected _isReadyPromise: Promise<void>;
|
|
94
|
+
protected connectionManager: ConnectionManager;
|
|
95
|
+
private subscriptions: InternalSubscriptionAdapter;
|
|
96
|
+
|
|
97
|
+
get syncStreamImplementation() {
|
|
98
|
+
return this.connectionManager.syncStreamImplementation;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The connector used to connect to the PowerSync service.
|
|
103
|
+
*
|
|
104
|
+
* @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
|
|
105
|
+
*/
|
|
106
|
+
get connector() {
|
|
107
|
+
return this.connectionManager.connector;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The resolved connection options used to connect to the PowerSync service.
|
|
112
|
+
*
|
|
113
|
+
* @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
|
|
114
|
+
*/
|
|
115
|
+
get connectionOptions() {
|
|
116
|
+
return this.connectionManager.connectionOptions;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
protected _schema: Schema;
|
|
120
|
+
private _database: DBAdapter;
|
|
121
|
+
|
|
122
|
+
protected runExclusiveMutex: Mutex;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @experimental
|
|
126
|
+
* Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
|
|
127
|
+
*/
|
|
128
|
+
readonly triggers: TriggerManager;
|
|
129
|
+
protected triggersImpl: TriggerManagerImpl;
|
|
130
|
+
|
|
131
|
+
logger: PowerSyncLogger;
|
|
132
|
+
|
|
133
|
+
constructor(protected options: Options) {
|
|
134
|
+
super();
|
|
135
|
+
this.logger = options.logger ?? createConsoleLogger();
|
|
136
|
+
|
|
137
|
+
const { schema } = options;
|
|
138
|
+
|
|
139
|
+
if (typeof schema?.toJSON != 'function') {
|
|
140
|
+
throw new Error('The `schema` option should be provided and should be an instance of `Schema`.');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
this._database = this.openDBAdapter();
|
|
144
|
+
this.bucketStorageAdapter = this.generateBucketStorageAdapter();
|
|
145
|
+
this.closed = false;
|
|
146
|
+
this.currentStatus = new SyncStatusSnapshot(null, {});
|
|
147
|
+
this.options = { ...options };
|
|
148
|
+
this._schema = schema;
|
|
149
|
+
this.ready = false;
|
|
150
|
+
this.sdkVersion = '';
|
|
151
|
+
this.runExclusiveMutex = new Mutex();
|
|
152
|
+
|
|
153
|
+
// Start async init
|
|
154
|
+
this.subscriptions = {
|
|
155
|
+
firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
|
|
156
|
+
resolveOfflineSyncStatus: () => this.resolveOfflineSyncStatus(),
|
|
157
|
+
rustSubscriptionsCommand: async (payload) => {
|
|
158
|
+
await this.writeTransaction((tx) => {
|
|
159
|
+
return tx.execute('select powersync_control(?,?)', ['subscriptions', JSON.stringify(payload)]);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
this.connectionManager = new ConnectionManager({
|
|
164
|
+
createSyncImplementation: async (connector, options) => {
|
|
165
|
+
await this.waitForReady();
|
|
166
|
+
return this.runExclusive(async () => {
|
|
167
|
+
const sync = this.generateSyncStreamImplementation(connector, options);
|
|
168
|
+
const onDispose = sync.registerListener({
|
|
169
|
+
statusChanged: (snapshot) => {
|
|
170
|
+
this.currentStatus = snapshot;
|
|
171
|
+
this.iterateListeners((cb) => cb.statusChanged?.(snapshot));
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
await sync.waitForReady();
|
|
175
|
+
|
|
176
|
+
return {
|
|
177
|
+
sync,
|
|
178
|
+
onDispose
|
|
179
|
+
};
|
|
180
|
+
});
|
|
181
|
+
},
|
|
182
|
+
logger: this.logger,
|
|
183
|
+
defaultConnectionMethod: this.defaultConnectionMethod
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
this._isReadyPromise = this.initialize();
|
|
187
|
+
|
|
188
|
+
this.triggers = this.triggersImpl = new TriggerManagerImpl({
|
|
189
|
+
db: this,
|
|
190
|
+
schema: this.schema,
|
|
191
|
+
...this.generateTriggerManagerConfig()
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The default connection method to use on this platform.
|
|
197
|
+
*
|
|
198
|
+
* This defaults to `HTTP` on most SDKs. On React Native, it defaults to RSocket if a streaming HTTP client is
|
|
199
|
+
* unavailable.
|
|
200
|
+
*/
|
|
201
|
+
protected get defaultConnectionMethod(): SyncStreamConnectionMethod {
|
|
202
|
+
return SyncStreamConnectionMethod.HTTP;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
get schema() {
|
|
206
|
+
return this._schema;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The underlying database.
|
|
211
|
+
*
|
|
212
|
+
* For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.
|
|
213
|
+
*/
|
|
214
|
+
get database() {
|
|
215
|
+
return this._database;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Whether a connection to the PowerSync service is currently open.
|
|
220
|
+
*/
|
|
221
|
+
get connected() {
|
|
222
|
+
return this.currentStatus?.connected || false;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
get connecting() {
|
|
226
|
+
return this.currentStatus?.connecting || false;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Opens the DBAdapter given open options using a default open factory
|
|
231
|
+
*/
|
|
232
|
+
protected abstract openDBAdapter(): DBAdapter;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Generates a base configuration for {@link TriggerManagerImpl}.
|
|
236
|
+
* Implementations should override this if necessary.
|
|
237
|
+
*/
|
|
238
|
+
protected generateTriggerManagerConfig(): TriggerManagerConfig {
|
|
239
|
+
return {
|
|
240
|
+
claimManager: MEMORY_TRIGGER_CLAIM_MANAGER
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
protected abstract generateSyncStreamImplementation(
|
|
245
|
+
connector: PowerSyncBackendConnector,
|
|
246
|
+
options: CreateSyncImplementationOptions
|
|
247
|
+
): StreamingSyncImplementation;
|
|
248
|
+
|
|
249
|
+
protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
|
|
250
|
+
|
|
251
|
+
async waitForReady(): Promise<void> {
|
|
252
|
+
if (this.ready) {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
await this._isReadyPromise;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async waitForFirstSync(request?: AbortSignal | { signal?: AbortSignal; priority?: number }): Promise<void> {
|
|
260
|
+
const signal = request instanceof AbortSignal ? request : request?.signal;
|
|
261
|
+
const priority = request && 'priority' in request ? request.priority : undefined;
|
|
262
|
+
|
|
263
|
+
const statusMatches =
|
|
264
|
+
priority === undefined
|
|
265
|
+
? (status: SyncStatus) => status.hasSynced
|
|
266
|
+
: (status: SyncStatus) => status.statusForPriority(priority)?.hasSynced == true;
|
|
267
|
+
|
|
268
|
+
return this.waitForStatus(statusMatches, signal);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void> {
|
|
272
|
+
if (predicate(this.currentStatus)) {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return new Promise((resolve) => {
|
|
277
|
+
const dispose = this.registerListener({
|
|
278
|
+
statusChanged: (status) => {
|
|
279
|
+
if (predicate(status)) {
|
|
280
|
+
abort();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
function abort() {
|
|
286
|
+
dispose();
|
|
287
|
+
resolve();
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (signal?.aborted) {
|
|
291
|
+
abort();
|
|
292
|
+
} else {
|
|
293
|
+
signal?.addEventListener('abort', abort);
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Allows for extended implementations to execute custom initialization
|
|
300
|
+
* logic as part of the total init process
|
|
301
|
+
*/
|
|
302
|
+
protected abstract _initialize(): Promise<void>;
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Entry point for executing initialization logic.
|
|
306
|
+
* This is to be automatically executed in the constructor.
|
|
307
|
+
*/
|
|
308
|
+
protected async initialize() {
|
|
309
|
+
await this._initialize();
|
|
310
|
+
await this.bucketStorageAdapter.init();
|
|
311
|
+
await this.loadVersion();
|
|
312
|
+
await this.updateSchema(this.options.schema);
|
|
313
|
+
await this.resolveOfflineSyncStatus();
|
|
314
|
+
await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
|
|
315
|
+
await this.triggersImpl.cleanupResources();
|
|
316
|
+
this.ready = true;
|
|
317
|
+
this.iterateListeners((cb) => cb.initialized?.());
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
protected async loadVersion() {
|
|
321
|
+
try {
|
|
322
|
+
const { version } = await this.database.get<{ version: string }>('SELECT powersync_rs_version() as version');
|
|
323
|
+
this.sdkVersion = version;
|
|
324
|
+
} catch (e: any) {
|
|
325
|
+
throw new Error(`The powersync extension is not loaded correctly. Details: ${e.message}`);
|
|
326
|
+
}
|
|
327
|
+
let versionInts: number[];
|
|
328
|
+
try {
|
|
329
|
+
versionInts = this.sdkVersion!.split(/[.\/]/)
|
|
330
|
+
.slice(0, 3)
|
|
331
|
+
.map((n) => parseInt(n));
|
|
332
|
+
} catch (e: any) {
|
|
333
|
+
throw new Error(
|
|
334
|
+
`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}. Details: ${e.message}`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// Validate >=0.4.10 <1.0.0
|
|
339
|
+
if (versionInts[0] != 0 || versionInts[1] < 4 || (versionInts[1] == 4 && versionInts[2] < 10)) {
|
|
340
|
+
throw new Error(`Unsupported powersync extension version. Need >=0.4.10 <1.0.0, got: ${this.sdkVersion}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
protected async resolveOfflineSyncStatus() {
|
|
345
|
+
const result = await this.database.get<{ r: string }>('SELECT powersync_offline_sync_status() as r');
|
|
346
|
+
const parsed = JSON.parse(result.r) as CoreSyncStatus;
|
|
347
|
+
|
|
348
|
+
const updatedStatus = new SyncStatusSnapshot(parsed, this.currentStatus.jsState);
|
|
349
|
+
|
|
350
|
+
if (!updatedStatus.isEqual(this.currentStatus)) {
|
|
351
|
+
this.currentStatus = updatedStatus;
|
|
352
|
+
this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async updateSchema(schema: Schema) {
|
|
357
|
+
if (this.syncStreamImplementation) {
|
|
358
|
+
throw new Error('Cannot update schema while connected');
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* TODO
|
|
363
|
+
* Validations only show a warning for now.
|
|
364
|
+
* The next major release should throw an exception.
|
|
365
|
+
*/
|
|
366
|
+
try {
|
|
367
|
+
schema.validate();
|
|
368
|
+
} catch (ex) {
|
|
369
|
+
this.logger.log({
|
|
370
|
+
level: LogLevels.warn,
|
|
371
|
+
message: 'Schema validation failed. Unexpected behaviour could occur',
|
|
372
|
+
error: ex
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
this._schema = schema;
|
|
376
|
+
|
|
377
|
+
await this.database.writeTransaction((tx) =>
|
|
378
|
+
tx.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())])
|
|
379
|
+
);
|
|
380
|
+
await this.database.refreshSchema();
|
|
381
|
+
this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async init() {
|
|
385
|
+
return this.waitForReady();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Locking mechanism for exclusively running critical portions of connect/disconnect operations.
|
|
390
|
+
* Locking here is mostly only important on web for multiple tab scenarios.
|
|
391
|
+
*/
|
|
392
|
+
protected runExclusive<T>(callback: () => Promise<T>): Promise<T> {
|
|
393
|
+
return this.runExclusiveMutex.runExclusive(callback);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async connect(connector: PowerSyncBackendConnector, options?: SyncOptions) {
|
|
397
|
+
return this.connectionManager.connect(connector, options ?? {}, this.schema.toJSON());
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async disconnect() {
|
|
401
|
+
return this.connectionManager.disconnect();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
async disconnectAndClear(options = DEFAULT_DISCONNECT_CLEAR_OPTIONS) {
|
|
405
|
+
await this.disconnect();
|
|
406
|
+
await this.waitForReady();
|
|
407
|
+
|
|
408
|
+
const { clearLocal } = options;
|
|
409
|
+
|
|
410
|
+
await this.database.writeTransaction(async (tx) => {
|
|
411
|
+
await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
// The data has been deleted - reset the sync status
|
|
415
|
+
await this.resolveOfflineSyncStatus();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
syncStream(name: string, params?: Record<string, any>): SyncStream {
|
|
419
|
+
return this.connectionManager.stream(this.subscriptions, name, params ?? null);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async close(options: PowerSyncCloseOptions = DEFAULT_POWERSYNC_CLOSE_OPTIONS) {
|
|
423
|
+
await this.waitForReady();
|
|
424
|
+
|
|
425
|
+
if (this.closed) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
this.triggersImpl.dispose();
|
|
430
|
+
|
|
431
|
+
await this.iterateAsyncListeners(async (cb) => cb.closing?.());
|
|
432
|
+
|
|
433
|
+
const { disconnect } = options;
|
|
434
|
+
if (disconnect) {
|
|
435
|
+
await this.disconnect();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
await this.connectionManager.close();
|
|
439
|
+
await this.database.close();
|
|
440
|
+
this.closed = true;
|
|
441
|
+
await this.iterateAsyncListeners(async (cb) => cb.closed?.());
|
|
442
|
+
super.dispose();
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
async getUploadQueueStats(includeSize?: boolean): Promise<UploadQueueStats> {
|
|
446
|
+
return this.readTransaction(async (tx) => {
|
|
447
|
+
if (includeSize) {
|
|
448
|
+
const row = await tx.get<{ size: number; count: number }>(
|
|
449
|
+
`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${PSInternalTable.CRUD}`
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
return new UploadQueueStats(row.count ?? 0, row.size ?? 0);
|
|
453
|
+
} else {
|
|
454
|
+
const { count } = await tx.get<{ count: number }>(`SELECT count(*) as count FROM ${PSInternalTable.CRUD}`);
|
|
455
|
+
return new UploadQueueStats(count ?? 0);
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async getCrudBatch(limit: number = DEFAULT_CRUD_BATCH_LIMIT): Promise<CrudBatch | null> {
|
|
461
|
+
const result = await this.getAll<CrudEntryJSON>(
|
|
462
|
+
`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} ORDER BY id ASC LIMIT ?`,
|
|
463
|
+
[limit + 1]
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
const all: CrudEntry[] = result.map((row) => CrudEntryImpl.fromRow(row)) ?? [];
|
|
467
|
+
|
|
468
|
+
let haveMore = false;
|
|
469
|
+
if (all.length > limit) {
|
|
470
|
+
all.pop();
|
|
471
|
+
haveMore = true;
|
|
472
|
+
}
|
|
473
|
+
if (all.length == 0) {
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const last = all[all.length - 1];
|
|
478
|
+
return new CrudBatch(all, haveMore, async (writeCheckpoint?: string) =>
|
|
479
|
+
this.handleCrudCheckpoint(last.clientId, writeCheckpoint)
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
async getNextCrudTransaction(): Promise<CrudTransaction | null> {
|
|
484
|
+
const iterator = this.getCrudTransactions()[symbolAsyncIterator]();
|
|
485
|
+
return (await iterator.next()).value;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
getCrudTransactions(): AsyncIterable<CrudTransaction, null> {
|
|
489
|
+
return {
|
|
490
|
+
[symbolAsyncIterator]: () => {
|
|
491
|
+
let lastCrudItemId = -1;
|
|
492
|
+
const sql = `
|
|
493
|
+
WITH RECURSIVE crud_entries AS (
|
|
494
|
+
SELECT id, tx_id, data FROM ps_crud WHERE id = (SELECT min(id) FROM ps_crud WHERE id > ?)
|
|
495
|
+
UNION ALL
|
|
496
|
+
SELECT ps_crud.id, ps_crud.tx_id, ps_crud.data FROM ps_crud
|
|
497
|
+
INNER JOIN crud_entries ON crud_entries.id + 1 = rowid
|
|
498
|
+
WHERE crud_entries.tx_id = ps_crud.tx_id
|
|
499
|
+
)
|
|
500
|
+
SELECT * FROM crud_entries;
|
|
501
|
+
`;
|
|
502
|
+
|
|
503
|
+
return {
|
|
504
|
+
next: async () => {
|
|
505
|
+
const nextTransaction = await this.database.getAll<CrudEntryJSON>(sql, [lastCrudItemId]);
|
|
506
|
+
if (nextTransaction.length == 0) {
|
|
507
|
+
return { done: true, value: null };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const items = nextTransaction.map((row) => CrudEntryImpl.fromRow(row));
|
|
511
|
+
const last = items[items.length - 1];
|
|
512
|
+
const txId = last.transactionId;
|
|
513
|
+
lastCrudItemId = last.clientId;
|
|
514
|
+
|
|
515
|
+
return {
|
|
516
|
+
done: false,
|
|
517
|
+
value: new CrudTransaction(
|
|
518
|
+
items,
|
|
519
|
+
async (writeCheckpoint?: string) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint),
|
|
520
|
+
txId
|
|
521
|
+
)
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
async getClientId(): Promise<string> {
|
|
530
|
+
return this.bucketStorageAdapter.getClientId();
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
private async handleCrudCheckpoint(lastClientId: number, writeCheckpoint?: string) {
|
|
534
|
+
return this.writeTransaction(async (tx) => {
|
|
535
|
+
await tx.execute(`DELETE FROM ${PSInternalTable.CRUD} WHERE id <= ?`, [lastClientId]);
|
|
536
|
+
if (writeCheckpoint) {
|
|
537
|
+
const check = await tx.execute(`SELECT 1 FROM ${PSInternalTable.CRUD} LIMIT 1`);
|
|
538
|
+
if (!check.rows?.length) {
|
|
539
|
+
await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [
|
|
540
|
+
writeCheckpoint
|
|
541
|
+
]);
|
|
542
|
+
}
|
|
543
|
+
} else {
|
|
544
|
+
await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [
|
|
545
|
+
this.bucketStorageAdapter.getMaxOpId()
|
|
546
|
+
]);
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async execute<T = SqliteRecord>(sql: string, parameters?: any[]) {
|
|
552
|
+
return this.writeLock((tx) => tx.execute<T>(sql, parameters));
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async executeRaw(sql: string, parameters?: any[]) {
|
|
556
|
+
await this.waitForReady();
|
|
557
|
+
return this.database.executeRaw(sql, parameters);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async executeBatch(sql: string, parameters?: any[][]) {
|
|
561
|
+
await this.waitForReady();
|
|
562
|
+
return this.database.executeBatch(sql, parameters);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
|
|
566
|
+
await this.waitForReady();
|
|
567
|
+
return this.database.getAll(sql, parameters);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
|
|
571
|
+
await this.waitForReady();
|
|
572
|
+
return this.database.getOptional(sql, parameters);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
async get<T>(sql: string, parameters?: any[]): Promise<T> {
|
|
576
|
+
await this.waitForReady();
|
|
577
|
+
return this.database.get(sql, parameters);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async readLock<T>(callback: (db: LockContext) => Promise<T>) {
|
|
581
|
+
await this.waitForReady();
|
|
582
|
+
return this.database.readLock(callback);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async writeLock<T>(callback: (db: LockContext) => Promise<T>) {
|
|
586
|
+
await this.waitForReady();
|
|
587
|
+
return this.database.writeLock(callback);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async readTransaction<T>(
|
|
591
|
+
callback: (tx: Transaction) => Promise<T>,
|
|
592
|
+
lockTimeout: number = DEFAULT_LOCK_TIMEOUT_MS
|
|
593
|
+
): Promise<T> {
|
|
594
|
+
await this.waitForReady();
|
|
595
|
+
return this.database.readTransaction(
|
|
596
|
+
async (tx) => {
|
|
597
|
+
const res = await callback(tx);
|
|
598
|
+
await tx.rollback();
|
|
599
|
+
return res;
|
|
600
|
+
},
|
|
601
|
+
{ timeoutMs: lockTimeout }
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async writeTransaction<T>(
|
|
606
|
+
callback: (tx: Transaction) => Promise<T>,
|
|
607
|
+
lockTimeout: number = DEFAULT_LOCK_TIMEOUT_MS
|
|
608
|
+
): Promise<T> {
|
|
609
|
+
await this.waitForReady();
|
|
610
|
+
return this.database.writeTransaction(
|
|
611
|
+
async (tx) => {
|
|
612
|
+
const res = await callback(tx);
|
|
613
|
+
await tx.commit();
|
|
614
|
+
return res;
|
|
615
|
+
},
|
|
616
|
+
{ timeoutMs: lockTimeout }
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
watch(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
|
|
621
|
+
|
|
622
|
+
watch(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
|
|
623
|
+
|
|
624
|
+
watch(
|
|
625
|
+
sql: string,
|
|
626
|
+
parameters?: any[],
|
|
627
|
+
handlerOrOptions?: WatchHandler | SQLWatchOptions,
|
|
628
|
+
maybeOptions?: SQLWatchOptions
|
|
629
|
+
): void | AsyncIterable<QueryResult> {
|
|
630
|
+
if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onResult' in handlerOrOptions) {
|
|
631
|
+
const handler = handlerOrOptions as WatchHandler;
|
|
632
|
+
const options = maybeOptions;
|
|
633
|
+
|
|
634
|
+
return this.watchWithCallback(sql, parameters, handler, options);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const options = handlerOrOptions as SQLWatchOptions | undefined;
|
|
638
|
+
return this.watchWithAsyncGenerator(sql, parameters, options);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
query<RowType>(query: ArrayQueryDefinition<RowType>): Query<RowType> {
|
|
642
|
+
const { sql, parameters = [], mapper } = query;
|
|
643
|
+
const compatibleQuery: WatchCompatibleQuery<RowType[]> = {
|
|
644
|
+
compile: () => ({
|
|
645
|
+
sql,
|
|
646
|
+
parameters
|
|
647
|
+
}),
|
|
648
|
+
execute: async ({ sql, parameters }) => {
|
|
649
|
+
const result = await this.getAll<Record<string, any>>(sql, parameters);
|
|
650
|
+
return mapper ? result.map(mapper) : (result as RowType[]);
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
return this.customQuery(compatibleQuery);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
customQuery<RowType>(query: WatchCompatibleQuery<RowType[]>): Query<RowType> {
|
|
657
|
+
return new CustomQuery({
|
|
658
|
+
db: this,
|
|
659
|
+
query
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void {
|
|
664
|
+
const {
|
|
665
|
+
onResult,
|
|
666
|
+
onError = (e: Error) => this.logger.log({ level: LogLevels.error, message: 'Error in watch', error: e })
|
|
667
|
+
} = handler ?? {};
|
|
668
|
+
if (!onResult) {
|
|
669
|
+
throw new Error('onResult is required');
|
|
670
|
+
}
|
|
671
|
+
const { comparator } = options ?? {};
|
|
672
|
+
|
|
673
|
+
// This API yields a QueryResult type.
|
|
674
|
+
// This is not a standard Array result, which makes it incompatible with the .query API.
|
|
675
|
+
const watchedQuery = new OnChangeQueryProcessor({
|
|
676
|
+
db: this,
|
|
677
|
+
comparator,
|
|
678
|
+
placeholderData: null as unknown as QueryResult, // FIXME
|
|
679
|
+
watchOptions: {
|
|
680
|
+
query: {
|
|
681
|
+
compile: () => ({
|
|
682
|
+
sql: sql,
|
|
683
|
+
parameters: parameters ?? []
|
|
684
|
+
}),
|
|
685
|
+
execute: () => this.executeReadOnly<SqliteRecord>(sql, parameters)
|
|
686
|
+
},
|
|
687
|
+
reportFetching: false,
|
|
688
|
+
throttleMs: options?.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS,
|
|
689
|
+
triggerOnTables: options?.tables
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
const dispose = watchedQuery.registerListener({
|
|
694
|
+
onData: (data) => {
|
|
695
|
+
if (!data) {
|
|
696
|
+
// This should not happen. We only use null for the initial data.
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
onResult(data);
|
|
700
|
+
},
|
|
701
|
+
onError: (error) => {
|
|
702
|
+
onError(error);
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
options?.signal?.addEventListener('abort', () => {
|
|
707
|
+
dispose();
|
|
708
|
+
watchedQuery.close();
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult> {
|
|
713
|
+
return EventQueue.queueBasedAsyncIterable((queue, abort) => {
|
|
714
|
+
const handler: WatchHandler = {
|
|
715
|
+
onResult: (result) => {
|
|
716
|
+
queue.notify(result);
|
|
717
|
+
},
|
|
718
|
+
onError: (error) => {
|
|
719
|
+
queue.notifyError(error);
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
|
|
723
|
+
this.watchWithCallback(sql, parameters, handler, { ...options, signal: abort });
|
|
724
|
+
}, options?.signal);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
async resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]> {
|
|
728
|
+
const resolvedTables = options?.tables ? [...options.tables] : [];
|
|
729
|
+
if (!options?.tables) {
|
|
730
|
+
const explained = await this.getAll<{ opcode: string; p3: number; p2: number }>(`EXPLAIN ${sql}`, parameters);
|
|
731
|
+
const rootPages = explained
|
|
732
|
+
.filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')
|
|
733
|
+
.map((row) => row.p2);
|
|
734
|
+
const tables = await this.getAll<{ tbl_name: string }>(
|
|
735
|
+
`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`,
|
|
736
|
+
[JSON.stringify(rootPages)]
|
|
737
|
+
);
|
|
738
|
+
for (const table of tables) {
|
|
739
|
+
resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
return resolvedTables;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
onChange(options?: SQLOnChangeOptions): AsyncIterable<WatchOnChangeEvent>;
|
|
747
|
+
onChange(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
|
|
748
|
+
|
|
749
|
+
onChange(
|
|
750
|
+
handlerOrOptions?: WatchOnChangeHandler | SQLOnChangeOptions,
|
|
751
|
+
maybeOptions?: SQLOnChangeOptions
|
|
752
|
+
): (() => void) | AsyncIterable<WatchOnChangeEvent> {
|
|
753
|
+
if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onChange' in handlerOrOptions) {
|
|
754
|
+
const handler = handlerOrOptions as WatchOnChangeHandler;
|
|
755
|
+
const options = maybeOptions;
|
|
756
|
+
|
|
757
|
+
return this.onChangeWithCallback(handler, options);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
const options = handlerOrOptions as SQLWatchOptions | undefined;
|
|
761
|
+
return this.onChangeWithAsyncGenerator(options);
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void {
|
|
765
|
+
const { onChange } = handler ?? {};
|
|
766
|
+
if (!onChange) {
|
|
767
|
+
throw new Error('onChange is required');
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const resolvedOptions = options ?? {};
|
|
771
|
+
const watchedTables = new Set<string>(
|
|
772
|
+
(resolvedOptions?.tables ?? []).flatMap((table) => [table, `ps_data__${table}`, `ps_data_local__${table}`])
|
|
773
|
+
);
|
|
774
|
+
|
|
775
|
+
const changedTables = new Set<string>();
|
|
776
|
+
const throttleMs = resolvedOptions.throttleMs ?? DEFAULT_WATCH_THROTTLE_MS;
|
|
777
|
+
|
|
778
|
+
const executor = new ControlledExecutor(onChange);
|
|
779
|
+
|
|
780
|
+
const flushTableUpdates = throttleTrailing(
|
|
781
|
+
() =>
|
|
782
|
+
this.handleTableChanges(changedTables, watchedTables, (intersection) => {
|
|
783
|
+
if (resolvedOptions?.signal?.aborted) return;
|
|
784
|
+
executor.schedule({ changedTables: intersection });
|
|
785
|
+
}),
|
|
786
|
+
throttleMs
|
|
787
|
+
);
|
|
788
|
+
|
|
789
|
+
if (options?.triggerImmediate) {
|
|
790
|
+
executor.schedule({ changedTables: [] });
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const dispose = this.database.registerListener({
|
|
794
|
+
tablesUpdated: async (update) => {
|
|
795
|
+
this.processTableUpdates(update, changedTables);
|
|
796
|
+
flushTableUpdates();
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
|
|
800
|
+
resolvedOptions.signal?.addEventListener('abort', () => {
|
|
801
|
+
executor.dispose();
|
|
802
|
+
dispose();
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
return () => dispose();
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// Note: do not declare this as `async *onChange` as it will not work in React Native.
|
|
809
|
+
onChangeWithAsyncGenerator(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent> {
|
|
810
|
+
return EventQueue.queueBasedAsyncIterable((queue, abort) => {
|
|
811
|
+
this.onChangeWithCallback(
|
|
812
|
+
{
|
|
813
|
+
onChange: (event): void => {
|
|
814
|
+
queue.notify(event);
|
|
815
|
+
}
|
|
816
|
+
},
|
|
817
|
+
{ ...options, signal: abort }
|
|
818
|
+
);
|
|
819
|
+
|
|
820
|
+
// Note: We don't have to track the dispose function returned by onChangeWithCallback, it cleans up
|
|
821
|
+
// after the abort signal completes.
|
|
822
|
+
}, options?.signal);
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
createMutex() {
|
|
826
|
+
return new Mutex();
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
private handleTableChanges(
|
|
830
|
+
changedTables: Set<string>,
|
|
831
|
+
watchedTables: Set<string>,
|
|
832
|
+
onDetectedChanges: (changedTables: string[]) => void
|
|
833
|
+
): void {
|
|
834
|
+
if (changedTables.size > 0) {
|
|
835
|
+
const intersection = Array.from(changedTables.values()).filter((change) => watchedTables.has(change));
|
|
836
|
+
if (intersection.length) {
|
|
837
|
+
onDetectedChanges(intersection);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
changedTables.clear();
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
private processTableUpdates({ tables }: BatchedUpdateNotification, changedTables: Set<string>): void {
|
|
844
|
+
for (const table of tables) {
|
|
845
|
+
changedTables.add(table);
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
private async executeReadOnly<T>(sql: string, params?: any[]) {
|
|
850
|
+
await this.waitForReady();
|
|
851
|
+
return this.database.readLock((tx) => tx.execute<T>(sql, params));
|
|
852
|
+
}
|
|
853
|
+
}
|