@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
@@ -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, manageDestinationExternally = 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);
@@ -10016,23 +10025,27 @@ class TriggerManagerImpl {
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 (!manageDestinationExternally) {
10029
+ await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10030
+ }
10020
10031
  await releaseStorageClaim?.();
10021
10032
  });
10022
10033
  };
10023
10034
  const setup = async (tx) => {
10024
10035
  // Allow user code to execute in this lock context before the trigger is created.
10025
10036
  await hooks?.beforeCreate?.(tx);
10026
- await tx.execute(/* sql */ `
10027
- CREATE ${tableTriggerTypeClause} TABLE ${destination} (
10028
- operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
10029
- id TEXT,
10030
- operation TEXT,
10031
- timestamp TEXT,
10032
- value TEXT,
10033
- previous_value TEXT
10034
- )
10035
- `);
10037
+ if (!manageDestinationExternally) {
10038
+ await tx.execute(/* sql */ `
10039
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
10040
+ operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
10041
+ id TEXT,
10042
+ operation TEXT,
10043
+ timestamp TEXT,
10044
+ value TEXT,
10045
+ previous_value TEXT
10046
+ )
10047
+ `);
10048
+ }
10036
10049
  if (operations.includes(DiffTriggerOperation.INSERT)) {
10037
10050
  const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
10038
10051
  triggerIds.push(insertTriggerId);
@@ -10500,11 +10513,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
10500
10513
  this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);
10501
10514
  }
10502
10515
  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
- });
10516
+ await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
10508
10517
  await this.database.refreshSchema();
10509
10518
  this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
10510
10519
  }
@@ -11609,39 +11618,6 @@ class ConnectionClosedError extends Error {
11609
11618
  }
11610
11619
  }
11611
11620
 
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
11621
  /**
11646
11622
  * A schema is a collection of tables. It is used to define the structure of a database.
11647
11623
  */
@@ -11686,7 +11662,7 @@ class Schema {
11686
11662
  */
11687
11663
  withRawTables(tables) {
11688
11664
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
11689
- this.rawTables.push(new RawTable(name, rawTableDefinition));
11665
+ this.rawTables.push({ name, ...rawTableDefinition });
11690
11666
  }
11691
11667
  }
11692
11668
  validate() {
@@ -11697,8 +11673,30 @@ class Schema {
11697
11673
  toJSON() {
11698
11674
  return {
11699
11675
  tables: this.tables.map((t) => t.toJSON()),
11700
- raw_tables: this.rawTables
11676
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
11677
+ };
11678
+ }
11679
+ /**
11680
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
11681
+ *
11682
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
11683
+ * to define triggers for this table.
11684
+ */
11685
+ static rawTableToJson(table) {
11686
+ const serialized = {
11687
+ name: table.name,
11688
+ put: table.put,
11689
+ delete: table.delete,
11690
+ clear: table.clear
11701
11691
  };
11692
+ if ('schema' in table) {
11693
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
11694
+ const schema = table.schema;
11695
+ serialized.table_name = schema.tableName ?? table.name;
11696
+ serialized.synced_columns = schema.syncedColumns;
11697
+ Object.assign(serialized, encodeTableOptions(table.schema));
11698
+ }
11699
+ return serialized;
11702
11700
  }
11703
11701
  }
11704
11702
 
@@ -11857,5 +11855,5 @@ const parseQuery = (query, parameters) => {
11857
11855
  return { sqlStatement, parameters: parameters };
11858
11856
  };
11859
11857
 
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 };
11858
+ 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
11859
  //# sourceMappingURL=bundle.node.mjs.map