@powersync/node
Enumerations
| Enumeration | Description |
|---|---|
| AttachmentState | AttachmentState represents the current synchronization state of an attachment. |
| ColumnType | - |
| DiffTriggerOperation | SQLite operations to track changes for with TriggerManager |
| EncodingType | - |
| FetchStrategy | - |
| LockType | - |
| PowerSyncControlCommand | - |
| PSInternalTable | - |
| RowUpdateType | Update table operation numbers from SQLite |
| - | |
| SyncStreamConnectionMethod | - |
| UpdateType | Type of local change. |
| WatchedQueryListenerEvent | - |
Classes
| Class | Description |
|---|---|
| AbortOperation | Calls 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 | - |
| AbstractQueryProcessor | Performs underlying watching and yields a stream of results. |
| AbstractRemote | - |
| AbstractStreamingSyncImplementation | - |
| ArrayComparator | An 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. |
| AttachmentContext | AttachmentContext provides database operations for managing attachment records. |
| AttachmentQueue | AttachmentQueue manages the lifecycle and synchronization of attachments between local and remote storage. Provides automatic synchronization, upload/download queuing, attachment monitoring, verification and repair of local files, and cleanup of archived attachments. |
| AttachmentService | Service for querying and watching attachment records in the database. |
| AttachmentTable | AttachmentTable defines the schema for the attachment queue table. |
| BaseObserver | - |
| Column | - |
| ConnectionClosedError | Thrown when an underlying database connection is closed. This is particularly relevant when worker connections are marked as closed while operations are still in progress. |
| ConnectionManager | - |
| ControlledExecutor | - |
| CrudBatch | A batch of client-side changes. |
| CrudEntry | A single client-side change. |
| CrudTransaction | - |
| DifferentialQueryProcessor | Uses the PowerSync onChange event to trigger watched queries. Results are emitted on every change of the relevant tables. |
| FetchImplementationProvider | Class 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" |
| GetAllQuery | Performs a AbstractPowerSyncDatabase.getAll operation for a watched query. |
| Index | - |
| IndexedColumn | - |
| Mutex | An asynchronous mutex implementation. |
| NodeFileSystemAdapter | NodeFileSystemAdapter implements LocalStorageAdapter using Node.js filesystem. Suitable for Node.js environments and Electron applications. |
| OnChangeQueryProcessor | Uses the PowerSync onChange event to trigger watched queries. Results are emitted on every change of the relevant tables. |
| PowerSyncDatabase | A PowerSync database which provides SQLite functionality which is automatically synced. |
| Schema | A schema is a collection of tables. It is used to define the structure of a database. |
| Semaphore | An asynchronous semaphore implementation with associated items per lease. |
| SqliteBucketStorage | - |
| SyncingService | Orchestrates attachment synchronization between local and remote storage. Handles uploads, downloads, deletions, and state transitions. |
| SyncProgress | Provides realtime progress on how PowerSync is downloading rows. |
| SyncStatus | - |
| Table | - |
| Generate a new table from the columns and indexes | |
| TriggerManagerImpl | - |
| UploadQueueStats | - |
Interfaces
AbstractQueryProcessorOptions<Data, Settings>
Internal
Extended by
Type Parameters
| Type Parameter | Default type |
|---|---|
Data | - |
Settings extends WatchedQueryOptions | WatchedQueryOptions |
Properties
| Property | Type |
|---|---|
db | AbstractPowerSyncDatabase |
placeholderData | Data |
watchOptions | Settings |
AbstractStreamingSyncImplementationOptions
Internal
Extends
Properties
| Property | Type | Description | Overrides | Inherited from |
|---|---|---|---|---|
adapter | BucketStorageAdapter | - | - | - |
crudUploadThrottleMs | number | Backend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds. | - | RequiredAdditionalConnectionOptions.crudUploadThrottleMs |
identifier? | string | An identifier for which PowerSync DB this sync implementation is linked to. Most commonly DB name, but not restricted to DB name. | - | - |
logger? | ILogger | - | - | - |
remote | AbstractRemote | - | - | - |
retryDelayMs | number | Delay for retrying sync streaming operations from the PowerSync backend after an error occurs. | - | RequiredAdditionalConnectionOptions.retryDelayMs |
subscriptions | SubscribedStream[] | - | RequiredAdditionalConnectionOptions.subscriptions | - |
uploadCrud | () => Promise<void> | - | - | - |
AdditionalConnectionOptions
Internal
Extended by
Properties
ArrayQueryDefinition<RowType>
Options for building a query with AbstractPowerSyncDatabase#query. This query will be executed with AbstractPowerSyncDatabase#getAll.
Type Parameters
| Type Parameter | Default type |
|---|---|
RowType | unknown |
Properties
| Property | Type | Description |
|---|---|---|
mapper? | (row: Record<string, unknown>) => RowType | Maps 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>[] | - |
sql | string | - |
AttachmentErrorHandler
Experimental Alpha
SyncErrorHandler provides custom error handling for attachment sync operations. Implementations determine whether failed operations should be retried or archived.
This is currently experimental and may change without a major version bump.
Methods
onDeleteError()
onDeleteError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to delete |
error | unknown | The error encountered during the delete |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
onDownloadError()
onDownloadError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to download |
error | unknown | The error encountered during the download |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
onUploadError()
onUploadError(attachment, error): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
attachment | AttachmentRecord | The attachment that failed to upload |
error | unknown | The error encountered during the upload |
Returns
Promise<boolean>
true to retry the operation, false to archive the attachment
AttachmentQueueOptions
Experimental Alpha
Configuration options for AttachmentQueue.
This is currently experimental and may change without a major version bump.
Properties
| Property | Type | Description |
|---|---|---|
archivedCacheLimit? | number | Alpha Maximum archived attachments before cleanup. Default: 100 |
db | AbstractPowerSyncDatabase | Alpha PowerSync database instance |
downloadAttachments? | boolean | Alpha Whether to automatically download remote attachments. Default: true |
errorHandler? | AttachmentErrorHandler | Alpha Handler for upload, download and delete errors |
localStorage | LocalStorageAdapter | Alpha Local storage adapter for file persistence |
logger? | ILogger | Alpha Logger instance. Defaults to db.logger |
remoteStorage | RemoteStorageAdapter | Alpha Remote storage adapter for upload/download operations |
syncIntervalMs? | number | Alpha Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000 |
syncThrottleDuration? | number | Alpha Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30 |
tableName? | string | Alpha Name of the table to store attachment records. Default: 'ps_attachment_queue' |
watchAttachments | (onUpdate: (attachment) => Promise<void>, signal: AbortSignal) => void | Alpha Callback for monitoring attachment changes in your data model |
AttachmentRecord
Alpha
AttachmentRecord represents an attachment in the local database.
Properties
| Property | Type | Description |
|---|---|---|
filename | string | Alpha |
hasSynced? | boolean | Alpha |
id | string | Alpha |
localUri? | string | Alpha |
mediaType? | string | Alpha |
metaData? | string | Alpha |
size? | number | Alpha |
state | AttachmentState | Alpha |
timestamp? | number | Alpha |
AttachmentTableOptions
Alpha
Extends
Omit<TableV2Options,"name"|"columns">
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
ignoreEmptyUpdates? | boolean | Alpha | Omit.ignoreEmptyUpdates |
indexes? | IndexShorthand | Alpha | Omit.indexes |
insertOnly? | boolean | Alpha | Omit.insertOnly |
localOnly? | boolean | Alpha | Omit.localOnly |
trackMetadata? | boolean | Alpha | Omit.trackMetadata |
trackPrevious? | boolean | TrackPreviousOptions | Alpha | Omit.trackPrevious |
viewName? | string | Alpha | Omit.viewName |
BaseConnectionOptions
Extended by
Properties
| Property | Type | Description |
|---|---|---|
appMetadata? | Record<string, string> | A set of metadata to be included in service logs. |
clientImplementation? | RUST | Deprecated The Rust sync client is used unconditionally, so this option can't be configured. |
connectionMethod? | SyncStreamConnectionMethod | The connection method to use when streaming updates from the PowerSync backend instance. Defaults to a HTTP streaming connection. |
fetchStrategy? | FetchStrategy | The fetch strategy to use when streaming updates from the PowerSync backend instance. |
includeDefaultStreams? | boolean | Whether to include streams that have auto_subscribe: true in their definition. This defaults to true. |
params? | Record<string, JSONValue> | These parameters are passed to the sync rules, and will be available under theuser_parameters object. |
serializedSchema? | any | The 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
| Parameter | Type |
|---|---|
listener | Partial<T> |
Returns
Function
Returns
void
BasePowerSyncDatabaseOptions
Extends
Extended by
PowerSyncDatabaseOptionsPowerSyncDatabaseOptionsWithDBAdapterPowerSyncDatabaseOptionsWithOpenFactoryPowerSyncDatabaseOptionsWithSettings
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
crudUploadThrottleMs? | number | Backend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds. | AdditionalConnectionOptions.crudUploadThrottleMs |
logger? | ILogger | - | - |
retryDelay? | number | Deprecated Use AdditionalConnectionOptions.retryDelayMs instead as this will be removed in future releases. | - |
retryDelayMs? | number | Delay for retrying sync streaming operations from the PowerSync backend after an error occurs. | AdditionalConnectionOptions.retryDelayMs |
schema | Schema | Schema used for the local database. | - |
BaseTriggerDiffRecord<TOperationId>
Experimental Alpha
Diffs created by TriggerManager#createDiffTrigger are stored in a temporary table. This is the base record structure for all diff records.
Extended by
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
TOperationId extends string | number | number | The type for operation_id. Defaults to number as returned by default SQLite database queries. Use string for full 64-bit precision when using { castOperationIdAsText: true } option. |
Properties
| Property | Type | Description |
|---|---|---|
id | string | Alpha The modified row's id column value. |
operation | DiffTriggerOperation | Alpha The operation performed which created this record. |
operation_id | TOperationId | Alpha Auto-incrementing primary key for the operation. Defaults to number as returned by database queries (wa-sqlite returns lower 32 bits). Can be string for full 64-bit precision when using { castOperationIdAsText: true } option. |
timestamp | string | Alpha Time the change operation was recorded. This is in ISO 8601 format, e.g. 2023-10-01T12:00:00.000Z. |
BatchedUpdateNotification
Properties
| Property | Type |
|---|---|
groupedUpdates | Record<string, TableUpdateOperation[]> |
rawUpdates | UpdateNotification[] |
tables | string[] |
BetterSqlite3Options
Use the better-sqlite3 package as a SQLite driver for PowerSync.
Properties
| Property | Type |
|---|---|
type | "better-sqlite3" |
BucketStorageAdapter
Internal
Extends
Properties
| Property | Type | Inherited from |
|---|---|---|
dispose | () => void | Promise<void> | Disposable.dispose |
Methods
control()
control(op, payload): Promise<string>
Invokes the powersync_control function for the sync client.
Parameters
| Parameter | Type |
|---|---|
op | PowerSyncControlCommand |
payload | null | string | Uint8Array<ArrayBufferLike> |
Returns
Promise<string>
getClientId()
getClientId(): Promise<string>
Get an unique client id.
Returns
Promise<string>
getCrudBatch()
getCrudBatch(limit?): Promise<null | CrudBatch>
Parameters
| Parameter | Type |
|---|---|
limit? | number |
Returns
Promise<null | CrudBatch>
getMaxOpId()
getMaxOpId(): string
Returns
string
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
| Parameter | Type |
|---|---|
listener | Partial<BucketStorageListener> |
Returns
Function
Returns
void
Inherited from
BaseObserverInterface.registerListener
updateLocalTarget()
updateLocalTarget(cb): Promise<boolean>
Parameters
| Parameter | Type |
|---|---|
cb | () => Promise<string> |
Returns
Promise<boolean>
BucketStorageListener
Internal
Extends
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type |
|---|---|
crudUpdate | () => void |
ColumnOptions
Properties
| Property | Type |
|---|---|
name | string |
type? | ColumnType |
CompilableQuery<T>
Type Parameters
| Type Parameter |
|---|
T |
Methods
compile()
compile(): CompiledQuery
Returns
execute()
execute(): Promise<T[]>
Returns
Promise<T[]>
CompilableQueryWatchHandler<T>
Type Parameters
| Type Parameter |
|---|
T |
Properties
| Property | Type |
|---|---|
onError? | (error: Error) => void |
onResult | (results: T[]) => void |
CompiledQuery
Properties
| Property | Modifier | Type |
|---|---|---|
parameters | readonly | readonly unknown[] |
sql | readonly | string |
ConnectionManagerListener
Internal
Extends
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type |
|---|---|
syncStreamCreated | (sync: StreamingSyncImplementation) => void |
ConnectionManagerOptions
Internal
Properties
| Property | Type |
|---|---|
logger | ILogger |
Methods
createSyncImplementation()
createSyncImplementation(connector, options): Promise<ConnectionManagerSyncImplementationResult>
Parameters
| Parameter | Type |
|---|---|
connector | PowerSyncBackendConnector |
options | CreateSyncImplementationOptions |
Returns
Promise<ConnectionManagerSyncImplementationResult>
ConnectionManagerSyncImplementationResult
Internal
Properties
| Property | Type | Description |
|---|---|---|
onDispose | () => void | Promise<void> | Additional cleanup function which is called after the sync stream implementation is disposed. |
sync | StreamingSyncImplementation | - |
ConnectionPool
Extends
Extended by
Properties
| Property | Type | Description |
|---|---|---|
close | () => void | Promise<void> | - |
name | string | - |
readLock | <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> | - |
Methods
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<DBAdapterListener> |
Returns
Function
Returns
void
Inherited from
BaseObserverInterface.registerListener
ControlledExecutorOptions
Internal
Properties
CreateDiffTriggerOptions
Experimental Alpha
Options for TriggerManager#createDiffTrigger.
Extends
BaseCreateDiffTriggerOptions
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
columns? | string[] | Alpha Columns to track and report changes for. Defaults to all columns in the source table. Use an empty array to track only the ID and operation. | BaseCreateDiffTriggerOptions.columns |
destination | string | Alpha Destination table to send changes to. This table is created internally as a SQLite temporary table. This table will be dropped once the trigger is removed. | - |
hooks? | TriggerCreationHooks | Alpha Hooks which allow execution during the trigger creation process. | BaseCreateDiffTriggerOptions.hooks |
setupContext? | LockContext | Alpha Context to use for the setup operation. This is useful for when the setup operation needs to be executed in a specific context. | - |
source | string | Alpha PowerSync source table/view to trigger and track changes from. This should be present in the PowerSync database's schema. | BaseCreateDiffTriggerOptions.source |
useStorage? | boolean | Alpha Use storage-backed (non-TEMP) tables and triggers that persist across sessions. These resources are still automatically disposed when no longer claimed. | BaseCreateDiffTriggerOptions.useStorage |
when | Partial<Record<DiffTriggerOperation, string>> | Alpha Condition to filter when the triggers should fire. This corresponds to a SQLite WHEN clause in the trigger body. This is useful for only triggering on specific conditions. For example, you can use it to only trigger on certain values in the NEW row. Note that for PowerSync the row data is stored in a JSON column named data. The row id is available in the id column. NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL. Any user input strings here should be sanitized externally. The when string template function performs some basic sanitization, extra external sanitization is recommended. Example { * 'INSERT': sanitizeSQLjson_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}, * 'INSERT': TRUE, * 'UPDATE': sanitizeSQLNEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active', * 'DELETE': sanitizeSQLjson_extract(OLD.data, '$.list_id') = 'abcd' * } | BaseCreateDiffTriggerOptions.when |
CreateLoggerOptions
Properties
| Property | Type |
|---|---|
logLevel? | ILogLevel |
CreateSyncImplementationOptions
Internal
The subset of AbstractStreamingSyncImplementationOptions managed by the connection manager.
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
crudUploadThrottleMs? | number | Backend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds. | AdditionalConnectionOptions.crudUploadThrottleMs |
retryDelayMs? | number | Delay for retrying sync streaming operations from the PowerSync backend after an error occurs. | AdditionalConnectionOptions.retryDelayMs |
subscriptions | SubscribedStream[] | - | - |
DBAdapter
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
close | () => void | Promise<void> | - | ConnectionPool.close |
execute | (query: string, params?: any[]) => Promise<QueryResult> | Execute a single write statement. | SqlExecutor.execute |
executeBatch | (query: string, params?: any[][]) => Promise<QueryResult> | - | SqlExecutor.executeBatch |
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' } ] | SqlExecutor.executeRaw |
name | string | - | ConnectionPool.name |
readLock | <T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T> | - | ConnectionPool.readLock |
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. | ConnectionPool.refreshSchema |
writeLock | <T>(fn: (tx) => Promise<T>, options?: DBLockOptions) => Promise<T> | - | ConnectionPool.writeLock |
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
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<T>
Inherited from
getAll()
getAll<T>(sql, parameters?): Promise<T[]>
Execute a read-only query and return results.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<T[]>
Inherited from
getOptional()
getOptional<T>(sql, parameters?): Promise<null | T>
Execute a read-only query and return the first result, or null if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<null | T>
Inherited from
registerListener()
registerListener(listener): () => void
Parameters
| Parameter | Type |
|---|---|
listener | Partial<DBAdapterListener> |
Returns
Function
Returns
void
Inherited from
ConnectionPool.registerListener
DBAdapterListener
Extends
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type | Description |
|---|---|---|
tablesUpdated | (updateNotification: | UpdateNotification | BatchedUpdateNotification) => void | Listener 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
| Parameter | Type |
|---|---|
sql | string |
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
| Parameter | Type |
|---|---|
sql | string |
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
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<null | T>
DBLockOptions
Properties
| Property | Type |
|---|---|
timeoutMs? | number |
DifferentialQueryProcessorOptions<RowType>
Internal
Extends
AbstractQueryProcessorOptions<RowType[],DifferentialWatchedQuerySettings<RowType>>
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Inherited from |
|---|---|---|
db | AbstractPowerSyncDatabase | AbstractQueryProcessorOptions.db |
placeholderData | RowType[] | AbstractQueryProcessorOptions.placeholderData |
rowComparator? | DifferentialWatchedQueryComparator<RowType> | - |
watchOptions | DifferentialWatchedQuerySettings | AbstractQueryProcessorOptions.watchOptions |
DifferentialWatchedQueryComparator<RowType>
Row comparator for differentially watched queries which keys and compares items in the result set.
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Description |
|---|---|---|
compareBy | (item: RowType) => string | Generates a token for comparing items with matching keys. |
keyBy | (item: RowType) => string | Generates a unique key for the item. |
DifferentialWatchedQueryListener<RowType>
Extends
WatchedQueryListener<ReadonlyArray<Readonly<RowType>>>
Type Parameters
| Type Parameter |
|---|
RowType |
Indexable
[key: string]: undefined | (...event) => any
Properties
| Property | Type | Inherited 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 |
settingsWillUpdate? | () => void | WatchedQueryListener.settingsWillUpdate |
DifferentialWatchedQueryOptions<RowType>
Options for building a differential watched query with the Query builder.
Extends
Extended by
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Default value | Description | Inherited from |
|---|---|---|---|---|
placeholderData? | RowType[] | undefined | Initial result data which is presented while the initial loading is executing. | - |
reportFetching? | boolean | undefined | If 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_COMPARATOR | Row comparator used to identify and compare rows in the result set. If not provided, the default comparator will be used which keys items by their id property if available, otherwise it uses JSON stringification of the entire item for keying and comparison. | - |
throttleMs? | number | undefined | The minimum interval between queries. | WatchedQueryOptions.throttleMs |
triggerOnTables? | string[] | undefined | By default, watched queries requery the database on any change to any dependent table of the query. Supplying an override here can be used to limit the tables which trigger querying the database. | WatchedQueryOptions.triggerOnTables |
DifferentialWatchedQuerySettings<RowType>
Settings for differential incremental watched queries using.
Extends
DifferentialWatchedQueryOptions<RowType>
Type Parameters
| Type Parameter |
|---|
RowType |
Properties
| Property | Type | Default value | Description | Inherited from |
|---|---|---|---|---|
placeholderData? | RowType[] | undefined | Initial result data which is presented while the initial loading is executing. | DifferentialWatchedQueryOptions.placeholderData |
query | WatchCompatibleQuery<RowType[]> | undefined | The query here must return an array of items that can be differentiated. | - |
reportFetching? | boolean | undefined | If 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_COMPARATOR | Row comparator used to identify and compare rows in the result set. If not provided, the default comparator will be used which keys items by their id property if available, otherwise it uses JSON stringification of the entire item for keying and comparison. | DifferentialWatchedQueryOptions.rowComparator |
throttleMs? | number | undefined | The minimum interval between queries. | DifferentialWatchedQueryOptions.throttleMs |
triggerOnTables? | string[] | undefined | By default, watched queries requery the database on any change to any dependent table of the query. Supplying an override here can be used to limit the tables which trigger querying the database. | DifferentialWatchedQueryOptions.triggerOnTables |
DisconnectAndClearOptions
Properties
| Property | Type | Description |
|---|---|---|
clearLocal? | boolean | When set to false, data in local-only tables is preserved. |
Disposable
Extended by
Properties
| Property | Type |
|---|---|
dispose | () => void | Promise<void> |
IndexColumnOptions
Properties
| Property | Type |
|---|---|
ascending? | boolean |
name | string |
IndexOptions
Properties
| Property | Type |
|---|---|
columns? | IndexedColumn[] |
name | string |
InternalConnectionOptions
Internal
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
appMetadata? | Record<string, string> | A set of metadata to be included in service logs. | BaseConnectionOptions.appMetadata |
clientImplementation? | RUST | Deprecated The Rust sync client is used unconditionally, so this option can't be configured. | BaseConnectionOptions.clientImplementation |
connectionMethod? | SyncStreamConnectionMethod | The connection method to use when streaming updates from the PowerSync backend instance. Defaults to a HTTP streaming connection. | BaseConnectionOptions.connectionMethod |
crudUploadThrottleMs? | number | Backend Connector CRUD operations are throttled to occur at most every crudUploadThrottleMs milliseconds. | AdditionalConnectionOptions.crudUploadThrottleMs |
fetchStrategy? | FetchStrategy | The fetch strategy to use when streaming updates from the PowerSync backend instance. | BaseConnectionOptions.fetchStrategy |
includeDefaultStreams? | boolean | Whether to include streams that have auto_subscribe: true in their definition. This defaults to true. | BaseConnectionOptions.includeDefaultStreams |
params? | Record<string, JSONValue> | These parameters are passed to the sync rules, and will be available under theuser_parameters object. | BaseConnectionOptions.params |
retryDelayMs? | number | Delay for retrying sync streaming operations from the PowerSync backend after an error occurs. | AdditionalConnectionOptions.retryDelayMs |
serializedSchema? | any | The serialized schema - mainly used to forward information about raw tables to the sync client. | BaseConnectionOptions.serializedSchema |
InternalSubscriptionAdapter
Internal
Methods
firstStatusMatching()
firstStatusMatching(predicate, abort?): Promise<void>
Parameters
| Parameter | Type |
|---|---|
predicate | (status) => any |
abort? | AbortSignal |
Returns
Promise<void>
resolveOfflineSyncStatus()
resolveOfflineSyncStatus(): Promise<void>
Returns
Promise<void>
rustSubscriptionsCommand()
rustSubscriptionsCommand(payload): Promise<void>
Parameters
| Parameter | Type |
|---|---|
payload | any |
Returns
Promise<void>
LinkQueryOptions<Data, Settings>
Internal
Type Parameters
| Type Parameter | Default type |
|---|---|
Data | - |
Settings extends WatchedQueryOptions | WatchedQueryOptions |
Properties
| Property | Type |
|---|---|
abortSignal | AbortSignal |
settings | Settings |
LocalStorageAdapter
Experimental Alpha
LocalStorageAdapter defines the interface for local file storage operations. Implementations handle file I/O, directory management, and storage initialization.
This is currently experimental and may change without a major version bump.
Methods
clear()
clear(): Promise<void>
Alpha
Returns
Promise<void>
deleteFile()
deleteFile(filePath): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<void>
fileExists()
fileExists(filePath): Promise<boolean>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<boolean>
True if the file exists, false otherwise
getLocalUri()
getLocalUri(filename): string
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filename | string | The filename to get the path for |
Returns
string
The full file path
initialize()
initialize(): Promise<void>
Alpha
Returns
Promise<void>
makeDir()
makeDir(path): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The full path to the directory |
Returns
Promise<void>
readFile()
readFile(filePath): Promise<ArrayBuffer>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file is stored |
Returns
Promise<ArrayBuffer>
ArrayBuffer containing the file data
rmDir()
rmDir(path): Promise<void>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The full path to the directory |
Returns
Promise<void>
saveFile()
saveFile(filePath, data): Promise<number>
Alpha
Parameters
| Parameter | Type | Description |
|---|---|---|
filePath | string | Path where the file will be stored |
data | AttachmentData | Data to store (ArrayBuffer, Blob, or string) |
Returns
Promise<number>
Number of bytes written
LockContext
Extends
Extended by
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
connectionType? | "writer" | "queryOnly" | "readOnly" | How the connection has been opened. writer indicates that the lock context is capable of writing to the database. queryOnly indicates that the lock context has been opened in a readwrite mode, but a PRAGMA query_only = TRUE disabled writes. readOnly indicates that the lock context has been opened by passing SQLITE_OPEN_READONLY to sqlite3_open_v2. | - |
execute | (query: string, params?: any[]) => Promise<QueryResult> | Execute a single write statement. | SqlExecutor.execute |
executeBatch | (query: string, params?: any[][]) => Promise<QueryResult> | - | SqlExecutor.executeBatch |
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' } ] | SqlExecutor.executeRaw |
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
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<T>
Inherited from
getAll()
getAll<T>(sql, parameters?): Promise<T[]>
Execute a read-only query and return results.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<T[]>
Inherited from
getOptional()
getOptional<T>(sql, parameters?): Promise<null | T>
Execute a read-only query and return the first result, or null if the ResultSet is empty.
Type Parameters
| Type Parameter |
|---|
T |
Parameters
| Parameter | Type |
|---|---|
sql | string |
parameters? | any[] |
Returns
Promise<null | T>
Inherited from
LockOptions<T>
Internal
Abstract Lock to be implemented by various JS environments
Type Parameters
| Type Parameter |
|---|
T |
Properties
| Property | Type |
|---|---|
callback | () => Promise<T> |
signal? | AbortSignal |
type | LockType |
NodeSqliteOptions
Use the experimental node:sqlite interface as a SQLite driver for PowerSync.
Note that this option is not currently tested and highly unstable.
Properties
| Property | Type |
|---|---|
type | "node:sqlite" |
NodeSQLOpenOptions
The SQLOpenOptions available across all PowerSync SDKs for JavaScript extended with Node.JS-specific options.
Extends
Properties
| Property | Type | Description | Inherited from |
|---|---|---|---|
dbFilename | string | Filename for the database. | SQLOpenOptions.dbFilename |
dbLocation? | string | Directory 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? | 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 |
implementation? | NodeDatabaseImplementation | - | - |
initializeConnection? | (db: LockContext, isWriter: boolean) => Promise<void> | Initializes a created database connection. This can be used to e.g. set encryption keys, if an encrypted database should be used. | - |
openWorker? | WorkerOpener | A callback to allow customizing how the Node.JS SDK loads workers. This can be customized to use workers at different paths. Param The arguments that would otherwise be passed to the Worker constructor. | - |
readWorkerCount? | number | The Node.JS SDK will use one worker to run writing queries and additional workers to run reads. This option controls how many workers to use for reads. | - |
OnChangeQueryProcessorOptions<Data>
Internal
Extends
AbstractQueryProcessorOptions<Data,WatchedQuerySettings<Data>>
Type Parameters
| Type Parameter |
|---|
Data |
Properties
| Property | Type | Inherited from |
|---|---|---|
comparator? | WatchedQueryComparator<Data> | - |
db | AbstractPowerSyncDatabase | AbstractQueryProcessorOptions.db |
placeholderData | Data | AbstractQueryProcessorOptions.placeholderData |
watchOptions | WatchedQuerySettings | AbstractQueryProcessorOptions.watchOptions |
ParsedQuery
Internal
Properties
| Property | Type |
|---|---|
parameters | any[] |
sqlStatement | string |
PowerSyncBackendConnector
Properties
| Property | Type | Description |
|---|---|---|
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). |