PowerSyncDatabase
A PowerSync database which provides SQLite functionality which is automatically synced.
Example
export const db = new PowerSyncDatabase({
schema: AppSchema,
database: {
dbFilename: 'example.db'
}
});
Extends
Constructors
new PowerSyncDatabase()
new PowerSyncDatabase(options): PowerSyncDatabase
Parameters
Parameter | Type |
---|---|
options | NodePowerSyncDatabaseOptions |
Returns
Overrides
AbstractPowerSyncDatabase
.constructor
Properties
Property | Type | Description | Inherited from |
---|---|---|---|
closed | boolean | Returns true if the connection is closed. | AbstractPowerSyncDatabase .closed |
currentStatus | SyncStatus | Current connection status. | AbstractPowerSyncDatabase .currentStatus |
ready | boolean | - | AbstractPowerSyncDatabase .ready |
sdkVersion | string | - | AbstractPowerSyncDatabase .sdkVersion |
syncStreamImplementation? | StreamingSyncImplementation | - | AbstractPowerSyncDatabase .syncStreamImplementation |
Accessors
connected
Get Signature
get connected(): boolean
Whether a connection to the PowerSync service is currently open.
Returns
boolean
Inherited from
AbstractPowerSyncDatabase
.connected
connecting
Get Signature
get connecting(): boolean
Returns
boolean
Inherited from
AbstractPowerSyncDatabase
.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 AbstractPowerSyncDatabase.
Returns
Inherited from
AbstractPowerSyncDatabase
.database
schema
Get Signature
get schema(): Schema<{}>
Schema used for the local database.
Returns
Schema
<{}>
Inherited from
AbstractPowerSyncDatabase
.schema
Methods
_initialize()
_initialize(): Promise<void>
Allows for extended implementations to execute custom initialization logic as part of the total init process
Returns
Promise
<void
>
Overrides
AbstractPowerSyncDatabase
._initialize
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
AbstractPowerSyncDatabase
.close
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
>
Inherited from
AbstractPowerSyncDatabase
.connect
disconnect()
disconnect(): Promise<void>
Close the sync connection.
Use connect to connect again.
Returns
Promise
<void
>
Inherited from
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.disconnectAndClear
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
Inherited from
AbstractPowerSyncDatabase
.execute
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
Inherited from
AbstractPowerSyncDatabase
.executeBatch
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.
Inherited from
AbstractPowerSyncDatabase
.executeRaw
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
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.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 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
Inherited from
AbstractPowerSyncDatabase
.getCrudBatch
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
Inherited from
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.getOptional
getUploadQueueStats()
getUploadQueueStats(includeSize?): Promise<UploadQueueStats>
Get upload queue size estimate and count.
Parameters
Parameter | Type |
---|---|
includeSize ? | boolean |
Returns
Promise
<UploadQueueStats
>
Inherited from
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.init
iterateAsyncListeners()
iterateAsyncListeners(cb): Promise<void>
Parameters
Parameter | Type |
---|---|
cb | (listener ) => Promise <any > |
Returns
Promise
<void
>
Inherited from
AbstractPowerSyncDatabase
.iterateAsyncListeners
iterateListeners()
iterateListeners(cb): void
Parameters
Parameter | Type |
---|---|
cb | (listener ) => any |
Returns
void
Inherited from
AbstractPowerSyncDatabase
.iterateListeners
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 ? | SQLWatchOptions |
Returns
AsyncIterable
<WatchOnChangeEvent
>
Example
async monitorChanges() {
for await (const event of this.powersync.onChange({tables: ['todos']})) {
console.log('Detected change event:', event);
}
}
Inherited from
AbstractPowerSyncDatabase
.onChange
Call Signature
onChange(handler?, options?): () => void
See onChangeWithCallback.
Parameters
Parameter | Type |
---|---|
handler ? | WatchOnChangeHandler |
options ? | SQLWatchOptions |
Returns
Function
Returns
void
Example
monitorChanges() {
this.powersync.onChange({
onChange: (event) => {
console.log('Change detected:', event);
}
}, { tables: ['todos'] });
}
Inherited from
AbstractPowerSyncDatabase
.onChange
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
Inherited from
AbstractPowerSyncDatabase
.onChangeWithAsyncGenerator
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 ? | SQLWatchOptions | Options for configuring watch behavior |
Returns
Function
A dispose function to stop watching for changes
Returns
void
Inherited from
AbstractPowerSyncDatabase
.onChangeWithCallback
readLock()
readLock<T>(callback): Promise<T>
Takes a read lock, without starting a transaction. In most cases, readTransaction should be used instead.
Type Parameters
Type Parameter |
---|
T |
Parameters
Parameter | Type |
---|---|
callback | (db ) => Promise <T > |
Returns
Promise
<T
>
Inherited from
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.readTransaction
registerListener()
registerListener(listener): () => void
Register a listener for updates to the PowerSync client.
Parameters
Parameter | Type |
---|---|
listener | Partial <PowerSyncDBListener > |
Returns
Function
Returns
void
Inherited from
AbstractPowerSyncDatabase
.registerListener
resolvedConnectionOptions()
resolvedConnectionOptions(options?): Required<AdditionalConnectionOptions>
Parameters
Parameter | Type |
---|---|
options ? | PowerSyncConnectionOptions |
Returns
Required
<AdditionalConnectionOptions
>
Inherited from
AbstractPowerSyncDatabase
.resolvedConnectionOptions
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
AbstractPowerSyncDatabase
.resolveTables
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 AbstractPowerSyncDatabase.connect.
Parameters
Parameter | Type |
---|---|
schema | Schema |
Returns
Promise
<void
>
Inherited from
AbstractPowerSyncDatabase
.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
AbstractPowerSyncDatabase
.waitForFirstSync
waitForReady()
waitForReady(): Promise<void>
Returns
Promise
<void
>
A promise which will resolve once initialization is completed.
Inherited from
AbstractPowerSyncDatabase
.waitForReady
watch()
Call Signature
watch(
sql,
parameters?,
options?): AsyncIterable<QueryResult>
This version of watch
uses AsyncGenerator, for documentation see watchWithAsyncGenerator.
Can be overloaded to use a callback handler instead, for documentation see watchWithCallback.
Parameters
Parameter | Type |
---|---|
sql | string |
parameters ? | any [] |
options ? | SQLWatchOptions |
Returns
AsyncIterable
<QueryResult
>
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
AbstractPowerSyncDatabase
.watch
Call Signature
watch(
sql,
parameters?,
handler?,
options?): void
See 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
AbstractPowerSyncDatabase
.watch
watchWithAsyncGenerator()
watchWithAsyncGenerator(
sql,
parameters?,
options?): AsyncIterable<QueryResult>
Execute a read query every time the source tables are modified.
Use SQLWatchOptions.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
>
An AsyncIterable that yields QueryResults whenever the data changes
Inherited from
AbstractPowerSyncDatabase
.watchWithAsyncGenerator
watchWithCallback()
watchWithCallback(
sql,
parameters?,
handler?,
options?): void
Execute a read query every time the source tables are modified.
Use SQLWatchOptions.throttleMs to specify the minimum interval between queries.
Source tables are automatically detected using EXPLAIN QUERY PLAN
.
Note that the onChange
callback member of the handler is required.
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
AbstractPowerSyncDatabase
.watchWithCallback
writeLock()
writeLock<T>(callback): Promise<T>
Takes a global lock, without starting a transaction. In most cases, writeTransaction should be used instead.
Type Parameters
Type Parameter |
---|
T |
Parameters
Parameter | Type |
---|---|
callback | (db ) => Promise <T > |
Returns
Promise
<T
>
Inherited from
AbstractPowerSyncDatabase
.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