Skip to main content

@powersync/web

Enumerations

EnumerationDescription
AttachmentStateAttachmentState represents the current synchronization state of an attachment.
ColumnType-
DiffTriggerOperationSQLite operations to track changes for with TriggerManager
EncodingType-
FetchStrategy-
SyncStreamConnectionMethod-
TemporaryStorageOption-
UpdateTypeType of local change.
WASQLiteVFSList of currently tested virtual filesystems
WatchedQueryListenerEvent-

Classes

ClassDescription
ArrayComparatorAn 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.
AttachmentContextAttachmentContext provides database operations for managing attachment records.
AttachmentQueueAttachmentQueue 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.
AttachmentTableAttachmentTable defines the schema for the attachment queue table.
BaseObserver-
Column-
CrudBatchA batch of client-side changes.
CrudTransaction-
DBAdapter-
GetAllQueryPerforms a DBGetUtils.getAll operation for a watched query.
Index-
IndexDBFileSystemStorageAdapterIndexDBFileSystemStorageAdapter implements LocalStorageAdapter using IndexedDB. Suitable for web browsers and web-based environments.
IndexedColumn-
LockContext-
ResolvedTableA resolved table in the PowerSync schema, with all columns, index definitions and options.
SchemaA schema is a collection of tables. It is used to define the structure of a database.
SharedWebStreamingSyncImplementationThe local part of the sync implementation on the web, which talks to a sync implementation hosted in a shared worker.
TableA table with a statically-typed Columns record structure.
UploadQueueStats-
WASQLiteOpenFactoryOpens a SQLite connection using WA-SQLite.
WebRemote-
WebStreamingSyncImplementation-

Interfaces

ArrayQueryDefinition

Options for building a query with AbstractPowerSyncDatabase#query. This query will be executed with AbstractPowerSyncDatabase#getAll.

Type Parameters

Type ParameterDefault type
RowTypeunknown

Properties

PropertyTypeDescription
mapper?(row) => RowTypeMaps 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>[]-
sqlstring-

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

Handles a delete error for a specific attachment.

Parameters
ParameterTypeDescription
attachmentAttachmentRecordThe attachment that failed to delete
errorunknownThe 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

Handles a download error for a specific attachment.

Parameters
ParameterTypeDescription
attachmentAttachmentRecordThe attachment that failed to download
errorunknownThe 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

Handles an upload error for a specific attachment.

Parameters
ParameterTypeDescription
attachmentAttachmentRecordThe attachment that failed to upload
errorunknownThe 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

PropertyTypeDescription
archivedCacheLimit?numberAlpha Maximum archived attachments before cleanup. Default: 100
dbCommonPowerSyncDatabaseAlpha PowerSync database instance
downloadAttachments?booleanAlpha Whether to automatically download remote attachments. Default: true
errorHandler?AttachmentErrorHandlerAlpha Handler for upload, download and delete errors
localStorageLocalStorageAdapterAlpha Local storage adapter for file persistence
logger?PowerSyncLoggerAlpha Logger instance. Defaults to db.logger
remoteStorageRemoteStorageAdapterAlpha Remote storage adapter for upload/download operations
syncIntervalMs?numberAlpha Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
syncThrottleDuration?numberAlpha Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
tableName?stringAlpha Name of the table to store attachment records. Default: 'ps_attachment_queue'
watchAttachments(onUpdate, signal) => voidAlpha Callback for monitoring attachment changes in your data model

AttachmentRecord

Alpha

AttachmentRecord represents an attachment in the local database.

Properties

PropertyTypeDescription
filenamestringAlpha
hasSynced?booleanAlpha
idstringAlpha
localUri?stringAlpha
mediaType?stringAlpha
metaData?stringAlpha
size?numberAlpha
stateAttachmentStateAlpha
timestamp?numberAlpha

AttachmentTableOptions

Alpha

Extends

Properties

PropertyTypeDescriptionInherited from
ignoreEmptyUpdates?booleanAlphaTableOrRawTableOptions.ignoreEmptyUpdates
indexes?IndexShorthandAlphaTableOptions.indexes
insertOnly?booleanAlphaTableOrRawTableOptions.insertOnly
localOnly?booleanAlphaTableOrRawTableOptions.localOnly
trackMetadata?booleanAlphaTableOrRawTableOptions.trackMetadata
trackPrevious?boolean | TrackPreviousOptionsAlphaTableOrRawTableOptions.trackPrevious
viewName?stringAlphaResolvedTableOptions.viewName

BaseCreateDiffTriggerOptions

Alpha Experimental

Common interface for options used in creating a diff trigger.

Extended by

Properties

PropertyTypeDescription
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?TriggerCreationHooksAlpha Hooks which allow execution during the trigger creation process.
sourcestringAlpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema.
useStorage?booleanAlpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed.
whenPartial<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

Extended by

Type Parameters

Type Parameter
T extends BaseListener

Methods

registerListener()
registerListener(listener): () => void;
Parameters
ParameterType
listenerPartial<T>
Returns

() => void


BasePowerSyncDatabaseOptions

Options required regardless of how a PowerSync database is opened.

Properties

PropertyTypeDescription
logger?PowerSyncLogger-
schemaSchemaSchema used for the local database.

BaseQueryResult

Shared superinterface for QueryResult and RawQueryResult.

Extended by

Properties

PropertyTypeDescription
insertId?numberRepresents the auto-generated row id if applicable.
rowsAffected?numberNumber 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

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 ParameterDefault typeDescription
TOperationId extends string | numbernumberThe 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

PropertyTypeDescription
idstringAlpha The modified row's id column value.
operationDiffTriggerOperationAlpha The operation performed which created this record.
operation_idTOperationIdAlpha 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.
timestampstringAlpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z.

BatchedUpdateNotification

Properties

PropertyType
tablesstring[]

ColumnOptions

Properties

PropertyType
namestring
type?ColumnType

CommonPowerSyncDatabase

Extends

Extended by

Properties

PropertyModifierTypeDescriptionInherited from
closedreadonlybooleanReturns true if the connection is closed.-
currentStatusreadonlySyncStatusCurrent connection status.-
executepublic<T>(query, params?) => 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
executeBatchpublic(query, params?) => 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
executeRawpublic(query, params?) => 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
loggerreadonlyPowerSyncLogger--
readyreadonlyboolean--
schemareadonlySchemaSchema used for the local database.-
sdkVersionreadonlystring--
triggersreadonlyTriggerManagerExperimental 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

DBAdapter

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
ParameterType
options?PowerSyncCloseOptions
Returns

Promise<void>

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

Connects to stream of events from the PowerSync instance.

Parameters
ParameterType
connectorPowerSyncBackendConnector
options?SyncOptions
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
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.
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
ParameterType
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
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

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

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

getCrudBatch()
getCrudBatch(limit?): Promise<CrudBatch | null>;

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
ParameterTypeDescription
limit?numberMaximum number of CRUD entries to include in the batch
Returns

Promise<CrudBatch | null>

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<CrudTransaction | null>;

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<CrudTransaction | null>

A transaction of CRUD operations to upload, or null if there are none

getOptional()
getOptional<T>(sql, parameters?): Promise<T | null>;

Execute a read-only query and return the first result, or null 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 | null>

The first result if found, or null if no results are returned

Inherited from

DBGetUtils.getOptional

getUploadQueueStats()
getUploadQueueStats(includeSize?): Promise<UploadQueueStats>;

Get upload queue size estimate and count.

Parameters
ParameterType
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
ParameterType
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
ParameterType
handler?WatchOnChangeHandler
options?SQLOnChangeOptions
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
ParameterTypeDescription
options?SQLWatchOptionsOptions 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
ParameterTypeDescription
handler?WatchOnChangeHandlerCallbacks for handling change events and errors
options?SQLOnChangeOptionsOptions for configuring watch behavior
Returns

A dispose function to stop watching for changes

() => 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
ParameterType
queryArrayQueryDefinition<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
ParameterType
callback(db) => Promise<T>
Returns

Promise<T>

readTransaction()
readTransaction<T>(callback, lockTimeout?): Promise<T>;

Open a read-only transaction. When multiple connections are available, 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
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime 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
ParameterType
listenerPartial<T>
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
ParameterTypeDescription
sqlstringThe SQL query to analyze
parameters?any[]Optional parameters for the SQL query
options?SQLWatchOptionsOptional 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
ParameterTypeDescription
namestringThe name of the stream to subscribe to.
params?Record<string, any>Optional parameters for the stream subscription.
Returns

SyncStream

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
ParameterType
schemaSchema
Returns

Promise<void>

waitForFirstSync()
waitForFirstSync(request?): Promise<void>;

Wait for the first sync operation to complete.

Parameters
ParameterTypeDescription
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
ParameterType
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
ParameterType
sqlstring
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
ParameterType
sqlstring
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
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
options?SQLWatchOptionsOptions 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
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
handler?WatchHandlerCallbacks for handling results and errors
options?SQLWatchOptionsOptions 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
ParameterType
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
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime 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

Type Parameters

Type Parameter
T

Methods

compile()
compile(): CompiledQuery;
Returns

CompiledQuery

execute()
execute(): Promise<T[]>;
Returns

Promise<T[]>


CompilableQueryWatchHandler

Type Parameters

Type Parameter
T

Properties

PropertyType
onError?(error) => void
onResult(results) => void

CompiledQuery

Properties

PropertyModifierType
parametersreadonlyreadonly unknown[]
sqlreadonlystring

CreateDiffTriggerOptions

Experimental Alpha

Options for TriggerManager#createDiffTrigger.

Extends

Properties

PropertyTypeDescriptionInherited 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
destinationstringAlpha 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?TriggerCreationHooksAlpha Hooks which allow execution during the trigger creation process.BaseCreateDiffTriggerOptions.hooks
setupContext?LockContextAlpha Context to use for the setup operation. This is useful for when the setup operation needs to be executed in a specific context.-
sourcestringAlpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema.BaseCreateDiffTriggerOptions.source
useStorage?booleanAlpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed.BaseCreateDiffTriggerOptions.useStorage
whenPartial<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

PropertyTypeDescription
minLevelnumberThe minimum log level to consider for messages. Defaults to LogLevels.info.
prefixstringA prefix for messages emitted by createConsoleLogger to make them more recognizable. Defaults to 'PowerSync'.

CrudEntry

A single client-side change.

Properties

PropertyTypeDescription
clientIdnumberAuto-incrementing client-side id.
idstringID of the changed row.
metadata?stringClient-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.
opUpdateTypeType 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.
tablestringTable that contained the change.
transactionId?numberAuto-incrementing transaction id. This is the same for all operations within the same transaction.

Methods

equals()
equals(entry): boolean;
Parameters
ParameterType
entryCrudEntry
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]: ((...event) => any) | undefined

Properties

PropertyTypeDescription
tablesUpdated(updateNotification) => voidListener 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
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

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

getOptional()
getOptional<T>(sql, parameters?): Promise<T | null>;

Execute a read-only query and return the first result, or null 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 | null>

The first result if found, or null if no results are returned


DBLockOptions

Properties

PropertyType
timeoutMs?number

DifferentialWatchedQueryComparator

Row comparator for differentially watched queries which keys and compares items in the result set.

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDescription
compareBy(item) => stringGenerates a token for comparing items with matching keys.
keyBy(item) => stringGenerates a unique key for the item.

DifferentialWatchedQueryListener

Extends

Type Parameters

Type Parameter
RowType

Indexable

[key: string]: ((...event) => any) | undefined

Properties

PropertyTypeInherited from
closed?() => void | Promise<void>WatchedQueryListener.closed
onData?(data) => void | Promise<void>WatchedQueryListener.onData
onDiff?(diff) => void | Promise<void>-
onError?(error) => void | Promise<void>WatchedQueryListener.onError
onStateChange?(state) => void | Promise<void>WatchedQueryListener.onStateChange
settingsWillUpdate?() => voidWatchedQueryListener.settingsWillUpdate

DifferentialWatchedQueryOptions

Options for building a differential watched query with the Query builder.

Extends

Extended by

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDescriptionInherited from
placeholderData?RowType[]Initial result data which is presented while the initial loading is executing.-
reportFetching?booleanIf 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?numberThe 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

Settings for differential incremental watched queries using.

Extends

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDescriptionInherited from
placeholderData?RowType[]Initial result data which is presented while the initial loading is executing.DifferentialWatchedQueryOptions.placeholderData
queryWatchCompatibleQuery<RowType[]>The query here must return an array of items that can be differentiated.-
reportFetching?booleanIf 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?numberThe 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

PropertyTypeDescription
clearLocal?booleanWhen set to false, data in local-only tables is preserved.

Disposable

Properties

PropertyType
dispose() => void | Promise<void>

IndexColumnOptions

Properties

PropertyType
ascending?boolean
namestring

IndexOptions

Properties

PropertyType
columns?IndexedColumn[]
namestring

ListenerMetaManager

Extends

Type Parameters

Type Parameter
Listener extends BaseListener

Properties

PropertyType
countsListenerCounts<Listener>

Methods

registerListener()
registerListener(listener): () => void;
Parameters
ParameterType
listenerPartial<T>
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

Clears all files in the storage.

Returns

Promise<void>

deleteFile()
deleteFile(filePath): Promise<void>;

Alpha

Deletes the file at the given path.

Parameters
ParameterTypeDescription
filePathstringPath where the file is stored
Returns

Promise<void>

fileExists()
fileExists(filePath): Promise<boolean>;

Alpha

Checks if a file exists at the given path.

Parameters
ParameterTypeDescription
filePathstringPath where the file is stored
Returns

Promise<boolean>

True if the file exists, false otherwise

getLocalUri()
getLocalUri(filename): string;

Alpha

Returns the file path for the provided filename in the storage directory.

Parameters
ParameterTypeDescription
filenamestringThe filename to get the path for
Returns

string

The full file path

initialize()
initialize(): Promise<void>;

Alpha

Initializes the storage adapter (e.g., creating necessary directories).

Returns

Promise<void>

makeDir()
makeDir(path): Promise<void>;

Alpha

Creates a directory at the specified path.

Parameters
ParameterTypeDescription
pathstringThe full path to the directory
Returns

Promise<void>

readFile()
readFile(filePath): Promise<ArrayBuffer>;

Alpha

Retrieves file data as an ArrayBuffer.

Parameters
ParameterTypeDescription
filePathstringPath where the file is stored
Returns

Promise<ArrayBuffer>

ArrayBuffer containing the file data

rmDir()
rmDir(path): Promise<void>;

Alpha

Removes a directory at the specified path.

Parameters
ParameterTypeDescription
pathstringThe full path to the directory
Returns

Promise<void>

saveFile()
saveFile(filePath, data): Promise<number>;

Alpha

Saves data to a local file.

Parameters
ParameterTypeDescription
filePathstringPath where the file will be stored
dataAttachmentDataData to store (ArrayBuffer, Blob, or string)
Returns

Promise<number>

Number of bytes written


LogRecord

A log record passed to a PowerSyncLogger.

Properties

PropertyTypeDescription
error?unknownWhen 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.
levelnumberThe 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.
messagestringThe main message to log.

MetaBaseObserverInterface

Extends

Extended by

Type Parameters

Type Parameter
Listener extends BaseListener

Properties

PropertyType
listenerMetaListenerMetaManager<Listener>

Methods

registerListener()
registerListener(listener): () => void;
Parameters
ParameterType
listenerPartial<T>
Returns

() => void

Inherited from

BaseObserverInterface.registerListener


MetaListener

Meta listener which reports the counts of listeners for each event type.

Extends

Type Parameters

Type Parameter
ParentListener extends BaseListener

Indexable

[key: string]: ((...event) => any) | undefined

Properties

PropertyType
listenersChanged?(counts) => void

PowerSyncBackendConnector

Properties

PropertyTypeDescription
fetchCredentials() => Promise<PowerSyncCredentials | null>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) => 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

PropertyTypeDescription
disconnect?booleanDisconnect 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

PropertyType
endpointstring
expiresAt?Date
tokenstring

PowerSyncDatabase

Extends

Properties

PropertyModifierTypeDescriptionInherited from
closedreadonlybooleanReturns true if the connection is closed.CommonPowerSyncDatabase.closed
currentStatusreadonlySyncStatusCurrent connection status.CommonPowerSyncDatabase.currentStatus
executepublic<T>(query, params?) => 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
executeBatchpublic(query, params?) => 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
executeRawpublic(query, params?) => 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
loggerreadonlyPowerSyncLogger-CommonPowerSyncDatabase.logger
readyreadonlyboolean-CommonPowerSyncDatabase.ready
schemareadonlySchemaSchema used for the local database.CommonPowerSyncDatabase.schema
sdkVersionreadonlystring-CommonPowerSyncDatabase.sdkVersion
triggersreadonlyTriggerManagerExperimental 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

DBAdapter

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
ParameterType
options?PowerSyncCloseOptions
Returns

Promise<void>

Inherited from

CommonPowerSyncDatabase.close

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

Connects to stream of events from the PowerSync instance.

Parameters
ParameterType
connectorPowerSyncBackendConnector
options?SyncOptions
Returns

Promise<void>

Inherited from

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

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

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

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<CrudBatch | null>;

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
ParameterTypeDescription
limit?numberMaximum number of CRUD entries to include in the batch
Returns

Promise<CrudBatch | null>

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<CrudTransaction | null>;

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<CrudTransaction | null>

A transaction of CRUD operations to upload, or null if there are none

Inherited from

CommonPowerSyncDatabase.getNextCrudTransaction

getOptional()
getOptional<T>(sql, parameters?): Promise<T | null>;

Execute a read-only query and return the first result, or null 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 | null>

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

CommonPowerSyncDatabase.init

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
ParameterType
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
ParameterType
handler?WatchOnChangeHandler
options?SQLOnChangeOptions
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
ParameterTypeDescription
options?SQLWatchOptionsOptions 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
ParameterTypeDescription
handler?WatchOnChangeHandlerCallbacks for handling change events and errors
options?SQLOnChangeOptionsOptions for configuring watch behavior
Returns

A dispose function to stop watching for changes

() => 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
ParameterType
queryArrayQueryDefinition<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

CommonPowerSyncDatabase.query

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
ParameterType
callback(db) => Promise<T>
Returns

Promise<T>

Inherited from

CommonPowerSyncDatabase.readLock

readTransaction()
readTransaction<T>(callback, lockTimeout?): Promise<T>;

Open a read-only transaction. When multiple connections are available, 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
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime 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
ParameterType
listenerPartial<T>
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
ParameterTypeDescription
sqlstringThe SQL query to analyze
parameters?any[]Optional parameters for the SQL query
options?SQLWatchOptionsOptional 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
ParameterTypeDescription
namestringThe name of the stream to subscribe to.
params?Record<string, any>Optional parameters for the stream subscription.
Returns

SyncStream

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
ParameterType
schemaSchema
Returns

Promise<void>

Inherited from

CommonPowerSyncDatabase.updateSchema

waitForFirstSync()
waitForFirstSync(request?): Promise<void>;

Wait for the first sync operation to complete.

Parameters
ParameterTypeDescription
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
ParameterType
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
ParameterType
sqlstring
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

CommonPowerSyncDatabase.watch

Call Signature
watch(
sql,
parameters?,
handler?,
options?): void;

See CommonPowerSyncDatabase.watchWithCallback.

Parameters
ParameterType
sqlstring
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

CommonPowerSyncDatabase.watch

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
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
options?SQLWatchOptionsOptions 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
ParameterTypeDescription
sqlstringThe SQL query to execute
parameters?any[]Optional array of parameters to bind to the query
handler?WatchHandlerCallbacks for handling results and errors
options?SQLWatchOptionsOptions 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
ParameterType
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
ParameterTypeDescription
callback(tx) => Promise<T>Function to execute within the transaction
lockTimeout?numberTime 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

Type Parameters

Type Parameter
Options

Constructors

Constructor
new PowerSyncDatabaseConstructor(options): CommonPowerSyncDatabase;
Parameters
ParameterType
optionsOptions
Returns

CommonPowerSyncDatabase


PowerSyncDBListener

Extends

Indexable

[key: string]: ((...event) => any) | undefined

Properties

PropertyType
closed() => void | Promise<void>
closing() => void | Promise<void>
initialized() => void
schemaChanged(schema) => void
statusChanged?(status) => void

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

PropertyTypeDescription
downloadedFractionnumberRelative 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.
downloadedOperationsnumberThe amount of operations that have already been downloaded.
totalOperationsnumberThe total amount of operations to download for the current sync iteration to complete.

Query

Type Parameters

Type Parameter
RowType

Methods

differentialWatch()
differentialWatch(options?): DifferentialWatchedQuery<RowType>;

Creates a WatchedQuery which watches and emits results of the linked query.

This query method watches for changes in the underlying SQLite tables and runs the query on each table change. The difference between the current and previous result set is computed. The watched query will not emit changes if the result set is identical to the previous result set.

If the result set is different, the watched query will emit the new result set and emit a detailed diff of the changes via the onData and onDiff listeners.

The deep differentiation allows maintaining result set object references between result emissions. The DifferentialWatchedQuery#state data array will contain the previous row references for unchanged rows.

Parameters
ParameterType
options?DifferentialWatchedQueryOptions<RowType>
Returns

DifferentialWatchedQuery<RowType>

Example
const watchedLists = powerSync.query({sql: 'SELECT * FROM lists'})
.differentialWatch();

const disposeListener = watchedLists.registerListener({
onData: (lists) => {
console.log('The latest result set for the query is', lists);
},
onDiff: (diff) => {
console.log('The lists result set has changed since the last emission', diff.added, diff.removed, diff.updated, diff.all)
}
})
watch()
watch(options?): StandardWatchedQuery<readonly Readonly<RowType>[]>;

Creates a WatchedQuery which watches and emits results of the linked query.

By default the returned watched query will emit changes whenever a change to the underlying SQLite tables is made. These changes might not be relevant to the query, but the query will emit a new result set.

A StandardWatchedQueryOptions#comparator can be provided to limit the data emissions. The watched query will still query the underlying DB on underlying table changes, but the result will only be emitted if the comparator detects a change in the results.

The comparator in this method is optimized and returns early as soon as it detects a change. Each data emission will correlate to a change in the result set, but note that the result set will not maintain internal object references to the previous result set. If internal object references are needed, consider using Query#differentialWatch instead.

Parameters
ParameterType
options?StandardWatchedQueryOptions<RowType>
Returns

StandardWatchedQuery<readonly Readonly<RowType>[]>


QueryResult

Object returned by SQL Query executions.

Extends

Type Parameters

Type ParameterDefault type
TSqliteRecord

Properties

PropertyTypeDescriptionInherited from
arrayT[]Rows in this result set.-
insertId?numberRepresents the auto-generated row id if applicable.BaseQueryResult.insertId
rows?ResultSetIf the query returned rows, the result set containing returned values.-
rowsAffected?numberNumber 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.BaseQueryResult.rowsAffected

RawQueryResult

A raw array-based result set representing rows returned by SQLite.

Extends

Properties

PropertyTypeDescriptionInherited from
columnNamesstring[]Names of columns in this result set. Every column has a name, so the length of this array is always equal to the amount of columns in the result set. Note that column names are not necessarily unique, e.g. a SELECT foo.user, bar.user FROM ... will have ['user', 'user'] in this array.-
insertId?numberRepresents the auto-generated row id if applicable.BaseQueryResult.insertId
rawRowsSqliteValue[][]Rows in the result set. Each row has a length equal to RawQueryResult.columnNames.-
rowsAffected?numberNumber 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.BaseQueryResult.rowsAffected

RemoteStorageAdapter

Experimental Alpha

RemoteStorageAdapter defines the interface for remote storage operations. Implementations handle uploading, downloading, and deleting files from remote storage.

This is currently experimental and may change without a major version bump.

Methods

deleteFile()
deleteFile(attachment): Promise<void>;

Alpha

Deletes a file from remote storage.

Parameters
ParameterTypeDescription
attachmentAttachmentRecordThe attachment describing the file to delete
Returns

Promise<void>

downloadFile()
downloadFile(attachment): Promise<ArrayBuffer>;

Alpha

Downloads a file from remote storage.

Parameters
ParameterTypeDescription
attachmentAttachmentRecordThe attachment describing the file to download
Returns

Promise<ArrayBuffer>

The binary data of the downloaded file

uploadFile()
uploadFile(fileData, attachment): Promise<void>;

Alpha

Uploads a file to remote storage.

Parameters
ParameterTypeDescription
fileDataArrayBufferThe binary content of the file to upload
attachmentAttachmentRecordThe associated attachment metadata
Returns

Promise<void>


ResolvedTableOptions

Extends

  • SharedTableOptions

Properties

PropertyTypeDescriptionInherited from
columnsColumn[]--
ignoreEmptyUpdates?boolean-SharedTableOptions.ignoreEmptyUpdates
indexes?Index[]--
insertOnly?boolean-SharedTableOptions.insertOnly
localOnly?boolean-SharedTableOptions.localOnly
namestringThe synced table name, matching sync rules-
trackMetadata?boolean-SharedTableOptions.trackMetadata
trackPrevious?boolean | TrackPreviousOptions-SharedTableOptions.trackPrevious
viewName?string-SharedTableOptions.viewName

ResolvedWebSQLOpenOptions

Extends

Properties

PropertyTypeDescriptionInherited from
additionalReadersnumberIf the vfs supports it, an additional amount of read-only connections to open. Using additional read connections can speed up queries by dispatching them to multiple workers running them concurrently. WASQLiteVFS.OPFSWriteAheadVFS is the only VFS with support for multiple connections, so this option is ignored for other VFS implementations. Defaults to 1.WebSpecificOpenOptions.additionalReaders
cacheSizeKbnumberMaximum SQLite cache size. Defaults to 50MB. For details, see: https://www.sqlite.org/pragma.html#pragma_cache_sizeWebSpecificOpenOptions.cacheSizeKb
databaseWorkerLogLevelnumberThe log level for database workers. Defaults to LogLevels.info.WebSpecificOpenOptions.databaseWorkerLogLevel
dbFilenamestringFilename for the database.SQLOpenOptions.dbFilename
dbLocation?stringDirectory where the database file is located. When set, the directory must exist when the database is opened, it will not be created automatically.SQLOpenOptions.dbLocation
debugMode?booleanEnable debugMode to log queries to the performance timeline. Defaults to false. To enable in development builds, use: debugMode: process.env.NODE_ENV !== 'production'SQLOpenOptions.debugMode
disableSSRWarningbooleanSQLite operations are currently not supported in SSR mode. A warning will be logged if attempting to use SQLite in SSR. Setting this to true will disabled the warning above.WebSpecificOpenOptions.disableSSRWarning
enableMultiTabsbooleanEnables multi tab support. Enabling multi-tab support will transparently make PowerSync manage the sync process in a shared worker collecting Sync Streams across tabs. Additionally, it enables a shared worker for IndexedDB databases. It is still valid to open multiple tabs when this option is disabled, but the experience may be degrated as only one tab can sync at the time. This is enabled by default on Desktop browsers if shared workers are enabled, except for Safari.WebSpecificOpenOptions.enableMultiTabs
encryptionKeystring | undefinedEncryption key for the database. If set, the database will be encrypted using ChaCha20.WebSpecificOpenOptions.encryptionKey
preparedStatementsCache?numberIf set to a value greater than zero, the worker will cache prepared statements to avoid preparing them every time a query runs. Defaults to 0 (disabling the cache).WebSpecificOpenOptions.preparedStatementsCache
ssrModebooleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-opWebSpecificOpenOptions.ssrMode
temporaryStorageTemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.WebSpecificOpenOptions.temporaryStorage
useWebWorkerbooleanThe SQLite connection is often executed through a web worker in order to offload computation and because some file system implementations (notably those based on web filesystem APIs like OPFS) are only available in workers. Manually disabling the use of web workers is not recommended, but can be useful for testing or for environments or toolchains where web workers are not supported.WebSpecificOpenOptions.useWebWorker
vfsWASQLiteVFS-WebSpecificOpenOptions.vfs
worker?string | URL | ((options) => Worker | SharedWorker)Allows you to override the default wasqlite db worker. You can either provide a path to the worker script or a factory method that returns a worker.WebSpecificOpenOptions.worker
workerPort?MessagePortUse an existing port to an initialized worker. A worker will be initialized if none is providedWebSpecificOpenOptions.workerPort

ResultSet

A representation of query results as JavaScript object.

Accessors

_array
Get Signature
get _array(): any[];
Deprecated

Use QueryResult.array instead.

Returns

any[]

length
Get Signature
get length(): number;

The amount of rows in the result set.

Returns

number

Methods

item()
item<T>(idx): T;
Type Parameters
Type Parameter
T
Parameters
ParameterType
idxnumber
Returns

T

Deprecated

Use QueryResult.array instead.


SharedWebStreamingSyncImplementationOptions

Extends

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter-WebStreamingSyncImplementationOptions.adapter
dbWebDBAdapter--
enableBroadcastLogsboolean--
identifier?stringAn identifier for which PowerSync DB this sync implementation is linked to. Most commonly DB name, but not restricted to DB name.WebStreamingSyncImplementationOptions.identifier
loggerPowerSyncLogger-WebStreamingSyncImplementationOptions.logger
logLevelnumber--
remoteAbstractRemote-WebStreamingSyncImplementationOptions.remote
serializedSchemaanyThe serialized schema - mainly used to forward information about raw tables to the sync client.WebStreamingSyncImplementationOptions.serializedSchema
subscriptionsSubscribedStream[]-WebStreamingSyncImplementationOptions.subscriptions
sync?{ worker?: string | URL | (() => SharedWorker); }-WebStreamingSyncImplementationOptions.sync
sync.worker?string | URL | (() => SharedWorker)--
uploadCrud() => Promise<void>-WebStreamingSyncImplementationOptions.uploadCrud

SqlExecutor

Extended by

Properties

PropertyTypeDescription
execute<T>(query, params?) => 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.
executeBatch(query, params?) => 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.
executeRaw(query, params?) => 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.

SQLOnChangeOptions

Extended by

Properties

PropertyTypeDescription
signal?AbortSignal-
tables?string[]-
throttleMs?numberThe minimum interval between queries.
triggerImmediate?booleanEmits an empty result set immediately

SQLOpenFactory

Methods

openDB()
openDB(): DBAdapter;

Opens a connection adapter to a SQLite DB

Returns

DBAdapter


SQLOpenOptions

Extended by

Properties

PropertyTypeDescription
dbFilenamestringFilename for the database.
dbLocation?stringDirectory where the database file is located. When set, the directory must exist when the database is opened, it will not be created automatically.
debugMode?booleanEnable debugMode to log queries to the performance timeline. Defaults to false. To enable in development builds, use: debugMode: process.env.NODE_ENV !== 'production'

SQLWatchOptions

Extends

Properties

PropertyTypeDescriptionInherited from
comparator?WatchedQueryComparator<QueryResult<SqliteRecord>>Optional comparator which will be used to compare the results of the query. The watched query will only yield results if the comparator returns false.-
signal?AbortSignal-SQLOnChangeOptions.signal
tables?string[]-SQLOnChangeOptions.tables
throttleMs?numberThe minimum interval between queries.SQLOnChangeOptions.throttleMs
triggerImmediate?booleanEmits an empty result set immediatelySQLOnChangeOptions.triggerImmediate

StandardWatchedQueryOptions

Options for Query#watch.

Extends

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDescriptionInherited from
comparator?WatchedQueryComparator<RowType[]>The underlying watched query implementation (re)evaluates the query on any SQLite table change. Providing this optional comparator can be used to filter duplicate result set emissions when the result set is unchanged. The comparator compares the previous and current result set. For an efficient comparator see ArrayComparator. Example comparator: new ArrayComparator({ compareBy: (item) => JSON.stringify(item) })-
placeholderData?RowType[]The initial data state reported while the query is loading for the first time. Default []-
reportFetching?booleanIf 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
throttleMs?numberThe 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

SyncDataFlowStatus

Deprecated

All fields are available on SyncStatus directly.

Properties

PropertyTypeDescription
downloadError?ErrorError during downloading (including connecting). Cleared on the next successful data download.
downloadingboolean-
uploadError?ErrorError during uploading. Cleared on the next successful upload.
uploadingboolean-

SyncOptions

Options that affect how the PowerSync SDK connects to the PowerSync Service.

Properties

PropertyTypeDescription
appMetadata?Record<string, string>A set of metadata to be included in service logs.
connectionMethod?SyncStreamConnectionMethodThe connection method to use when streaming updates from the PowerSync backend instance. The default value is SDK-specific. SyncStreamConnectionMethod.HTTP is the preferred implementation and used by default, except for React Native apps without Expo. Those don't support streaming HTTP responses, which is why SyncStreamConnectionMethod.WEB_SOCKET is used as a workaround.
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.
fetchStrategy?FetchStrategy-
includeDefaultStreams?booleanWhether to include streams that have auto_subscribe: true in their definition. This defaults to true.
params?Record<string, JSONValue>These parameters are passed to the sync rules, and will be available under theuser_parameters object.
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.

SyncPriorityStatus

Properties

PropertyType
hasSynced?boolean
lastSyncedAt?Date
prioritynumber

SyncProgress

Provides realtime progress on how PowerSync is downloading rows.

The progress until the next complete sync is available through the fields on ProgressWithOperations, which this class implements. Additionally, the SyncProgress.untilPriority method can be used to otbain progress towards a specific priority (instead of the progress for the entire download).

The reported progress always reflects the status towards the end of a sync iteration (after which a consistent snapshot of all buckets is available locally).

In rare cases (in particular, when a compacting operation takes place between syncs), it's possible for the returned numbers to be slightly inaccurate. For this reason, SyncProgress should be seen as an approximation of progress. The information returned is good enough to build progress bars, but not exact enough to track individual download counts.

Also note that data is downloaded in bulk, which means that individual counters are unlikely to be updated one-by-one.

Extends

Properties

PropertyTypeDescriptionInherited from
downloadedFractionnumberRelative 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.ProgressWithOperations.downloadedFraction
downloadedOperationsnumberThe amount of operations that have already been downloaded.ProgressWithOperations.downloadedOperations
totalOperationsnumberThe total amount of operations to download for the current sync iteration to complete.ProgressWithOperations.totalOperations

Methods

untilPriority()
untilPriority(priority): ProgressWithOperations;

Returns download progress towards all data up until the specified priority being received.

The returned ProgressWithOperations tracks the target amount of operations that need to be downloaded in total and how many of them have already been received.

Parameters
ParameterType
prioritynumber
Returns

ProgressWithOperations


SyncStatus

Accessors

connected
Get Signature
get connected(): boolean;

Indicates if the client is currently connected to the PowerSync service.

Returns

boolean

True if connected, false otherwise. Defaults to false if not specified.

connecting
Get Signature
get connecting(): boolean;

Indicates if the client is in the process of establishing a connection to the PowerSync service.

Returns

boolean

True if connecting, false otherwise. Defaults to false if not specified.

dataFlowStatus
Get Signature
get dataFlowStatus(): SyncDataFlowStatus;
Deprecated

All fields on SyncDataFlowStatus are available on SyncStatus directly.

Returns

SyncDataFlowStatus

downloadError
Get Signature
get downloadError(): Error | undefined;

An error that occurred during downloads (including connection establishment errors).

A download error will be reported on all sync status entries until the next successful sync.

Returns

Error | undefined

downloading
Get Signature
get downloading(): boolean;

Whether the PowerSync SDK is currently downloading data from the connected PowerSync service.

Returns

boolean

downloadProgress
Get Signature
get downloadProgress(): SyncProgress | null;

A realtime progress report on how many operations have been downloaded and how many are necessary in total to complete the next sync iteration.

This field is only set when SyncStatus#downloading is also true.

Returns

SyncProgress | null

hasSynced
Get Signature
get hasSynced(): boolean | undefined;

Indicates whether there has been at least one full sync completed since initialization.

Returns

boolean | undefined

True if at least one sync has completed, false if no sync has completed, or undefined when the state is still being loaded from the database.

lastSyncedAt
Get Signature
get lastSyncedAt(): Date | undefined;

Time that a last sync has fully completed, if any. This timestamp is reset to null after a restart of the PowerSync service.

Returns

Date | undefined

The timestamp of the last successful sync, or undefined if no sync has completed.

priorityStatusEntries
Get Signature
get priorityStatusEntries(): SyncPriorityStatus[] | undefined;

Provides sync status information for all bucket priorities, sorted by priority (highest first).

Returns

SyncPriorityStatus[] | undefined

An array of status entries for different sync priority levels, sorted with highest priorities (lower numbers) first.

syncStreams
Get Signature
get syncStreams(): SyncStreamStatus[] | undefined;

All sync streams currently being tracked in the database.

This returns null when the database is currently being opened and we don't have reliable information about all included streams yet.

Returns

SyncStreamStatus[] | undefined

uploadError
Get Signature
get uploadError(): Error | undefined;

Error during uploading. Cleared on the next successful upload.

Returns

Error | undefined

uploading
Get Signature
get uploading(): boolean;

Whether the PowerSync SDK is currently uploading local mutations through the configured PowerSyncBackendConnector.

Returns

boolean

Methods

forStream()
forStream(stream): SyncStreamStatus | undefined;

If the stream appears in SyncStatus.syncStreams, returns the current status for that stream.

Parameters
ParameterType
streamSyncStreamDescription
Returns

SyncStreamStatus | undefined

getMessage()
getMessage(): string;

Creates a human-readable string representation of the current sync status. Includes information about connection state, sync completion, and data flow.

Returns

string

A string representation of the sync status

isEqual()
isEqual(status): boolean;

Compares this SyncStatus instance with another to determine if they are equal. Equality is determined by comparing the serialized JSON representation of both instances.

Parameters
ParameterTypeDescription
statusSyncStatusThe SyncStatus instance to compare against
Returns

boolean

True if the instances are considered equal, false otherwise

statusForPriority()
statusForPriority(priority): SyncPriorityStatus | undefined;

Reports the sync status (a pair of SyncStatus#hasSynced and SyncStatus#lastSyncedAt fields) for a specific bucket priority level.

When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority buckets first. When a consistent view over all buckets for all priorities up until the given priority is reached, PowerSync makes data from those buckets available before lower-priority buckets have finished syncing.

This method returns the status for the requested priority or the next higher priority level that has status information available. This is because when PowerSync makes data for a given priority available, all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.

For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method with a priority of 1 may return information for priority level 3.

Parameters
ParameterTypeDescription
prioritynumberThe bucket priority for which the status should be reported
Returns

SyncPriorityStatus | undefined

Status information for the requested priority level or the next higher level with available status


SyncStream

A handle to a SyncStreamDescription that allows subscribing to the stream.

To obtain an instance of SyncStream, call CommonPowerSyncDatabase.syncStream.

Extends

Properties

PropertyTypeDescriptionInherited from
namestringThe name of the stream as it appears in the stream definition for the PowerSync service.SyncStreamDescription.name
parametersRecord<string, any> | nullThe parameters used to subscribe to the stream, if any. The same stream can be subscribed to multiple times with different parameters.SyncStreamDescription.parameters

Methods

subscribe()
subscribe(options?): Promise<SyncStreamSubscription>;

Adds a subscription to this stream, requesting it to be included when connecting to the sync service.

You should keep a reference to the returned SyncStreamSubscription object along as you need data for that stream. As soon as SyncStreamSubscription.unsubscribe is called for all subscriptions on this stream (including subscriptions created on other tabs), the SyncStreamSubscribeOptions.ttl starts ticking and will eventually evict the stream (unless SyncStream.subscribe is called again).

Parameters
ParameterType
options?SyncStreamSubscribeOptions
Returns

Promise<SyncStreamSubscription>

unsubscribeAll()
unsubscribeAll(): Promise<void>;

Clears all subscriptions attached to this stream and resets the TTL for the stream.

This is a potentially dangerous operations, as it interferes with other stream subscriptions.

Returns

Promise<void>


SyncStreamDescription

A description of a sync stream, consisting of its SyncStreamDescription.name and the SyncStreamDescription.parameters used when subscribing.

Extended by

Properties

PropertyTypeDescription
namestringThe name of the stream as it appears in the stream definition for the PowerSync service.
parametersRecord<string, any> | nullThe parameters used to subscribe to the stream, if any. The same stream can be subscribed to multiple times with different parameters.

SyncStreamStatus

Information about a sync stream subscription.

Properties

PropertyType
prioritynumber | null
progressProgressWithOperations | null
subscriptionSyncSubscriptionDescription

SyncStreamSubscribeOptions

Properties

PropertyTypeDescription
priority?0 | 1 | 2 | 3A priority to assign to this subscription. This overrides the default priority that may have been set on streams. For details on priorities, see priotized sync.
ttl?numberA "time to live" for this stream subscription, in seconds. The TTL control when a stream gets evicted after not having an active SyncStreamSubscription object attached to it.

SyncStreamSubscription

Extends

Properties

PropertyTypeDescriptionInherited from
namestringThe name of the stream as it appears in the stream definition for the PowerSync service.SyncStreamDescription.name
parametersRecord<string, any> | nullThe parameters used to subscribe to the stream, if any. The same stream can be subscribed to multiple times with different parameters.SyncStreamDescription.parameters

Methods

unsubscribe()
unsubscribe(): void;

Removes this stream subscription.

Returns

void

waitForFirstSync()
waitForFirstSync(abort?): Promise<void>;

A promise that resolves once data from in this sync stream has been synced and applied.

Parameters
ParameterType
abort?AbortSignal
Returns

Promise<void>


SyncSubscriptionDescription

Information about a subscribed sync stream.

This includes the SyncStreamDescription, along with information about the current sync status.

Extends

Properties

PropertyTypeDescriptionInherited from
activeboolean--
expiresAtDate | nullFor sync streams that have a time-to-live, the current time at which the stream would expire if not subscribed to again.-
hasExplicitSubscriptionbooleanWhether this stream has been subscribed to explicitly. It's possible for both SyncSubscriptionDescription.isDefault and SyncSubscriptionDescription.hasExplicitSubscription to be true at the same time - this happens when a default stream was subscribed explicitly.-
hasSyncedbooleanWhether this stream subscription has been synced at least once.-
isDefaultbooleanWhether this stream subscription is included by default, regardless of whether the stream has explicitly been subscribed to or not. It's possible for both SyncSubscriptionDescription.isDefault and SyncSubscriptionDescription.hasExplicitSubscription to be true at the same time - this happens when a default stream was subscribed explicitly.-
lastSyncedAtDate | nullIf SyncSubscriptionDescription.hasSynced is true, the last time data from this stream has been synced.-
namestringThe name of the stream as it appears in the stream definition for the PowerSync service.SyncStreamDescription.name
parametersRecord<string, any> | nullThe parameters used to subscribe to the stream, if any. The same stream can be subscribed to multiple times with different parameters.SyncStreamDescription.parameters

TableOptions

Extends

  • SharedTableOptions

Properties

PropertyTypeInherited from
ignoreEmptyUpdates?booleanSharedTableOptions.ignoreEmptyUpdates
indexes?IndexShorthand-
insertOnly?booleanSharedTableOptions.insertOnly
localOnly?booleanSharedTableOptions.localOnly
trackMetadata?booleanSharedTableOptions.trackMetadata
trackPrevious?boolean | TrackPreviousOptionsSharedTableOptions.trackPrevious
viewName?stringSharedTableOptions.viewName

TableOrRawTableOptions

Options that apply both to JSON-based tables and raw tables.

Properties

PropertyType
ignoreEmptyUpdates?boolean
insertOnly?boolean
localOnly?boolean
trackMetadata?boolean
trackPrevious?boolean | TrackPreviousOptions

TrackDiffOptions

Experimental Alpha

Options for tracking changes to a table with TriggerManager#trackTableDiff.

Extends

Properties

PropertyTypeDescriptionInherited 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
hooks?TriggerCreationHooksAlpha Hooks which allow execution during the trigger creation process.BaseCreateDiffTriggerOptions.hooks
onChange(context) => Promise<void>Alpha Handler for processing diff operations. Automatically invoked once diff items are present. Diff items are automatically cleared after the handler is invoked.-
sourcestringAlpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema.BaseCreateDiffTriggerOptions.source
throttleMs?numberAlpha The minimum interval, in milliseconds, between TrackDiffOptions.onChange invocations.-
useStorage?booleanAlpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed.BaseCreateDiffTriggerOptions.useStorage
whenPartial<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

TrackPreviousOptions

Whether to include previous column values when PowerSync tracks local changes.

Including old values may be helpful for some backend connector implementations, which is why it can be enabled on per-table or per-columm basis.

Properties

PropertyTypeDescription
columns?string[]When defined, a list of column names for which old values should be tracked.
onlyWhenChanged?booleanWhen enabled, only include values that have actually been changed by an update.

Transaction

Extends

Properties

PropertyTypeDescription
commit() => Promise<void>Commit multiple changes to the local DB using the Transaction context.
rollback() => Promise<void>Roll back multiple attempted changes using the Transaction context.

Methods

execute()
execute<T>(query, params?): 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.

Type Parameters
Type ParameterDefault type
TSqliteRecord
Parameters
ParameterType
querystring
params?any[]
Returns

Promise<QueryResult<T>>

The query result as an object with structured key-value pairs

Inherited from

LockContext.execute

executeBatch()
executeBatch(query, params?): 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.

Parameters
ParameterType
querystring
params?any[][]
Returns

Promise<QueryResult<never>>

The query result

Inherited from

LockContext.executeBatch

executeRaw()
abstract executeRaw<T>(query, params?): 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.

Type Parameters
Type Parameter
T
Parameters
ParameterType
querystring
params?any[]
Returns

Promise<RawQueryResult>

The RawQueryResult representing each row as an array.

Inherited from

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

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

LockContext.getAll

getOptional()
getOptional<T>(sql, parameters?): Promise<T | null>;

Execute a read-only query and return the first result, or null 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 | null>

The first result if found, or null if no results are returned

Inherited from

LockContext.getOptional


TriggerCreationHooks

Experimental Alpha

Hooks used in the creation of a table diff trigger.

Properties

PropertyTypeDescription
beforeCreate?(context) => Promise<void>Alpha Executed inside a write lock before the trigger is created.

TriggerDiffDeleteRecord

Experimental Alpha

Represents a diff record for a SQLite DELETE operation. This record contains the new value represented as a JSON string.

Extends

Type Parameters

Type ParameterDefault type
TOperationId extends string | numbernumber

Properties

PropertyTypeDescriptionOverridesInherited from
idstringAlpha The modified row's id column value.-BaseTriggerDiffRecord.id
operationDELETEAlpha The operation performed which created this record.BaseTriggerDiffRecord.operation-
operation_idTOperationIdAlpha 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.-BaseTriggerDiffRecord.operation_id
timestampstringAlpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z.-BaseTriggerDiffRecord.timestamp
valuestringAlpha The value of the row, before the DELETE operation, in JSON string format.--

TriggerDiffHandlerContext

Experimental Alpha

Context for the onChange handler provided to TriggerManager#trackTableDiff.

Properties

PropertyTypeDescription
contextLockContextAlpha Experimental
destinationTablestringAlpha The name of the temporary destination table created by the trigger.
withDiff<T>(query, params?, options?) => Promise<T[]>Alpha Allows querying the database with access to the table containing DIFF records. The diff table is accessible via the DIFF accessor. The DIFF table is of the form described in TriggerManager#createDiffTrigger CREATE TEMP DIFF ( operation_id INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT, operation TEXT, timestamp TEXT, value TEXT, previous_value TEXT ); Note that the value and previous_value columns store the row state in JSON string format. To access the row state in an extracted form see TriggerDiffHandlerContext#withExtractedDiff. Examples --- This fetches the current state of todo rows which have a diff operation present. --- The state of the row at the time of the operation is accessible in the DIFF records. SELECT todos.* FROM DIFF JOIN todos ON DIFF.id = todos.id WHERE json_extract(DIFF.value, '$.status') = 'active' // With operation_id cast as TEXT for full precision const diffs = await context.withDiff<TriggerDiffRecord<string>>( 'SELECT * FROM DIFF', undefined, { castOperationIdAsText: true } ); // diffs[0].operation_id is now typed as string
withExtractedDiff<T>(query, params?) => Promise<T[]>Alpha Allows querying the database with access to the table containing diff records. The diff table is accessible via the DIFF accessor. This is similar to TriggerDiffHandlerContext#withDiff but extracts the row columns from the tracked JSON value. The diff operation data is aliased as __ columns to avoid column conflicts. For DiffTriggerOperation#DELETE operations the previous_value columns are extracted for convenience. CREATE TEMP TABLE DIFF ( id TEXT, replicated_column_1 COLUMN_TYPE, replicated_column_2 COLUMN_TYPE, __operation TEXT, __timestamp TEXT, __previous_value TEXT ); Example SELECT todos.* FROM DIFF JOIN todos ON DIFF.id = todos.id --- The todo column names are extracted from json and are available as DIFF.name WHERE DIFF.name = 'example'

TriggerDiffInsertRecord

Experimental Alpha

Represents a diff record for a SQLite INSERT operation. This record contains the new value represented as a JSON string.

Extends

Type Parameters

Type ParameterDefault type
TOperationId extends string | numbernumber

Properties

PropertyTypeDescriptionOverridesInherited from
idstringAlpha The modified row's id column value.-BaseTriggerDiffRecord.id
operationINSERTAlpha The operation performed which created this record.BaseTriggerDiffRecord.operation-
operation_idTOperationIdAlpha 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.-BaseTriggerDiffRecord.operation_id
timestampstringAlpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z.-BaseTriggerDiffRecord.timestamp
valuestringAlpha The value of the row, at the time of INSERT, in JSON string format.--

TriggerDiffUpdateRecord

Experimental Alpha

Represents a diff record for a SQLite UPDATE operation. This record contains the new value and optionally the previous value. Values are stored as JSON strings.

Extends

Type Parameters

Type ParameterDefault type
TOperationId extends string | numbernumber

Properties

PropertyTypeDescriptionOverridesInherited from
idstringAlpha The modified row's id column value.-BaseTriggerDiffRecord.id
operationUPDATEAlpha The operation performed which created this record.BaseTriggerDiffRecord.operation-
operation_idTOperationIdAlpha 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.-BaseTriggerDiffRecord.operation_id
previous_valuestringAlpha The previous value of the row in JSON string format.--
timestampstringAlpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z.-BaseTriggerDiffRecord.timestamp
valuestringAlpha The updated state of the row in JSON string format.--

TriggerManager

Experimental Alpha

Methods

createDiffTrigger()
createDiffTrigger(options): Promise<TriggerRemoveCallback>;

Experimental

Creates a temporary trigger which tracks changes to a source table and writes changes to a destination table. The temporary destination table is created internally and will be dropped when the trigger is removed. The temporary destination table is created with the structure:

CREATE TEMP TABLE ${destination} (
operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT,
operation TEXT,
timestamp TEXT,
value TEXT,
previous_value TEXT
);

The value column contains the JSON representation of the row's value at the change.

For DiffTriggerOperation#UPDATE operations the previous_value column contains the previous value of the changed row in a JSON format.

NB: The triggers created by this method might be invalidated by AbstractPowerSyncDatabase#updateSchema calls. These triggers should manually be dropped and recreated when updating the schema.

Parameters
ParameterType
optionsCreateDiffTriggerOptions
Returns

Promise<TriggerRemoveCallback>

A callback to remove the trigger and drop the destination table.

Example
const dispose = await database.triggers.createDiffTrigger({
source: 'lists',
destination: 'ps_temp_lists_diff',
columns: ['name'],
when: {
[DiffTriggerOperation.INSERT]: 'TRUE',
[DiffTriggerOperation.UPDATE]: 'TRUE',
[DiffTriggerOperation.DELETE]: 'TRUE'
}
});
trackTableDiff()
trackTableDiff(options): Promise<TriggerRemoveCallback>;

Experimental

Tracks changes for a table. Triggering a provided handler on changes. Uses TriggerManager.createDiffTrigger internally to create a temporary destination table.

Parameters
ParameterType
optionsTrackDiffOptions
Returns

Promise<TriggerRemoveCallback>

A callback to cleanup the trigger and stop tracking changes.

NB: The triggers created by this method might be invalidated by AbstractPowerSyncDatabase#updateSchema calls. These triggers should manually be dropped and recreated when updating the schema.

Example
const dispose = database.triggers.trackTableDiff({
source: 'todos',
columns: ['list_id'],
when: {
[DiffTriggerOperation.INSERT]: sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(someIdVariable)}`
},
onChange: async (context) => {
// Fetches the todo records that were inserted during this diff
const newTodos = await context.withDiff<Database['todos']>(`
SELECT
todos.*
FROM
DIFF
JOIN todos ON DIFF.id = todos.id
`);

// Process newly created todos
},
hooks: {
beforeCreate: async (lockContext) => {
// This hook is executed inside the write lock before the trigger is created.
// It can be used to synchronize the current state of the table with processor logic.
// Any changes after this callback are guaranteed to trigger the `onChange` handler.

// Read the current state of the todos table
const currentTodos = await lockContext.getAll<Database['todos']>(
`
SELECT
*
FROM
todos
WHERE
list_id = ?
`,
['123']
);

// Process existing todos
}
}
});

TriggerRemoveCallbackOptions

Experimental Alpha

Options for TriggerRemoveCallback.

Properties

PropertyTypeDescription
context?LockContextAlpha Experimental

WASQLiteOpenFactoryOptions

Properties

PropertyType
loggerPowerSyncLogger
openWebSQLOpenOptions

WatchCompatibleQuery

Type Parameters

Type Parameter
ResultType

Methods

compile()
compile(): CompiledQuery;
Returns

CompiledQuery

execute()
execute(options): Promise<ResultType>;
Parameters
ParameterType
optionsWatchExecuteOptions
Returns

Promise<ResultType>


WatchedQuery

Extends

Type Parameters

Type ParameterDefault type
Dataunknown
Settings extends WatchedQueryOptionsWatchedQueryOptions
Listener extends WatchedQueryListener<Data>WatchedQueryListener<Data>

Properties

PropertyModifierTypeDescriptionInherited from
closedreadonlyboolean--
listenerMetapublicListenerMetaManager<Listener>-MetaBaseObserverInterface.listenerMeta
statereadonlyWatchedQueryState<Data>Current state of the watched query.-

Methods

close()
close(): Promise<void>;

Close the watched query and end all subscriptions.

Returns

Promise<void>

registerListener()
registerListener(listener): () => void;

Subscribe to watched query events.

Parameters
ParameterType
listenerListener
Returns

A function to unsubscribe from the events.

() => void

Overrides

MetaBaseObserverInterface.registerListener

updateSettings()
updateSettings(options): Promise<void>;

Updates the underlying query options. This will trigger a re-evaluation of the query and update the state.

Parameters
ParameterType
optionsSettings
Returns

Promise<void>


WatchedQueryComparator

A basic comparator for incrementally watched queries. This performs a single comparison which determines if the result set has changed. The WatchedQuery will only emit the new result if a change has been detected.

Type Parameters

Type Parameter
Data

Properties

PropertyType
checkEquality(current, previous) => boolean

WatchedQueryDifferential

Represents the result of a watched query that has been diffed. DifferentialWatchedQueryState#diff is of the WatchedQueryDifferential form.

Type Parameters

Type Parameter
RowType

Properties

PropertyModifierTypeDescription
addedreadonlyreadonly Readonly<RowType>[]-
allreadonlyreadonly Readonly<RowType>[]The entire current result set. Array item object references are preserved between updates if the item is unchanged. e.g. In the query SELECT name, make FROM assets ORDER BY make ASC; If a previous result set contains an item (A) {name: 'pc', make: 'Cool PC'} and an update has been made which adds another item (B) to the result set (the item A is unchanged) - then the updated result set will be contain the same object reference, to item A, as the previous result set. This is regardless of the item A's position in the updated result set.
removedreadonlyreadonly Readonly<RowType>[]-
unchangedreadonlyreadonly Readonly<RowType>[]-
updatedreadonlyreadonly WatchedQueryRowDifferential<Readonly<RowType>>[]-

WatchedQueryListener

Extends

Extended by

Type Parameters

Type Parameter
Data

Indexable

[key: string]: ((...event) => any) | undefined

Properties

PropertyType
closed?() => void | Promise<void>
onData?(data) => void | Promise<void>
onError?(error) => void | Promise<void>
onStateChange?(state) => void | Promise<void>
settingsWillUpdate?() => void

WatchedQueryOptions

Extended by

Properties

PropertyTypeDescription
reportFetching?booleanIf 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.
throttleMs?numberThe minimum interval between queries.
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.

WatchedQueryRowDifferential

Represents an updated row in a differential watched query. It contains both the current and previous state of the row.

Type Parameters

Type Parameter
RowType

Properties

PropertyModifierType
currentreadonlyRowType
previousreadonlyRowType

WatchedQuerySettings

Settings for WatchedQuery instances created via Query#watch.

Extends

Type Parameters

Type Parameter
DataType

Properties

PropertyTypeDescriptionInherited from
queryWatchCompatibleQuery<DataType>--
reportFetching?booleanIf 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
throttleMs?numberThe 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

WatchedQueryState

State for WatchedQuery instances.

Type Parameters

Type Parameter
Data

Properties

PropertyModifierTypeDescription
datareadonlyDataThe last data returned by the query.
errorreadonlyError | nullThe last error that occurred while executing the query.
isFetchingreadonlybooleanIndicates whether the query is currently fetching data, is true during the initial load and any time when the query is re-evaluating (useful for large queries).
isLoadingreadonlybooleanIndicates the initial loading state (hard loading). Loading becomes false once the first set of results from the watched query is available or an error occurs.
lastUpdatedreadonlyDate | nullThe last time the query was updated.

WatchExecuteOptions

Options provided to the execute method of a WatchCompatibleQuery.

Properties

PropertyType
dbCommonPowerSyncDatabase
parametersany[]
sqlstring

WatchHandler

Properties

PropertyType
onError?(error) => void
onResult(results) => void

WatchOnChangeEvent

Properties

PropertyType
changedTablesstring[]

WatchOnChangeHandler

Properties

PropertyType
onChange(event) => void | Promise<void>

WebDBAdapter

Extends

Accessors

name
Get Signature
get abstract name(): string;
Returns

string

Inherited from

DBAdapter.name

Methods

close()
abstract close(): void | Promise<void>;
Returns

void | Promise<void>

Inherited from

DBAdapter.close

dispose()
dispose(): void;
Returns

void

Inherited from

DBAdapter.dispose

execute()
execute<T>(query, params?): 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.

Type Parameters
Type Parameter
T
Parameters
ParameterType
querystring
params?any[]
Returns

Promise<QueryResult<T>>

The query result as an object with structured key-value pairs

Inherited from

DBAdapter.execute

executeBatch()
executeBatch(query, params?): 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.

Parameters
ParameterType
querystring
params?any[][]
Returns

Promise<QueryResult<never>>

The query result

Inherited from

DBAdapter.executeBatch

executeRaw()
executeRaw(query, params?): 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.

Parameters
ParameterType
querystring
params?any[]
Returns

Promise<RawQueryResult>

The RawQueryResult representing each row as an array.

Inherited from

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

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

DBAdapter.getAll

getConfiguration()
getConfiguration(): WebDBAdapterConfiguration;

Get the config options used to open this connection. This is useful for sharing connections.

Returns

WebDBAdapterConfiguration

getOptional()
getOptional<T>(sql, parameters?): Promise<T | null>;

Execute a read-only query and return the first result, or null 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 | null>

The first result if found, or null if no results are returned

Inherited from

DBAdapter.getOptional

iterateAsyncListeners()
iterateAsyncListeners(cb): Promise<void>;
Parameters
ParameterType
cb(listener) => Promise<any>
Returns

Promise<void>

Inherited from

DBAdapter.iterateAsyncListeners

iterateListeners()
iterateListeners(cb): void;
Parameters
ParameterType
cb(listener) => any
Returns

void

Inherited from

DBAdapter.iterateListeners

readLock()
abstract readLock<T>(fn, options?): Promise<T>;
Type Parameters
Type Parameter
T
Parameters
ParameterType
fn(tx) => Promise<T>
options?DBLockOptions
Returns

Promise<T>

Inherited from

DBAdapter.readLock

readTransaction()
readTransaction<T>(fn, options?): Promise<T>;
Type Parameters
Type Parameter
T
Parameters
ParameterType
fn(tx) => Promise<T>
options?DBLockOptions
Returns

Promise<T>

Inherited from

DBAdapter.readTransaction

refreshSchema()
abstract refreshSchema(): Promise<void>;

This method refreshes the schema information across all connections. This is for advanced use cases, and should generally not be needed.

Returns

Promise<void>

Inherited from

DBAdapter.refreshSchema

registerListener()
registerListener(listener): () => void;

Register a listener for updates to the PowerSync client.

Parameters
ParameterType
listenerPartial<T>
Returns

() => void

Inherited from

DBAdapter.registerListener

shareConnection()
shareConnection(): Promise<SharedConnectionWorker>;

Get a MessagePort which can be used to share the internals of this connection.

Returns

Promise<SharedConnectionWorker>

writeLock()
abstract writeLock<T>(fn, options?): Promise<T>;
Type Parameters
Type Parameter
T
Parameters
ParameterType
fn(tx) => Promise<T>
options?DBLockOptions
Returns

Promise<T>

Inherited from

DBAdapter.writeLock

writeTransaction()
writeTransaction<T>(fn, options?): Promise<T>;
Type Parameters
Type Parameter
T
Parameters
ParameterType
fn(tx) => Promise<T>
options?DBLockOptions
Returns

Promise<T>

Inherited from

DBAdapter.writeTransaction


WebSpecificOpenOptions

Extended by

Properties

PropertyTypeDescription
additionalReadersnumberIf the vfs supports it, an additional amount of read-only connections to open. Using additional read connections can speed up queries by dispatching them to multiple workers running them concurrently. WASQLiteVFS.OPFSWriteAheadVFS is the only VFS with support for multiple connections, so this option is ignored for other VFS implementations. Defaults to 1.
cacheSizeKbnumberMaximum SQLite cache size. Defaults to 50MB. For details, see: https://www.sqlite.org/pragma.html#pragma_cache_size
databaseWorkerLogLevelnumberThe log level for database workers. Defaults to LogLevels.info.
disableSSRWarningbooleanSQLite operations are currently not supported in SSR mode. A warning will be logged if attempting to use SQLite in SSR. Setting this to true will disabled the warning above.
enableMultiTabsbooleanEnables multi tab support. Enabling multi-tab support will transparently make PowerSync manage the sync process in a shared worker collecting Sync Streams across tabs. Additionally, it enables a shared worker for IndexedDB databases. It is still valid to open multiple tabs when this option is disabled, but the experience may be degrated as only one tab can sync at the time. This is enabled by default on Desktop browsers if shared workers are enabled, except for Safari.
encryptionKeystring | undefinedEncryption key for the database. If set, the database will be encrypted using ChaCha20.
preparedStatementsCache?numberIf set to a value greater than zero, the worker will cache prepared statements to avoid preparing them every time a query runs. Defaults to 0 (disabling the cache).
ssrModebooleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-op
temporaryStorageTemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.
useWebWorkerbooleanThe SQLite connection is often executed through a web worker in order to offload computation and because some file system implementations (notably those based on web filesystem APIs like OPFS) are only available in workers. Manually disabling the use of web workers is not recommended, but can be useful for testing or for environments or toolchains where web workers are not supported.
vfsWASQLiteVFS-
worker?string | URL | ((options) => Worker | SharedWorker)Allows you to override the default wasqlite db worker. You can either provide a path to the worker script or a factory method that returns a worker.
workerPort?MessagePortUse an existing port to an initialized worker. A worker will be initialized if none is provided

WebSpecificOptions

Properties

PropertyTypeDescription
broadcastLogs?booleanBroadcast logs from shared workers, such as the shared sync worker, to individual tabs. This defaults to true.
sync?WebSyncOptions-

WebSQLOpenOptions

Extends

Properties

PropertyTypeDescriptionInherited from
additionalReaders?numberIf the vfs supports it, an additional amount of read-only connections to open. Using additional read connections can speed up queries by dispatching them to multiple workers running them concurrently. WASQLiteVFS.OPFSWriteAheadVFS is the only VFS with support for multiple connections, so this option is ignored for other VFS implementations. Defaults to 1.WebSpecificOpenOptions.additionalReaders
cacheSizeKb?numberMaximum SQLite cache size. Defaults to 50MB. For details, see: https://www.sqlite.org/pragma.html#pragma_cache_sizeWebSpecificOpenOptions.cacheSizeKb
databaseWorkerLogLevel?numberThe log level for database workers. Defaults to LogLevels.info.WebSpecificOpenOptions.databaseWorkerLogLevel
dbFilenamestringFilename for the database.SQLOpenOptions.dbFilename
dbLocation?stringDirectory where the database file is located. When set, the directory must exist when the database is opened, it will not be created automatically.SQLOpenOptions.dbLocation
debugMode?booleanEnable debugMode to log queries to the performance timeline. Defaults to false. To enable in development builds, use: debugMode: process.env.NODE_ENV !== 'production'SQLOpenOptions.debugMode
disableSSRWarning?booleanSQLite operations are currently not supported in SSR mode. A warning will be logged if attempting to use SQLite in SSR. Setting this to true will disabled the warning above.WebSpecificOpenOptions.disableSSRWarning
enableMultiTabs?booleanEnables multi tab support. Enabling multi-tab support will transparently make PowerSync manage the sync process in a shared worker collecting Sync Streams across tabs. Additionally, it enables a shared worker for IndexedDB databases. It is still valid to open multiple tabs when this option is disabled, but the experience may be degrated as only one tab can sync at the time. This is enabled by default on Desktop browsers if shared workers are enabled, except for Safari.WebSpecificOpenOptions.enableMultiTabs
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.WebSpecificOpenOptions.encryptionKey
preparedStatementsCache?numberIf set to a value greater than zero, the worker will cache prepared statements to avoid preparing them every time a query runs. Defaults to 0 (disabling the cache).WebSpecificOpenOptions.preparedStatementsCache
ssrMode?booleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-opWebSpecificOpenOptions.ssrMode
temporaryStorage?TemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.WebSpecificOpenOptions.temporaryStorage
useWebWorker?booleanThe SQLite connection is often executed through a web worker in order to offload computation and because some file system implementations (notably those based on web filesystem APIs like OPFS) are only available in workers. Manually disabling the use of web workers is not recommended, but can be useful for testing or for environments or toolchains where web workers are not supported.WebSpecificOpenOptions.useWebWorker
vfs?WASQLiteVFS-WebSpecificOpenOptions.vfs
worker?string | URL | ((options) => Worker | SharedWorker)Allows you to override the default wasqlite db worker. You can either provide a path to the worker script or a factory method that returns a worker.WebSpecificOpenOptions.worker
workerPort?MessagePortUse an existing port to an initialized worker. A worker will be initialized if none is providedWebSpecificOpenOptions.workerPort

WebStreamingSyncImplementationOptions

Extends

  • AbstractStreamingSyncImplementationOptions

Extended by

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter-AbstractStreamingSyncImplementationOptions.adapter
identifier?stringAn identifier for which PowerSync DB this sync implementation is linked to. Most commonly DB name, but not restricted to DB name.AbstractStreamingSyncImplementationOptions.identifier
loggerPowerSyncLogger-AbstractStreamingSyncImplementationOptions.logger
remoteAbstractRemote-AbstractStreamingSyncImplementationOptions.remote
serializedSchemaanyThe serialized schema - mainly used to forward information about raw tables to the sync client.AbstractStreamingSyncImplementationOptions.serializedSchema
subscriptionsSubscribedStream[]-AbstractStreamingSyncImplementationOptions.subscriptions
sync?{ worker?: string | URL | (() => SharedWorker); }--
sync.worker?string | URL | (() => SharedWorker)--
uploadCrud() => Promise<void>-AbstractStreamingSyncImplementationOptions.uploadCrud

WebSyncOptions

Properties

PropertyTypeDescription
logLevel?numberThe log level for logs from the sync worker. Defaults to LogLevels.info.
worker?string | URL | (() => SharedWorker)Allows you to override the default sync worker. You can either provide a path to the worker script or a factory method that returns a worker.

WithDiffOptions

Experimental Alpha

Options for TriggerDiffHandlerContext#withDiff.

Properties

PropertyTypeDescription
castOperationIdAsText?booleanAlpha If true, casts operation_id as TEXT in the internal CTE to preserve full 64-bit precision. Use this when you need to ensure operation_id is treated as a string to avoid precision loss for values exceeding JavaScript's Number.MAX_SAFE_INTEGER. When enabled, use TriggerDiffRecord to type the result correctly.

Type Aliases

AbstractPowerSyncDatabase

type AbstractPowerSyncDatabase = CommonPowerSyncDatabase;

Deprecated

Use CommonPowerSyncDatabase instead.


ArrayComparatorOptions

type ArrayComparatorOptions<ItemType> = {
compareBy: (item) => string;
};

Options for ArrayComparator

Type Parameters

Type Parameter
ItemType

Properties

PropertyTypeDescription
compareBy(item) => stringReturns a string to uniquely identify an item in the array.

AttachmentData

type AttachmentData = ArrayBuffer | string;

Alpha


AttachmentTableRecord

type AttachmentTableRecord = RowType<AttachmentTable>;

Alpha

AttachmentTableRecord represents the row type of the attachment table.


BaseColumnType

type BaseColumnType<T> = {
type: ColumnType;
};

Type Parameters

Type Parameter
T extends number | string | null

Properties

PropertyType
typeColumnType

BaseListener

type BaseListener = Record<string, ((...event) => any) | undefined>;

ColumnsType

type ColumnsType = Record<string, BaseColumnType<any>>;

DatabaseSource

type DatabaseSource<OpenOptions> =
| {
opened: DBAdapter;
}
| {
factory: SQLOpenFactory;
}
| {
database: OpenOptions;
};

A source describing how to open databases.

For most apps, using the database key with SQLOpenOptions is the easiest and recommended option.

Type Parameters

Type ParameterDefault type
OpenOptions extends SQLOpenOptionsSQLOpenOptions

Union Members

Type Literal
{
opened: DBAdapter;
}
NameTypeDescription
openedDBAdapterWrap an opened DBAdapter as a PowerSync database instance. This is primarily useful for testing. On most platforms, PowerSync would open a pool of SQLite connections by default. This option allows using a single in-memory instance instead. It can also be used to customize the database used by default, e.g. to install additional logging on SQL statements by intercepting methods.

Type Literal
{
factory: SQLOpenFactory;
}
NameTypeDescription
factorySQLOpenFactoryConstruct a PowerSync database that will call SQLOpenFactory.openDB when opened. On most SDKs, passing SQLOpenOptions is a better option. An exception is React Native, where using an OP-SQLite factory is recommended.

Type Literal
{
database: OpenOptions;
}
NameTypeDescription
databaseOpenOptionsConstruct a PowerSync database opening a connection pool from the SQLOpenOptions. At the very least, options include the SQLOpenOptions.dbFilename to open. Depending on the PowerSync SDK used, additional options are available. For example, the web SDK allows configuring the virtual file system implementation used to persist files on the web too.

DifferentialWatchedQuery

type DifferentialWatchedQuery<RowType> = WatchedQuery<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>, DifferentialWatchedQueryListener<RowType>>;

Type Parameters

Type Parameter
RowType

ExtractColumnValueType

type ExtractColumnValueType<T> = T extends BaseColumnType<infer R> ? R : unknown;

Type Parameters

Type Parameter
T extends BaseColumnType<any>

ExtractedTriggerDiffRecord

type ExtractedTriggerDiffRecord<T, TOperationId> = T & { [K in keyof Omit<BaseTriggerDiffRecord<TOperationId>, "id"> as `__${string & K}`]: TriggerDiffRecord<TOperationId>[K] } & {
__previous_value?: string;
};

Experimental Alpha

Querying the DIFF table directly with TriggerDiffHandlerContext#withExtractedDiff will return records with the tracked columns extracted from the JSON value. This type represents the structure of such records.

Type Declaration

NameType
__previous_value?string

Type Parameters

Type ParameterDefault typeDescription
T-The type for the extracted columns from the tracked JSON value.
TOperationId extends string | numbernumberThe type for operation_id. Defaults to number as returned by database queries. Use string for full 64-bit precision when using { castOperationIdAsText: true } option.

Example

// Default: operation_id is number
const diffs = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}>>('SELECT * FROM DIFF');

// With string operation_id for full precision
const diffsWithString = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}, string>>(
'SELECT * FROM DIFF',
undefined,
{ castOperationIdAsText: true }
);

GetAllQueryOptions

type GetAllQueryOptions<RowType> = {
mapper?: (rawRow) => RowType;
parameters?: ReadonlyArray<unknown>;
sql: string;
};

Options for GetAllQuery.

Type Parameters

Type ParameterDefault type
RowTypeunknown

Properties

PropertyTypeDescription
mapper?(rawRow) => RowTypeOptional mapper function to convert raw rows into the desired RowType. Example (rawRow) => ({ id: rawRow.id, created_at: new Date(rawRow.created_at), })
parameters?ReadonlyArray<unknown>-
sqlstring-

IndexShorthand

type IndexShorthand = Record<string, (string | IndexedColumn)[]>;

ListenerCounts

type ListenerCounts<Listener> = Partial<Record<keyof Listener, number>> & {
total: number;
};

Represents the counts of listeners for each event type in a BaseListener.

Type Declaration

NameType
totalnumber

Type Parameters

Type Parameter
Listener extends BaseListener

OpId

type OpId = string;

64-bit unsigned integer stored as a string in base-10.

Not sortable as a string.


PendingStatement

type PendingStatement = {
params: PendingStatementParameter[];
sql: string;
};

A statement that the PowerSync client should use to insert or delete data into a table managed by the user.

Properties

PropertyType
paramsPendingStatementParameter[]
sqlstring

PendingStatementParameter

type PendingStatementParameter =
| "Id"
| {
Column: string;
}
| "Rest";

A parameter to use as part of PendingStatement.

For delete statements, only the "Id" value is supported - the sync client will replace it with the id of the row to be synced.

For insert and replace operations, the values of columns in the table are available as parameters through {Column: 'name'}. The "Rest" parameter gets resolved to a JSON object covering all values from the synced row that haven't been covered by a Column parameter.


PowerSyncDatabaseOptions

type PowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions & DatabaseSource;

QueryParam

type QueryParam = string | number | boolean | null | undefined | bigint | Uint8Array;

Query parameters for ArrayQueryDefinition#parameters


RawTableType

type RawTableType = RawTableTypeWithStatements | InferredRawTableType;

Instructs PowerSync to sync data into a "raw" table.

Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow using client-side table and column constraints.

To collect local writes to raw tables with PowerSync, custom triggers are required. See https://docs.powersync.com/usage/use-case-examples/raw-tables for details and an example on using raw tables.


RowType

type RowType<T> = T extends Table<infer Columns> ? { [K in keyof Columns]: ExtractColumnValueType<Columns[K]> } & {
id: string;
} : never;

Type Parameters

Type Parameter
T extends Table<any>

SchemaTableType

type SchemaTableType<S> = { [K in keyof S]: RowType<S[K]> };

Type Parameters

Type Parameter
S extends SchemaType

SharedConnectionWorker

type SharedConnectionWorker = {
identifier: string;
port: MessagePort;
};

Properties

PropertyType
identifierstring
portMessagePort

SqliteRecord

type SqliteRecord = Record<string, SqliteValue>;

A record of SQLite values representing a row.


SqliteValue

type SqliteValue = string | number | bigint | number[] | Uint8Array | null;

A SQLite value, either text, a number, a blob value or null.


StandardWatchedQuery

type StandardWatchedQuery<DataType> = WatchedQuery<DataType, WatchedQuerySettings<DataType>>;

WatchedQuery returned from Query#watch.

Type Parameters

Type Parameter
DataType

StreamingSyncRequestParameterType

type StreamingSyncRequestParameterType = JSONValue;

TriggerDiffRecord

type TriggerDiffRecord<TOperationId> =
| TriggerDiffUpdateRecord<TOperationId>
| TriggerDiffInsertRecord<TOperationId>
| TriggerDiffDeleteRecord<TOperationId>;

Experimental Alpha

Diffs created by TriggerManager#createDiffTrigger are stored in a temporary table. This is the record structure for all diff records.

Querying the DIFF table directly with TriggerDiffHandlerContext#withDiff will return records with the structure of this type.

Type Parameters

Type ParameterDefault typeDescription
TOperationId extends string | numbernumberThe type for operation_id. Defaults to number as returned by database queries. Use string for full 64-bit precision when using { castOperationIdAsText: true } option.

Example

// Default: operation_id is number
const diffs = await context.withDiff<TriggerDiffRecord>('SELECT * FROM DIFF');

// With string operation_id for full precision
const diffsWithString = await context.withDiff<TriggerDiffRecord<string>>(
'SELECT * FROM DIFF',
undefined,
{ castOperationIdAsText: true }
);

TriggerRemoveCallback

type TriggerRemoveCallback = (options?) => Promise<void>;

Experimental Alpha

Callback to drop a trigger after it has been created.

Parameters

ParameterType
options?TriggerRemoveCallbackOptions

Returns

Promise<void>


WatchedAttachmentItem

type WatchedAttachmentItem =
| {
fileExtension?: never;
filename: string;
id: string;
mediaType?: string;
metaData?: string;
}
| {
fileExtension: string;
filename?: never;
id: string;
mediaType?: string;
metaData?: string;
};

Alpha

WatchedAttachmentItem represents an attachment reference in your application's data model. Use either filename OR fileExtension (not both).


WebDBAdapterConfiguration

type WebDBAdapterConfiguration = ResolvedWebSQLOpenOptions & {
requiresPersistentTriggers: boolean;
};

Type Declaration

NameType
requiresPersistentTriggersboolean

WebPowerSyncDatabaseOptions

type WebPowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions & DatabaseSource<WebSQLOpenOptions> & WebSpecificOptions;

Variables

ATTACHMENT_TABLE

const ATTACHMENT_TABLE: "attachments" = "attachments";

Alpha

The default name of the local table storing attachment data.


ATTACHMENT_TABLE_COLUMNS

const ATTACHMENT_TABLE_COLUMNS: {
filename: BaseColumnType;
has_synced: BaseColumnType;
local_uri: BaseColumnType;
media_type: BaseColumnType;
meta_data: BaseColumnType;
size: BaseColumnType;
state: BaseColumnType;
timestamp: BaseColumnType;
};

Alpha

Type Declaration

NameType
filenameBaseColumnType
has_syncedBaseColumnType
local_uriBaseColumnType
media_typeBaseColumnType
meta_dataBaseColumnType
sizeBaseColumnType
stateBaseColumnType
timestampBaseColumnType

column

const column: {
integer: BaseColumnType<number | null>;
real: BaseColumnType<number | null>;
text: BaseColumnType<string | null>;
};

Type Declaration

NameType
integerBaseColumnType<number | null>
realBaseColumnType<number | null>
textBaseColumnType<string | null>

FalsyComparator

const FalsyComparator: WatchedQueryComparator<unknown>;

Watched query comparator that always reports changed result sets.


LogLevels

const LogLevels: {
debug: 20;
error: 50;
info: 30;
trace: 10;
warn: 40;
};

Type Declaration

NameType
debug20
error50
info30
trace10
warn40

PowerSyncDatabase

const PowerSyncDatabase: PowerSyncDatabaseConstructor<WebPowerSyncDatabaseOptions> = WebPowerSyncDatabase;

A PowerSync database which provides SQLite functionality which is automatically synced.

Example

export const db = new PowerSyncDatabase({
schema: AppSchema,
database: {
dbFilename: 'example.db'
}
});

Functions

FunctionDescription
attachmentFromSqlMaps a database row to an AttachmentRecord.
compilableQueryWatch-
createConsoleLoggerA very simple PowerSyncLogger implementation forwarding messages to console.log.
queryResultFromMappedCreates a query result from rows that have already been mapped to JavaScript.
queryResultFromRawCreates a query result by mapping raw rows to JavaScript.
queryResultWithoutRowsCreates a QueryResult not containing any rows.
sanitizeSQLSQL string template function for TrackDiffOptions#when and CreateDiffTriggerOptions#when.
sanitizeUUIDHelper function for sanitizing UUID input strings. Typically used with sanitizeSQL.