-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathAbstractPowerSyncDatabase.ts
1143 lines (1015 loc) · 38 KB
/
AbstractPowerSyncDatabase.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Mutex } from 'async-mutex';
import { EventIterator } from 'event-iterator';
import Logger, { ILogger } from 'js-logger';
import {
BatchedUpdateNotification,
DBAdapter,
QueryResult,
Transaction,
UpdateNotification,
isBatchedUpdateNotification
} from '../db/DBAdapter.js';
import { SyncPriorityStatus, SyncStatus } from '../db/crud/SyncStatus.js';
import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
import { Schema } from '../db/schema/Schema.js';
import { BaseObserver } from '../utils/BaseObserver.js';
import { ControlledExecutor } from '../utils/ControlledExecutor.js';
import { mutexRunExclusive } from '../utils/mutex.js';
import { throttleTrailing } from '../utils/async.js';
import { SQLOpenFactory, SQLOpenOptions, isDBAdapter, isSQLOpenFactory, isSQLOpenOptions } from './SQLOpenFactory.js';
import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
import { runOnSchemaChange } from './runOnSchemaChange.js';
import { BucketStorageAdapter, PSInternalTable } from './sync/bucket/BucketStorageAdapter.js';
import { CrudBatch } from './sync/bucket/CrudBatch.js';
import { CrudEntry, CrudEntryJSON } from './sync/bucket/CrudEntry.js';
import { CrudTransaction } from './sync/bucket/CrudTransaction.js';
import {
DEFAULT_CRUD_UPLOAD_THROTTLE_MS,
DEFAULT_RETRY_DELAY_MS,
StreamingSyncImplementation,
StreamingSyncImplementationListener,
type AdditionalConnectionOptions,
type PowerSyncConnectionOptions,
type RequiredAdditionalConnectionOptions
} from './sync/stream/AbstractStreamingSyncImplementation.js';
export interface DisconnectAndClearOptions {
/** When set to false, data in local-only tables is preserved. */
clearLocal?: boolean;
}
export interface BasePowerSyncDatabaseOptions extends AdditionalConnectionOptions {
/** Schema used for the local database. */
schema: Schema;
/**
* @deprecated Use {@link retryDelayMs} instead as this will be removed in future releases.
*/
retryDelay?: number;
logger?: ILogger;
}
export interface PowerSyncDatabaseOptions extends BasePowerSyncDatabaseOptions {
/**
* Source for a SQLite database connection.
* This can be either:
* - A {@link DBAdapter} if providing an instantiated SQLite connection
* - A {@link SQLOpenFactory} which will be used to open a SQLite connection
* - {@link SQLOpenOptions} for opening a SQLite connection with a default {@link SQLOpenFactory}
*/
database: DBAdapter | SQLOpenFactory | SQLOpenOptions;
}
export interface PowerSyncDatabaseOptionsWithDBAdapter extends BasePowerSyncDatabaseOptions {
database: DBAdapter;
}
export interface PowerSyncDatabaseOptionsWithOpenFactory extends BasePowerSyncDatabaseOptions {
database: SQLOpenFactory;
}
export interface PowerSyncDatabaseOptionsWithSettings extends BasePowerSyncDatabaseOptions {
database: SQLOpenOptions;
}
export interface SQLWatchOptions {
signal?: AbortSignal;
tables?: string[];
/** The minimum interval between queries. */
throttleMs?: number;
/**
* @deprecated All tables specified in {@link tables} will be watched, including PowerSync tables with prefixes.
*
* Allows for watching any SQL table
* by not removing PowerSync table name prefixes
*/
rawTableNames?: boolean;
}
export interface WatchOnChangeEvent {
changedTables: string[];
}
export interface WatchHandler {
onResult: (results: QueryResult) => void;
onError?: (error: Error) => void;
}
export interface WatchOnChangeHandler {
onChange: (event: WatchOnChangeEvent) => Promise<void> | void;
onError?: (error: Error) => void;
}
export interface PowerSyncDBListener extends StreamingSyncImplementationListener {
initialized: () => void;
schemaChanged: (schema: Schema) => void;
}
export interface PowerSyncCloseOptions {
/**
* Disconnect the sync stream client if connected.
* This is usually true, but can be false for Web when using
* multiple tabs and a shared sync provider.
*/
disconnect?: boolean;
}
const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
const DEFAULT_DISCONNECT_CLEAR_OPTIONS: DisconnectAndClearOptions = {
clearLocal: true
};
export const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions = {
disconnect: true
};
export const DEFAULT_WATCH_THROTTLE_MS = 30;
export const DEFAULT_POWERSYNC_DB_OPTIONS = {
retryDelayMs: 5000,
logger: Logger.get('PowerSyncDatabase'),
crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
};
export const DEFAULT_CRUD_BATCH_LIMIT = 100;
/**
* Requesting nested or recursive locks can block the application in some circumstances.
* This default lock timeout will act as a failsafe to throw an error if a lock cannot
* be obtained.
*/
export const DEFAULT_LOCK_TIMEOUT_MS = 120_000; // 2 mins
/**
* Tests if the input is a {@link PowerSyncDatabaseOptionsWithSettings}
* @internal
*/
export const isPowerSyncDatabaseOptionsWithSettings = (test: any): test is PowerSyncDatabaseOptionsWithSettings => {
return typeof test == 'object' && isSQLOpenOptions(test.database);
};
/**
* The priority used by the core extension to indicate that a full sync was completed.
*/
const FULL_SYNC_PRIORITY = 2147483647;
export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDBListener> {
/**
* Transactions should be queued in the DBAdapter, but we also want to prevent
* calls to `.execute` while an async transaction is running.
*/
protected static transactionMutex: Mutex = new Mutex();
/**
* Returns true if the connection is closed.
*/
closed: boolean;
ready: boolean;
/**
* Current connection status.
*/
currentStatus: SyncStatus;
syncStreamImplementation?: StreamingSyncImplementation;
sdkVersion: string;
protected bucketStorageAdapter: BucketStorageAdapter;
private syncStatusListenerDisposer?: () => void;
protected _isReadyPromise: Promise<void>;
protected _schema: Schema;
private _database: DBAdapter;
constructor(options: PowerSyncDatabaseOptionsWithDBAdapter);
constructor(options: PowerSyncDatabaseOptionsWithOpenFactory);
constructor(options: PowerSyncDatabaseOptionsWithSettings);
constructor(options: PowerSyncDatabaseOptions); // Note this is important for extending this class and maintaining API compatibility
constructor(protected options: PowerSyncDatabaseOptions) {
super();
const { database, schema } = options;
if (typeof schema?.toJSON != 'function') {
throw new Error('The `schema` option should be provided and should be an instance of `Schema`.');
}
if (isDBAdapter(database)) {
this._database = database;
} else if (isSQLOpenFactory(database)) {
this._database = database.openDB();
} else if (isPowerSyncDatabaseOptionsWithSettings(options)) {
this._database = this.openDBAdapter(options);
} else {
throw new Error('The provided `database` option is invalid.');
}
this.bucketStorageAdapter = this.generateBucketStorageAdapter();
this.closed = false;
this.currentStatus = new SyncStatus({});
this.options = { ...DEFAULT_POWERSYNC_DB_OPTIONS, ...options };
this._schema = schema;
this.ready = false;
this.sdkVersion = '';
// Start async init
this._isReadyPromise = this.initialize();
}
/**
* Schema used for the local database.
*/
get schema() {
return this._schema;
}
/**
* The underlying database.
*
* For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.
*/
get database() {
return this._database;
}
/**
* Whether a connection to the PowerSync service is currently open.
*/
get connected() {
return this.currentStatus?.connected || false;
}
get connecting() {
return this.currentStatus?.connecting || false;
}
/**
* Opens the DBAdapter given open options using a default open factory
*/
protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
protected abstract generateSyncStreamImplementation(
connector: PowerSyncBackendConnector,
options: RequiredAdditionalConnectionOptions
): StreamingSyncImplementation;
protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
/**
* @returns A promise which will resolve once initialization is completed.
*/
async waitForReady(): Promise<void> {
if (this.ready) {
return;
}
await this._isReadyPromise;
}
/**
* Wait for the first sync operation to complete.
*
* @param request Either an abort signal (after which the promise will complete regardless of
* whether a full sync was completed) or an object providing an abort signal and a priority target.
* When a priority target is set, the promise may complete when all buckets with the given (or higher)
* priorities have been synchronized. This can be earlier than a complete sync.
* @returns A promise which will resolve once the first full sync has completed.
*/
async waitForFirstSync(request?: AbortSignal | { signal?: AbortSignal; priority?: number }): Promise<void> {
const signal = request instanceof AbortSignal ? request : request?.signal;
const priority = request && 'priority' in request ? request.priority : undefined;
const statusMatches =
priority === undefined
? (status: SyncStatus) => status.hasSynced
: (status: SyncStatus) => status.statusForPriority(priority).hasSynced;
if (statusMatches(this.currentStatus)) {
return;
}
return new Promise((resolve) => {
const dispose = this.registerListener({
statusChanged: (status) => {
if (statusMatches(status)) {
dispose();
resolve();
}
}
});
signal?.addEventListener('abort', () => {
dispose();
resolve();
});
});
}
/**
* Allows for extended implementations to execute custom initialization
* logic as part of the total init process
*/
abstract _initialize(): Promise<void>;
/**
* Entry point for executing initialization logic.
* This is to be automatically executed in the constructor.
*/
protected async initialize() {
await this._initialize();
await this.bucketStorageAdapter.init();
await this._loadVersion();
await this.updateSchema(this.options.schema);
await this.updateHasSynced();
await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
this.ready = true;
this.iterateListeners((cb) => cb.initialized?.());
}
private async _loadVersion() {
try {
const { version } = await this.database.get<{ version: string }>('SELECT powersync_rs_version() as version');
this.sdkVersion = version;
} catch (e) {
throw new Error(`The powersync extension is not loaded correctly. Details: ${e.message}`);
}
let versionInts: number[];
try {
versionInts = this.sdkVersion!.split(/[.\/]/)
.slice(0, 3)
.map((n) => parseInt(n));
} catch (e) {
throw new Error(
`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}. Details: ${e.message}`
);
}
// Validate >=0.3.11 <1.0.0
if (versionInts[0] != 0 || versionInts[1] < 3 || (versionInts[1] == 3 && versionInts[2] < 11)) {
throw new Error(`Unsupported powersync extension version. Need >=0.3.11 <1.0.0, got: ${this.sdkVersion}`);
}
}
protected async updateHasSynced() {
const result = await this.database.getAll<{ priority: number; last_synced_at: string }>(
'SELECT priority, last_synced_at FROM ps_sync_state ORDER BY priority DESC'
);
let lastCompleteSync: Date | undefined;
const priorityStatusEntries: SyncPriorityStatus[] = [];
for (const { priority, last_synced_at } of result) {
const parsedDate = new Date(last_synced_at + 'Z');
if (priority == FULL_SYNC_PRIORITY) {
// This lowest-possible priority represents a complete sync.
lastCompleteSync = parsedDate;
} else {
priorityStatusEntries.push({ priority, hasSynced: true, lastSyncedAt: parsedDate });
}
}
const hasSynced = lastCompleteSync != null;
const updatedStatus = new SyncStatus({
...this.currentStatus.toJSON(),
hasSynced,
priorityStatusEntries,
lastSyncedAt: lastCompleteSync
});
if (!updatedStatus.isEqual(this.currentStatus)) {
this.currentStatus = updatedStatus;
this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));
}
}
/**
* Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
*
* Cannot be used while connected - this should only be called before {@link AbstractPowerSyncDatabase.connect}.
*/
async updateSchema(schema: Schema) {
if (this.syncStreamImplementation) {
throw new Error('Cannot update schema while connected');
}
/**
* TODO
* Validations only show a warning for now.
* The next major release should throw an exception.
*/
try {
schema.validate();
} catch (ex) {
this.options.logger?.warn('Schema validation failed. Unexpected behaviour could occur', ex);
}
this._schema = schema;
await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
await this.database.refreshSchema();
this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
}
/**
* Wait for initialization to complete.
* While initializing is automatic, this helps to catch and report initialization errors.
*/
async init() {
return this.waitForReady();
}
// Use the options passed in during connect, or fallback to the options set during database creation or fallback to the default options
resolvedConnectionOptions(options?: PowerSyncConnectionOptions): RequiredAdditionalConnectionOptions {
return {
...options,
retryDelayMs:
options?.retryDelayMs ?? this.options.retryDelayMs ?? this.options.retryDelay ?? DEFAULT_RETRY_DELAY_MS,
crudUploadThrottleMs:
options?.crudUploadThrottleMs ?? this.options.crudUploadThrottleMs ?? DEFAULT_CRUD_UPLOAD_THROTTLE_MS
};
}
/**
* Connects to stream of events from the PowerSync instance.
*/
async connect(connector: PowerSyncBackendConnector, options?: PowerSyncConnectionOptions) {
await this.waitForReady();
// close connection if one is open
await this.disconnect();
if (this.closed) {
throw new Error('Cannot connect using a closed client');
}
const resolvedConnectOptions = this.resolvedConnectionOptions(options);
this.syncStreamImplementation = this.generateSyncStreamImplementation(connector, resolvedConnectOptions);
this.syncStatusListenerDisposer = this.syncStreamImplementation.registerListener({
statusChanged: (status) => {
this.currentStatus = new SyncStatus({
...status.toJSON(),
hasSynced: this.currentStatus?.hasSynced || !!status.lastSyncedAt
});
this.iterateListeners((cb) => cb.statusChanged?.(this.currentStatus));
}
});
await this.syncStreamImplementation.waitForReady();
this.syncStreamImplementation.triggerCrudUpload();
await this.syncStreamImplementation.connect(options);
}
/**
* Close the sync connection.
*
* Use {@link connect} to connect again.
*/
async disconnect() {
await this.waitForReady();
await this.syncStreamImplementation?.disconnect();
this.syncStatusListenerDisposer?.();
await this.syncStreamImplementation?.dispose();
this.syncStreamImplementation = undefined;
}
/**
* Disconnect and clear the database.
* Use this when logging out.
* The database can still be queried after this is called, but the tables
* would be empty.
*
* To preserve data in local-only tables, set clearLocal to false.
*/
async disconnectAndClear(options = DEFAULT_DISCONNECT_CLEAR_OPTIONS) {
await this.disconnect();
await this.waitForReady();
const { clearLocal } = options;
// TODO DB name, verify this is necessary with extension
await this.database.writeTransaction(async (tx) => {
await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
});
// The data has been deleted - reset the sync status
this.currentStatus = new SyncStatus({});
this.iterateListeners((l) => l.statusChanged?.(this.currentStatus));
}
/**
* Close the database, releasing resources.
*
* Also disconnects any active connection.
*
* Once close is called, this connection cannot be used again - a new one
* must be constructed.
*/
async close(options: PowerSyncCloseOptions = DEFAULT_POWERSYNC_CLOSE_OPTIONS) {
await this.waitForReady();
if (this.closed) {
return;
}
const { disconnect } = options;
if (disconnect) {
await this.disconnect();
}
await this.syncStreamImplementation?.dispose();
await this.database.close();
this.closed = true;
}
/**
* Get upload queue size estimate and count.
*/
async getUploadQueueStats(includeSize?: boolean): Promise<UploadQueueStats> {
return this.readTransaction(async (tx) => {
if (includeSize) {
const result = await tx.execute(
`SELECT SUM(cast(data as blob) + 20) as size, count(*) as count FROM ${PSInternalTable.CRUD}`
);
const row = result.rows!.item(0);
return new UploadQueueStats(row?.count ?? 0, row?.size ?? 0);
} else {
const result = await tx.execute(`SELECT count(*) as count FROM ${PSInternalTable.CRUD}`);
const row = result.rows!.item(0);
return new UploadQueueStats(row?.count ?? 0);
}
});
}
/**
* Get a batch of CRUD data to upload.
*
* Returns null if there is no data to upload.
*
* Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
*
* Once the data have been successfully uploaded, call {@link CrudBatch.complete} before
* requesting the next batch.
*
* Use {@link limit} to specify the maximum number of updates to return in a single
* batch.
*
* This method does include transaction ids in the result, but does not group
* data by transaction. One batch may contain data from multiple transactions,
* and a single transaction may be split over multiple batches.
*
* @param limit Maximum number of CRUD entries to include in the batch
* @returns A batch of CRUD operations to upload, or null if there are none
*/
async getCrudBatch(limit: number = DEFAULT_CRUD_BATCH_LIMIT): Promise<CrudBatch | null> {
const result = await this.getAll<CrudEntryJSON>(
`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} ORDER BY id ASC LIMIT ?`,
[limit + 1]
);
const all: CrudEntry[] = result.map((row) => CrudEntry.fromRow(row)) ?? [];
let haveMore = false;
if (all.length > limit) {
all.pop();
haveMore = true;
}
if (all.length == 0) {
return null;
}
const last = all[all.length - 1];
return new CrudBatch(all, haveMore, async (writeCheckpoint?: string) =>
this.handleCrudCheckpoint(last.clientId, writeCheckpoint)
);
}
/**
* Get the next recorded transaction to upload.
*
* Returns null if there is no data to upload.
*
* Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
*
* Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before
* requesting the next transaction.
*
* Unlike {@link getCrudBatch}, this only returns data from a single transaction at a time.
* All data for the transaction is loaded into memory.
*
* @returns A transaction of CRUD operations to upload, or null if there are none
*/
async getNextCrudTransaction(): Promise<CrudTransaction | null> {
return await this.readTransaction(async (tx) => {
const first = await tx.getOptional<CrudEntryJSON>(
`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} ORDER BY id ASC LIMIT 1`
);
if (!first) {
return null;
}
const txId = first.tx_id;
let all: CrudEntry[];
if (!txId) {
all = [CrudEntry.fromRow(first)];
} else {
const result = await tx.getAll<CrudEntryJSON>(
`SELECT id, tx_id, data FROM ${PSInternalTable.CRUD} WHERE tx_id = ? ORDER BY id ASC`,
[txId]
);
all = result.map((row) => CrudEntry.fromRow(row));
}
const last = all[all.length - 1];
return new CrudTransaction(
all,
async (writeCheckpoint?: string) => this.handleCrudCheckpoint(last.clientId, writeCheckpoint),
txId
);
});
}
/**
* Get an unique client id for this database.
*
* The id is not reset when the database is cleared, only when the database is deleted.
*
* @returns A unique identifier for the database instance
*/
async getClientId(): Promise<string> {
return this.bucketStorageAdapter.getClientId();
}
private async handleCrudCheckpoint(lastClientId: number, writeCheckpoint?: string) {
return this.writeTransaction(async (tx) => {
await tx.execute(`DELETE FROM ${PSInternalTable.CRUD} WHERE id <= ?`, [lastClientId]);
if (writeCheckpoint) {
const check = await tx.execute(`SELECT 1 FROM ${PSInternalTable.CRUD} LIMIT 1`);
if (!check.rows?.length) {
await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [
writeCheckpoint
]);
}
} else {
await tx.execute(`UPDATE ${PSInternalTable.BUCKETS} SET target_op = CAST(? as INTEGER) WHERE name='$local'`, [
this.bucketStorageAdapter.getMaxOpId()
]);
}
});
}
/**
* Execute a SQL write (INSERT/UPDATE/DELETE) query
* and optionally return results.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @returns The query result as an object with structured key-value pairs
*/
async execute(sql: string, parameters?: any[]) {
await this.waitForReady();
return this.database.execute(sql, parameters);
}
/**
* Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.
* This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @returns The raw query result from the underlying database as a nested array of raw values, where each row is
* represented as an array of column values without field names.
*/
async executeRaw(sql: string, parameters?: any[]) {
await this.waitForReady();
return this.database.executeRaw(sql, parameters);
}
/**
* Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set
* and optionally return results.
* This is faster than executing separately with each parameter set.
*
* @param sql The SQL query to execute
* @param parameters Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution
* @returns The query result
*/
async executeBatch(sql: string, parameters?: any[][]) {
await this.waitForReady();
return this.database.executeBatch(sql, parameters);
}
/**
* Execute a read-only query and return results.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @returns An array of results
*/
async getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
await this.waitForReady();
return this.database.getAll(sql, parameters);
}
/**
* Execute a read-only query and return the first result, or null if the ResultSet is empty.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @returns The first result if found, or null if no results are returned
*/
async getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
await this.waitForReady();
return this.database.getOptional(sql, parameters);
}
/**
* Execute a read-only query and return the first result, error if the ResultSet is empty.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @returns The first result matching the query
* @throws Error if no rows are returned
*/
async get<T>(sql: string, parameters?: any[]): Promise<T> {
await this.waitForReady();
return this.database.get(sql, parameters);
}
/**
* Takes a read lock, without starting a transaction.
* In most cases, {@link readTransaction} should be used instead.
*/
async readLock<T>(callback: (db: DBAdapter) => Promise<T>) {
await this.waitForReady();
return mutexRunExclusive(AbstractPowerSyncDatabase.transactionMutex, () => callback(this.database));
}
/**
* Takes a global lock, without starting a transaction.
* In most cases, {@link writeTransaction} should be used instead.
*/
async writeLock<T>(callback: (db: DBAdapter) => Promise<T>) {
await this.waitForReady();
return mutexRunExclusive(AbstractPowerSyncDatabase.transactionMutex, async () => {
const res = await callback(this.database);
return res;
});
}
/**
* Open a read-only transaction.
* Read transactions can run concurrently to a write transaction.
* Changes from any write transaction are not visible to read transactions started before it.
*
* @param callback Function to execute within the transaction
* @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
* @returns The result of the callback
* @throws Error if the lock cannot be obtained within the timeout period
*/
async readTransaction<T>(
callback: (tx: Transaction) => Promise<T>,
lockTimeout: number = DEFAULT_LOCK_TIMEOUT_MS
): Promise<T> {
await this.waitForReady();
return this.database.readTransaction(
async (tx) => {
const res = await callback({ ...tx });
await tx.rollback();
return res;
},
{ timeoutMs: lockTimeout }
);
}
/**
* Open a read-write transaction.
* This takes a global lock - only one write transaction can execute against the database at a time.
* Statements within the transaction must be done on the provided {@link Transaction} interface.
*
* @param callback Function to execute within the transaction
* @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
* @returns The result of the callback
* @throws Error if the lock cannot be obtained within the timeout period
*/
async writeTransaction<T>(
callback: (tx: Transaction) => Promise<T>,
lockTimeout: number = DEFAULT_LOCK_TIMEOUT_MS
): Promise<T> {
await this.waitForReady();
return this.database.writeTransaction(
async (tx) => {
const res = await callback(tx);
await tx.commit();
return res;
},
{ timeoutMs: lockTimeout }
);
}
/**
* This version of `watch` uses {@link AsyncGenerator}, for documentation see {@link watchWithAsyncGenerator}.
* Can be overloaded to use a callback handler instead, for documentation see {@link watchWithCallback}.
*
* @example
* ```javascript
* async *attachmentIds() {
* for await (const result of this.powersync.watch(
* `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
* []
* )) {
* yield result.rows?._array.map((r) => r.id) ?? [];
* }
* }
* ```
*/
watch(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
/**
* See {@link watchWithCallback}.
*
* @example
* ```javascript
* onAttachmentIdsChange(onResult) {
* this.powersync.watch(
* `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
* [],
* {
* onResult: (result) => onResult(result.rows?._array.map((r) => r.id) ?? [])
* }
* );
* }
* ```
*/
watch(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
watch(
sql: string,
parameters?: any[],
handlerOrOptions?: WatchHandler | SQLWatchOptions,
maybeOptions?: SQLWatchOptions
): void | AsyncIterable<QueryResult> {
if (handlerOrOptions && typeof handlerOrOptions === 'object' && 'onResult' in handlerOrOptions) {
const handler = handlerOrOptions as WatchHandler;
const options = maybeOptions;
return this.watchWithCallback(sql, parameters, handler, options);
}
const options = handlerOrOptions as SQLWatchOptions | undefined;
return this.watchWithAsyncGenerator(sql, parameters, options);
}
/**
* Execute a read query every time the source tables are modified.
* Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.
* Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
*
* Note that the `onChange` callback member of the handler is required.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @param handler Callbacks for handling results and errors
* @param options Options for configuring watch behavior
*/
watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void {
const { onResult, onError = (e: Error) => this.options.logger?.error(e) } = handler ?? {};
if (!onResult) {
throw new Error('onResult is required');
}
const watchQuery = async (abortSignal: AbortSignal) => {
try {
const resolvedTables = await this.resolveTables(sql, parameters, options);
// Fetch initial data
const result = await this.executeReadOnly(sql, parameters);
onResult(result);
this.onChangeWithCallback(
{
onChange: async () => {
try {
const result = await this.executeReadOnly(sql, parameters);
onResult(result);
} catch (error) {
onError?.(error);
}
},
onError
},
{
...(options ?? {}),
tables: resolvedTables,
// Override the abort signal since we intercept it
signal: abortSignal
}
);
} catch (error) {
onError?.(error);
}
};
runOnSchemaChange(watchQuery, this, options);
}
/**
* Execute a read query every time the source tables are modified.
* Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.
* Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
*
* @param sql The SQL query to execute
* @param parameters Optional array of parameters to bind to the query
* @param options Options for configuring watch behavior
* @returns An AsyncIterable that yields QueryResults whenever the data changes
*/
watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult> {
return new EventIterator<QueryResult>((eventOptions) => {
const handler: WatchHandler = {
onResult: (result) => {
eventOptions.push(result);
},
onError: (error) => {
eventOptions.fail(error);
}
};
this.watchWithCallback(sql, parameters, handler, options);
options?.signal?.addEventListener('abort', () => {
eventOptions.stop();
});
});
}
/**
* Resolves the list of tables that are used in a SQL query.
* If tables are specified in the options, those are used directly.
* Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.
*
* @param sql The SQL query to analyze
* @param parameters Optional parameters for the SQL query
* @param options Optional watch options that may contain explicit table list
* @returns Array of table names that the query depends on
*/
async resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]> {
const resolvedTables = options?.tables ? [...options.tables] : [];
if (!options?.tables) {
const explained = await this.getAll<{ opcode: string; p3: number; p2: number }>(`EXPLAIN ${sql}`, parameters);
const rootPages = explained
.filter((row) => row.opcode == 'OpenRead' && row.p3 == 0 && typeof row.p2 == 'number')
.map((row) => row.p2);
const tables = await this.getAll<{ tbl_name: string }>(
`SELECT DISTINCT tbl_name FROM sqlite_master WHERE rootpage IN (SELECT json_each.value FROM json_each(?))`,
[JSON.stringify(rootPages)]
);
for (const table of tables) {
resolvedTables.push(table.tbl_name.replace(POWERSYNC_TABLE_MATCH, ''));
}
}
return resolvedTables;
}
/**
* This version of `onChange` uses {@link AsyncGenerator}, for documentation see {@link onChangeWithAsyncGenerator}.
* Can be overloaded to use a callback handler instead, for documentation see {@link onChangeWithCallback}.
*
* @example
* ```javascript
* async monitorChanges() {
* for await (const event of this.powersync.onChange({tables: ['todos']})) {
* console.log('Detected change event:', event);
* }
* }
* ```
*/
onChange(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent>;
/**
* See {@link onChangeWithCallback}.
*
* @example
* ```javascript
* monitorChanges() {
* this.powersync.onChange({
* onChange: (event) => {
* console.log('Change detected:', event);
* }
* }, { tables: ['todos'] });
* }
* ```
*/
onChange(handler?: WatchOnChangeHandler, options?: SQLWatchOptions): () => void;
onChange(