Skip to main content

@powersync/web

Enumerations

EnumerationDescription
ColumnType-
LockType-
OpTypeEnum-
PSInternalTable-
RowUpdateTypeUpdate table operation numbers from SQLite
SyncStreamConnectionMethod-
UpdateTypeType of local change.

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-
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-
BaseObserver-
Column-
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.
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"
Index-
IndexedColumn-
OpTypeUsed internally for sync buckets.
OplogEntry-
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-
SyncStatus-
Table-
TableV2Generate a new table from the columns and indexes
UploadQueueStats-
WASQLiteDBAdapterAdapter for WA-SQLite SQLite connections.
WASQLiteOpenFactoryOpens a SQLite connection using WA-SQLite.
WASQLitePowerSyncDatabaseOpenFactory-
WebRemote-
WebStreamingSyncImplementation-

Functions

FunctionDescription
extractTableUpdates-
isBatchedUpdateNotification-
isContinueCheckpointRequest-
isDBAdapterTests if input is a DBAdapter
isPowerSyncDatabaseOptionsWithSettingsTests if the input is a PowerSyncDatabaseOptionsWithSettings
isSQLOpenFactoryTests if input is a SQLOpenFactory
isSQLOpenOptionsTests if the input is a SQLOpenOptions
isServerSide-
isStreamingKeepalive-
isStreamingSyncCheckpoint-
isStreamingSyncCheckpointComplete-
isStreamingSyncCheckpointDiff-
isStreamingSyncData-
isSyncNewCheckpointRequest-
parseQuery-
resolveWebPowerSyncFlags-
resolveWebSQLFlags-
runOnSchemaChange-

Interfaces

AbstractStreamingSyncImplementationOptions

Extended by

Properties

PropertyTypeDescription
adapterBucketStorageAdapter-
crudUploadThrottleMs?number-
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?number-
uploadCrud() => Promise<void>-

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

Extended by

Properties

PropertyTypeDescription
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.
logger?ILogger-
retryDelay?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.
schemaSchema<SchemaType>Schema 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.

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() => Promise<void>Disposable.dispose

Methods

autoCompact()
autoCompact(): Promise<void>

Exposed for tests only.

Returns

Promise<void>


forceCompact()
forceCompact(): Promise<void>

Exposed for tests only.

Returns

Promise<void>


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>


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

Promise<void>


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

Promise<void>

Inherited from

BaseObserver.iterateAsyncListeners


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

void

Inherited from

BaseObserver.iterateListeners


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

Promise<undefined | CrudEntry>


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

Register a listener for updates to the PowerSync client.

Parameters
ParameterType
listenerPartial<BucketStorageListener>
Returns

Function

Returns

void

Inherited from

BaseObserver.registerListener


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

Promise<void>


saveSyncData()
saveSyncData(batch): Promise<void>
Parameters
ParameterType
batchSyncDataBatch
Returns

Promise<void>


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

Promise<void>


startSession()
startSession(): void
Returns

void


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

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

MemberType
checkpointValidboolean
failuresany[]
readyboolean

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

Promise<boolean>


BucketStorageListener

Extends

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


CompiledQuery

Properties

PropertyModifierType
parametersreadonlyreadonly unknown[]
sqlreadonlystring

ContinueCheckpointRequest

For sync2.json

Properties

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

CrudRequest

For crud.json

Properties

PropertyType
dataCrudEntry[]

CrudResponse

Properties

PropertyTypeDescription
checkpoint?string

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


DBAdapter

Extends

Properties

PropertyTypeDescription
close() => void-
execute(query: string, params?: any[]) => Promise<QueryResult>-
executeBatch(query: string, params?: any[][]) => Promise<QueryResult>-
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

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

DataStreamListener<Data>

Extends

Type parameters

Type parameterValue
Data extends anyany

Properties

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

DisconnectAndClearOptions

Properties

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

Disposable

Extended by

Properties

PropertyType
dispose() => Promise<void>

IndexColumnOptions

Properties

PropertyType
ascending?boolean
namestring

IndexOptions

Properties

PropertyType
columns?IndexedColumn[]
namestring

LockContext

Extends

Extended by

Properties

PropertyTypeDescription
execute(query: string, params?: any[]) => Promise<QueryResult>Execute a single write statement.

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

OplogEntryJSON

Properties

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

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.

PowerSyncConnectionOptions

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

Properties

PropertyTypeDescription
connectionMethod?SyncStreamConnectionMethodThe connection method to use when streaming updates from the PowerSync backend instance. Defaults to a HTTP streaming connection.
params?Record<string, JSONValue>These parameters are passed to the sync rules, and will be available under theuser_parameters object.

PowerSyncCredentials

Properties

PropertyType
endpointstring
expiresAt?Date
tokenstring

PowerSyncDBListener

Extends

Properties

PropertyTypeDescriptionInherited from
initialized() => void--
schemaChanged(schema: Schema<SchemaType>) => 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

PowerSyncDatabaseOptions

Extends

Properties

PropertyTypeDescriptionInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.BasePowerSyncDatabaseOptions.crudUploadThrottleMs
databaseSQLOpenOptions | DBAdapter | SQLOpenFactory

Source for a SQLite database connection. This can be either:

-
logger?ILogger-BasePowerSyncDatabaseOptions.logger
retryDelay?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelay
schemaSchema<SchemaType>Schema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithDBAdapter

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?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelay
schemaSchema<SchemaType>Schema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithOpenFactory

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?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelay
schemaSchema<SchemaType>Schema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncDatabaseOptionsWithSettings

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?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.BasePowerSyncDatabaseOptions.retryDelay
schemaSchema<SchemaType>Schema used for the local database.BasePowerSyncDatabaseOptions.schema

PowerSyncOpenFactoryOptions

Extends

Extended by

Properties

PropertyTypeDescriptionOverridesInherited from
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.Partial.crudUploadThrottleMsPartial.crudUploadThrottleMs
database?SQLOpenOptions | DBAdapter | SQLOpenFactory

Source for a SQLite database connection. This can be either:

Partial.databasePartial.database
dbFilenamestringFilename for the database.SQLOpenOptions.dbFilenameSQLOpenOptions.dbFilename
dbLocation?stringDirectory where the database file is located.SQLOpenOptions.dbLocationSQLOpenOptions.dbLocation
debugMode?boolean

Enable debugMode to log queries to the performance timeline.

Defaults to false.

To enable in development builds, use:

debugMode: process.env.NODE_ENV !== 'production'

SQLOpenOptions.debugModeSQLOpenOptions.debugMode
logger?ILogger-Partial.loggerPartial.logger
retryDelay?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.Partial.retryDelayPartial.retryDelay
schemaSchema<SchemaType>Schema used for the local database.Partial.schemaPartial.schema

ResolvedWebSQLOpenOptions

Extends

Properties

PropertyTypeDescriptionInherited from
dbFilenamestringFilename for the database.SQLOpenOptions.dbFilename
dbLocation?stringDirectory where the database file is located.SQLOpenOptions.dbLocation
debugMode?boolean

Enable 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
flagsRequired<WebSQLFlags>--

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.
debugMode?boolean

Enable debugMode to log queries to the performance timeline.

Defaults to false.

To enable in development builds, use:

debugMode: process.env.NODE_ENV !== 'production'


SQLWatchOptions

Properties

PropertyTypeDescription
rawTableNames?boolean

Deprecated

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.

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_checkpointstring

StreamingSyncDataJSON

Properties

PropertyType
dataSyncDataBucketJSON

StreamingSyncImplementation

Extends

Properties

PropertyTypeInherited from
dispose() => 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?PowerSyncConnectionOptions
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


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

Promise<void>

Inherited from

BaseObserver.iterateAsyncListeners


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

void

Inherited from

BaseObserver.iterateListeners


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

Register a listener for updates to the PowerSync client.

Parameters
ParameterType
listenerPartial<StreamingSyncImplementationListener>
Returns

Function

Returns

void

Inherited from

BaseObserver.registerListener


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

Promise<void>


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

Promise<void>


StreamingSyncImplementationListener

Extends

Extended by

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.

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

Properties

PropertyTypeDescription
columnsColumn[]-
indexes?Index[]-
insertOnly?boolean-
localOnly?boolean-
namestringThe synced table name, matching sync rules
viewName?string-

TableUpdateOperation

Extended by

Properties

PropertyType
opTypeRowUpdateType
rowIdnumber

TableV2Options

Properties

PropertyType
indexes?IndexShorthand
insertOnly?boolean
localOnly?boolean
viewName?string

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
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
crudUploadThrottleMs?numberBackend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds.Omit.crudUploadThrottleMs
database?SQLOpenOptions | DBAdapter | SQLOpenFactory

Source for a SQLite database connection. This can be either:

Omit.database
dbFilenamestringFilename for the database.Omit.dbFilename
dbLocation?stringDirectory where the database file is located.Omit.dbLocation
debugMode?boolean

Enable 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
flags?WebSQLFlags--
logger?ILogger-Omit.logger
retryDelay?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.Omit.retryDelay
worker?string | URL | (options) => SharedWorker | Worker--
workerPort?MessagePortUse an existing port to an initialized worker. A worker will be initialized if none is provided-

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

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

Source for a SQLite database connection. This can be either:

PowerSyncOpenFactoryOptions.database
dbFilenamestringFilename for the database.PowerSyncOpenFactoryOptions.dbFilename
dbLocation?stringDirectory where the database file is located.PowerSyncOpenFactoryOptions.dbLocation
debugMode?boolean

Enable 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?numberDelay for retrying sync streaming operations from the PowerSync backend after an error occurs.PowerSyncOpenFactoryOptions.retryDelay
schemaSchema<SchemaType>Schema 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

Properties

PropertyTypeDescriptionInherited from
dbFilenamestringFilename for the database.SQLOpenOptions.dbFilename
dbLocation?stringDirectory where the database file is located.SQLOpenOptions.dbLocation
debugMode?boolean

Enable 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
flags?WebSQLFlags--
worker?string | URL | (options) => SharedWorker | Worker

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.

-

WebStreamingSyncImplementationOptions

Extends

Properties

PropertyTypeDescriptionInherited from
adapterBucketStorageAdapter-AbstractStreamingSyncImplementationOptions.adapter
crudUploadThrottleMs?number-AbstractStreamingSyncImplementationOptions.crudUploadThrottleMs
database?{ options: { worker: string | URL | (options) => SharedWorker | Worker; }; }--
database.options{ worker: string | URL | (options) => SharedWorker | Worker; }--
database.options.worker?string | URL | (options) => SharedWorker | Worker--
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?number-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) => 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.

Type Aliases

AbstractRemoteOptions

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

Type declaration

MemberTypeDescription
fetchImplementationFetchImplementation | 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.
socketUrlTransformer(url) => stringTransforms the PowerSync base URL which might contain http(s):// to the corresponding WebSocket variant e.g. ws(s)://

BSONImplementation

type BSONImplementation: typeof BSON;

BaseColumnType<T>

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

Type parameters

Type parameter
T extends number | string | null

Type declaration

MemberType
typeColumnType

BaseListener

type BaseListener: {};

Index signature

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


ColumnsType

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

DataStreamCallback()<Data>

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

Type parameters

Type parameterValue
Data extends anyany

Parameters

ParameterType
dataData

Returns

Promise<void>


DataStreamOptions

type DataStreamOptions: {
closeOnError: boolean;
logger: ILogger;
pressure: {
highWaterMark: number;
lowWaterMark: number;
};
};

Type declaration

MemberTypeDescription
closeOnErrorbooleanClose the stream if any consumer throws an error
loggerILogger-
pressure{
highWaterMark: number;
lowWaterMark: number;
}-
pressure.highWaterMarknumber-
pressure.lowWaterMarknumber-

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;

IndexShorthand

type IndexShorthand: Record<string, string[]>;

OpId

type OpId: string;

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

Not sortable as a string.


OpTypeJSON

type OpTypeJSON: string;

QueryResult

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

Object returned by SQL Query executions.

Type declaration

MemberTypeDescription
insertIdnumberRepresents 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) => any

A 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>;
};

Type declaration

MemberType
fetchCredentials() => Promise<PowerSyncCredentials | null>

ResolvedWebSQLFlags

type ResolvedWebSQLFlags: Required<WebSQLFlags>;

RowType<T>

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

Type declaration

MemberType
idstring

Type parameters

Type parameter
T extends TableV2<any>

StreamingSyncLine

type StreamingSyncLine: 
| StreamingSyncDataJSON
| StreamingSyncCheckpoint
| StreamingSyncCheckpointDiff
| StreamingSyncCheckpointComplete
| StreamingSyncKeepalive;

StreamingSyncRequestParameterType

type StreamingSyncRequestParameterType: JSONValue;

SyncDataBucketJSON

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

Type declaration

MemberType
afterstring
bucketstring
dataOplogEntryJSON[]
has_moreboolean
next_afterstring

SyncDataFlowStatus

type SyncDataFlowStatus: Partial<{
downloading: boolean;
uploading: boolean;
}>;

Type declaration

MemberType
downloadingboolean
uploadingboolean

SyncRequest

type SyncRequest: ContinueCheckpointRequest | SyncNewCheckpointRequest;

SyncStatusOptions

type SyncStatusOptions: {
connected: boolean;
dataFlow: SyncDataFlowStatus;
hasSynced: boolean;
lastSyncedAt: Date;
};

Type declaration

MemberType
connectedboolean
dataFlowSyncDataFlowStatus
hasSyncedboolean
lastSyncedAtDate

SyncStreamOptions

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

Type declaration

MemberType
abortSignalAbortSignal
dataStreamingSyncRequest
fetchOptionsRequest
headersRecord<string, string>
pathstring

WASQLiteFlags

type WASQLiteFlags: WebSQLFlags;

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


WebPowerSyncDatabaseOptions

type WebPowerSyncDatabaseOptions: WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptions>>;

WebPowerSyncDatabaseOptionsWithAdapter

type WebPowerSyncDatabaseOptionsWithAdapter: WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptionsWithDBAdapter>>;

WebPowerSyncDatabaseOptionsWithOpenFactory

type WebPowerSyncDatabaseOptionsWithOpenFactory: WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptionsWithOpenFactory>>;

WebPowerSyncDatabaseOptionsWithSettings

type WebPowerSyncDatabaseOptionsWithSettings: WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptionsWithSettings>>;

Variables

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_POWERSYNC_CLOSE_OPTIONS

const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions;

DEFAULT_POWERSYNC_DB_OPTIONS

const DEFAULT_POWERSYNC_DB_OPTIONS: {
crudUploadThrottleMs: number;
logger: Logger.ILogger;
retryDelay: number;
};

Type declaration

MemberType
crudUploadThrottleMsnumber
loggerLogger.ILogger
retryDelaynumber

DEFAULT_POWERSYNC_FLAGS

const DEFAULT_POWERSYNC_FLAGS: Required<WebPowerSyncFlags>;

DEFAULT_PRESSURE_LIMITS

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

Type declaration

MemberType
highWaternumber
lowWaternumber

DEFAULT_REMOTE_LOGGER

const DEFAULT_REMOTE_LOGGER: Logger.ILogger;

DEFAULT_REMOTE_OPTIONS

const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;

DEFAULT_STREAMING_SYNC_OPTIONS

const DEFAULT_STREAMING_SYNC_OPTIONS: {
crudUploadThrottleMs: number;
logger: Logger.ILogger;
retryDelayMs: number;
};

Type declaration

MemberType
crudUploadThrottleMsnumber
loggerLogger.ILogger
retryDelayMsnumber

DEFAULT_STREAM_CONNECTION_OPTIONS

const DEFAULT_STREAM_CONNECTION_OPTIONS: Required<PowerSyncConnectionOptions>;

DEFAULT_TABLE_OPTIONS

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

Type declaration

MemberType
indexesnever[]
insertOnlyboolean
localOnlyboolean

DEFAULT_WATCH_THROTTLE_MS

const DEFAULT_WATCH_THROTTLE_MS: 30 = 30;

DEFAULT_WEB_SQL_FLAGS

const DEFAULT_WEB_SQL_FLAGS: ResolvedWebSQLFlags;

InvalidSQLCharacters

const InvalidSQLCharacters: RegExp;

MAX_AMOUNT_OF_COLUMNS

const MAX_AMOUNT_OF_COLUMNS: 63 = 63;

MAX_OP_ID

const MAX_OP_ID: "9223372036854775807" = "9223372036854775807";

column

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

Type declaration

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