@powersync/react-native
Enumerations
| Enumeration | Description |
|---|---|
| AttachmentState | AttachmentState represents the current synchronization state of an attachment. |
| ColumnType | - |
| DiffTriggerOperation | SQLite operations to track changes for with TriggerManager |
| EncodingType | - |
| FetchStrategy | - |
| SyncStreamConnectionMethod | - |
| UpdateType | Type of local change. |
| WatchedQueryListenerEvent | - |
Classes
| Class | Description |
|---|---|
| ArrayComparator | An efficient comparator for WatchedQuery created with Query#watch. This has the ability to determine if a query result has changes without necessarily processing all items in the result. |
| AttachmentContext | AttachmentContext provides database operations for managing attachment records. |
| AttachmentQueue | AttachmentQueue manages the lifecycle and synchronization of attachments between local and remote storage. Provides automatic synchronization, upload/download queuing, attachment monitoring, verification and repair of local files, and cleanup of archived attachments. |
| AttachmentTable | AttachmentTable defines the schema for the attachment queue table. |
| BaseObserver | - |
| Column | - |
| CrudBatch | A batch of client-side changes. |
| CrudTransaction | - |
| DBAdapter | - |
| GetAllQuery | Performs a DBGetUtils.getAll operation for a watched query. |
| Index | - |
| IndexedColumn | - |
| LockContext | - |
| ReactNativeRemote | - |
| ReactNativeStreamingSyncImplementation | - |
| ResolvedTable | A resolved table in the PowerSync schema, with all columns, index definitions and options. |
| Schema | A schema is a collection of tables. It is used to define the structure of a database. |
| Table | A table with a statically-typed Columns record structure. |
| UploadQueueStats | - |
Interfaces
AdditionalOptions
Extends
HookWatchOptions
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
reportFetching? | boolean | - | HookWatchOptions.reportFetching |
runQueryOnce? | boolean | - | - |
streams? | QuerySyncStreamOptions[] | An optional array of sync streams (with names and parameters) backing the query. When set, useQuery will subscribe to those streams (and automatically handle unsubscribing from them, too). If QuerySyncStreamOptions is set on a stream, useQuery will remain in a loading state until that stream is marked as SyncSubscriptionDescription.hasSynced. This ensures the query is not missing rows that haven't been downloaded. Note however that after an initial sync, the query will not block itself while new rows are downloading. Instead, consistent sync snapshots will be made available as they've been processed by PowerSync. | HookWatchOptions.streams |
tables? | string[] | - | HookWatchOptions.tables |
throttleMs? | number | The minimum interval between queries. | HookWatchOptions.throttleMs |
triggerImmediate? | boolean | Emits an empty result set immediately | HookWatchOptions.triggerImmediate |
ArrayQueryDefinition<RowType>
Options for building a query with AbstractPowerSyncDatabase#query. This query will be executed with AbstractPowerSyncDatabase#getAll.
Type Parameters
| Type Parameter | Default type |
|---|---|
RowType | unknown |
Properties
| Property | Type | Description |
|---|---|---|
mapper? | (row: Record<string, unknown>) => RowType | Maps the raw SQLite row to a custom typed object. Example mapper: (row) => ({ ...row, created_at: new Date(row.created_at as string), }) |
parameters? | readonly Readonly<QueryParam>[] | - |
sql | string | - |
AttachmentErrorHandler
Experimental Alpha
SyncErrorHandler provides custom error handling for attachment sync operations. Implementations determine whether failed operations should be retried or archived.
This is currently experimental and may change without a major version bump.
Methods
onDeleteError()
onDeleteError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to delete |
error | unknown | The error encountered during the delete |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
onDownloadError()
onDownloadError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to download |
error | unknown | The error encountered during the download |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
onUploadError()
onUploadError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to upload |
error | unknown | The error encountered during the upload |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
AttachmentQueueOptions
Experimental Alpha
Configuration options for AttachmentQueue.
This is currently experimental and may change without a major version bump.
Properties
| Property | Type | Description |
|---|---|---|
archivedCacheLimit? | number | Alpha Maximum archived attachments before cleanup. Default: 100 |
db | CommonPowerSyncDatabase | Alpha PowerSync database instance |
downloadAttachments? | boolean | Alpha Whether to automatically download remote attachments. Default: true |
errorHandler? | AttachmentErrorHandler | Alpha Handler for upload, download and delete errors |
localStorage | LocalStorageAdapter | Alpha Local storage adapter for file persistence |
logger? | PowerSyncLogger | Alpha Logger instance. Defaults to db.logger |
remoteStorage | RemoteStorageAdapter | Alpha Remote storage adapter for upload/download operations |
syncIntervalMs? | number | Alpha Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000 |
syncThrottleDuration? | number | Alpha Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30 |
tableName? | string | Alpha Name of the table to store attachment records. Default: 'ps_attachment_queue' |
watchAttachments | (onUpdate: (attachment) => Promise<void>, signal: AbortSignal) => void | Alpha Callback for monitoring attachment changes in your data model |
AttachmentRecord
Alpha
AttachmentRecord represents an attachment in the local database.
Properties
| Property | Type | Description |
|---|---|---|
filename | string | Alpha |
hasSynced? | boolean | Alpha |
id | string | Alpha |
localUri? | string | Alpha |
mediaType? | string | Alpha |
metaData? | string | Alpha |
size? | number | Alpha |
state | AttachmentState | Alpha |
timestamp? | number | Alpha |
AttachmentTableOptions
Alpha
Extends
Omit<TableOptions,"name"|"columns">
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
ignoreEmptyUpdates? | boolean | Alpha | Omit.ignoreEmptyUpdates |
indexes? | IndexShorthand | Alpha | Omit.indexes |
insertOnly? | boolean | Alpha | Omit.insertOnly |
localOnly? | boolean | Alpha | Omit.localOnly |
trackMetadata? | boolean | Alpha | Omit.trackMetadata |
trackPrevious? | boolean | TrackPreviousOptions | Alpha | Omit.trackPrevious |
viewName? | string | Alpha | Omit.viewName |
BaseCreateDiffTriggerOptions
Alpha Experimental
Common interface for options used in creating a diff trigger.
Extended by
Properties
| Property | Type | Description |
|---|---|---|
columns? | string[] | Alpha Columns to track and report changes for. Defaults to all columns in the source table. Use an empty array to track only the ID and operation. |
hooks? | TriggerCreationHooks | Alpha Hooks which allow execution during the trigger creation process. |
source | string | Alpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema. |
useStorage? | boolean | Alpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed. |
when | Partial<Record<DiffTriggerOperation, string>> | Alpha Condition to filter when the triggers should fire. This corresponds to a SQLite WHEN clause in the trigger body. This is useful for only triggering on specific conditions. For example, you can use it to only trigger on certain values in the NEW row. Note that for PowerSync the row data is stored in a JSON column named data. The row id is available in the id column. NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL. Any user input strings here should be sanitized externally. The BaseCreateDiffTriggerOptions.when string template function performs some basic sanitization, extra external sanitization is recommended. Example { 'INSERT': sanitizeSQLjson_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}, 'INSERT': TRUE, 'UPDATE': sanitizeSQLNEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active', 'DELETE': sanitizeSQLjson_extract(OLD.data, '$.list_id') = 'abcd' } |
BaseObserverInterface<T>
Extended by
Type Parameters
| Type Parameter |
|---|
T extends BaseListener |
Methods
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<T> |
Returns
Function
Returns
void
BasePowerSyncDatabaseOptions
Options required regardless of how a PowerSync database is opened.
Properties
| Property | Type | Description |
|---|---|---|
logger? | PowerSyncLogger | - |
schema | Schema | Schema used for the local database. |
BaseQueryResult
Shared superinterface for QueryResult and RawQueryResult.
Extended by
Properties
| Property | Type | Description |
|---|---|---|
insertId? | number | Represents the auto-generated row id if applicable. |
rowsAffected? | number | Number of affected rows reported by SQLite for a write query. When using the default client-side JSON-based view system, rowsAffected may be 0 for successful UPDATE and DELETE statements. Use a RETURNING clause and inspect rows when you need to confirm which rows changed. |
BaseTriggerDiffRecord<TOperationId>
Experimental Alpha
Diffs created by TriggerManager#createDiffTrigger are stored in a temporary table. This is the base record structure for all diff records.
Extended by
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TOperationId extends string | number | number | The type for operation_id. Defaults to number as returned by default SQLite database queries. Use string for full 64-bit precision when using { castOperationIdAsText: true } option. |
Properties
| Property | Type | Description |
|---|---|---|
id | string | Alpha The modified row's id column value. |
operation | DiffTriggerOperation | Alpha The operation performed which created this record. |
operation_id | TOperationId | Alpha Auto-incrementing primary key for the operation. Defaults to number as returned by database queries (wa-sqlite returns lower 32 bits). Can be string for full 64-bit precision when using { castOperationIdAsText: true } option. |
timestamp | string | Alpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z. |
BatchedUpdateNotification
Properties
| Property | Type |
|---|---|
tables | string[] |
ColumnOptions
Properties
| Property | Type |
|---|---|
name | string |
type? | ColumnType |
CommonPowerSyncDatabase
Extends
Extended by
Properties
| Property | Modifier | Type | Description | Inherited from |
|---|---|---|---|---|
closed | readonly | boolean | Returns true if the connection is closed. | - |
currentStatus | readonly | SyncStatus | Current connection status. | - |
execute | public | <T>(query: string, params?: any[]) => Promise<QueryResult<T>> | Execute a SQL write (INSERT/UPDATE/DELETE) query and optionally return results. When using the default client-side JSON-based view system, the returned result's rowsAffected may be 0 for successful UPDATE and DELETE statements. Use a RETURNING clause and inspect result.rows when you need to confirm which rows changed. | SqlExecutor.execute |
executeBatch | public | (query: string, params?: any[][]) => Promise<QueryResult<never>> | 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. | SqlExecutor.executeBatch |
executeRaw | public | (query: string, params?: any[]) => Promise<RawQueryResult> | 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. | SqlExecutor.executeRaw |
logger | readonly | PowerSyncLogger | - | - |
ready | readonly | boolean | - | - |
schema | readonly | Schema | Schema used for the local database. | - |
sdkVersion | readonly | string | - | - |
triggers | readonly | TriggerManager | Experimental Alpha Allows creating SQLite triggers which can be used to track various operations on SQLite tables. | - |
Accessors
connected
Get Signature
get connected(): boolean
Whether a connection to the PowerSync service is currently open.
Returns
boolean
connecting
Get Signature
get connecting(): boolean
Returns
boolean
database
Get Signature
get database(): DBAdapter
The underlying database.
For the most part, behavior is the same whether querying on the underlying database, or on CommonPowerSyncDatabase.
Returns
Methods
close()
close(options?): Promise<void>
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.
Parameters
| Parameter | Type |
|---|---|
options? | PowerSyncCloseOptions |
Returns
Promise<void>
connect()
connect(connector, options?): Promise<void>
Connects to stream of events from the PowerSync instance.
Parameters
| Parameter | Type |
|---|---|
connector | PowerSyncBackendConnector |
options? | SyncOptions |
Returns
Promise<void>
createMutex()
createMutex(): Mutex
Internal
Returns
customQuery()
customQuery<RowType>(query): Query<RowType>
Allows building a WatchedQuery using an existing WatchCompatibleQuery. The watched query will use the provided WatchCompatibleQuery.execute method to query results.
Type Parameters
| Type Parameter |
|---|
RowType |
Parameters
| Parameter | Type |
|---|---|
query | WatchCompatibleQuery<RowType[]> |
Returns
Query<RowType>
Example
// Potentially a query from an ORM like Drizzle
const query = db.select().from(lists);
const watchedTodos = powersync.customQuery(query)
.watch()
// OR use .differentialWatch() for fine-grained watches.
disconnect()
disconnect(): Promise<void>
Close the sync connection.
Use CommonPowerSyncDatabase.connect to connect again.
Returns
Promise<void>
disconnectAndClear()
disconnectAndClear(options?): Promise<void>
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.
Parameters
| Parameter | Type |
|---|---|
options? | DisconnectAndClearOptions |
Returns
Promise<void>
get()
get<T>(sql, parameters?): Promise<T>
Execute a read-only query and return the first result, error if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T>
The first result matching the query
Throws
Error if no rows are returned
Inherited from
getAll()
getAll<T>(sql, parameters?): Promise<T[]>
Execute a read-only query and return results.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T[]>
An array of results
Inherited from
getClientId()
getClientId(): Promise<string>
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
Promise<string>
A unique identifier for the database instance
getCrudBatch()
getCrudBatch(limit?): Promise<null | CrudBatch>
Get a batch of CRUD data to upload.
Returns null if there is no data to upload.
Use this from the PowerSyncBackendConnector.uploadData callback.
Once the data have been successfully uploaded, call CrudBatch.complete before requesting the next batch.
Use the limit parameter 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit? | number | Maximum number of CRUD entries to include in the batch |
Returns
Promise<null | CrudBatch>
A batch of CRUD operations to upload, or null if there are none
getCrudTransactions()
getCrudTransactions(): AsyncIterable<CrudTransaction, null>
Returns an async iterator of completed transactions with local writes against the database.
This is typically used from the PowerSyncBackendConnector.uploadData callback. Each entry emitted by the returned iterator is a full transaction containing all local writes made while that transaction was active.
Unlike CommonPowerSyncDatabase.getNextCrudTransaction, which always returns the oldest transaction that hasn't been CrudTransaction.completed yet, this iterator can be used to receive multiple transactions. Calling CrudTransaction.complete will mark that and all prior transactions emitted by the iterator as completed.
This can be used to upload multiple transactions in a single batch, e.g with:
let lastTransaction = null;
let batch = [];
for await (const transaction of database.getCrudTransactions()) {
batch.push(...transaction.crud);
lastTransaction = transaction;
if (batch.length > 10) {
break;
}
}
If there is no local data to upload, the async iterator complete without emitting any items.
Note that iterating over async iterables requires a polyfill for React Native.
Returns
AsyncIterable<CrudTransaction, null>
getNextCrudTransaction()
getNextCrudTransaction(): Promise<null | CrudTransaction>
Get the next recorded transaction to upload.
Returns null if there is no data to upload.
Use this from the PowerSyncBackendConnector.uploadData callback.
Once the data have been successfully uploaded, call CrudTransaction.complete before requesting the next transaction.
Unlike CommonPowerSyncDatabase.getCrudBatch, this only returns data from a single transaction at a time. All data for the transaction is loaded into memory.
Returns
Promise<null | CrudTransaction>
A transaction of CRUD operations to upload, or null if there are none
getOptional()
getOptional<T>(sql, parameters?): Promise<null | T>
Execute a read-only query and return the first result, or null if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<null | T>
The first result if found, or null if no results are returned
Inherited from
getUploadQueueStats()
getUploadQueueStats(includeSize?): Promise<UploadQueueStats>
Get upload queue size estimate and count.
Parameters
| Parameter | Type |
|---|---|
includeSize? | boolean |
Returns
Promise<UploadQueueStats>
init()
init(): Promise<void>
Wait for initialization to complete. While initializing is automatic, this helps to catch and report initialization errors.
Returns
Promise<void>
onChange()
Call Signature
onChange(options?): AsyncIterable<WatchOnChangeEvent>
This version of onChange uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.onChangeWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.onChangeWithCallback.
Parameters
| Parameter | Type |
|---|---|
options? | SQLOnChangeOptions |
Returns
AsyncIterable<WatchOnChangeEvent>
Example
async monitorChanges() {
for await (const event of this.powersync.onChange({tables: ['todos']})) {
console.log('Detected change event:', event);
}
}
Call Signature
onChange(handler?, options?): () => void
See CommonPowerSyncDatabase.onChangeWithCallback.
Parameters
| Parameter | Type |
|---|---|
handler? | WatchOnChangeHandler |
options? | SQLOnChangeOptions |
Returns
Function
Returns
void
Example
monitorChanges() {
this.powersync.onChange({
onChange: (event) => {
console.log('Change detected:', event);
}
}, { tables: ['todos'] });
}
onChangeWithAsyncGenerator()
onChangeWithAsyncGenerator(options?): AsyncIterable<WatchOnChangeEvent>
Create a Stream of changes to any of the specified tables.
This is preferred over CommonPowerSyncDatabase.watchWithAsyncGenerator when multiple queries need to be performed together when data is changed.
Note: do not declare this as async *onChange as it will not work in React Native.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
AsyncIterable<WatchOnChangeEvent>
An AsyncIterable that yields change events whenever the specified tables change
onChangeWithCallback()
onChangeWithCallback(handler?, options?): () => void
Invoke the provided callback on any changes to any of the specified tables.
This is preferred over CommonPowerSyncDatabase.watchWithCallback when multiple queries need to be performed together when data is changed.
Note that the onChange callback member of the handler is required.
Parameters
| Parameter | Type | Description |
|---|---|---|
handler? | WatchOnChangeHandler | Callbacks for handling change events and errors |
options? | SQLOnChangeOptions | Options for configuring watch behavior |
Returns
Function
A dispose function to stop watching for changes
Returns
void
query()
query<RowType>(query): Query<RowType>
Allows defining a query which can be used to build a WatchedQuery. The defined query will be executed with CommonPowerSyncDatabase#getAll. An optional mapper function can be provided to transform the results.
Type Parameters
| Type Parameter |
|---|
RowType |
Parameters
| Parameter | Type |
|---|---|
query | ArrayQueryDefinition<RowType> |
Returns
Query<RowType>
Example
const watchedTodos = powersync.query({
sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
parameters: [],
mapper: (row) => ({
...row,
created_at: new Date(row.created_at as string)
})
})
.watch()
// OR use .differentialWatch() for fine-grained watches.
readLock()
readLock<T>(callback): Promise<T>
Takes a read lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.readTransaction should be used instead.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
callback | (db) => Promise<T> |
Returns
Promise<T>
readTransaction()
readTransaction<T>(callback, lockTimeout?): Promise<T>
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.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (tx) => Promise<T> | Function to execute within the transaction |
lockTimeout? | number | Time in milliseconds to wait for a lock before throwing an error |
Returns
Promise<T>
The result of the callback
Throws
Error if the lock cannot be obtained within the timeout period
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<PowerSyncDBListener> |
Returns
Function
Returns
void
Inherited from
BaseObserverInterface.registerListener
resolveTables()
resolveTables(
sql,
parameters?,
options?): Promise<string[]>
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to analyze |
parameters? | any[] | Optional parameters for the SQL query |
options? | SQLWatchOptions | Optional watch options that may contain explicit table list |
Returns
Promise<string[]>
Array of table names that the query depends on
syncStream()
syncStream(name, params?): SyncStream
Create a sync stream to query its status or to subscribe to it.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the stream to subscribe to. |
params? | Record<string, any> | Optional parameters for the stream subscription. |
Returns
A SyncStream instance that can be subscribed to.
updateSchema()
updateSchema(schema): Promise<void>
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 CommonPowerSyncDatabase.connect.
Parameters
| Parameter | Type |
|---|---|
schema | Schema |
Returns
Promise<void>
waitForFirstSync()
waitForFirstSync(request?): Promise<void>
Wait for the first sync operation to complete.
Parameters
| Parameter | Type | Description |
|---|---|---|
request? | | AbortSignal | { priority: number; signal: AbortSignal; } | 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
Promise<void>
A promise which will resolve once the first full sync has completed.
waitForReady()
waitForReady(): Promise<void>
Returns
Promise<void>
A promise which will resolve once initialization is completed.
waitForStatus()
waitForStatus(predicate, signal?): Promise<void>
Waits for the first sync status for which the status callback returns a truthy value.
Parameters
| Parameter | Type |
|---|---|
predicate | (status) => any |
signal? | AbortSignal |
Returns
Promise<void>
watch()
Call Signature
watch(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>
This version of watch uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.watchWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.watchWithCallback.
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
options? | SQLWatchOptions |
Returns
AsyncIterable<QueryResult<SqliteRecord>>
Example
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) ?? [];
}
}
Call Signature
watch(
sql,
parameters?,
handler?,
options?): void
See CommonPowerSyncDatabase.watchWithCallback.
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
handler? | WatchHandler |
options? | SQLWatchOptions |
Returns
void
Example
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) ?? [])
}
);
}
watchWithAsyncGenerator()
watchWithAsyncGenerator(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>
Execute a read query every time the source tables are modified.
Use SQLOnChangeOptions.throttleMs to specify the minimum interval between queries.
Source tables are automatically detected using EXPLAIN QUERY PLAN.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
AsyncIterable<QueryResult<SqliteRecord>>
An AsyncIterable that yields QueryResults whenever the data changes
watchWithCallback()
watchWithCallback(
sql,
parameters?,
handler?,
options?): void
Execute a read query every time the source tables are modified.
Use SQLOnChangeOptions.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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
handler? | WatchHandler | Callbacks for handling results and errors |
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
void
writeLock()
writeLock<T>(callback): Promise<T>
Takes a global lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.writeTransaction should be used instead.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
callback | (db) => Promise<T> |
Returns
Promise<T>
writeTransaction()
writeTransaction<T>(callback, lockTimeout?): Promise<T>
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 Transaction interface.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (tx) => Promise<T> | Function to execute within the transaction |
lockTimeout? | number | Time in milliseconds to wait for a lock before throwing an error |
Returns
Promise<T>
The result of the callback
Throws
Error if the lock cannot be obtained within the timeout period
CompilableQuery<T>
Type Parameters
| Type Parameter |
|---|
T |
Methods
compile()
compile(): CompiledQuery
Returns
execute()
execute(): Promise<T[]>
Returns
Promise<T[]>
CompilableQueryWatchHandler<T>
Type Parameters
| Type Parameter |
|---|
T |
Properties
| Property | Type |
|---|---|
onError? | (error: Error) => void |
onResult | (results: T[]) => void |
CompiledQuery
Properties
| Property | Modifier | Type |
|---|---|---|
parameters | readonly | readonly unknown[] |
sql | readonly | string |
CreateDiffTriggerOptions
Experimental Alpha
Options for TriggerManager#createDiffTrigger.
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
columns? | string[] | Alpha Columns to track and report changes for. Defaults to all columns in the source table. Use an empty array to track only the ID and operation. | BaseCreateDiffTriggerOptions.columns |
destination | string | Alpha Destination table to send changes to. This table is created internally as a SQLite temporary table. This table will be dropped once the trigger is removed. | - |
hooks? | TriggerCreationHooks | Alpha Hooks which allow execution during the trigger creation process. | BaseCreateDiffTriggerOptions.hooks |
setupContext? | LockContext | Alpha Context to use for the setup operation. This is useful for when the setup operation needs to be executed in a specific context. | - |
source | string | Alpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema. | BaseCreateDiffTriggerOptions.source |
useStorage? | boolean | Alpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed. | BaseCreateDiffTriggerOptions.useStorage |
when | Partial<Record<DiffTriggerOperation, string>> | Alpha Condition to filter when the triggers should fire. This corresponds to a SQLite WHEN clause in the trigger body. This is useful for only triggering on specific conditions. For example, you can use it to only trigger on certain values in the NEW row. Note that for PowerSync the row data is stored in a JSON column named data. The row id is available in the id column. NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL. Any user input strings here should be sanitized externally. The BaseCreateDiffTriggerOptions.when string template function performs some basic sanitization, extra external sanitization is recommended. Example { 'INSERT': sanitizeSQLjson_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}, 'INSERT': TRUE, 'UPDATE': sanitizeSQLNEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active', 'DELETE': sanitizeSQLjson_extract(OLD.data, '$.list_id') = 'abcd' } | BaseCreateDiffTriggerOptions.when |
CreateLoggerOptions
Properties
| Property | Type | Description |
|---|---|---|
minLevel | number | The minimum log level to consider for messages. Defaults to LogLevels.info. |
prefix | string | A prefix for messages emitted by createConsoleLogger to make them more recognizable. Defaults to 'PowerSync'. |
CrudEntry
A single client-side change.
Properties
| Property | Type | Description |
|---|---|---|
clientId | number | Auto-incrementing client-side id. |
id | string | ID of the changed row. |
metadata? | string | Client-side metadata attached with this write. This field is only available when the trackMetadata option was set to true when creating a table and the insert or update statement set the _metadata column. |
op | UpdateType | Type of change. |
opData? | Record<string, any> | Data associated with the change. |
previousValues? | Record<string, any> | For tables where the trackPreviousValues option has been enabled, this tracks previous values for UPDATE and DELETE statements. |
table | string | Table that contained the change. |
transactionId? | number | Auto-incrementing transaction id. This is the same for all operations within the same transaction. |
Methods
equals()
equals(entry): boolean
Parameters
| Parameter | Type |
|---|---|
entry | CrudEntry |
Returns
boolean
toComparisonArray()
toComparisonArray(): unknown[]
Generates an array for use in deep comparison operations
Returns
unknown[]
toJSON()
toJSON(): unknown
Converts the change to JSON format.
Returns
unknown
DBAdapterListener
Extends
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type | Description |
|---|---|---|
tablesUpdated | (updateNotification: BatchedUpdateNotification) => void | Listener for table updates. Allows for single table updates in order to maintain API compatibility without the need for a major version bump The DB adapter can also batch update notifications if supported. |
DBGetUtils
Extended by
Methods
get()
get<T>(sql, parameters?): Promise<T>
Execute a read-only query and return the first result, error if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T>
The first result matching the query
Throws
Error if no rows are returned
getAll()
getAll<T>(sql, parameters?): Promise<T[]>
Execute a read-only query and return results.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T[]>
An array of results
getOptional()
getOptional<T>(sql, parameters?): Promise<null | T>
Execute a read-only query and return the first result, or null if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<null | T>
The first result if found, or null if no results are returned
DBLockOptions
Properties
| Property | Type |
|---|---|
timeoutMs? | number |
DifferentialWatchedQueryComparator<RowType>
Row comparator for differentially watched queries which keys and compares items in the result set.
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Description |
|---|---|---|
compareBy | (item: RowType) => string | Generates a token for comparing items with matching keys. |
keyBy | (item: RowType) => string | Generates a unique key for the item. |
DifferentialWatchedQueryListener<RowType>
Extends
WatchedQueryListener<ReadonlyArray<Readonly<RowType>>>
Type Parameters
| Type Parameter |
|---|
RowType |
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type | Inherited from |
|---|---|---|
closed? | () => void | Promise<void> | WatchedQueryListener.closed |
onData? | (data: readonly Readonly<RowType>[]) => void | Promise<void> | WatchedQueryListener.onData |
onDiff? | (diff: WatchedQueryDifferential<RowType>) => void | Promise<void> | - |
onError? | (error: Error) => void | Promise<void> | WatchedQueryListener.onError |
onStateChange? | (state: WatchedQueryState<readonly Readonly<RowType>[]>) => void | Promise<void> | WatchedQueryListener.onStateChange |
settingsWillUpdate? | () => void | WatchedQueryListener.settingsWillUpdate |
DifferentialWatchedQueryOptions<RowType>
Options for building a differential watched query with the Query builder.
Extends
Extended by
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
placeholderData? | RowType[] | Initial result data which is presented while the initial loading is executing. | - |
reportFetching? | boolean | If true (default) the watched query will update its state to report on the fetching state of the query. Setting to false reduces the number of state changes if the fetch status is not relevant to the consumer. | WatchedQueryOptions.reportFetching |
rowComparator? | DifferentialWatchedQueryComparator<RowType> | Row comparator used to identify and compare rows in the result set. If not provided, the default comparator will be used which keys items by their id property if available, otherwise it uses JSON stringification of the entire item for keying and comparison. | - |
throttleMs? | number | The minimum interval between queries. | WatchedQueryOptions.throttleMs |
triggerOnTables? | string[] | By default, watched queries requery the database on any change to any dependent table of the query. Supplying an override here can be used to limit the tables which trigger querying the database. | WatchedQueryOptions.triggerOnTables |
DifferentialWatchedQuerySettings<RowType>
Settings for differential incremental watched queries using.
Extends
DifferentialWatchedQueryOptions<RowType>
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
placeholderData? | RowType[] | Initial result data which is presented while the initial loading is executing. | DifferentialWatchedQueryOptions.placeholderData |
query | WatchCompatibleQuery<RowType[]> | The query here must return an array of items that can be differentiated. | - |
reportFetching? | boolean | If true (default) the watched query will update its state to report on the fetching state of the query. Setting to false reduces the number of state changes if the fetch status is not relevant to the consumer. | DifferentialWatchedQueryOptions.reportFetching |
rowComparator? | DifferentialWatchedQueryComparator<RowType> | Row comparator used to identify and compare rows in the result set. If not provided, the default comparator will be used which keys items by their id property if available, otherwise it uses JSON stringification of the entire item for keying and comparison. | DifferentialWatchedQueryOptions.rowComparator |
throttleMs? | number | The minimum interval between queries. | DifferentialWatchedQueryOptions.throttleMs |
triggerOnTables? | string[] | By default, watched queries requery the database on any change to any dependent table of the query. Supplying an override here can be used to limit the tables which trigger querying the database. | DifferentialWatchedQueryOptions.triggerOnTables |
DisconnectAndClearOptions
Properties
| Property | Type | Description |
|---|---|---|
clearLocal? | boolean | When set to false, data in local-only tables is preserved. |
Disposable
Properties
| Property | Type |
|---|---|
dispose | () => void | Promise<void> |
IndexColumnOptions
Properties
| Property | Type |
|---|---|
ascending? | boolean |
name | string |
IndexOptions
Properties
| Property | Type |
|---|---|
columns? | IndexedColumn[] |
name | string |
ListenerMetaManager<Listener>
Extends
BaseObserverInterface<MetaListener<Listener>>
Type Parameters
| Type Parameter |
|---|
Listener extends BaseListener |
Properties
| Property | Type |
|---|---|
counts | ListenerCounts<Listener> |
Methods
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<MetaListener<Listener>> |
Returns
Function
Returns
void
Inherited from
BaseObserverInterface.registerListener
LocalStorageAdapter
Experimental Alpha
LocalStorageAdapter defines the interface for local file storage operations. Implementations handle file I/O, directory management, and storage initialization.
This is currently experimental and may change without a major version bump.
Methods
clear()
clear(): Promise<void>
Alpha
Returns
Promise<void>
deleteFile()
deleteFile(filePath): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<void>
fileExists()
fileExists(filePath): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<boolean>
True if the file exists, false otherwise
getLocalUri()
getLocalUri(filename): string
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filename | string | The filename to get the path for |
Returns
string
The full file path
initialize()
initialize(): Promise<void>
Alpha
Returns
Promise<void>
makeDir()
makeDir(path): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The full path to the directory |
Returns
Promise<void>
readFile()
readFile(filePath): Promise<ArrayBuffer>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<ArrayBuffer>
ArrayBuffer containing the file data
rmDir()
rmDir(path): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The full path to the directory |
Returns
Promise<void>
saveFile()
saveFile(filePath, data): Promise<number>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file will be stored |
data | AttachmentData | Data to store (ArrayBuffer, Blob, or string) |
Returns
Promise<number>
Number of bytes written
LogRecord
A log record passed to a PowerSyncLogger.
Properties
| Property | Type | Description |
|---|---|---|
error? | unknown | When the log message contains an error, the error causing the log. This is not guaranteed to be an Error instance. On the web, we might have to serialize objects across message channels and represent them as a string. |
level | number | The log level (see LogLevels for preconfigured values) for the message. Depending on how a receiving logger has been configured, messages below a configured minimum level may be ignored. |
message | string | The main message to log. |
MetaBaseObserverInterface<Listener>
Extends
BaseObserverInterface<Listener>
Extended by
Type Parameters
| Type Parameter |
|---|
Listener extends BaseListener |
Properties
| Property | Type |
|---|---|
listenerMeta | ListenerMetaManager<Listener> |
Methods
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<Listener> |
Returns
Function
Returns
void
Inherited from
BaseObserverInterface.registerListener
MetaListener<ParentListener>
Meta listener which reports the counts of listeners for each event type.
Extends
Type Parameters
| Type Parameter |
|---|
ParentListener extends BaseListener |
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type |
|---|---|
listenersChanged? | (counts: ListenerCounts<ParentListener>) => void |
Mutex
Internal
This is implemented in @powersync/shared-internals, but we need it in the attachment service
implementation.
Methods
runExclusive()
runExclusive<T>(fn, abort?): Promise<T>
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
fn | () => T | PromiseLike<T> |
abort? | AbortSignal |
Returns
Promise<T>
PowerSyncBackendConnector
Properties
| Property | Type | Description |
|---|---|---|
fetchCredentials | () => Promise<null | PowerSyncCredentials> | Allows the PowerSync client to retrieve an authentication token from your backend which is used to authenticate against the PowerSync service. This should always fetch a fresh set of credentials - don't use cached values. Return null if the user is not signed in. Throw an error if credentials cannot be fetched due to a network error or other temporary error. This token is kept for the duration of a sync connection. |
uploadData | (database: CommonPowerSyncDatabase) => Promise<void> | Upload local changes to the app backend. Use CommonPowerSyncDatabase.getCrudBatch to get a batch of changes to upload. Any thrown errors will result in a retry after the configured wait period (default: 5 seconds). |
PowerSyncCloseOptions
Properties
| Property | Type | Description |
|---|---|---|
disconnect? | boolean | 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. |
PowerSyncCredentials
Properties
| Property | Type |
|---|---|
endpoint | string |
expiresAt? | Date |
token | string |
PowerSyncDatabase
Extends
Properties
| Property | Modifier | Type | Description | Inherited from |
|---|---|---|---|---|
closed | readonly | boolean | Returns true if the connection is closed. | CommonPowerSyncDatabase.closed |
currentStatus | readonly | SyncStatus | Current connection status. | CommonPowerSyncDatabase.currentStatus |
execute | public | <T>(query: string, params?: any[]) => Promise<QueryResult<T>> | Execute a SQL write (INSERT/UPDATE/DELETE) query and optionally return results. When using the default client-side JSON-based view system, the returned result's rowsAffected may be 0 for successful UPDATE and DELETE statements. Use a RETURNING clause and inspect result.rows when you need to confirm which rows changed. | CommonPowerSyncDatabase.execute |
executeBatch | public | (query: string, params?: any[][]) => Promise<QueryResult<never>> | 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. | CommonPowerSyncDatabase.executeBatch |
executeRaw | public | (query: string, params?: any[]) => Promise<RawQueryResult> | 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. | CommonPowerSyncDatabase.executeRaw |
logger | readonly | PowerSyncLogger | - | CommonPowerSyncDatabase.logger |
ready | readonly | boolean | - | CommonPowerSyncDatabase.ready |
schema | readonly | Schema | Schema used for the local database. | CommonPowerSyncDatabase.schema |
sdkVersion | readonly | string | - | CommonPowerSyncDatabase.sdkVersion |
triggers | readonly | TriggerManager | Experimental Alpha Allows creating SQLite triggers which can be used to track various operations on SQLite tables. | CommonPowerSyncDatabase.triggers |
Accessors
connected
Get Signature
get connected(): boolean
Whether a connection to the PowerSync service is currently open.
Returns
boolean
Inherited from
CommonPowerSyncDatabase.connected
connecting
Get Signature
get connecting(): boolean
Returns
boolean
Inherited from
CommonPowerSyncDatabase.connecting
database
Get Signature
get database(): DBAdapter
The underlying database.
For the most part, behavior is the same whether querying on the underlying database, or on CommonPowerSyncDatabase.
Returns
Inherited from
CommonPowerSyncDatabase.database
Methods
close()
close(options?): Promise<void>
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.
Parameters
| Parameter | Type |
|---|---|
options? | PowerSyncCloseOptions |
Returns
Promise<void>
Inherited from
connect()
connect(connector, options?): Promise<void>
Connects to stream of events from the PowerSync instance.
Parameters
| Parameter | Type |
|---|---|
connector | PowerSyncBackendConnector |
options? | SyncOptions |
Returns
Promise<void>
Inherited from
CommonPowerSyncDatabase.connect
createMutex()
createMutex(): Mutex
Internal
Returns
Inherited from
CommonPowerSyncDatabase.createMutex
customQuery()
customQuery<RowType>(query): Query<RowType>
Allows building a WatchedQuery using an existing WatchCompatibleQuery. The watched query will use the provided WatchCompatibleQuery.execute method to query results.
Type Parameters
| Type Parameter |
|---|
RowType |
Parameters
| Parameter | Type |
|---|---|
query | WatchCompatibleQuery<RowType[]> |
Returns
Query<RowType>
Example
// Potentially a query from an ORM like Drizzle
const query = db.select().from(lists);
const watchedTodos = powersync.customQuery(query)
.watch()
// OR use .differentialWatch() for fine-grained watches.
Inherited from
CommonPowerSyncDatabase.customQuery
disconnect()
disconnect(): Promise<void>
Close the sync connection.
Use CommonPowerSyncDatabase.connect to connect again.
Returns
Promise<void>
Inherited from
CommonPowerSyncDatabase.disconnect
disconnectAndClear()
disconnectAndClear(options?): Promise<void>
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.
Parameters
| Parameter | Type |
|---|---|
options? | DisconnectAndClearOptions |
Returns
Promise<void>
Inherited from
CommonPowerSyncDatabase.disconnectAndClear
get()
get<T>(sql, parameters?): Promise<T>
Execute a read-only query and return the first result, error if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T>
The first result matching the query
Throws
Error if no rows are returned
Inherited from
getAll()
getAll<T>(sql, parameters?): Promise<T[]>
Execute a read-only query and return results.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<T[]>
An array of results
Inherited from
CommonPowerSyncDatabase.getAll
getClientId()
getClientId(): Promise<string>
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
Promise<string>
A unique identifier for the database instance
Inherited from
CommonPowerSyncDatabase.getClientId
getCrudBatch()
getCrudBatch(limit?): Promise<null | CrudBatch>
Get a batch of CRUD data to upload.
Returns null if there is no data to upload.
Use this from the PowerSyncBackendConnector.uploadData callback.
Once the data have been successfully uploaded, call CrudBatch.complete before requesting the next batch.
Use the limit parameter 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
limit? | number | Maximum number of CRUD entries to include in the batch |
Returns
Promise<null | CrudBatch>
A batch of CRUD operations to upload, or null if there are none
Inherited from
CommonPowerSyncDatabase.getCrudBatch
getCrudTransactions()
getCrudTransactions(): AsyncIterable<CrudTransaction, null>
Returns an async iterator of completed transactions with local writes against the database.
This is typically used from the PowerSyncBackendConnector.uploadData callback. Each entry emitted by the returned iterator is a full transaction containing all local writes made while that transaction was active.
Unlike CommonPowerSyncDatabase.getNextCrudTransaction, which always returns the oldest transaction that hasn't been CrudTransaction.completed yet, this iterator can be used to receive multiple transactions. Calling CrudTransaction.complete will mark that and all prior transactions emitted by the iterator as completed.
This can be used to upload multiple transactions in a single batch, e.g with:
let lastTransaction = null;
let batch = [];
for await (const transaction of database.getCrudTransactions()) {
batch.push(...transaction.crud);
lastTransaction = transaction;
if (batch.length > 10) {
break;
}
}
If there is no local data to upload, the async iterator complete without emitting any items.
Note that iterating over async iterables requires a polyfill for React Native.
Returns
AsyncIterable<CrudTransaction, null>
Inherited from
CommonPowerSyncDatabase.getCrudTransactions
getNextCrudTransaction()
getNextCrudTransaction(): Promise<null | CrudTransaction>
Get the next recorded transaction to upload.
Returns null if there is no data to upload.
Use this from the PowerSyncBackendConnector.uploadData callback.
Once the data have been successfully uploaded, call CrudTransaction.complete before requesting the next transaction.
Unlike CommonPowerSyncDatabase.getCrudBatch, this only returns data from a single transaction at a time. All data for the transaction is loaded into memory.
Returns
Promise<null | CrudTransaction>
A transaction of CRUD operations to upload, or null if there are none
Inherited from
CommonPowerSyncDatabase.getNextCrudTransaction
getOptional()
getOptional<T>(sql, parameters?): Promise<null | T>
Execute a read-only query and return the first result, or null if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<null | T>
The first result if found, or null if no results are returned
Inherited from
CommonPowerSyncDatabase.getOptional
getUploadQueueStats()
getUploadQueueStats(includeSize?): Promise<UploadQueueStats>
Get upload queue size estimate and count.
Parameters
| Parameter | Type |
|---|---|
includeSize? | boolean |
Returns
Promise<UploadQueueStats>
Inherited from
CommonPowerSyncDatabase.getUploadQueueStats
init()
init(): Promise<void>
Wait for initialization to complete. While initializing is automatic, this helps to catch and report initialization errors.
Returns
Promise<void>
Inherited from
onChange()
Call Signature
onChange(options?): AsyncIterable<WatchOnChangeEvent>
This version of onChange uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.onChangeWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.onChangeWithCallback.
Parameters
| Parameter | Type |
|---|---|
options? | SQLOnChangeOptions |
Returns
AsyncIterable<WatchOnChangeEvent>
Example
async monitorChanges() {
for await (const event of this.powersync.onChange({tables: ['todos']})) {
console.log('Detected change event:', event);
}
}
Inherited from
CommonPowerSyncDatabase.onChange
Call Signature
onChange(handler?, options?): () => void
See CommonPowerSyncDatabase.onChangeWithCallback.
Parameters
| Parameter | Type |
|---|---|
handler? | WatchOnChangeHandler |
options? | SQLOnChangeOptions |
Returns
Function
Returns
void
Example
monitorChanges() {
this.powersync.onChange({
onChange: (event) => {
console.log('Change detected:', event);
}
}, { tables: ['todos'] });
}
Inherited from
CommonPowerSyncDatabase.onChange
onChangeWithAsyncGenerator()
onChangeWithAsyncGenerator(options?): AsyncIterable<WatchOnChangeEvent>
Create a Stream of changes to any of the specified tables.
This is preferred over CommonPowerSyncDatabase.watchWithAsyncGenerator when multiple queries need to be performed together when data is changed.
Note: do not declare this as async *onChange as it will not work in React Native.
Parameters
| Parameter | Type | Description |
|---|---|---|
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
AsyncIterable<WatchOnChangeEvent>
An AsyncIterable that yields change events whenever the specified tables change
Inherited from
CommonPowerSyncDatabase.onChangeWithAsyncGenerator
onChangeWithCallback()
onChangeWithCallback(handler?, options?): () => void
Invoke the provided callback on any changes to any of the specified tables.
This is preferred over CommonPowerSyncDatabase.watchWithCallback when multiple queries need to be performed together when data is changed.
Note that the onChange callback member of the handler is required.
Parameters
| Parameter | Type | Description |
|---|---|---|
handler? | WatchOnChangeHandler | Callbacks for handling change events and errors |
options? | SQLOnChangeOptions | Options for configuring watch behavior |
Returns
Function
A dispose function to stop watching for changes
Returns
void
Inherited from
CommonPowerSyncDatabase.onChangeWithCallback
query()
query<RowType>(query): Query<RowType>
Allows defining a query which can be used to build a WatchedQuery. The defined query will be executed with CommonPowerSyncDatabase#getAll. An optional mapper function can be provided to transform the results.
Type Parameters
| Type Parameter |
|---|
RowType |
Parameters
| Parameter | Type |
|---|---|
query | ArrayQueryDefinition<RowType> |
Returns
Query<RowType>
Example
const watchedTodos = powersync.query({
sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
parameters: [],
mapper: (row) => ({
...row,
created_at: new Date(row.created_at as string)
})
})
.watch()
// OR use .differentialWatch() for fine-grained watches.
Inherited from
readLock()
readLock<T>(callback): Promise<T>
Takes a read lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.readTransaction should be used instead.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
callback | (db) => Promise<T> |
Returns
Promise<T>
Inherited from
CommonPowerSyncDatabase.readLock
readTransaction()
readTransaction<T>(callback, lockTimeout?): Promise<T>
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.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (tx) => Promise<T> | Function to execute within the transaction |
lockTimeout? | number | Time in milliseconds to wait for a lock before throwing an error |
Returns
Promise<T>
The result of the callback
Throws
Error if the lock cannot be obtained within the timeout period
Inherited from
CommonPowerSyncDatabase.readTransaction
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<PowerSyncDBListener> |
Returns
Function
Returns
void
Inherited from
CommonPowerSyncDatabase.registerListener
resolveTables()
resolveTables(
sql,
parameters?,
options?): Promise<string[]>
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to analyze |
parameters? | any[] | Optional parameters for the SQL query |
options? | SQLWatchOptions | Optional watch options that may contain explicit table list |
Returns
Promise<string[]>
Array of table names that the query depends on
Inherited from
CommonPowerSyncDatabase.resolveTables
syncStream()
syncStream(name, params?): SyncStream
Create a sync stream to query its status or to subscribe to it.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the stream to subscribe to. |
params? | Record<string, any> | Optional parameters for the stream subscription. |
Returns
A SyncStream instance that can be subscribed to.
Inherited from
CommonPowerSyncDatabase.syncStream
updateSchema()
updateSchema(schema): Promise<void>
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 CommonPowerSyncDatabase.connect.
Parameters
| Parameter | Type |
|---|---|
schema | Schema |
Returns
Promise<void>
Inherited from
CommonPowerSyncDatabase.updateSchema
waitForFirstSync()
waitForFirstSync(request?): Promise<void>
Wait for the first sync operation to complete.
Parameters
| Parameter | Type | Description |
|---|---|---|
request? | | AbortSignal | { priority: number; signal: AbortSignal; } | 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
Promise<void>
A promise which will resolve once the first full sync has completed.
Inherited from
CommonPowerSyncDatabase.waitForFirstSync
waitForReady()
waitForReady(): Promise<void>
Returns
Promise<void>
A promise which will resolve once initialization is completed.
Inherited from
CommonPowerSyncDatabase.waitForReady
waitForStatus()
waitForStatus(predicate, signal?): Promise<void>
Waits for the first sync status for which the status callback returns a truthy value.
Parameters
| Parameter | Type |
|---|---|
predicate | (status) => any |
signal? | AbortSignal |
Returns
Promise<void>
Inherited from
CommonPowerSyncDatabase.waitForStatus
watch()
Call Signature
watch(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>
This version of watch uses AsyncGenerator, for documentation see CommonPowerSyncDatabase.watchWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see CommonPowerSyncDatabase.watchWithCallback.
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
options? | SQLWatchOptions |
Returns
AsyncIterable<QueryResult<SqliteRecord>>
Example
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) ?? [];
}
}
Inherited from
Call Signature
watch(
sql,
parameters?,
handler?,
options?): void
See CommonPowerSyncDatabase.watchWithCallback.
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
handler? | WatchHandler |
options? | SQLWatchOptions |
Returns
void
Example
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) ?? [])
}
);
}
Inherited from
watchWithAsyncGenerator()
watchWithAsyncGenerator(
sql,
parameters?,
options?): AsyncIterable<QueryResult<SqliteRecord>>
Execute a read query every time the source tables are modified.
Use SQLOnChangeOptions.throttleMs to specify the minimum interval between queries.
Source tables are automatically detected using EXPLAIN QUERY PLAN.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
AsyncIterable<QueryResult<SqliteRecord>>
An AsyncIterable that yields QueryResults whenever the data changes
Inherited from
CommonPowerSyncDatabase.watchWithAsyncGenerator
watchWithCallback()
watchWithCallback(
sql,
parameters?,
handler?,
options?): void
Execute a read query every time the source tables are modified.
Use SQLOnChangeOptions.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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
handler? | WatchHandler | Callbacks for handling results and errors |
options? | SQLWatchOptions | Options for configuring watch behavior |
Returns
void
Inherited from
CommonPowerSyncDatabase.watchWithCallback
writeLock()
writeLock<T>(callback): Promise<T>
Takes a global lock, without starting a transaction. In most cases, CommonPowerSyncDatabase.writeTransaction should be used instead.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
callback | (db) => Promise<T> |
Returns
Promise<T>
Inherited from
CommonPowerSyncDatabase.writeLock
writeTransaction()
writeTransaction<T>(callback, lockTimeout?): Promise<T>
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 Transaction interface.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type | Description |
|---|---|---|
callback | (tx) => Promise<T> | Function to execute within the transaction |
lockTimeout? | number | Time in milliseconds to wait for a lock before throwing an error |
Returns
Promise<T>
The result of the callback
Throws
Error if the lock cannot be obtained within the timeout period
Inherited from
CommonPowerSyncDatabase.writeTransaction
PowerSyncDatabaseConstructor<Options>
Type Parameters
| Type Parameter |
|---|
Options |
Constructors
new PowerSyncDatabaseConstructor()
new PowerSyncDatabaseConstructor(options): CommonPowerSyncDatabase
Parameters
| Parameter | Type |
|---|---|
options | Options |
Returns
PowerSyncDBListener
Extends
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type |
|---|---|
closed | () => void | Promise<void> |
closing | () => void | Promise<void> |
initialized | () => void |
schemaChanged | (schema: Schema) => void |
statusChanged? | (status: SyncStatus) => void |
PowerSyncFetchImplementation
Properties
Methods
run()
run(options): Promise<Response>
Parameters
| Parameter | Type |
|---|---|
options | FetchOptions |
Returns
Promise<Response>
PowerSyncLogger
A logger used by the PowerSync SDK.
This is deliberately a very simple interface, and it's not a designed to be a general-purpose logger you would use in your application. Instead, you can provide an implementation of this to PowerSync to make it use your preferred logging libraries.
By default, the SDK uses a createConsoleLogger instance forwarding messages to console.log.
Methods
log()
log(record): void
Parameters
| Parameter | Type |
|---|---|
record | LogRecord |
Returns
void
ProgressWithOperations
Information about a progressing download made by the PowerSync SDK.
To obtain these values, use SyncProgress, available through SyncStatus#downloadProgress.
Extended by
Properties
| Property | Type | Description |
|---|---|---|
downloadedFraction | number | Relative progress, as ProgressWithOperations.downloadedOperations of ProgressWithOperations.totalOperations. This will be a number between 0.0 and 1.0 (inclusive). When this number reaches 1.0, all changes have been received from the sync service. Actually applying these changes happens before the downloadProgress field is cleared from SyncStatus, so progress can stay at 1.0 for a short while before completing. |
downloadedOperations | number | The amount of operations that have already been downloaded. |
totalOperations | number | The total amount of operations to download for the current sync iteration to complete. |