@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
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, persistDestination = 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);
@@ -12534,11 +12543,13 @@ class TriggerManagerImpl {
12534
12543
  * we need to ensure we can cleanup the created resources.
12535
12544
  * We unfortunately cannot rely on transaction rollback.
12536
12545
  */
12537
- const cleanup = async () => {
12546
+ const cleanup = async (force) => {
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 (!persistDestination || force) {
12551
+ await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
12552
+ }
12542
12553
  await releaseStorageClaim?.();
12543
12554
  });
12544
12555
  };
@@ -12546,7 +12557,7 @@ class TriggerManagerImpl {
12546
12557
  // Allow user code to execute in this lock context before the trigger is created.
12547
12558
  await hooks?.beforeCreate?.(tx);
12548
12559
  await tx.execute(/* sql */ `
12549
- CREATE ${tableTriggerTypeClause} TABLE ${destination} (
12560
+ CREATE ${tableTriggerTypeClause} TABLE ${persistDestination ? 'IF NOT EXISTS ' : ''}${destination} (
12550
12561
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
12551
12562
  id TEXT,
12552
12563
  operation TEXT,
@@ -13022,11 +13033,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13022
13033
  this.logger.warn('Schema validation failed. Unexpected behaviour could occur', ex);
13023
13034
  }
13024
13035
  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
- });
13036
+ await this.database.execute('SELECT powersync_replace_schema(?)', [JSON.stringify(this.schema.toJSON())]);
13030
13037
  await this.database.refreshSchema();
13031
13038
  this.iterateListeners(async (cb) => cb.schemaChanged?.(schema));
13032
13039
  }
@@ -14131,39 +14138,6 @@ class ConnectionClosedError extends Error {
14131
14138
  }
14132
14139
  }
14133
14140
 
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
14141
  /**
14168
14142
  * A schema is a collection of tables. It is used to define the structure of a database.
14169
14143
  */
@@ -14208,7 +14182,7 @@ class Schema {
14208
14182
  */
14209
14183
  withRawTables(tables) {
14210
14184
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
14211
- this.rawTables.push(new RawTable(name, rawTableDefinition));
14185
+ this.rawTables.push({ name, ...rawTableDefinition });
14212
14186
  }
14213
14187
  }
14214
14188
  validate() {
@@ -14219,8 +14193,30 @@ class Schema {
14219
14193
  toJSON() {
14220
14194
  return {
14221
14195
  tables: this.tables.map((t) => t.toJSON()),
14222
- raw_tables: this.rawTables
14196
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
14197
+ };
14198
+ }
14199
+ /**
14200
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
14201
+ *
14202
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
14203
+ * to define triggers for this table.
14204
+ */
14205
+ static rawTableToJson(table) {
14206
+ const serialized = {
14207
+ name: table.name,
14208
+ put: table.put,
14209
+ delete: table.delete,
14210
+ clear: table.clear
14223
14211
  };
14212
+ if ('schema' in table) {
14213
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
14214
+ const schema = table.schema;
14215
+ serialized.table_name = schema.tableName ?? table.name;
14216
+ serialized.synced_columns = schema.syncedColumns;
14217
+ Object.assign(serialized, encodeTableOptions(table.schema));
14218
+ }
14219
+ return serialized;
14224
14220
  }
14225
14221
  }
14226
14222
 
@@ -14379,5 +14375,5 @@ const parseQuery = (query, parameters) => {
14379
14375
  return { sqlStatement, parameters: parameters };
14380
14376
  };
14381
14377
 
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 };
14378
+ 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
14379
  //# sourceMappingURL=bundle.mjs.map