Skip to main content

@powersync/common

Enumerations​

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

Classes​

ClassDescription
ArrayComparatorAn efficient comparator for WatchedQuery created with Query#watch. This has the ability to determine if a query result has changes without necessarily processing all items in the result.
AttachmentContextAttachmentContext provides database operations for managing attachment records.
AttachmentQueueAttachmentQueue manages the lifecycle and synchronization of attachments between local and remote storage. Provides automatic synchronization, upload/download queuing, attachment monitoring, verification and repair of local files, and cleanup of archived attachments.
AttachmentTableAttachmentTable defines the schema for the attachment queue table.
BaseObserver-
Column-
CrudBatchA batch of client-side changes.
CrudTransaction-
DBAdapter-
GetAllQueryPerforms a DBGetUtils.getAll operation for a watched query.
Index-
IndexedColumn-
LockContext-
ResolvedTableA resolved table in the PowerSync schema, with all columns, index definitions and options.
SchemaA schema is a collection of tables. It is used to define the structure of a database.
TableA table with a statically-typed Columns record structure.
UploadQueueStats-

Interfaces​

InterfaceDescription
ArrayQueryDefinitionOptions for building a query with AbstractPowerSyncDatabase#query. This query will be executed with AbstractPowerSyncDatabase#getAll.
AttachmentErrorHandlerSyncErrorHandler provides custom error handling for attachment sync operations. Implementations determine whether failed operations should be retried or archived.
AttachmentRecordAttachmentRecord represents an attachment in the local database.
AttachmentTableOptions-
AttachmentTransportAdapterAttachmentTransportAdapter owns all remote-side operations for an attachment — transfer (upload/download) and delete — as single operations.
BaseAttachmentQueueOptionsFields common to every AttachmentQueueOptions variant.
BaseCreateDiffTriggerOptionsCommon interface for options used in creating a diff trigger.
BaseObserverInterface-
BasePowerSyncDatabaseOptionsOptions required regardless of how a PowerSync database is opened.
BaseQueryResultShared superinterface for QueryResult and RawQueryResult.
BaseTriggerDiffRecordDiffs created by TriggerManager#createDiffTrigger are stored in a temporary table. This is the base record structure for all diff records.
BatchedUpdateNotification-
CheckpointRequestA checkpoint request created by CommonPowerSyncDatabase#requestCheckpoint.
CheckpointRequestsOptionsOptions associated with a CheckpointMode when the requests-based checkpoint option is used.
ColumnOptions-
CommonPowerSyncDatabase-
CompilableQuery-
CompilableQueryWatchHandler-
CompiledQuery-
CreateDiffTriggerOptionsOptions for TriggerManager#createDiffTrigger.
CreateLoggerOptions-
CrudEntryA single client-side change.
DBAdapterListener-
DBGetUtils-
DBLockOptions-
DifferentialWatchedQueryComparatorRow comparator for differentially watched queries which keys and compares items in the result set.
DifferentialWatchedQueryListener-
DifferentialWatchedQueryOptionsOptions for building a differential watched query with the Query builder.
DifferentialWatchedQuerySettingsSettings for differential incremental watched queries using.
DisconnectAndClearOptionsOptions passed to CommonPowerSyncDatabase#disconnectAndClear.
Disposable-
IndexColumnOptions-
IndexOptions-
ListenerMetaManager-
LocalStorageAdapterLocalStorageAdapter defines the interface for local file storage operations. Implementations handle file I/O, directory management, and storage initialization.
LogRecordA log record passed to a PowerSyncLogger.
MetaBaseObserverInterface-
MetaListenerMeta listener which reports the counts of listeners for each event type.
PowerSyncBackendConnector-
PowerSyncCloseOptions-
PowerSyncCredentials-
PowerSyncDatabaseConstructor-
PowerSyncDBListener-
PowerSyncLoggerA logger used by the PowerSync SDK.
ProgressWithOperationsInformation about a progressing download made by the PowerSync SDK.
Query-
QueryResultObject returned by SQL Query executions.
RawQueryResultA raw array-based result set representing rows returned by SQLite.
RemoteStorageAdapterRemoteStorageAdapter defines the interface for remote storage operations. Implementations handle uploading, downloading, and deleting files from remote storage.
ResolvedTableOptions-
ResultSetA representation of query results as JavaScript object.
SaveAttachmentOptionsFields shared by AttachmentQueue.saveFile and AttachmentQueue.saveFileFromUri.
SqlExecutor-
SQLOnChangeOptions-
SQLOpenFactory-
SQLOpenOptions-
SQLWatchOptions-
StandardWatchedQueryOptionsOptions for Query#watch.
StreamingLocalStorageAdapterA LocalStorageAdapter that can relocate a file into managed storage without loading it into memory. Required for AttachmentQueue.saveFileFromUri; only queues configured with a streaming-capable local adapter expose that method.
SyncDataFlowStatus-
SyncOptionsOptions that affect how the PowerSync SDK connects to the PowerSync Service.
SyncPriorityStatus-
SyncProgressProvides realtime progress on how PowerSync is downloading rows.
SyncStatus-
SyncStreamA handle to a SyncStreamDescription that allows subscribing to the stream.
SyncStreamDescriptionA description of a sync stream, consisting of its SyncStreamDescription.name and the SyncStreamDescription.parameters used when subscribing.
SyncStreamStatusInformation about a sync stream subscription.
SyncStreamSubscribeOptions-
SyncStreamSubscription-
SyncSubscriptionDescriptionInformation about a subscribed sync stream.
TableOptions-
TableOrRawTableOptionsOptions that apply both to JSON-based tables and raw tables.
TrackDiffOptionsOptions for tracking changes to a table with TriggerManager#trackTableDiff.
TrackPreviousOptionsWhether to include previous column values when PowerSync tracks local changes.
Transaction-
TriggerCreationHooksHooks used in the creation of a table diff trigger.
TriggerDiffDeleteRecordRepresents a diff record for a SQLite DELETE operation. This record contains the new value represented as a JSON string.
TriggerDiffHandlerContextContext for the onChange handler provided to TriggerManager#trackTableDiff.
TriggerDiffInsertRecordRepresents a diff record for a SQLite INSERT operation. This record contains the new value represented as a JSON string.
TriggerDiffUpdateRecordRepresents a diff record for a SQLite UPDATE operation. This record contains the new value and optionally the previous value. Values are stored as JSON strings.
TriggerManager-
TriggerRemoveCallbackOptionsOptions for TriggerRemoveCallback.
WatchCompatibleQuery-
WatchedQuery-
WatchedQueryComparatorA 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.
WatchedQueryDifferentialRepresents the result of a watched query that has been diffed. DifferentialWatchedQueryState#diff is of the WatchedQueryDifferential form.
WatchedQueryListener-
WatchedQueryOptions-
WatchedQueryRowDifferentialRepresents an updated row in a differential watched query. It contains both the current and previous state of the row.
WatchedQuerySettingsSettings for WatchedQuery instances created via Query#watch.
WatchedQueryStateState for WatchedQuery instances.
WatchExecuteOptionsOptions provided to the execute method of a WatchCompatibleQuery.
WatchHandler-
WatchOnChangeEvent-
WatchOnChangeHandler-
WithDiffOptionsOptions for TriggerDiffHandlerContext#withDiff.

Type Aliases​

AbstractPowerSyncDatabase​

type AbstractPowerSyncDatabase = CommonPowerSyncDatabase;

Deprecated​

Use CommonPowerSyncDatabase instead.


ArrayComparatorOptions​

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

Options for ArrayComparator

Type Parameters​

Type Parameter
ItemType

Properties​

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

AttachmentData​

type AttachmentData = ArrayBuffer | string;

Alpha


AttachmentQueueOptions​

type AttachmentQueueOptions<TLocal> = BaseAttachmentQueueOptions<TLocal> &
| {
remoteStorage: RemoteStorageAdapter;
transportAdapter?: never;
}
| {
remoteStorage?: never;
transportAdapter: AttachmentTransportAdapter;
};

Experimental Alpha

Configuration options for AttachmentQueue.

Provide exactly one remote mechanism:

  • remoteStorage — a RemoteStorageAdapter, wrapped in the default default buffered transport that delegates upload/download/delete to it.
  • transportAdapter — an AttachmentTransportAdapter that owns all remote operations directly (e.g. a native file-URI implementation for buffer-free transfer of large files). No remoteStorage is needed in this case.

Supplying both, or neither, is a type error.

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

Type Parameters​

Type ParameterDefault type
TLocal extends LocalStorageAdapterLocalStorageAdapter

AttachmentTableRecord​

type AttachmentTableRecord = RowType<AttachmentTable>;

Alpha

AttachmentTableRecord represents the row type of the attachment table.


BaseColumnType​

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

Type Parameters​

Type Parameter
T extends number | string | null

Properties​

PropertyType
typeColumnType

BaseListener​

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

CheckpointMode​

type CheckpointMode =
| "legacy"
| "requests"
| {
requests: CheckpointRequestsOptions;
};

The mechanism to request checkpoints from the PowerSync service.

Checkpoint requests are used after a client uploads local mutations. The PowerSync service later references them in downloaded data, allowing the SDK to assume that uploaded data has been synced down again.

There are two ways to send checkpoint requests: A legacy (but default and stable) format supported by all PowerSync service versions, and a newer (requests) method which is only available from PowerSync service version 1.24.0 or later.

Note that the requests checkpoint mode is an alpha API.


ColumnsType​

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

DatabaseSource​

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

A source describing how to open databases.

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

Type Parameters​

Type ParameterDefault type
OpenOptions extends SQLOpenOptionsSQLOpenOptions

Union Members​

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

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

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

DifferentialWatchedQuery​

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

Type Parameters​

Type Parameter
RowType

ExtractColumnValueType​

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

Type Parameters​

Type Parameter
T extends BaseColumnType<any>

ExtractedTriggerDiffRecord​

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

Experimental Alpha

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

Type Declaration​

NameType
__previous_value?string

Type Parameters​

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

Example​

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

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

GetAllQueryOptions​

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

Options for GetAllQuery.

Type Parameters​

Type ParameterDefault type
RowTypeunknown

Properties​

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

IndexShorthand​

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

ListenerCounts​

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

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

Type Declaration​

NameType
totalnumber

Type Parameters​

Type Parameter
Listener extends BaseListener

LocatedAttachmentRecord​

type LocatedAttachmentRecord = AttachmentRecord & {
localUri: string;
};

Alpha

An AttachmentRecord that is guaranteed to have a localUri.

The syncing service assigns localUri before invoking a transport download, so implementations always receive both the metadata and the destination path.

Type Declaration​

NameType
localUristring

OpId​

type OpId = string;

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

Not sortable as a string.


PendingStatement​

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

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

Properties​

PropertyType
paramsPendingStatementParameter[]
sqlstring

PendingStatementParameter​

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

A parameter to use as part of PendingStatement.

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

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


PowerSyncDatabaseOptions​

type PowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions & DatabaseSource;

QueryParam​

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

Query parameters for ArrayQueryDefinition#parameters


RawTableType​

type RawTableType = RawTableTypeWithStatements | InferredRawTableType;

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

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

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


RowType​

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

Type Parameters​

Type Parameter
T extends Table<any>

SchemaTableType​

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

Type Parameters​

Type Parameter
S extends SchemaType

SqliteRecord​

type SqliteRecord = Record<string, SqliteValue>;

A record of SQLite values representing a row.


SqliteValue​

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

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


StandardWatchedQuery​

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

WatchedQuery returned from Query#watch.

Type Parameters​

Type Parameter
DataType

StreamingSyncRequestParameterType​

type StreamingSyncRequestParameterType = JSONValue;

TriggerDiffRecord​

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

Experimental Alpha

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

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

Type Parameters​

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

Example​

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

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

TriggerRemoveCallback​

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

Experimental Alpha

Callback to drop a trigger after it has been created.

Parameters​

ParameterType
options?TriggerRemoveCallbackOptions

Returns​

Promise<void>


WatchedAttachmentItem​

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

Alpha

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

Variables​

ATTACHMENT_TABLE​

const ATTACHMENT_TABLE: "attachments" = 'attachments';

Alpha

The default name of the local table storing attachment data.


ATTACHMENT_TABLE_COLUMNS​

const ATTACHMENT_TABLE_COLUMNS: {
filename: BaseColumnType<string | null>;
has_synced: BaseColumnType<number | null>;
local_uri: BaseColumnType<string | null>;
media_type: BaseColumnType<string | null>;
meta_data: BaseColumnType<string | null>;
size: BaseColumnType<number | null>;
state: BaseColumnType<number | null>;
timestamp: BaseColumnType<number | null>;
};

Alpha

Type Declaration​

NameTypeDefault value
filenameBaseColumnType<string | null>column.text
has_syncedBaseColumnType<number | null>column.integer
local_uriBaseColumnType<string | null>column.text
media_typeBaseColumnType<string | null>column.text
meta_dataBaseColumnType<string | null>column.text
sizeBaseColumnType<number | null>column.integer
stateBaseColumnType<number | null>column.integer
timestampBaseColumnType<number | null>column.integer

column​

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

Type Declaration​

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

FalsyComparator​

const FalsyComparator: WatchedQueryComparator<unknown>;

Watched query comparator that always reports changed result sets.


LogLevels​

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

Type Declaration​

NameTypeDefault value
debug2020
error5050
info3030
trace1010
warn4040

Functions​

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