Skip to main content

@powersync/web

Enumerations

EnumerationDescription
ColumnType-
FetchStrategy-
LockType-
OpTypeEnum-
PowerSyncControlCommand-
PSInternalTable-
RowUpdateTypeUpdate table operation numbers from SQLite
SyncClientImplementation-
SyncStreamConnectionMethod-
TemporaryStorageOption-
UpdateTypeType of local change.
WASQLiteVFSList of currently tested virtual filesystems
WatchedQueryListenerEvent-

Classes

ClassDescription
AbortOperationCalls to Abortcontroller.abort(reason: any) will result in the reason being thrown. This is not necessarily an error, but extends error for better logging purposes.
AbstractPowerSyncDatabase-
AbstractPowerSyncDatabaseOpenFactory-
AbstractQueryProcessorPerforms underlying watching and yields a stream of results.
AbstractRemote-
AbstractStreamingSyncImplementation-
AbstractWebPowerSyncDatabaseOpenFactoryIntermediate PowerSync Database Open factory for Web which uses a mock SSR DB Adapter if running on server side. Most SQLite DB implementations only run on client side, this will safely return empty query results in SSR which will allow for generating server partial views.
AbstractWebSQLOpenFactory-
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.
BaseObserver-
Column-
ConnectionManager-
ControlledExecutor-
CrudBatchA batch of client-side changes.
CrudEntryA single client-side change.
CrudTransactionA batch of client-side changes.
DataStreamA very basic implementation of a data stream with backpressure support which does not use native JS streams or async iterators. This is handy for environments such as React Native which need polyfills for the above.
DifferentialQueryProcessorUses the PowerSync onChange event to trigger watched queries. Results are emitted on every change of the relevant tables.
FetchImplementationProviderClass wrapper for providing a fetch implementation. The class wrapper is used to distinguish the fetchImplementation option in [AbstractRemoteOptions] from the general fetch method which is typeof "function"
GetAllQueryPerforms a AbstractPowerSyncDatabase.getAll operation for a watched query.
Index-
IndexedColumn-
OnChangeQueryProcessorUses the PowerSync onChange event to trigger watched queries. Results are emitted on every change of the relevant tables.
OplogEntry-
OpTypeUsed internally for sync buckets.
PowerSyncDatabaseA PowerSync database which provides SQLite functionality which is automatically synced.
SchemaA schema is a collection of tables. It is used to define the structure of a database.
SharedWebStreamingSyncImplementation-
SqliteBucketStorage-
SyncDataBatch-
SyncDataBucket-
SyncProgressProvides realtime progress on how PowerSync is downloading rows.
SyncStatus-
Table-
TableV2Generate a new table from the columns and indexes
UploadQueueStats-
WASqliteConnectionWA-SQLite connection which directly interfaces with WA-SQLite. This is usually instantiated inside a worker.
WASQLiteDBAdapterAdapter for WA-SQLite SQLite connections.
WASQLiteOpenFactoryOpens a SQLite connection using WA-SQLite.
WASQLitePowerSyncDatabaseOpenFactory-
WebRemote-
WebStreamingSyncImplementation-

Interfaces

AbstractQueryProcessorOptions<Data, Settings>

Internal

Extended by

Type Parameters

Type ParameterDefault type
Data-
Settings extends WatchedQueryOptionsWatchedQueryOptions

Properties

PropertyType
dbAbstractPowerSyncDatabase
placeholderDataData
watchOptionsSettings

AbstractStreamingSyncImplementationOptions

Internal

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter--
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.AdditionalConnectionOptions.crudUploadThrottleMs
identifier?stringAn identifier for which PowerSync DB this sync implementation is linked to. Most commonly DB name, but not restricted to DB name.-
logger?ILogger--
remoteAbstractRemote--
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.AdditionalConnectionOptions.retryDelayMs
uploadCrud() => Promise<void>--

AdditionalConnectionOptions

Internal

Extended by

Properties

PropertyTypeDescription
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.

ArrayQueryDefinition<RowType>

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: Record<string, unknown>) => 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-

AsyncDatabaseConnection<Config>

Internal

An async Database connection which provides basic async SQL methods. This is usually a proxied through a web worker.

Type Parameters

Type ParameterDefault type
Config extends ResolvedWebSQLOpenOptionsResolvedWebSQLOpenOptions

Methods

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

Promise<void>


execute()
execute(sql, params?): Promise<ProxiedQueryResult>
Parameters
ParameterType
sqlstring
params?any[]
Returns

Promise<ProxiedQueryResult>


executeBatch()
executeBatch(sql, params?): Promise<ProxiedQueryResult>
Parameters
ParameterType
sqlstring
params?any[]
Returns

Promise<ProxiedQueryResult>


executeRaw()
executeRaw(sql, params?): Promise<any[][]>
Parameters
ParameterType
sqlstring
params?any[]
Returns

Promise<any[][]>


getConfig()
getConfig(): Promise<Config>
Returns

Promise<Config>


init()
init(): Promise<void>
Returns

Promise<void>


registerOnTableChange()
registerOnTableChange(callback): Promise<() => void>
Parameters
ParameterType
callbackOnTableChangeCallback
Returns

Promise<() => void>


BaseConnectionOptions

Internal

Extended by

Properties

PropertyTypeDescription
clientImplementation?SyncClientImplementationWhether to use a JavaScript implementation to handle received sync lines from the sync service, or whether this work should be offloaded to the PowerSync core extension. This defaults to the JavaScript implementation (SyncClientImplementation.JAVASCRIPT) since the (SyncClientImplementation.RUST) implementation is experimental at the moment.
connectionMethod?SyncStreamConnectionMethodThe connection method to use when streaming updates from the PowerSync backend instance. Defaults to a HTTP streaming connection.
fetchStrategy?FetchStrategyThe fetch strategy to use when streaming updates from the PowerSync backend instance.
params?Record<string, JSONValue>These parameters are passed to the sync rules, and will be available under theuser_parameters object.
serializedSchema?anyThe serialized schema - mainly used to forward information about raw tables to the sync client.

BaseObserverInterface<T>

Extended by

Type Parameters

Type Parameter
T extends BaseListener

Methods

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

Function

Returns

void


BasePowerSyncDatabaseOptions

Internal

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.AdditionalConnectionOptions.crudUploadThrottleMs
logger?ILogger--
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.-
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.AdditionalConnectionOptions.retryDelayMs
schemaSchemaSchema used for the local database.-

BatchedUpdateNotification

Properties

PropertyType
groupedUpdatesRecord<string, TableUpdateOperation[]>
rawUpdatesUpdateNotification[]
tablesstring[]

BucketChecksum

Properties

PropertyTypeDescription
bucketstring-
checksumnumber32-bit unsigned hash.
count?numberCount of operations - informational only.
priority?number-

BucketDescription

Properties

PropertyType
namestring
prioritynumber

BucketRequest

Properties

PropertyTypeDescription
afterstringBase-10 number. Sync all data from this bucket with op_id > after.
namestring-

BucketState

Properties

PropertyType
bucketstring
op_idstring

BucketStorageAdapter

Extends

Properties

PropertyTypeInherited from
dispose() => void | Promise<void>Disposable.dispose

Methods

control()
control(op, payload): Promise<string>

Invokes the powersync_control function for the sync client.

Parameters
ParameterType
opPowerSyncControlCommand
payloadnull | string | Uint8Array<ArrayBufferLike>
Returns

Promise<string>


getBucketOperationProgress()
getBucketOperationProgress(): Promise<BucketOperationProgress>
Returns

Promise<BucketOperationProgress>


getBucketStates()
getBucketStates(): Promise<BucketState[]>
Returns

Promise<BucketState[]>


getClientId()
getClientId(): Promise<string>

Get an unique client id.

Returns

Promise<string>


getCrudBatch()
getCrudBatch(limit?): Promise<null | CrudBatch>
Parameters
ParameterType
limit?number
Returns

Promise<null | CrudBatch>


getMaxOpId()
getMaxOpId(): string
Returns

string


hasCompletedSync()
hasCompletedSync(): Promise<boolean>
Returns

Promise<boolean>


hasCrud()
hasCrud(): Promise<boolean>
Returns

Promise<boolean>


hasMigratedSubkeys()
hasMigratedSubkeys(): Promise<boolean>
Returns

Promise<boolean>


init()
init(): Promise<void>
Returns

Promise<void>


migrateToFixedSubkeys()
migrateToFixedSubkeys(): Promise<void>
Returns

Promise<void>


nextCrudItem()
nextCrudItem(): Promise<undefined | CrudEntry>
Returns

Promise<undefined | CrudEntry>


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

Function

Returns

void

Inherited from

BaseObserverInterface.registerListener


removeBuckets()
removeBuckets(buckets): Promise<void>
Parameters
ParameterType
bucketsstring[]
Returns

Promise<void>


saveSyncData()
saveSyncData(batch, fixedKeyFormat?): Promise<void>
Parameters
ParameterType
batchSyncDataBatch
fixedKeyFormat?boolean
Returns

Promise<void>


setTargetCheckpoint()
setTargetCheckpoint(checkpoint): Promise<void>
Parameters
ParameterType
checkpointCheckpoint
Returns

Promise<void>


startSession()
startSession(): void
Returns

void


syncLocalDatabase()
syncLocalDatabase(checkpoint, priority?): Promise<{
checkpointValid: boolean;
failures: any[];
ready: boolean;
}>
Parameters
ParameterType
checkpointCheckpoint
priority?number
Returns

Promise<{ checkpointValid: boolean; failures: any[]; ready: boolean; }>


updateLocalTarget()
updateLocalTarget(cb): Promise<boolean>
Parameters
ParameterType
cb() => Promise<string>
Returns

Promise<boolean>


BucketStorageListener

Extends

Indexable

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

Properties

PropertyType
crudUpdate() => void

Checkpoint

Properties

PropertyType
bucketsBucketChecksum[]
last_op_idstring
write_checkpoint?string

ChecksumCache

Properties

PropertyType
checksumsMap<string, { checksum: BucketChecksum; last_op_id: string; }>
lastOpIdstring

ColumnOptions

Properties

PropertyType
namestring
type?ColumnType

CompilableQuery<T>

Type Parameters

Type Parameter
T

Methods

compile()
compile(): CompiledQuery
Returns

CompiledQuery


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

Promise<T[]>


CompilableQueryWatchHandler<T>

Type Parameters

Type Parameter
T

Properties

PropertyType
onError?(error: Error) => void
onResult(results: T[]) => void

CompiledQuery

Properties

PropertyModifierType
parametersreadonlyreadonly unknown[]
sqlreadonlystring

ConnectionManagerListener

Internal

Extends

Indexable

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

Properties

PropertyType
syncStreamCreated(sync: StreamingSyncImplementation) => void

ConnectionManagerOptions

Internal

Properties

PropertyType
loggerILogger

Methods

createSyncImplementation()
createSyncImplementation(connector, options): Promise<ConnectionManagerSyncImplementationResult>
Parameters
ParameterType
connectorPowerSyncBackendConnector
optionsInternalConnectionOptions
Returns

Promise<ConnectionManagerSyncImplementationResult>


ConnectionManagerSyncImplementationResult

Internal

Properties

PropertyTypeDescription
onDispose() => void | Promise<void>Additional cleanup function which is called after the sync stream implementation is disposed.
syncStreamingSyncImplementation-

ContinueCheckpointRequest

For sync2.json

Properties

PropertyTypeDescription
bucketsBucketRequest[]Existing bucket states. Only these buckets are synchronized.
checkpoint_tokenstring-
limit?number-

ControlledExecutorOptions

Properties

PropertyTypeDescription
throttleEnabled?booleanIf throttling is enabled, it ensures only one task runs at a time, and only one additional task can be scheduled to run after the current task completes. The pending task will be overwritten by the latest task. Enabled by default.

CreateLoggerOptions

Properties

PropertyType
logLevel?ILogLevel

CrudRequest

For crud.json

Properties

PropertyType
dataCrudEntry[]

CrudResponse

Properties

PropertyTypeDescription
checkpoint?stringA sync response with a checkpoint >= this checkpoint would contain all the changes in this request. Any earlier checkpoint may or may not contain these changes. May be empty when the request contains no ops.

DataStreamListener<Data>

Extends

Type Parameters

Type ParameterDefault type
Data extends anyany

Indexable

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

Properties

PropertyType
closed() => void
data(data: Data) => Promise<void>
error(error: Error) => void
highWater() => Promise<void>
lowWater() => Promise<void>

DBAdapter

Extends

Properties

PropertyTypeDescription
close() => void | Promise<void>-
execute(query: string, params?: any[]) => Promise<QueryResult>-
executeBatch(query: string, params?: any[][]) => Promise<QueryResult>-
executeRaw(query: string, params?: any[]) => Promise<any[][]>-
namestring-
readLock<T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T>-
readTransaction<T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T>-
refreshSchema() => Promise<void>This method refreshes the schema information across all connections. This is for advanced use cases, and should generally not be needed.
writeLock<T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T>-
writeTransaction<T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T>-

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T>

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T[]>

Inherited from

DBGetUtils.getAll


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

Execute a read-only query and return the first result, or null if the ResultSet is empty.

Type Parameters
Type Parameter
T
Parameters
ParameterType
sqlstring
parameters?any[]
Returns

Promise<null | T>

Inherited from

DBGetUtils.getOptional


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

Function

Returns

void

Inherited from

BaseObserverInterface.registerListener


DBAdapterListener

Extends

Indexable

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

Properties

PropertyTypeDescription
tablesUpdated(updateNotification: | BatchedUpdateNotification | 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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T>


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

Execute a read-only query and return results.

Type Parameters
Type Parameter
T
Parameters
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T[]>


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

Execute a read-only query and return the first result, or null if the ResultSet is empty.

Type Parameters
Type Parameter
T
Parameters
ParameterType
sqlstring
parameters?any[]
Returns

Promise<null | T>


DBLockOptions

Properties

PropertyType
timeoutMs?number

DifferentialQueryProcessorOptions<RowType>

Internal

Extends

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeInherited from
dbAbstractPowerSyncDatabaseAbstractQueryProcessorOptions.db
placeholderDataRowType[]AbstractQueryProcessorOptions.placeholderData
rowComparator?DifferentialWatchedQueryComparator<RowType>-
watchOptionsDifferentialWatchedQuerySettingsAbstractQueryProcessorOptions.watchOptions

DifferentialWatchedQueryComparator<RowType>

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

Type Parameters

Type Parameter
RowType

Properties

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

DifferentialWatchedQueryListener<RowType>

Extends

Type Parameters

Type Parameter
RowType

Indexable

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

Properties

PropertyTypeInherited from
closed?() => void | Promise<void>WatchedQueryListener.closed
onData?(data: readonly Readonly<RowType>[]) => void | Promise<void>WatchedQueryListener.onData
onDiff?(diff: WatchedQueryDifferential<RowType>) => void | Promise<void>-
onError?(error: Error) => void | Promise<void>WatchedQueryListener.onError
onStateChange?(state: WatchedQueryState<readonly Readonly<RowType>[]>) => void | Promise<void>WatchedQueryListener.onStateChange

DifferentialWatchedQueryOptions<RowType>

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

Extends

Extended by

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDefault valueDescriptionInherited from
placeholderData?RowType[]undefinedInitial result data which is presented while the initial loading is executing.-
reportFetching?booleanundefinedIf 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>DEFAULT_ROW_COMPARATORRow 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?numberundefinedThe minimum interval between queries.WatchedQueryOptions.throttleMs
triggerOnTables?string[]undefinedBy 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<RowType>

Settings for differential incremental watched queries using.

Extends

Type Parameters

Type Parameter
RowType

Properties

PropertyTypeDefault valueDescriptionInherited from
placeholderData?RowType[]undefinedInitial result data which is presented while the initial loading is executing.DifferentialWatchedQueryOptions.placeholderData
queryWatchCompatibleQuery<RowType[]>undefinedThe query here must return an array of items that can be differentiated.-
reportFetching?booleanundefinedIf 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>DEFAULT_ROW_COMPARATORRow 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?numberundefinedThe minimum interval between queries.DifferentialWatchedQueryOptions.throttleMs
triggerOnTables?string[]undefinedBy 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

Extended by

Properties

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

IndexColumnOptions

Properties

PropertyType
ascending?boolean
namestring

IndexOptions

Properties

PropertyType
columns?IndexedColumn[]
namestring

InternalConnectionOptions

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
clientImplementation?SyncClientImplementationWhether to use a JavaScript implementation to handle received sync lines from the sync service, or whether this work should be offloaded to the PowerSync core extension. This defaults to the JavaScript implementation (SyncClientImplementation.JAVASCRIPT) since the (SyncClientImplementation.RUST) implementation is experimental at the moment.BaseConnectionOptions.clientImplementation
connectionMethod?SyncStreamConnectionMethodThe connection method to use when streaming updates from the PowerSync backend instance. Defaults to a HTTP streaming connection.BaseConnectionOptions.connectionMethod
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.AdditionalConnectionOptions.crudUploadThrottleMs
fetchStrategy?FetchStrategyThe fetch strategy to use when streaming updates from the PowerSync backend instance.BaseConnectionOptions.fetchStrategy
params?Record<string, JSONValue>These parameters are passed to the sync rules, and will be available under theuser_parameters object.BaseConnectionOptions.params
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.AdditionalConnectionOptions.retryDelayMs
serializedSchema?anyThe serialized schema - mainly used to forward information about raw tables to the sync client.BaseConnectionOptions.serializedSchema

LinkQueryOptions<Data, Settings>

Internal

Type Parameters

Type ParameterDefault type
Data-
Settings extends WatchedQueryOptionsWatchedQueryOptions

Properties

PropertyType
abortSignalAbortSignal
settingsSettings

LockContext

Extends

Extended by

Properties

PropertyTypeDescription
execute(query: string, params?: any[]) => Promise<QueryResult>Execute a single write statement.
executeRaw(query: string, params?: any[]) => Promise<any[][]>Execute a single write statement and return raw results. Unlike execute, which returns an object with structured key-value pairs, executeRaw returns a nested array of raw values, where each row is represented as an array of column values without field names. Example result: [ [ '1', 'list 1', '33', 'Post content', '1' ] ] Where as execute's rows._array would have been: [ { id: '33', name: 'list 1', content: 'Post content', list_id: '1' } ]

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T>

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T[]>

Inherited from

DBGetUtils.getAll


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

Execute a read-only query and return the first result, or null if the ResultSet is empty.

Type Parameters
Type Parameter
T
Parameters
ParameterType
sqlstring
parameters?any[]
Returns

Promise<null | T>

Inherited from

DBGetUtils.getOptional


LockOptions<T>

Abstract Lock to be implemented by various JS environments

Type Parameters

Type Parameter
T

Properties

PropertyType
callback() => Promise<T>
signal?AbortSignal
typeLockType

OnChangeQueryProcessorOptions<Data>

Internal

Extends

Type Parameters

Type Parameter
Data

Properties

PropertyTypeInherited from
comparator?WatchedQueryComparator<Data>-
dbAbstractPowerSyncDatabaseAbstractQueryProcessorOptions.db
placeholderDataDataAbstractQueryProcessorOptions.placeholderData
watchOptionsWatchedQuerySettingsAbstractQueryProcessorOptions.watchOptions

OplogEntryJSON

Properties

PropertyType
checksumnumber
data?string
object_id?string
object_type?string
opstring
op_idstring
subkey?string

ParsedQuery

Properties

PropertyType
parametersany[]
sqlStatementstring

PowerSyncBackendConnector

Properties

PropertyTypeDescription
fetchCredentials() => Promise<null | PowerSyncCredentials>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: AbstractPowerSyncDatabase) => Promise<void>Upload local changes to the app backend. Use AbstractPowerSyncDatabase.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

PowerSyncDatabaseOptions

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.BasePowerSyncDatabaseOptions.crudUploadThrottleMs
database| SQLOpenOptions | DBAdapter | SQLOpenFactorySource for a SQLite database connection. This can be either: - A DBAdapter if providing an instantiated SQLite connection - A SQLOpenFactory which will be used to open a SQLite connection - SQLOpenOptions for opening a SQLite connection with a default SQLOpenFactory-
logger?ILogger-BasePowerSyncDatabaseOptions.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.BasePowerSyncDatabaseOptions.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelayMs
schemaSchemaSchema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithDBAdapter

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.BasePowerSyncDatabaseOptions.crudUploadThrottleMs
databaseDBAdapter--
logger?ILogger-BasePowerSyncDatabaseOptions.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.BasePowerSyncDatabaseOptions.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelayMs
schemaSchemaSchema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithOpenFactory

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.BasePowerSyncDatabaseOptions.crudUploadThrottleMs
databaseSQLOpenFactory--
logger?ILogger-BasePowerSyncDatabaseOptions.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.BasePowerSyncDatabaseOptions.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelayMs
schemaSchemaSchema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithSettings

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.BasePowerSyncDatabaseOptions.crudUploadThrottleMs
databaseSQLOpenOptions--
logger?ILogger-BasePowerSyncDatabaseOptions.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.BasePowerSyncDatabaseOptions.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelayMs
schemaSchemaSchema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDBListener

Extends

Indexable

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

Properties

PropertyTypeDescriptionInherited from
closed() => void | Promise<void>--
closing() => void | Promise<void>--
initialized() => void--
schemaChanged(schema: Schema) => void--
statusChanged?(status: SyncStatus) => voidTriggers whenever the status' members have changed in valueStreamingSyncImplementationListener.statusChanged
statusUpdated?(statusUpdate: SyncStatusOptions) => voidTriggered whenever a status update has been attempted to be made or refreshed.StreamingSyncImplementationListener.statusUpdated

PowerSyncOpenFactoryOptions

Extends

Extended by

Properties

PropertyTypeDescriptionOverridesInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.-Partial.crudUploadThrottleMs
database?| SQLOpenOptions | DBAdapter | SQLOpenFactorySource for a SQLite database connection. This can be either: - A DBAdapter if providing an instantiated SQLite connection - A SQLOpenFactory which will be used to open a SQLite connection - SQLOpenOptions for opening a SQLite connection with a default SQLOpenFactory-Partial.database
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
logger?ILogger--Partial.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.-Partial.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.-Partial.retryDelayMs
schemaSchemaSchema used for the local database.Partial.schema-

ProgressWithOperations

Information about a progressing download made by the PowerSync SDK.

To obtain these values, use SyncProgress, available through SyncStatus#downloadProgress.

Properties

PropertyTypeDescription
downloadedFractionnumberRelative progress, as downloadedOperations of 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<RowType>

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>[]>


ResolvedWASQLiteOpenFactoryOptions

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
cacheSizeKbnumber-ResolvedWebSQLOpenOptions.cacheSizeKb
dbFilenamestringFilename for the database.ResolvedWebSQLOpenOptions.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.ResolvedWebSQLOpenOptions.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'ResolvedWebSQLOpenOptions.debugMode
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.ResolvedWebSQLOpenOptions.encryptionKey
flagsRequired-ResolvedWebSQLOpenOptions.flags
temporaryStorageTemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.ResolvedWebSQLOpenOptions.temporaryStorage
vfsWASQLiteVFS--

ResolvedWebSQLOpenOptions

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
cacheSizeKbnumber--
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
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.-
flagsRequired--
temporaryStorageTemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.-

SharedWebStreamingSyncImplementationOptions

Internal

Extends

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter-WebStreamingSyncImplementationOptions.adapter
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.WebStreamingSyncImplementationOptions.crudUploadThrottleMs
dbWebDBAdapter--
flags?WebSQLFlags-WebStreamingSyncImplementationOptions.flags
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
logger?ILogger-WebStreamingSyncImplementationOptions.logger
remoteAbstractRemote-WebStreamingSyncImplementationOptions.remote
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.WebStreamingSyncImplementationOptions.retryDelayMs
sync?{ worker: string | URL | (options) => SharedWorker; }-WebStreamingSyncImplementationOptions.sync
sync.worker?string | URL | (options) => SharedWorker--
uploadCrud() => Promise<void>-WebStreamingSyncImplementationOptions.uploadCrud

SQLOnChangeOptions

Extended by

Properties

PropertyTypeDescription
rawTableNames?booleanDeprecated All tables specified in tables will be watched, including PowerSync tables with prefixes. Allows for watching any SQL table by not removing PowerSync table name prefixes
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>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.-
rawTableNames?booleanDeprecated All tables specified in tables will be watched, including PowerSync tables with prefixes. Allows for watching any SQL table by not removing PowerSync table name prefixesSQLOnChangeOptions.rawTableNames
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<RowType>

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

StreamingSyncCheckpoint

Properties

PropertyType
checkpointCheckpoint

StreamingSyncCheckpointComplete

Properties

PropertyType
checkpoint_complete{ last_op_id: string; }
checkpoint_complete.last_op_idstring

StreamingSyncCheckpointDiff

Properties

PropertyType
checkpoint_diff{ last_op_id: string; removed_buckets: string[]; updated_buckets: BucketChecksum[]; write_checkpoint: string; }
checkpoint_diff.last_op_idstring
checkpoint_diff.removed_bucketsstring[]
checkpoint_diff.updated_bucketsBucketChecksum[]
checkpoint_diff.write_checkpoint?string

StreamingSyncCheckpointPartiallyComplete

Properties

PropertyType
partial_checkpoint_complete{ last_op_id: string; priority: number; }
partial_checkpoint_complete.last_op_idstring
partial_checkpoint_complete.prioritynumber

StreamingSyncDataJSON

Properties

PropertyType
dataSyncDataBucketJSON

StreamingSyncImplementation

Extends

Properties

PropertyTypeInherited from
dispose() => void | Promise<void>Disposable.dispose
getWriteCheckpoint() => Promise<string>-
hasCompletedSync() => Promise<boolean>-
isConnectedboolean-
lastSyncedAt?Date-
syncStatusSyncStatus-
triggerCrudUpload() => void-

Methods

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

Connects to the sync service

Parameters
ParameterType
options?InternalConnectionOptions
Returns

Promise<void>


disconnect()
disconnect(): Promise<void>

Disconnects from the sync services.

Returns

Promise<void>

Throws

if not connected or if abort is not controlled internally


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

Function

Returns

void

Inherited from

BaseObserverInterface.registerListener


waitForReady()
waitForReady(): Promise<void>
Returns

Promise<void>


waitForStatus()
waitForStatus(status): Promise<void>
Parameters
ParameterType
statusSyncStatusOptions
Returns

Promise<void>


waitUntilStatusMatches()
waitUntilStatusMatches(predicate): Promise<void>
Parameters
ParameterType
predicate(status) => boolean
Returns

Promise<void>


StreamingSyncImplementationListener

Extends

Extended by

Indexable

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

Properties

PropertyTypeDescription
statusChanged?(status: SyncStatus) => voidTriggers whenever the status' members have changed in value
statusUpdated?(statusUpdate: SyncStatusOptions) => voidTriggered whenever a status update has been attempted to be made or refreshed.

StreamingSyncKeepalive

Properties

PropertyTypeDescription
token_expires_innumberIf specified, token expires in this many seconds.

StreamingSyncRequest

Properties

PropertyTypeDescription
buckets?BucketRequest[]Existing bucket states.
client_id?string-
include_checksumbooleanWhether or not to compute a checksum for each checkpoint
only?string[]If specified, limit the response to only include these buckets.
parameters?Record<string, JSONValue>Client parameters to be passed to the sync rules.
raw_databooleanChanges the response to stringified data in each OplogEntry

SyncLocalDatabaseResult

Properties

PropertyType
checkpointFailures?string[]
checkpointValidboolean
readyboolean

SyncNewCheckpointRequest

Properties

PropertyTypeDescription
buckets?BucketRequest[]Existing bucket states. Used if include_data is specified.
limit?number-
request_checkpoint{ include_checksum: boolean; include_data: boolean; }-
request_checkpoint.include_checksumbooleanWhether or not to compute a checksum.
request_checkpoint.include_databooleanWhether or not to include an initial data request.

SyncPriorityStatus

Properties

PropertyType
hasSynced?boolean
lastSyncedAt?Date
prioritynumber

SyncResponse

Properties

PropertyTypeDescription
checkpoint?Checkpoint-
checkpoint_token?string-
data?SyncDataBucketJSON[]Data for the buckets returned. May not have an an entry for each bucket in the request.
has_morebooleanTrue if the response limit has been reached, and another request must be made.

TableOptions

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

TableUpdateOperation

Extended by

Properties

PropertyType
opTypeRowUpdateType
rowIdnumber

TableV2Options

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

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

PropertyTypeDescriptionInherited from
commit() => Promise<QueryResult>Commit multiple changes to the local DB using the Transaction context.-
execute(query: string, params?: any[]) => Promise<QueryResult>Execute a single write statement.LockContext.execute
executeRaw(query: string, params?: any[]) => Promise<any[][]>Execute a single write statement and return raw results. Unlike execute, which returns an object with structured key-value pairs, executeRaw returns a nested array of raw values, where each row is represented as an array of column values without field names. Example result: [ [ '1', 'list 1', '33', 'Post content', '1' ] ] Where as execute's rows._array would have been: [ { id: '33', name: 'list 1', content: 'Post content', list_id: '1' } ]LockContext.executeRaw
rollback() => Promise<QueryResult>Roll back multiple attempted changes using the Transaction context.-

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T>

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
ParameterType
sqlstring
parameters?any[]
Returns

Promise<T[]>

Inherited from

LockContext.getAll


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

Execute a read-only query and return the first result, or null if the ResultSet is empty.

Type Parameters
Type Parameter
T
Parameters
ParameterType
sqlstring
parameters?any[]
Returns

Promise<null | T>

Inherited from

LockContext.getOptional


UpdateNotification

Notification of an update to one or more tables, for the purpose of realtime change notifications.

Extends

Properties

PropertyTypeInherited from
opTypeRowUpdateTypeTableUpdateOperation.opType
rowIdnumberTableUpdateOperation.rowId
tablestring-

WASQLiteDBAdapterOptions

Extends

Properties

PropertyTypeDescriptionInherited from
cacheSizeKb?number--
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.Omit.crudUploadThrottleMs
database?| SQLOpenOptions | DBAdapter | SQLOpenFactorySource for a SQLite database connection. This can be either: - A DBAdapter if providing an instantiated SQLite connection - A SQLOpenFactory which will be used to open a SQLite connection - SQLOpenOptions for opening a SQLite connection with a default SQLOpenFactoryOmit.database
dbFilenamestringFilename for the database.Omit.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.Omit.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'Omit.debugMode
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using multiple-ciphers.-
flags?WebSQLFlags--
logger?ILogger-Omit.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.Omit.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.Omit.retryDelayMs
temporaryStorage?TemporaryStorageOption--
vfs?WASQLiteVFS--
worker?string | URL | (options) => Worker | SharedWorker--
workerPort?MessagePortUse an existing port to an initialized worker. A worker will be initialized if none is provided-

WASQLiteOpenFactoryOptions

Options for opening a Web SQL connection

Extends

Properties

PropertyTypeDescriptionInherited from
cacheSizeKb?numberMaximum SQLite cache size. Defaults to 50MB. For details, see: https://www.sqlite.org/pragma.html#pragma_cache_sizeWebSQLOpenFactoryOptions.cacheSizeKb
dbFilenamestringFilename for the database.WebSQLOpenFactoryOptions.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.WebSQLOpenFactoryOptions.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'WebSQLOpenFactoryOptions.debugMode
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.WebSQLOpenFactoryOptions.encryptionKey
flags?WebSQLFlags-WebSQLOpenFactoryOptions.flags
logger?ILogger-WebSQLOpenFactoryOptions.logger
temporaryStorage?TemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets. For details, see: https://www.sqlite.org/pragma.html#pragma_temp_storeWebSQLOpenFactoryOptions.temporaryStorage
vfs?WASQLiteVFS--
worker?string | URL | (options) => Worker | SharedWorkerAllows 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.WebSQLOpenFactoryOptions.worker

WatchCompatibleQuery<ResultType>

Similar to CompatibleQuery, except the execute method does not enforce an Array result type.

Type Parameters

Type Parameter
ResultType

Methods

compile()
compile(): CompiledQuery
Returns

CompiledQuery


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

Promise<ResultType>


WatchedQuery<Data, Settings, Listener>

Extends

  • MetaBaseObserverInterface<Listener>

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

Function

A function to unsubscribe from the events.

Returns

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

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: Data, previous: Data) => boolean

WatchedQueryDifferential<RowType>

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

Extends

Extended by

Type Parameters

Type Parameter
Data

Indexable

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

Properties

PropertyType
closed?() => void | Promise<void>
onData?(data: Data) => void | Promise<void>
onError?(error: Error) => void | Promise<void>
onStateChange?(state: WatchedQueryState<Data>) => void | Promise<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<RowType>

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

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

State for WatchedQuery instances.

Type Parameters

Type Parameter
Data

Properties

PropertyModifierTypeDescription
datareadonlyDataThe last data returned by the query.
errorreadonlynull | ErrorThe 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.
lastUpdatedreadonlynull | DateThe last time the query was updated.

WatchExecuteOptions

Options provided to the execute method of a WatchCompatibleQuery.

Properties

PropertyType
dbAbstractPowerSyncDatabase
parametersany[]
sqlstring

WatchHandler

Properties

PropertyType
onError?(error: Error) => void
onResult(results: QueryResult) => void

WatchOnChangeEvent

Properties

PropertyType
changedTablesstring[]

WatchOnChangeHandler

Properties

PropertyType
onChange(event: WatchOnChangeEvent) => void | Promise<void>
onError?(error: Error) => void

WebEncryptionOptions

Properties

PropertyTypeDescription
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using Multiple Ciphers.

WebPowerSyncFlags

Common settings used when creating SQL connections on web.

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
broadcastLogs?booleanBroadcast logs from shared workers, such as the shared sync worker, to individual tabs. This defaults to true.WebSQLFlags.broadcastLogs
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.WebSQLFlags.disableSSRWarning
enableMultiTabs?booleanEnables multi tab supportWebSQLFlags.enableMultiTabs
externallyUnload?booleanExternally unload open PowerSync database instances when the window closes. Setting this to true requires calling close on all open PowerSyncDatabase instances before the window unloads-
ssrMode?booleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-opWebSQLFlags.ssrMode
useWebWorker?booleanThe SQLite connection is often executed through a web worker in order to offload computation. This can be used to manually disable the use of web workers in environments where web workers might be unstable.WebSQLFlags.useWebWorker

WebPowerSyncOpenFactoryOptions

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.PowerSyncOpenFactoryOptions.crudUploadThrottleMs
database?| SQLOpenOptions | DBAdapter | SQLOpenFactorySource for a SQLite database connection. This can be either: - A DBAdapter if providing an instantiated SQLite connection - A SQLOpenFactory which will be used to open a SQLite connection - SQLOpenOptions for opening a SQLite connection with a default SQLOpenFactoryPowerSyncOpenFactoryOptions.database
dbFilenamestringFilename for the database.PowerSyncOpenFactoryOptions.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.PowerSyncOpenFactoryOptions.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'PowerSyncOpenFactoryOptions.debugMode
flags?WebPowerSyncOpenFlags--
logger?ILogger-PowerSyncOpenFactoryOptions.logger
retryDelay?numberDeprecated Use retryDelayMs instead as this will be removed in future releases.PowerSyncOpenFactoryOptions.retryDelay
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.PowerSyncOpenFactoryOptions.retryDelayMs
schemaSchemaSchema used for the local database.PowerSyncOpenFactoryOptions.schema

WebPowerSyncOpenFlags

WebPowerSyncFlags Maintaining export for consistency with API from previous versions

Extends

Properties

PropertyTypeDescriptionInherited from
broadcastLogs?booleanBroadcast logs from shared workers, such as the shared sync worker, to individual tabs. This defaults to true.WebPowerSyncFlags.broadcastLogs
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.WebPowerSyncFlags.disableSSRWarning
enableMultiTabs?booleanEnables multi tab supportWebPowerSyncFlags.enableMultiTabs
externallyUnload?booleanExternally unload open PowerSync database instances when the window closes. Setting this to true requires calling close on all open PowerSyncDatabase instances before the window unloadsWebPowerSyncFlags.externallyUnload
ssrMode?booleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-opWebPowerSyncFlags.ssrMode
useWebWorker?booleanThe SQLite connection is often executed through a web worker in order to offload computation. This can be used to manually disable the use of web workers in environments where web workers might be unstable.WebPowerSyncFlags.useWebWorker

WebSQLFlags

Common settings used when creating SQL connections on web.

Extended by

Properties

PropertyTypeDescription
broadcastLogs?booleanBroadcast logs from shared workers, such as the shared sync worker, to individual tabs. This defaults to true.
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.
enableMultiTabs?booleanEnables multi tab support
ssrMode?booleanOpen in SSR placeholder mode. DB operations and Sync operations will be a No-op
useWebWorker?booleanThe SQLite connection is often executed through a web worker in order to offload computation. This can be used to manually disable the use of web workers in environments where web workers might be unstable.

WebSQLOpenFactoryOptions

Options for opening a Web SQL connection

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
cacheSizeKb?numberMaximum SQLite cache size. Defaults to 50MB. For details, see: https://www.sqlite.org/pragma.html#pragma_cache_size-
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
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.-
flags?WebSQLFlags--
logger?ILogger--
temporaryStorage?TemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets. For details, see: https://www.sqlite.org/pragma.html#pragma_temp_store-
worker?string | URL | (options) => Worker | SharedWorkerAllows 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.-

WebStreamingSyncImplementationOptions

Internal

Extends

Extended by

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter-AbstractStreamingSyncImplementationOptions.adapter
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.AbstractStreamingSyncImplementationOptions.crudUploadThrottleMs
flags?WebSQLFlags--
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
logger?ILogger-AbstractStreamingSyncImplementationOptions.logger
remoteAbstractRemote-AbstractStreamingSyncImplementationOptions.remote
retryDelayMs?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.AbstractStreamingSyncImplementationOptions.retryDelayMs
sync?{ worker: string | URL | (options) => SharedWorker; }--
sync.worker?string | URL | (options) => SharedWorker--
uploadCrud() => Promise<void>-AbstractStreamingSyncImplementationOptions.uploadCrud

WebSyncOptions

Properties

PropertyTypeDescription
worker?string | URL | (options) => SharedWorkerAllows 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.

WorkerDBOpenerOptions

Extends

Properties

PropertyTypeDescriptionInherited from
cacheSizeKbnumber-ResolvedWASQLiteOpenFactoryOptions.cacheSizeKb
dbFilenamestringFilename for the database.ResolvedWASQLiteOpenFactoryOptions.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.ResolvedWASQLiteOpenFactoryOptions.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'ResolvedWASQLiteOpenFactoryOptions.debugMode
encryptionKey?stringEncryption key for the database. If set, the database will be encrypted using ChaCha20.ResolvedWASQLiteOpenFactoryOptions.encryptionKey
flagsRequired-ResolvedWASQLiteOpenFactoryOptions.flags
logLevelILogLevel--
temporaryStorageTemporaryStorageOptionWhere to store SQLite temporary files. Defaults to 'MEMORY'. Setting this to FILESYSTEM can cause issues with larger queries or datasets.ResolvedWASQLiteOpenFactoryOptions.temporaryStorage
vfsWASQLiteVFS-ResolvedWASQLiteOpenFactoryOptions.vfs

Type Aliases

AbstractRemoteOptions

type AbstractRemoteOptions = {
fetchImplementation: | FetchImplementation
| FetchImplementationProvider;
fetchOptions: {};
socketUrlTransformer: (url) => string;
};

Type declaration

NameTypeDescription
fetchImplementation| FetchImplementation | FetchImplementationProviderOptionally provide the fetch implementation to use. Note that this usually needs to be bound to the global scope. Binding should be done before passing here.
fetchOptions?{}Optional options to pass directly to all fetch calls. This can include fields such as dispatcher (e.g. for proxy support), cache, or any other fetch-compatible options.
socketUrlTransformer(url) => stringTransforms the PowerSync base URL which might contain http(s):// to the corresponding WebSocket variant e.g. ws(s)://

ArrayComparatorOptions<ItemType>

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

Options for ArrayComparator

Type Parameters

Type Parameter
ItemType

Type declaration

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

BaseColumnType<T>

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

Type Parameters

Type Parameter
T extends number | string | null

Type declaration

NameType
typeColumnType

BaseListener

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

BSONImplementation

type BSONImplementation = typeof BSON;

BucketOperationProgress

type BucketOperationProgress = Record<string, SavedProgress>;

ColumnsType

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

CrudUploadNotification

type CrudUploadNotification = {
crud_upload_completed: null;
};

Type declaration

NameType
crud_upload_completednull

DataStreamCallback()<Data>

type DataStreamCallback<Data> = (data) => Promise<void>;

Type Parameters

Type ParameterDefault type
Data extends anyany

Parameters

ParameterType
dataData

Returns

Promise<void>


DataStreamOptions<ParsedData, SourceData>

type DataStreamOptions<ParsedData, SourceData> = {
closeOnError: boolean;
logger: ILogger;
mapLine: (line) => ParsedData;
pressure: {
highWaterMark: number;
lowWaterMark: number;
};
};

Type Parameters

Type Parameter
ParsedData
SourceData

Type declaration

NameTypeDescription
closeOnError?booleanClose the stream if any consumer throws an error
logger?ILogger-
mapLine?(line) => ParsedData-
pressure?{ highWaterMark: number; lowWaterMark: number; }-
pressure.highWaterMark?number-
pressure.lowWaterMark?number-

DifferentialWatchedQuery<RowType>

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

Type Parameters

Type Parameter
RowType

ExtractColumnValueType<T>

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

Type Parameters

Type Parameter
T extends BaseColumnType<any>

FetchImplementation

type FetchImplementation = typeof fetch;

GetAllQueryOptions<RowType>

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

Options for GetAllQuery.

Type Parameters

Type ParameterDefault type
RowTypeunknown

Type declaration

NameTypeDescription
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[]>;

MutableWatchedQueryState<Data>

type MutableWatchedQueryState<Data> = { -readonly [P in keyof WatchedQueryState<Data>]: MutableDeep<WatchedQueryState<Data>[P]> };

Internal

Mutable version of WatchedQueryState. This is used internally to allow updates to the state.

Type Parameters

Type Parameter
Data

OnTableChangeCallback()

type OnTableChangeCallback = (event) => void;

Internal

Parameters

ParameterType
eventBatchedUpdateNotification

Returns

void


OpenAsyncDatabaseConnection()<Config>

type OpenAsyncDatabaseConnection<Config> = (config) => AsyncDatabaseConnection;

Internal

Type Parameters

Type ParameterDefault type
Config extends ResolvedWebSQLOpenOptionsResolvedWebSQLOpenOptions

Parameters

ParameterType
configConfig

Returns

AsyncDatabaseConnection


OpId

type OpId = string;

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

Not sortable as a string.


OpTypeJSON

type OpTypeJSON = string;

PowerSyncConnectionOptions

type PowerSyncConnectionOptions = Omit<InternalConnectionOptions, "serializedSchema">;

Configurable options to be used when connecting to the PowerSync backend instance.


ProxiedQueryResult

type ProxiedQueryResult = Omit<QueryResult, "rows"> & {
rows: {
_array: any[];
length: number;
};
};

Internal

Proxied query result does not contain a function for accessing row values

Type declaration

NameType
rows{ _array: any[]; length: number; }
rows._arrayany[]
rows.lengthnumber

QueryParam

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

Query parameters for ArrayQueryDefinition#parameters


QueryResult

type QueryResult = {
insertId: number;
rows: {
_array: any[];
item: (idx) => any;
length: number;
};
rowsAffected: number;
};

Object returned by SQL Query executions.

Type declaration

NameTypeDescription
insertId?numberRepresents the auto-generated row id if applicable.
rows?{ _array: any[]; item: (idx) => any; length: number; }if status is undefined or 0 this object will contain the query results
rows._arrayany[]Raw array with all dataset
rows.item(idx) => anyA convenience function to acess the index based the row object
rows.lengthnumberThe length of the dataset
rowsAffectednumberNumber of affected rows if result of a update query.

RemoteConnector

type RemoteConnector = {
fetchCredentials: () => Promise<PowerSyncCredentials | null>;
invalidateCredentials: () => void;
};

Type declaration

NameType
fetchCredentials() => Promise<PowerSyncCredentials | null>
invalidateCredentials?() => void

RequiredAdditionalConnectionOptions

type RequiredAdditionalConnectionOptions = Required<AdditionalConnectionOptions>;

Internal


RequiredPowerSyncConnectionOptions

type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;

ResolvedWebSQLFlags

type ResolvedWebSQLFlags = Required<WebSQLFlags>;

RowType<T>

type RowType<T> = { [K in keyof T["columnMap"]]: ExtractColumnValueType<T["columnMap"][K]> } & {
id: string;
};

Type declaration

NameType
idstring

Type Parameters

Type Parameter
T extends TableV2<any>

SavedProgress

type SavedProgress = {
atLast: number;
sinceLast: number;
};

Type declaration

NameType
atLastnumber
sinceLastnumber

SchemaTableType<S>

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

Type Parameters

Type Parameter
S extends SchemaType

SocketSyncStreamOptions

type SocketSyncStreamOptions = SyncStreamOptions & {
fetchStrategy: FetchStrategy;
};

Type declaration

NameType
fetchStrategyFetchStrategy

SQLiteModule

type SQLiteModule = Parameters<typeof SQLite.Factory>[0];

Internal


StandardWatchedQuery<DataType>

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

WatchedQuery returned from Query#watch.

Type Parameters

Type Parameter
DataType

StreamingSyncLine

type StreamingSyncLine = 
| StreamingSyncDataJSON
| StreamingSyncCheckpoint
| StreamingSyncCheckpointDiff
| StreamingSyncCheckpointComplete
| StreamingSyncCheckpointPartiallyComplete
| StreamingSyncKeepalive;

StreamingSyncLineOrCrudUploadComplete

type StreamingSyncLineOrCrudUploadComplete = 
| StreamingSyncLine
| CrudUploadNotification;

StreamingSyncRequestParameterType

type StreamingSyncRequestParameterType = JSONValue;

SyncDataBucketJSON

type SyncDataBucketJSON = {
after: string;
bucket: string;
data: OplogEntryJSON[];
has_more: boolean;
next_after: string;
};

Type declaration

NameType
after?string
bucketstring
dataOplogEntryJSON[]
has_more?boolean
next_after?string

SyncDataFlowStatus

type SyncDataFlowStatus = Partial<{
downloadError: Error;
downloading: boolean;
downloadProgress: InternalProgressInformation | null;
uploadError: Error;
uploading: boolean;
}>;

SyncRequest

type SyncRequest = 
| ContinueCheckpointRequest
| SyncNewCheckpointRequest;

SyncStatusOptions

type SyncStatusOptions = {
connected: boolean;
connecting: boolean;
dataFlow: SyncDataFlowStatus;
hasSynced: boolean;
lastSyncedAt: Date;
priorityStatusEntries: SyncPriorityStatus[];
};

Type declaration

NameType
connected?boolean
connecting?boolean
dataFlow?SyncDataFlowStatus
hasSynced?boolean
lastSyncedAt?Date
priorityStatusEntries?SyncPriorityStatus[]

SyncStreamOptions

type SyncStreamOptions = {
abortSignal: AbortSignal;
data: StreamingSyncRequest;
fetchOptions: Request;
headers: Record<string, string>;
path: string;
};

Type declaration

NameType
abortSignal?AbortSignal
dataStreamingSyncRequest
fetchOptions?Request
headers?Record<string, string>
pathstring

WASQLiteBroadCastTableUpdateEvent

type WASQLiteBroadCastTableUpdateEvent = {
changedTables: Set<string>;
connectionId: number;
};

Internal

Type declaration

NameType
changedTablesSet<string>
connectionIdnumber

WASQLiteConnectionListener

type WASQLiteConnectionListener = {
tablesUpdated: (event) => void;
};

Internal

Type declaration

NameType
tablesUpdated(event) => void

WASQLiteFlags

type WASQLiteFlags = WebSQLFlags;

These flags are the same as WebSQLFlags. This export is maintained only for API consistency


WASQLiteModuleFactory()

type WASQLiteModuleFactory = (options) => Promise<{
module: SQLiteModule;
vfs: SQLiteVFS;
}>;

Internal

Parameters

ParameterType
optionsWASQLiteModuleFactoryOptions

Returns

Promise<{ module: SQLiteModule; vfs: SQLiteVFS; }>


WASQLiteModuleFactoryOptions

type WASQLiteModuleFactoryOptions = {
dbFileName: string;
encryptionKey: string;
};

Internal

Type declaration

NameType
dbFileNamestring
encryptionKey?string

WebPowerSyncDatabaseOptions

type WebPowerSyncDatabaseOptions = WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptions>>;

WebPowerSyncDatabaseOptionsWithAdapter

type WebPowerSyncDatabaseOptionsWithAdapter = WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptionsWithDBAdapter>>;

WebPowerSyncDatabaseOptionsWithOpenFactory

type WebPowerSyncDatabaseOptionsWithOpenFactory = WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptionsWithOpenFactory>>;

WebPowerSyncDatabaseOptionsWithSettings

type WebPowerSyncDatabaseOptionsWithSettings = WithWebSyncOptions<WithWebFlags<WithWebEncryptionOptions<PowerSyncDatabaseOptionsWithSettings>>>;

Variables

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>

DEFAULT_CACHE_SIZE_KB

const DEFAULT_CACHE_SIZE_KB: number;

DEFAULT_CRUD_BATCH_LIMIT

const DEFAULT_CRUD_BATCH_LIMIT: 100 = 100;

DEFAULT_CRUD_UPLOAD_THROTTLE_MS

const DEFAULT_CRUD_UPLOAD_THROTTLE_MS: 1000 = 1000;

DEFAULT_INDEX_COLUMN_OPTIONS

const DEFAULT_INDEX_COLUMN_OPTIONS: Partial<IndexColumnOptions>;

DEFAULT_INDEX_OPTIONS

const DEFAULT_INDEX_OPTIONS: Partial<IndexOptions>;

DEFAULT_LOCK_TIMEOUT_MS

const DEFAULT_LOCK_TIMEOUT_MS: 120000 = 120000;

Requesting nested or recursive locks can block the application in some circumstances. This default lock timeout will act as a failsafe to throw an error if a lock cannot be obtained.


DEFAULT_MODULE_FACTORIES

const DEFAULT_MODULE_FACTORIES: {
AccessHandlePoolVFS: (options) => Promise<{
module: any;
vfs: any;
}>;
IDBBatchAtomicVFS: (options) => Promise<{
module: any;
vfs: any;
}>;
OPFSCoopSyncVFS: (options) => Promise<{
module: any;
vfs: any;
}>;
};

Internal

Type declaration

NameType
AccessHandlePoolVFS(options) => Promise<{ module: any; vfs: any; }>
IDBBatchAtomicVFS(options) => Promise<{ module: any; vfs: any; }>
OPFSCoopSyncVFS(options) => Promise<{ module: any; vfs: any; }>

DEFAULT_POWERSYNC_CLOSE_OPTIONS

const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions;

DEFAULT_POWERSYNC_DB_OPTIONS

const DEFAULT_POWERSYNC_DB_OPTIONS: {
crudUploadThrottleMs: number;
retryDelayMs: number;
};

Type declaration

NameType
crudUploadThrottleMsnumber
retryDelayMsnumber

DEFAULT_POWERSYNC_FLAGS

const DEFAULT_POWERSYNC_FLAGS: Required<WebPowerSyncFlags>;

DEFAULT_PRESSURE_LIMITS

const DEFAULT_PRESSURE_LIMITS: {
highWater: number;
lowWater: number;
};

Type declaration

NameType
highWaternumber
lowWaternumber

DEFAULT_REMOTE_LOGGER

const DEFAULT_REMOTE_LOGGER: Logger.ILogger;

DEFAULT_REMOTE_OPTIONS

const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;

DEFAULT_RETRY_DELAY_MS

const DEFAULT_RETRY_DELAY_MS: 5000 = 5000;

DEFAULT_ROW_COMPARATOR

const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any>;

Default implementation of the DifferentialWatchedQueryComparator for watched queries. It keys items by their id property if available, alternatively it uses JSON stringification of the entire item for the key and comparison.


DEFAULT_STREAM_CONNECTION_OPTIONS

const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;

DEFAULT_STREAMING_SYNC_OPTIONS

const DEFAULT_STREAMING_SYNC_OPTIONS: {
crudUploadThrottleMs: number;
retryDelayMs: number;
};

Type declaration

NameType
crudUploadThrottleMsnumber
retryDelayMsnumber

DEFAULT_SYNC_CLIENT_IMPLEMENTATION

const DEFAULT_SYNC_CLIENT_IMPLEMENTATION: JAVASCRIPT = SyncClientImplementation.JAVASCRIPT;

The default SyncClientImplementation to use.

Please use this field instead of SyncClientImplementation.JAVASCRIPT directly. A future version of the PowerSync SDK will enable SyncClientImplementation.RUST by default and remove the JavaScript option.


DEFAULT_TABLE_OPTIONS

const DEFAULT_TABLE_OPTIONS: {
ignoreEmptyUpdates: boolean;
indexes: never[];
insertOnly: boolean;
localOnly: boolean;
trackMetadata: boolean;
trackPrevious: boolean;
};

Type declaration

NameType
ignoreEmptyUpdatesboolean
indexesnever[]
insertOnlyboolean
localOnlyboolean
trackMetadataboolean
trackPreviousboolean

DEFAULT_WATCH_QUERY_OPTIONS

const DEFAULT_WATCH_QUERY_OPTIONS: WatchedQueryOptions;

DEFAULT_WATCH_THROTTLE_MS

const DEFAULT_WATCH_THROTTLE_MS: 30 = 30;

DEFAULT_WEB_SQL_FLAGS

const DEFAULT_WEB_SQL_FLAGS: ResolvedWebSQLFlags;

EMPTY_DIFFERENTIAL

const EMPTY_DIFFERENTIAL: {
added: never[];
all: never[];
removed: never[];
unchanged: never[];
updated: never[];
};

An empty differential result set. This is used as the initial state for differential incrementally watched queries.

Type declaration

NameType
addednever[]
allnever[]
removednever[]
unchangednever[]
updatednever[]

FalsyComparator

const FalsyComparator: WatchedQueryComparator<unknown>;

Watched query comparator that always reports changed result sets.


InvalidSQLCharacters

const InvalidSQLCharacters: RegExp;

LogLevel

const LogLevel: {
DEBUG: Logger.ILogLevel;
ERROR: Logger.ILogLevel;
INFO: Logger.ILogLevel;
OFF: Logger.ILogLevel;
TIME: Logger.ILogLevel;
TRACE: Logger.ILogLevel;
WARN: Logger.ILogLevel;
};

Type declaration

NameType
DEBUGLogger.ILogLevel
ERRORLogger.ILogLevel
INFOLogger.ILogLevel
OFFLogger.ILogLevel
TIMELogger.ILogLevel
TRACELogger.ILogLevel
WARNLogger.ILogLevel

MAX_AMOUNT_OF_COLUMNS

const MAX_AMOUNT_OF_COLUMNS: 1999 = 1999;

MAX_OP_ID

const MAX_OP_ID: "9223372036854775807" = "9223372036854775807";

Functions

FunctionDescription
AsyncWASQLiteModuleFactory-
compilableQueryWatch-
createBaseLoggerRetrieves the base (default) logger instance.
createLoggerCreates and configures a new named logger based on the base logger.
extractTableUpdates-
isBatchedUpdateNotification-
isContinueCheckpointRequest-
isDBAdapterTests if input is a DBAdapter
isPowerSyncDatabaseOptionsWithSettingsTests if the input is a PowerSyncDatabaseOptionsWithSettings
isServerSide-
isSQLOpenFactoryTests if input is a SQLOpenFactory
isSQLOpenOptionsTests if the input is a SQLOpenOptions
isStreamingKeepalive-
isStreamingSyncCheckpoint-
isStreamingSyncCheckpointComplete-
isStreamingSyncCheckpointDiff-
isStreamingSyncCheckpointPartiallyComplete-
isStreamingSyncData-
isSyncNewCheckpointRequest-
MultiCipherAsyncWASQLiteModuleFactory-
MultiCipherSyncWASQLiteModuleFactory-
parseQuery-
resolveWebPowerSyncFlags-
resolveWebSQLFlags-
runOnSchemaChange-
SyncWASQLiteModuleFactory-