PowerSyncDatabase
Extends
Constructors
new PowerSyncDatabase(options)
new PowerSyncDatabase(
options
):PowerSyncDatabase
Parameters
Parameter | Type |
---|---|
options | WebPowerSyncDatabaseOptions |
Returns
Overrides
AbstractPowerSyncDatabase
.constructor
Source
packages/web/src/db/PowerSyncDatabase.ts:53
Properties
Property | Modifier | Type | Description | Inherited from |
---|---|---|---|---|
_isReadyPromise | protected | Promise < void > | - | AbstractPowerSyncDatabase ._isReadyPromise |
_schema | protected | Schema < SchemaType > | - | AbstractPowerSyncDatabase ._schema |
bucketStorageAdapter | protected | BucketStorageAdapter | - | AbstractPowerSyncDatabase .bucketStorageAdapter |
closed | public | boolean | Returns true if the connection is closed. | AbstractPowerSyncDatabase .closed |
currentStatus | public | SyncStatus | Current connection status. | AbstractPowerSyncDatabase .currentStatus |
listeners | protected | Set < Partial < PowerSyncDBListener > > | - | AbstractPowerSyncDatabase .listeners |
options | protected | WebPowerSyncDatabaseOptions | - | AbstractPowerSyncDatabase .options |
ready | public | boolean | - | AbstractPowerSyncDatabase .ready |
sdkVersion | public | string | - | AbstractPowerSyncDatabase .sdkVersion |
syncStreamImplementation? | public | StreamingSyncImplementation | - | AbstractPowerSyncDatabase .syncStreamImplementation |
unloadListener? | protected | () => Promise < void > | - | - |
SHARED_MUTEX | static | Mutex | - | - |
transactionMutex | static | Mutex | Transactions should be queued in the DBAdapter, but we also want to prevent calls to .execute while an async transaction is running. | AbstractPowerSyncDatabase .transactionMutex |
Accessors
connected
get
connected():boolean
Whether a connection to the PowerSync service is currently open.
Returns
boolean
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:119
database
get
database():DBAdapter
The underlying database.
For the most part, behavior is the same whether querying on the underlying database, or on AbstractPowerSyncDatabase.
Returns
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:115
schema
get
schema():Schema
<object
>
Schema used for the local database.
Returns
Schema
< object
>
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:107
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
Source
packages/web/src/db/PowerSyncDatabase.ts:64
close()
close(
options
):Promise
<void
>
Closes the database connection. By default the sync stream client is only disconnected if multiple tabs are not enabled.
Parameters
Parameter | Type | Default value |
---|---|---|
options | PowerSyncCloseOptions | DEFAULT_POWERSYNC_CLOSE_OPTIONS |
Returns
Promise
< void
>
Overrides
AbstractPowerSyncDatabase
.close
Source
packages/web/src/db/PowerSyncDatabase.ts:71
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
>
Overrides
AbstractPowerSyncDatabase
.connect
Source
packages/web/src/db/PowerSyncDatabase.ts:82
disconnect()
disconnect():
Promise
<void
>
Close the sync connection.
Use connect to connect again.
Returns
Promise
< void
>
Inherited from
AbstractPowerSyncDatabase
.disconnect
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:161
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
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:170
execute()
execute(
sql
,parameters
?):Promise
<QueryResult
>
Execute a write (INSERT/UPDATE/DELETE) query and optionally return results.
Parameters
Parameter | Type |
---|---|
sql | string |
parameters ? | any [] |
Returns
Promise
< QueryResult
>
Inherited from
AbstractPowerSyncDatabase
.execute
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:221
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 |
---|---|
sql | string |
parameters ? | any [][] |
Returns
Promise
< QueryResult
>
Inherited from
AbstractPowerSyncDatabase
.executeBatch
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:227
generateBucketStorageAdapter()
protected
generateBucketStorageAdapter():BucketStorageAdapter
Returns
Overrides
AbstractPowerSyncDatabase
.generateBucketStorageAdapter
Source
packages/web/src/db/PowerSyncDatabase.ts:94
generateSyncStreamImplementation()
protected
generateSyncStreamImplementation(connector
):AbstractStreamingSyncImplementation
Parameters
Parameter | Type |
---|---|
connector | PowerSyncBackendConnector |
Returns
AbstractStreamingSyncImplementation
Overrides
AbstractPowerSyncDatabase
.generateSyncStreamImplementation
Source
packages/web/src/db/PowerSyncDatabase.ts:105
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 |
---|---|
sql | string |
parameters ? | any [] |
Returns
Promise
< T
>
Inherited from
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:239
getAll()
getAll<
T
>(sql
,parameters
?):Promise
<T
[] >
Execute a read-only query and return results.
Type parameters
Type parameter |
---|
T |
Parameters
Parameter | Type |
---|---|
sql | string |
parameters ? | any [] |
Returns
Promise
< T
[] >
Inherited from
AbstractPowerSyncDatabase
.getAll
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:231
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 |
---|---|
limit | number |
Returns
Promise
< null
| CrudBatch
>
Inherited from
AbstractPowerSyncDatabase
.getCrudBatch
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:201
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
>
Inherited from
AbstractPowerSyncDatabase
.getNextCrudTransaction
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:215
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 |
---|---|
sql | string |
parameters ? | any [] |
Returns
Promise
< null
| T
>
Inherited from
AbstractPowerSyncDatabase
.getOptional
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:235
getUploadQueueStats()
getUploadQueueStats(
includeSize
?):Promise
<UploadQueueStats
>
Get upload queue size estimate and count.
Parameters
Parameter | Type |
---|---|
includeSize ? | boolean |
Returns
Promise
< UploadQueueStats
>
Inherited from
AbstractPowerSyncDatabase
.getUploadQueueStats
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:183
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
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:151
initialize()
protected
initialize():Promise
<void
>
Entry point for executing initialization logic. This is to be automatically executed in the constructor.
Returns
Promise
< void
>
Inherited from
AbstractPowerSyncDatabase
.initialize
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:139
iterateAsyncListeners()
iterateAsyncListeners(
cb
):Promise
<void
>
Parameters
Parameter | Type |
---|---|
cb | (listener ) => Promise < any > |
Returns
Promise
< void
>
Inherited from
AbstractPowerSyncDatabase
.iterateAsyncListeners
Source
packages/common/lib/utils/BaseObserver.d.ts:18
iterateListeners()
iterateListeners(
cb
):void
Parameters
Parameter | Type |
---|---|
cb | (listener ) => any |
Returns
void
Inherited from
AbstractPowerSyncDatabase
.iterateListeners
Source
packages/common/lib/utils/BaseObserver.d.ts:17
onChange()
onChange(options)
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
>
Inherited from
AbstractPowerSyncDatabase
.onChange
Example
async monitorChanges() {
for await (const event of this.powersync.onChange({tables: ['todos']})) {
console.log('Detected change event:', event);
}
}
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:324
onChange(handler, options)
onChange(
handler
?,options
?): () =>void
See onChangeWithCallback.
Parameters
Parameter | Type |
---|---|
handler ? | WatchOnChangeHandler |
options ? | SQLWatchOptions |
Returns
Function
Returns
void
Inherited from
AbstractPowerSyncDatabase
.onChange
Example
monitorChanges() {
this.powersync.onChange({
onChange: (event) => {
console.log('Change detected:', event);
}
}, { tables: ['todos'] });
}
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:339
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 |
---|---|
options ? | SQLWatchOptions |
Returns
AsyncIterable
< WatchOnChangeEvent
>
Inherited from
AbstractPowerSyncDatabase
.onChangeWithAsyncGenerator
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:359
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.
Returns dispose function to stop watching.
Parameters
Parameter | Type |
---|---|
handler ? | WatchOnChangeHandler |
options ? | SQLWatchOptions |
Returns
Function
Returns
void
Inherited from
AbstractPowerSyncDatabase
.onChangeWithCallback
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:350
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
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:244
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 |
---|---|
callback | (tx ) => Promise < T > |
lockTimeout ? | number |
Returns
Promise
< T
>
Inherited from
AbstractPowerSyncDatabase
.readTransaction
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:255
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
Source
packages/common/lib/utils/BaseObserver.d.ts:16
resolveTables()
resolveTables(
sql
,parameters
?,options
?):Promise
<string
[] >
Parameters
Parameter | Type |
---|---|
sql | string |
parameters ? | any [] |
options ? | SQLWatchOptions |
Returns
Promise
< string
[] >
Inherited from
AbstractPowerSyncDatabase
.resolveTables
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:310
runExclusive()
protected
runExclusive<T
>(cb
):Promise
<any
>
Type parameters
Type parameter |
---|
T |
Parameters
Parameter | Type |
---|---|
cb | () => Promise < T > |
Returns
Promise
< any
>
Source
packages/web/src/db/PowerSyncDatabase.ts:98
updateHasSynced()
protected
updateHasSynced():Promise
<void
>
Returns
Promise
< void
>
Inherited from
AbstractPowerSyncDatabase
.updateHasSynced
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:140
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 < SchemaType > |
Returns
Promise
< void
>
Inherited from
AbstractPowerSyncDatabase
.updateSchema
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:146
waitForFirstSync()
waitForFirstSync(
signal
?):Promise
<void
>
Parameters
Parameter | Type |
---|---|
signal ? | AbortSignal |
Returns
Promise
< void
>
A promise which will resolve once the first full sync has completed.
Inherited from
AbstractPowerSyncDatabase
.waitForFirstSync
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:129
waitForReady()
waitForReady():
Promise
<void
>
Returns
Promise
< void
>
A promise which will resolve once initialization is completed.
Inherited from
AbstractPowerSyncDatabase
.waitForReady
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:125
watch()
watch(sql, parameters, options)
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
>
Inherited from
AbstractPowerSyncDatabase
.watch
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) ?? [];
}
}
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:278
watch(sql, parameters, handler, options)
watch(
sql
,parameters
?,handler
?,options
?):void
See watchWithCallback.
Parameters
Parameter | Type |
---|---|
sql | string |
parameters ? | any [] |
handler ? | WatchHandler |
options ? | SQLWatchOptions |
Returns
void
Inherited from
AbstractPowerSyncDatabase
.watch
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) ?? [])
}
);
}
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:295
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 |
---|---|
sql | string |
parameters ? | any [] |
options ? | SQLWatchOptions |
Returns
AsyncIterable
< QueryResult
>
Inherited from
AbstractPowerSyncDatabase
.watchWithAsyncGenerator
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:309
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 |
---|---|
sql | string |
parameters ? | any [] |
handler ? | WatchHandler |
options ? | SQLWatchOptions |
Returns
void
Inherited from
AbstractPowerSyncDatabase
.watchWithCallback
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:303
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
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:249
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 |
---|---|
callback | (tx ) => Promise < T > |
lockTimeout ? | number |
Returns
Promise
< T
>
Inherited from
AbstractPowerSyncDatabase
.writeTransaction
Source
packages/common/lib/client/AbstractPowerSyncDatabase.d.ts:261