@powersync/common 0.0.0-dev-20260226160529 → 0.0.0-dev-20260305124002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/bundle.cjs +58 -61
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +59 -61
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +58 -61
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +59 -61
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +130 -79
  10. package/lib/client/AbstractPowerSyncDatabase.js +1 -5
  11. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -1
  12. package/lib/client/triggers/TriggerManager.d.ts +6 -0
  13. package/lib/client/triggers/TriggerManagerImpl.js +16 -12
  14. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  15. package/lib/db/schema/RawTable.d.ts +61 -26
  16. package/lib/db/schema/RawTable.js +1 -32
  17. package/lib/db/schema/RawTable.js.map +1 -1
  18. package/lib/db/schema/Schema.d.ts +14 -7
  19. package/lib/db/schema/Schema.js +25 -3
  20. package/lib/db/schema/Schema.js.map +1 -1
  21. package/lib/db/schema/Table.d.ts +13 -8
  22. package/lib/db/schema/Table.js +3 -8
  23. package/lib/db/schema/Table.js.map +1 -1
  24. package/lib/db/schema/internal.d.ts +12 -0
  25. package/lib/db/schema/internal.js +15 -0
  26. package/lib/db/schema/internal.js.map +1 -0
  27. package/lib/index.d.ts +1 -1
  28. package/lib/index.js +0 -1
  29. package/lib/index.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/client/AbstractPowerSyncDatabase.ts +1 -6
  32. package/src/client/triggers/TriggerManager.ts +7 -0
  33. package/src/client/triggers/TriggerManagerImpl.ts +16 -11
  34. package/src/db/schema/RawTable.ts +66 -31
  35. package/src/db/schema/Schema.ts +27 -2
  36. package/src/db/schema/Table.ts +11 -11
  37. package/src/db/schema/internal.ts +17 -0
  38. package/src/index.ts +1 -1
package/dist/bundle.mjs CHANGED
@@ -101,6 +101,21 @@ class Index {
101
101
  }
102
102
  }
103
103
 
104
+ /**
105
+ * @internal Not exported from `index.ts`.
106
+ */
107
+ function encodeTableOptions(options) {
108
+ const trackPrevious = options.trackPrevious;
109
+ return {
110
+ local_only: options.localOnly,
111
+ insert_only: options.insertOnly,
112
+ include_old: trackPrevious && (trackPrevious.columns ?? true),
113
+ include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
114
+ include_metadata: options.trackMetadata,
115
+ ignore_empty_update: options.ignoreEmptyUpdates
116
+ };
117
+ }
118
+
104
119
  const DEFAULT_TABLE_OPTIONS = {
105
120
  indexes: [],
106
121
  insertOnly: false,
@@ -290,18 +305,12 @@ class Table {
290
305
  }
291
306
  }
292
307
  toJSON() {
293
- const trackPrevious = this.trackPrevious;
294
308
  return {
295
309
  name: this.name,
296
310
  view_name: this.viewName,
297
- local_only: this.localOnly,
298
- insert_only: this.insertOnly,
299
- include_old: trackPrevious && (trackPrevious.columns ?? true),
300
- include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
301
- include_metadata: this.trackMetadata,
302
- ignore_empty_update: this.ignoreEmptyUpdates,
303
311
  columns: this.columns.map((c) => c.toJSON()),
304
- indexes: this.indexes.map((e) => e.toJSON(this))
312
+ indexes: this.indexes.map((e) => e.toJSON(this)),
313
+ ...encodeTableOptions(this)
305
314
  };
306
315
  }
307
316
  }
@@ -12479,7 +12488,7 @@ class TriggerManagerImpl {
12479
12488
  }
12480
12489
  async createDiffTrigger(options) {
12481
12490
  await this.db.waitForReady();
12482
- const { source, destination, columns, when, hooks,
12491
+ const { source, destination, columns, when, hooks, manageDestinationExternally = false,
12483
12492
  // Fall back to the provided default if not given on this level
12484
12493
  useStorage = this.defaultConfig.useStorageByDefault } = options;
12485
12494
  const operations = Object.keys(when);
@@ -12538,23 +12547,27 @@ class TriggerManagerImpl {
12538
12547
  disposeWarningListener();
12539
12548
  return this.db.writeLock(async (tx) => {
12540
12549
  await this.removeTriggers(tx, triggerIds);
12541
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
12550
+ if (!manageDestinationExternally) {
12551
+ await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
12552
+ }
12542
12553
  await releaseStorageClaim?.();
12543
12554
  });
12544
12555
  };
12545
12556
  const setup = async (tx) => {
12546
12557
  // Allow user code to execute in this lock context before the trigger is created.
12547
12558
  await hooks?.beforeCreate?.(tx);
12548
- await tx.execute(/* sql */ `
12549
- CREATE ${tableTriggerTypeClause} TABLE ${destination} (
12550
- operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
12551
- id TEXT,
12552
- operation TEXT,
12553
- timestamp TEXT,
12554
- value TEXT,
12555
- previous_value TEXT
12556
- )
12557
- `);
12559
+ if (!manageDestinationExternally) {
12560
+ await tx.execute(/* sql */ `
12561
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
12562
+ operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
12563
+ id TEXT,
12564
+ operation TEXT,
12565
+ timestamp TEXT,
12566
+ value TEXT,
12567
+ previous_value TEXT
12568
+ )
12569
+ `);
12570
+ }
12558
12571
  if (operations.includes(DiffTriggerOperation.INSERT)) {
12559
12572
  const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
12560
12573
  triggerIds.push(insertTriggerId);
@@ -13022,11 +13035,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13022
13035
  this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);
13023
13036
  }
13024
13037
  this._schema = schema;
13025
- // powersync_replace_schema starts a transaction internally, but we can be more efficient by using BEGIN EXCLUSIVE
13026
- // on some DB adapters.
13027
- this.database.writeTransaction((tx) => {
13028
- return tx.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
13029
- });
13038
+ await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
13030
13039
  await this.database.refreshSchema();
13031
13040
  this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
13032
13041
  }
@@ -14131,39 +14140,6 @@ class ConnectionClosedError extends Error {
14131
14140
  }
14132
14141
  }
14133
14142
 
14134
- /**
14135
- * Instructs PowerSync to sync data into a "raw" table.
14136
- *
14137
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
14138
- * using client-side table and column constraints.
14139
- *
14140
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
14141
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
14142
- * using raw tables.
14143
- *
14144
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
14145
- *
14146
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
14147
- * stability guarantees.
14148
- */
14149
- class RawTable {
14150
- /**
14151
- * The name of the table.
14152
- *
14153
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
14154
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
14155
- * appears in the source / backend database) are to be handled specially.
14156
- */
14157
- name;
14158
- put;
14159
- delete;
14160
- constructor(name, type) {
14161
- this.name = name;
14162
- this.put = type.put;
14163
- this.delete = type.delete;
14164
- }
14165
- }
14166
-
14167
14143
  /**
14168
14144
  * A schema is a collection of tables. It is used to define the structure of a database.
14169
14145
  */
@@ -14208,7 +14184,7 @@ class Schema {
14208
14184
  */
14209
14185
  withRawTables(tables) {
14210
14186
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
14211
- this.rawTables.push(new RawTable(name, rawTableDefinition));
14187
+ this.rawTables.push({ name, ...rawTableDefinition });
14212
14188
  }
14213
14189
  }
14214
14190
  validate() {
@@ -14219,8 +14195,30 @@ class Schema {
14219
14195
  toJSON() {
14220
14196
  return {
14221
14197
  tables: this.tables.map((t) => t.toJSON()),
14222
- raw_tables: this.rawTables
14198
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
14199
+ };
14200
+ }
14201
+ /**
14202
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
14203
+ *
14204
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
14205
+ * to define triggers for this table.
14206
+ */
14207
+ static rawTableToJson(table) {
14208
+ const serialized = {
14209
+ name: table.name,
14210
+ put: table.put,
14211
+ delete: table.delete,
14212
+ clear: table.clear
14223
14213
  };
14214
+ if ('schema' in table) {
14215
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
14216
+ const schema = table.schema;
14217
+ serialized.table_name = schema.tableName ?? table.name;
14218
+ serialized.synced_columns = schema.syncedColumns;
14219
+ Object.assign(serialized, encodeTableOptions(table.schema));
14220
+ }
14221
+ return serialized;
14224
14222
  }
14225
14223
  }
14226
14224
 
@@ -14379,5 +14377,5 @@ const parseQuery = (query, parameters) => {
14379
14377
  return { sqlStatement, parameters: parameters };
14380
14378
  };
14381
14379
 
14382
- export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RawTable, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
14380
+ export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
14383
14381
  //# sourceMappingURL=bundle.mjs.map