Skip to main content

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

ParameterType
optionsWebPowerSyncDatabaseOptionsWithAdapter

Returns

PowerSyncDatabase

Overrides

AbstractPowerSyncDatabase.constructor

new PowerSyncDatabase()

new PowerSyncDatabase(options): PowerSyncDatabase

Parameters

ParameterType
optionsWebPowerSyncDatabaseOptionsWithOpenFactory

Returns

PowerSyncDatabase

Overrides

AbstractPowerSyncDatabase.constructor

new PowerSyncDatabase()

new PowerSyncDatabase(options): PowerSyncDatabase

Parameters

ParameterType
optionsWebPowerSyncDatabaseOptionsWithSettings

Returns

PowerSyncDatabase

Overrides

AbstractPowerSyncDatabase.constructor

new PowerSyncDatabase()

new PowerSyncDatabase(options): PowerSyncDatabase

Parameters

ParameterType
optionsWebPowerSyncDatabaseOptions

Returns

PowerSyncDatabase

Overrides

AbstractPowerSyncDatabase.constructor

Properties

PropertyModifierTypeDescriptionInherited from
closedpublicbooleanReturns true if the connection is closed.AbstractPowerSyncDatabase.closed
currentStatuspublicSyncStatusCurrent connection status.AbstractPowerSyncDatabase.currentStatus
loggerpublicILogger-AbstractPowerSyncDatabase.logger
readypublicboolean-AbstractPowerSyncDatabase.ready
sdkVersionpublicstring-AbstractPowerSyncDatabase.sdkVersion
triggersreadonlyTriggerManagerExperimental Allows creating SQLite triggers which can be used to track various operations on SQLite tables.AbstractPowerSyncDatabase.triggers
SHARED_MUTEXstaticMutex--

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


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.

Inherited from

AbstractPowerSyncDatabase.connectionOptions


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.

Inherited from

AbstractPowerSyncDatabase.connector


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

DBAdapter

Inherited from

AbstractPowerSyncDatabase.database


schema

Get Signature

get schema(): Schema<{}>

Schema used for the local database.

Returns

Schema<{}>

Inherited from

AbstractPowerSyncDatabase.schema


syncStreamImplementation

Get Signature

get syncStreamImplementation(): 
| null
| StreamingSyncImplementation
Returns

| null | StreamingSyncImplementation

Inherited from

AbstractPowerSyncDatabase.syncStreamImplementation

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>

Closes the database connection. By default the sync stream client is only disconnected if multiple tabs are not enabled.

Parameters

ParameterType
options?PowerSyncCloseOptions

Returns

Promise<void>

Overrides

AbstractPowerSyncDatabase.close


connect()

connect(connector, options?): Promise<void>

Connects to stream of events from the PowerSync instance.

Parameters

ParameterType
connectorPowerSyncBackendConnector
options?PowerSyncConnectionOptions

Returns

Promise<void>

Inherited from

AbstractPowerSyncDatabase.connect


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

ParameterType
queryWatchCompatibleQuery<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

AbstractPowerSyncDatabase.customQuery


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

ParameterType
options?DisconnectAndClearOptions

Returns

Promise<void>

Inherited from

AbstractPowerSyncDatabase.disconnectAndClear


dispose()

dispose(): void

Returns

void

Deprecated

Use AbstractPowerSyncDatabase#close instead. Clears all listeners registered by AbstractPowerSyncDatabase#registerListener.

Inherited from

AbstractPowerSyncDatabase.dispose


execute()

execute(sql, parameters?): Promise<QueryResult>

Execute a SQL write (INSERT/UPDATE/DELETE) query and optionally return results.

Parameters

ParameterTypeDescription
sqlstringThe 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

ParameterTypeDescription
sqlstringThe 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

ParameterTypeDescription
sqlstringThe 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

ParameterTypeDescription
sqlstringThe 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

AbstractPowerSyncDatabase.get


getAll()

getAll<T>(sql, parameters?): Promise<T[]>

Execute a read-only query and return results.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
sqlstringThe 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

ParameterTypeDescription
limit?numberMaximum 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


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>

Inherited from

AbstractPowerSyncDatabase.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 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