Skip to content

Commit 3403329

Browse files
authored
Merge pull request #548 from powersync-ja/improve-database-comments
Add missing comments/improve others for the API reference (Docusaurus)
2 parents 6191e97 + db84156 commit 3403329

File tree

2 files changed

+133
-20
lines changed

2 files changed

+133
-20
lines changed

packages/common/src/client/AbstractPowerSyncDatabase.ts

+77-5
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
267267
/**
268268
* Wait for the first sync operation to complete.
269269
*
270-
* @argument request Either an abort signal (after which the promise will complete regardless of
270+
* @param request Either an abort signal (after which the promise will complete regardless of
271271
* whether a full sync was completed) or an object providing an abort signal and a priority target.
272272
* When a priority target is set, the promise may complete when all buckets with the given (or higher)
273273
* priorities have been synchronized. This can be earlier than a complete sync.
@@ -540,7 +540,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
540540
}
541541

542542
/**
543-
* Get a batch of crud data to upload.
543+
* Get a batch of CRUD data to upload.
544544
*
545545
* Returns null if there is no data to upload.
546546
*
@@ -555,6 +555,9 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
555555
* This method does include transaction ids in the result, but does not group
556556
* data by transaction. One batch may contain data from multiple transactions,
557557
* and a single transaction may be split over multiple batches.
558+
*
559+
* @param limit Maximum number of CRUD entries to include in the batch
560+
* @returns A batch of CRUD operations to upload, or null if there are none
558561
*/
559562
async getCrudBatch(limit: number = DEFAULT_CRUD_BATCH_LIMIT): Promise<CrudBatch | null> {
560563
const result = await this.getAll<CrudEntryJSON>(
@@ -591,6 +594,8 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
591594
*
592595
* Unlike {@link getCrudBatch}, this only returns data from a single transaction at a time.
593596
* All data for the transaction is loaded into memory.
597+
*
598+
* @returns A transaction of CRUD operations to upload, or null if there are none
594599
*/
595600
async getNextCrudTransaction(): Promise<CrudTransaction | null> {
596601
return await this.readTransaction(async (tx) => {
@@ -628,6 +633,8 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
628633
* Get an unique client id for this database.
629634
*
630635
* The id is not reset when the database is cleared, only when the database is deleted.
636+
*
637+
* @returns A unique identifier for the database instance
631638
*/
632639
async getClientId(): Promise<string> {
633640
return this.bucketStorageAdapter.getClientId();
@@ -652,14 +659,27 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
652659
}
653660

654661
/**
655-
* Execute a write (INSERT/UPDATE/DELETE) query
662+
* Execute a SQL write (INSERT/UPDATE/DELETE) query
656663
* and optionally return results.
664+
*
665+
* @param sql The SQL query to execute
666+
* @param parameters Optional array of parameters to bind to the query
667+
* @returns The query result as an object with structured key-value pairs
657668
*/
658669
async execute(sql: string, parameters?: any[]) {
659670
await this.waitForReady();
660671
return this.database.execute(sql, parameters);
661672
}
662673

674+
/**
675+
* Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.
676+
* This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.
677+
*
678+
* @param sql The SQL query to execute
679+
* @param parameters Optional array of parameters to bind to the query
680+
* @returns The raw query result from the underlying database as a nested array of raw values, where each row is
681+
* represented as an array of column values without field names.
682+
*/
663683
async executeRaw(sql: string, parameters?: any[]) {
664684
await this.waitForReady();
665685
return this.database.executeRaw(sql, parameters);
@@ -669,6 +689,10 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
669689
* Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set
670690
* and optionally return results.
671691
* This is faster than executing separately with each parameter set.
692+
*
693+
* @param sql The SQL query to execute
694+
* @param parameters Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution
695+
* @returns The query result
672696
*/
673697
async executeBatch(sql: string, parameters?: any[][]) {
674698
await this.waitForReady();
@@ -677,6 +701,10 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
677701

678702
/**
679703
* Execute a read-only query and return results.
704+
*
705+
* @param sql The SQL query to execute
706+
* @param parameters Optional array of parameters to bind to the query
707+
* @returns An array of results
680708
*/
681709
async getAll<T>(sql: string, parameters?: any[]): Promise<T[]> {
682710
await this.waitForReady();
@@ -685,6 +713,10 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
685713

686714
/**
687715
* Execute a read-only query and return the first result, or null if the ResultSet is empty.
716+
*
717+
* @param sql The SQL query to execute
718+
* @param parameters Optional array of parameters to bind to the query
719+
* @returns The first result if found, or null if no results are returned
688720
*/
689721
async getOptional<T>(sql: string, parameters?: any[]): Promise<T | null> {
690722
await this.waitForReady();
@@ -693,6 +725,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
693725

694726
/**
695727
* Execute a read-only query and return the first result, error if the ResultSet is empty.
728+
*
729+
* @param sql The SQL query to execute
730+
* @param parameters Optional array of parameters to bind to the query
731+
* @returns The first result matching the query
732+
* @throws Error if no rows are returned
696733
*/
697734
async get<T>(sql: string, parameters?: any[]): Promise<T> {
698735
await this.waitForReady();
@@ -724,6 +761,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
724761
* Open a read-only transaction.
725762
* Read transactions can run concurrently to a write transaction.
726763
* Changes from any write transaction are not visible to read transactions started before it.
764+
*
765+
* @param callback Function to execute within the transaction
766+
* @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
767+
* @returns The result of the callback
768+
* @throws Error if the lock cannot be obtained within the timeout period
727769
*/
728770
async readTransaction<T>(
729771
callback: (tx: Transaction) => Promise<T>,
@@ -744,6 +786,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
744786
* Open a read-write transaction.
745787
* This takes a global lock - only one write transaction can execute against the database at a time.
746788
* Statements within the transaction must be done on the provided {@link Transaction} interface.
789+
*
790+
* @param callback Function to execute within the transaction
791+
* @param lockTimeout Time in milliseconds to wait for a lock before throwing an error
792+
* @returns The result of the callback
793+
* @throws Error if the lock cannot be obtained within the timeout period
747794
*/
748795
async writeTransaction<T>(
749796
callback: (tx: Transaction) => Promise<T>,
@@ -818,6 +865,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
818865
* Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
819866
*
820867
* Note that the `onChange` callback member of the handler is required.
868+
*
869+
* @param sql The SQL query to execute
870+
* @param parameters Optional array of parameters to bind to the query
871+
* @param handler Callbacks for handling results and errors
872+
* @param options Options for configuring watch behavior
821873
*/
822874
watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void {
823875
const { onResult, onError = (e: Error) => this.options.logger?.error(e) } = handler ?? {};
@@ -863,6 +915,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
863915
* Execute a read query every time the source tables are modified.
864916
* Use {@link SQLWatchOptions.throttleMs} to specify the minimum interval between queries.
865917
* Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
918+
*
919+
* @param sql The SQL query to execute
920+
* @param parameters Optional array of parameters to bind to the query
921+
* @param options Options for configuring watch behavior
922+
* @returns An AsyncIterable that yields QueryResults whenever the data changes
866923
*/
867924
watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult> {
868925
return new EventIterator<QueryResult>((eventOptions) => {
@@ -883,6 +940,16 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
883940
});
884941
}
885942

943+
/**
944+
* Resolves the list of tables that are used in a SQL query.
945+
* If tables are specified in the options, those are used directly.
946+
* Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.
947+
*
948+
* @param sql The SQL query to analyze
949+
* @param parameters Optional parameters for the SQL query
950+
* @param options Optional watch options that may contain explicit table list
951+
* @returns Array of table names that the query depends on
952+
*/
886953
async resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]> {
887954
const resolvedTables = options?.tables ? [...options.tables] : [];
888955
if (!options?.tables) {
@@ -955,7 +1022,9 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
9551022
*
9561023
* Note that the `onChange` callback member of the handler is required.
9571024
*
958-
* Returns dispose function to stop watching.
1025+
* @param handler Callbacks for handling change events and errors
1026+
* @param options Options for configuring watch behavior
1027+
* @returns A dispose function to stop watching for changes
9591028
*/
9601029
onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLWatchOptions): () => void {
9611030
const { onChange, onError = (e: Error) => this.options.logger?.error(e) } = handler ?? {};
@@ -1008,8 +1077,11 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
10081077
*
10091078
* This is preferred over {@link watchWithAsyncGenerator} when multiple queries need to be performed
10101079
* together when data is changed.
1080+
*
1081+
* Note: do not declare this as `async *onChange` as it will not work in React Native.
10111082
*
1012-
* Note, do not declare this as `async *onChange` as it will not work in React Native
1083+
* @param options Options for configuring watch behavior
1084+
* @returns An AsyncIterable that yields change events whenever the specified tables change
10131085
*/
10141086
onChangeWithAsyncGenerator(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent> {
10151087
const resolvedOptions = options ?? {};

packages/common/src/db/crud/SyncStatus.ts

+56-15
Original file line numberDiff line numberDiff line change
@@ -33,34 +33,50 @@ export class SyncStatus {
3333
constructor(protected options: SyncStatusOptions) {}
3434

3535
/**
36-
* true if currently connected.
36+
* Indicates if the client is currently connected to the PowerSync service.
37+
*
38+
* @returns {boolean} True if connected, false otherwise. Defaults to false if not specified.
3739
*/
3840
get connected() {
3941
return this.options.connected ?? false;
4042
}
4143

44+
/**
45+
* Indicates if the client is in the process of establishing a connection to the PowerSync service.
46+
*
47+
* @returns {boolean} True if connecting, false otherwise. Defaults to false if not specified.
48+
*/
4249
get connecting() {
4350
return this.options.connecting ?? false;
4451
}
4552

4653
/**
47-
* Time that a last sync has fully completed, if any.
48-
* Currently this is reset to null after a restart.
54+
* Time that a last sync has fully completed, if any.
55+
* This timestamp is reset to null after a restart of the PowerSync service.
56+
*
57+
* @returns {Date | undefined} The timestamp of the last successful sync, or undefined if no sync has completed.
4958
*/
5059
get lastSyncedAt() {
5160
return this.options.lastSyncedAt;
5261
}
5362

5463
/**
55-
* Indicates whether there has been at least one full sync, if any.
56-
* Is undefined when unknown, for example when state is still being loaded from the database.
64+
* Indicates whether there has been at least one full sync completed since initialization.
65+
*
66+
* @returns {boolean | undefined} True if at least one sync has completed, false if no sync has completed,
67+
* or undefined when the state is still being loaded from the database.
5768
*/
5869
get hasSynced() {
5970
return this.options.hasSynced;
6071
}
6172

6273
/**
63-
* Upload/download status
74+
* Provides the current data flow status regarding uploads and downloads.
75+
*
76+
* @returns {SyncDataFlowStatus} An object containing:
77+
* - downloading: True if actively downloading changes (only when connected is also true)
78+
* - uploading: True if actively uploading changes
79+
* Defaults to {downloading: false, uploading: false} if not specified.
6480
*/
6581
get dataFlowStatus() {
6682
return (
@@ -79,26 +95,33 @@ export class SyncStatus {
7995
}
8096

8197
/**
82-
* Partial sync status for involved bucket priorities.
98+
* Provides sync status information for all bucket priorities, sorted by priority (highest first).
99+
*
100+
* @returns {SyncPriorityStatus[]} An array of status entries for different sync priority levels,
101+
* sorted with highest priorities (lower numbers) first.
83102
*/
84103
get priorityStatusEntries() {
85104
return (this.options.priorityStatusEntries ?? []).slice().sort(SyncStatus.comparePriorities);
86105
}
87106

88107
/**
89-
* Reports a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields that apply
90-
* to a specific bucket priority instead of the entire sync operation.
91-
*
108+
* Reports the sync status (a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields)
109+
* for a specific bucket priority level.
110+
*
92111
* When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority
93112
* buckets first. When a consistent view over all buckets for all priorities up until the given priority is
94113
* reached, PowerSync makes data from those buckets available before lower-priority buckets have finished
95-
* synchronizing.
96-
* When PowerSync makes data for a given priority available, all buckets in higher-priorities are guaranteed to
97-
* be consistent with that checkpoint. For this reason, this method may also return the status for lower priorities.
98-
* In a state where the PowerSync just finished synchronizing buckets in priority level 3, calling this method
114+
* syncing.
115+
*
116+
* This method returns the status for the requested priority or the next higher priority level that has
117+
* status information available. This is because when PowerSync makes data for a given priority available,
118+
* all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.
119+
*
120+
* For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method
99121
* with a priority of 1 may return information for priority level 3.
100122
*
101-
* @param priority The bucket priority for which the status should be reported.
123+
* @param {number} priority The bucket priority for which the status should be reported
124+
* @returns {SyncPriorityStatus} Status information for the requested priority level or the next higher level with available status
102125
*/
103126
statusForPriority(priority: number): SyncPriorityStatus {
104127
// priorityStatusEntries are sorted by ascending priorities (so higher numbers to lower numbers).
@@ -117,15 +140,33 @@ export class SyncStatus {
117140
};
118141
}
119142

143+
/**
144+
* Compares this SyncStatus instance with another to determine if they are equal.
145+
* Equality is determined by comparing the serialized JSON representation of both instances.
146+
*
147+
* @param {SyncStatus} status The SyncStatus instance to compare against
148+
* @returns {boolean} True if the instances are considered equal, false otherwise
149+
*/
120150
isEqual(status: SyncStatus) {
121151
return JSON.stringify(this.options) == JSON.stringify(status.options);
122152
}
123153

154+
/**
155+
* Creates a human-readable string representation of the current sync status.
156+
* Includes information about connection state, sync completion, and data flow.
157+
*
158+
* @returns {string} A string representation of the sync status
159+
*/
124160
getMessage() {
125161
const dataFlow = this.dataFlowStatus;
126162
return `SyncStatus<connected: ${this.connected} connecting: ${this.connecting} lastSyncedAt: ${this.lastSyncedAt} hasSynced: ${this.hasSynced}. Downloading: ${dataFlow.downloading}. Uploading: ${dataFlow.uploading}. UploadError: ${dataFlow.uploadError}, DownloadError?: ${dataFlow.downloadError}>`;
127163
}
128164

165+
/**
166+
* Serializes the SyncStatus instance to a plain object.
167+
*
168+
* @returns {SyncStatusOptions} A plain object representation of the sync status
169+
*/
129170
toJSON(): SyncStatusOptions {
130171
return {
131172
connected: this.connected,

0 commit comments

Comments
 (0)