abstract AbstractPowerSyncDatabase
Extends
Extended by
Constructors
new AbstractPowerSyncDatabase()
new AbstractPowerSyncDatabase(options): AbstractPowerSyncDatabase
Parameters
| Parameter | Type |
|---|---|
options | PowerSyncDatabaseOptionsWithDBAdapter |
Returns
Overrides
new AbstractPowerSyncDatabase()
new AbstractPowerSyncDatabase(options): AbstractPowerSyncDatabase
Parameters
| Parameter | Type |
|---|---|
options | PowerSyncDatabaseOptionsWithOpenFactory |
Returns
Overrides
BaseObserver<PowerSyncDBListener>.constructor
new AbstractPowerSyncDatabase()
new AbstractPowerSyncDatabase(options): AbstractPowerSyncDatabase
Parameters
| Parameter | Type |
|---|---|
options | PowerSyncDatabaseOptionsWithSettings |
Returns
Overrides
BaseObserver<PowerSyncDBListener>.constructor
new AbstractPowerSyncDatabase()
new AbstractPowerSyncDatabase(options): AbstractPowerSyncDatabase
Parameters
| Parameter | Type |
|---|---|
options | PowerSyncDatabaseOptions |
Returns
Overrides
BaseObserver<PowerSyncDBListener>.constructor
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
closed | public | boolean | Returns true if the connection is closed. |
currentStatus | public | SyncStatus | Current connection status. |
logger | public | ILogger | - |
ready | public | boolean | - |
sdkVersion | public | string | - |
triggers | readonly | TriggerManager | Experimental 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
connectionOptions
Get Signature
get connectionOptions():
| null
| InternalConnectionOptions
The resolved connection options used to connect to the PowerSync service.
Returns
| null
| InternalConnectionOptions
The resolved connection options used to connect to the PowerSync service or null if connect() has not been called.
connector
Get Signature
get connector():
| null
| PowerSyncBackendConnector
The connector used to connect to the PowerSync service.
Returns
| null
| PowerSyncBackendConnector
The connector used to connect to the PowerSync service or null if connect() has not been called.
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 AbstractPowerSyncDatabase.
Returns
schema
Get Signature
get schema(): Schema<{}>
Schema used for the local database.
Returns
Schema<{}>
syncStreamImplementation
Get Signature
get syncStreamImplementation():
| null
| StreamingSyncImplementation
Returns
| null
| StreamingSyncImplementation
Methods
_initialize()
abstract _initialize(): Promise<void>
Allows for extended implementations to execute custom initialization logic as part of the total init process
Returns
Promise<void>
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? | PowerSyncConnectionOptions |
Returns
Promise<void>
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 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>
dispose()
dispose(): void
Returns
void
Deprecated
Use AbstractPowerSyncDatabase#close instead. Clears all listeners registered by AbstractPowerSyncDatabase#registerListener.
Overrides
execute()
execute(sql, parameters?): Promise<QueryResult>
Execute a SQL write (INSERT/UPDATE/DELETE) query and optionally return results.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<QueryResult>
The query result as an object with structured key-value pairs
executeBatch()
executeBatch(sql, parameters?): Promise<QueryResult>
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[][] | Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution |
Returns
Promise<QueryResult>
The query result
executeRaw()
executeRaw(sql, parameters?): Promise<any[][]>
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
sql | string | The SQL query to execute |
parameters? | any[] | Optional array of parameters to bind to the query |
Returns
Promise<any[][]>
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.
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
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 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.
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 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 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
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>
iterateAsyncListeners()
iterateAsyncListeners(cb): Promise<void>
Parameters
| Parameter | Type |
|---|---|
cb | (listener) => Promise<any> |
Returns
Promise<void>
Inherited from
BaseObserver.iterateAsyncListeners
iterateListeners()
iterateListeners(cb): void
Parameters
| Parameter | Type |
|---|---|
cb | (listener) => any |
Returns
void
Inherited from
onChange()
Call Signature
onChange(options?): AsyncIterable<WatchOnChangeEvent>
This version of onChange uses AsyncGenerator, for documentation see onChangeWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see 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 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 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 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 AbstractPowerSyncDatabase#getAll. An optional mapper function can be provided to transform the results.
Type Parameters
| Type Parameter |
|---|
RowType |
Parameters
| Parameter | Type |
|---|---|
query | ArrayQueryDefinition<RowType> |