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

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 (39) hide show
  1. package/dist/bundle.cjs +48 -53
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +49 -53
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +48 -53
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +49 -53
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +130 -80
  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 +5 -0
  13. package/lib/client/triggers/TriggerManagerImpl.d.ts +1 -1
  14. package/lib/client/triggers/TriggerManagerImpl.js +6 -4
  15. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  16. package/lib/db/schema/RawTable.d.ts +61 -26
  17. package/lib/db/schema/RawTable.js +1 -32
  18. package/lib/db/schema/RawTable.js.map +1 -1
  19. package/lib/db/schema/Schema.d.ts +14 -7
  20. package/lib/db/schema/Schema.js +25 -3
  21. package/lib/db/schema/Schema.js.map +1 -1
  22. package/lib/db/schema/Table.d.ts +13 -8
  23. package/lib/db/schema/Table.js +3 -8
  24. package/lib/db/schema/Table.js.map +1 -1
  25. package/lib/db/schema/internal.d.ts +12 -0
  26. package/lib/db/schema/internal.js +15 -0
  27. package/lib/db/schema/internal.js.map +1 -0
  28. package/lib/index.d.ts +1 -1
  29. package/lib/index.js +0 -1
  30. package/lib/index.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/client/AbstractPowerSyncDatabase.ts +1 -6
  33. package/src/client/triggers/TriggerManager.ts +6 -0
  34. package/src/client/triggers/TriggerManagerImpl.ts +6 -3
  35. package/src/db/schema/RawTable.ts +66 -31
  36. package/src/db/schema/Schema.ts +27 -2
  37. package/src/db/schema/Table.ts +11 -11
  38. package/src/db/schema/internal.ts +17 -0
  39. package/src/index.ts +1 -1
@@ -103,6 +103,21 @@ class Index {
103
103
  }
104
104
  }
105
105
 
106
+ /**
107
+ * @internal Not exported from `index.ts`.
108
+ */
109
+ function encodeTableOptions(options) {
110
+ const trackPrevious = options.trackPrevious;
111
+ return {
112
+ local_only: options.localOnly,
113
+ insert_only: options.insertOnly,
114
+ include_old: trackPrevious && (trackPrevious.columns ?? true),
115
+ include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
116
+ include_metadata: options.trackMetadata,
117
+ ignore_empty_update: options.ignoreEmptyUpdates
118
+ };
119
+ }
120
+
106
121
  const DEFAULT_TABLE_OPTIONS = {
107
122
  indexes: [],
108
123
  insertOnly: false,
@@ -292,18 +307,12 @@ class Table {
292
307
  }
293
308
  }
294
309
  toJSON() {
295
- const trackPrevious = this.trackPrevious;
296
310
  return {
297
311
  name: this.name,
298
312
  view_name: this.viewName,
299
- local_only: this.localOnly,
300
- insert_only: this.insertOnly,
301
- include_old: trackPrevious && (trackPrevious.columns ?? true),
302
- include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
303
- include_metadata: this.trackMetadata,
304
- ignore_empty_update: this.ignoreEmptyUpdates,
305
313
  columns: this.columns.map((c) => c.toJSON()),
306
- indexes: this.indexes.map((e) => e.toJSON(this))
314
+ indexes: this.indexes.map((e) => e.toJSON(this)),
315
+ ...encodeTableOptions(this)
307
316
  };
308
317
  }
309
318
  }
@@ -9957,7 +9966,7 @@ class TriggerManagerImpl {
9957
9966
  }
9958
9967
  async createDiffTrigger(options) {
9959
9968
  await this.db.waitForReady();
9960
- const { source, destination, columns, when, hooks,
9969
+ const { source, destination, columns, when, hooks, persistDestination = false,
9961
9970
  // Fall back to the provided default if not given on this level
9962
9971
  useStorage = this.defaultConfig.useStorageByDefault } = options;
9963
9972
  const operations = Object.keys(when);
@@ -10012,11 +10021,13 @@ class TriggerManagerImpl {
10012
10021
  * we need to ensure we can cleanup the created resources.
10013
10022
  * We unfortunately cannot rely on transaction rollback.
10014
10023
  */
10015
- const cleanup = async () => {
10024
+ const cleanup = async (force) => {
10016
10025
  disposeWarningListener();
10017
10026
  return this.db.writeLock(async (tx) => {
10018
10027
  await this.removeTriggers(tx, triggerIds);
10019
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10028
+ if (!persistDestination || force) {
10029
+ await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10030
+ }
10020
10031
  await releaseStorageClaim?.();
10021
10032
  });
10022
10033
  };
@@ -10024,7 +10035,7 @@ class TriggerManagerImpl {
10024
10035
  // Allow user code to execute in this lock context before the trigger is created.
10025
10036
  await hooks?.beforeCreate?.(tx);
10026
10037
  await tx.execute(/* sql */ `
10027
- CREATE ${tableTriggerTypeClause} TABLE ${destination} (
10038
+ CREATE ${tableTriggerTypeClause} TABLE ${persistDestination ? 'IF NOT EXISTS ' : ''}${destination} (
10028
10039
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
10029
10040
  id TEXT,
10030
10041
  operation TEXT,
@@ -10500,11 +10511,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
10500
10511
  this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);
10501
10512
  }
10502
10513
  this._schema = schema;
10503
- // powersync_replace_schema starts a transaction internally, but we can be more efficient by using BEGIN EXCLUSIVE
10504
- // on some DB adapters.
10505
- this.database.writeTransaction((tx) => {
10506
- return tx.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
10507
- });
10514
+ await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
10508
10515
  await this.database.refreshSchema();
10509
10516
  this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
10510
10517
  }
@@ -11609,39 +11616,6 @@ class ConnectionClosedError extends Error {
11609
11616
  }
11610
11617
  }
11611
11618
 
11612
- /**
11613
- * Instructs PowerSync to sync data into a "raw" table.
11614
- *
11615
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
11616
- * using client-side table and column constraints.
11617
- *
11618
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
11619
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
11620
- * using raw tables.
11621
- *
11622
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
11623
- *
11624
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
11625
- * stability guarantees.
11626
- */
11627
- class RawTable {
11628
- /**
11629
- * The name of the table.
11630
- *
11631
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
11632
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
11633
- * appears in the source / backend database) are to be handled specially.
11634
- */
11635
- name;
11636
- put;
11637
- delete;
11638
- constructor(name, type) {
11639
- this.name = name;
11640
- this.put = type.put;
11641
- this.delete = type.delete;
11642
- }
11643
- }
11644
-
11645
11619
  /**
11646
11620
  * A schema is a collection of tables. It is used to define the structure of a database.
11647
11621
  */
@@ -11686,7 +11660,7 @@ class Schema {
11686
11660
  */
11687
11661
  withRawTables(tables) {
11688
11662
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
11689
- this.rawTables.push(new RawTable(name, rawTableDefinition));
11663
+ this.rawTables.push({ name, ...rawTableDefinition });
11690
11664
  }
11691
11665
  }
11692
11666
  validate() {
@@ -11697,8 +11671,30 @@ class Schema {
11697
11671
  toJSON() {
11698
11672
  return {
11699
11673
  tables: this.tables.map((t) => t.toJSON()),
11700
- raw_tables: this.rawTables
11674
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
11675
+ };
11676
+ }
11677
+ /**
11678
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
11679
+ *
11680
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
11681
+ * to define triggers for this table.
11682
+ */
11683
+ static rawTableToJson(table) {
11684
+ const serialized = {
11685
+ name: table.name,
11686
+ put: table.put,
11687
+ delete: table.delete,
11688
+ clear: table.clear
11701
11689
  };
11690
+ if ('schema' in table) {
11691
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
11692
+ const schema = table.schema;
11693
+ serialized.table_name = schema.tableName ?? table.name;
11694
+ serialized.synced_columns = schema.syncedColumns;
11695
+ Object.assign(serialized, encodeTableOptions(table.schema));
11696
+ }
11697
+ return serialized;
11702
11698
  }
11703
11699
  }
11704
11700
 
@@ -11857,5 +11853,5 @@ const parseQuery = (query, parameters) => {
11857
11853
  return { sqlStatement, parameters: parameters };
11858
11854
  };
11859
11855
 
11860
- 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 };
11856
+ 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 };
11861
11857
  //# sourceMappingURL=bundle.node.mjs.map