@powersync/common 1.47.0 → 1.49.0

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 (40) hide show
  1. package/dist/bundle.cjs +189 -52
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +188 -52
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +189 -52
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +188 -52
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +186 -89
  10. package/lib/client/triggers/TriggerManager.d.ts +13 -1
  11. package/lib/client/triggers/TriggerManagerImpl.d.ts +2 -2
  12. package/lib/client/triggers/TriggerManagerImpl.js +19 -7
  13. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  14. package/lib/db/DBAdapter.d.ts +48 -8
  15. package/lib/db/DBAdapter.js +126 -0
  16. package/lib/db/DBAdapter.js.map +1 -1
  17. package/lib/db/schema/RawTable.d.ts +61 -26
  18. package/lib/db/schema/RawTable.js +1 -32
  19. package/lib/db/schema/RawTable.js.map +1 -1
  20. package/lib/db/schema/Schema.d.ts +14 -7
  21. package/lib/db/schema/Schema.js +25 -3
  22. package/lib/db/schema/Schema.js.map +1 -1
  23. package/lib/db/schema/Table.d.ts +13 -8
  24. package/lib/db/schema/Table.js +3 -8
  25. package/lib/db/schema/Table.js.map +1 -1
  26. package/lib/db/schema/internal.d.ts +12 -0
  27. package/lib/db/schema/internal.js +15 -0
  28. package/lib/db/schema/internal.js.map +1 -0
  29. package/lib/index.d.ts +1 -1
  30. package/lib/index.js +0 -1
  31. package/lib/index.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/client/triggers/TriggerManager.ts +15 -2
  34. package/src/client/triggers/TriggerManagerImpl.ts +18 -6
  35. package/src/db/DBAdapter.ts +160 -8
  36. package/src/db/schema/RawTable.ts +66 -31
  37. package/src/db/schema/Schema.ts +27 -2
  38. package/src/db/schema/Table.ts +11 -11
  39. package/src/db/schema/internal.ts +17 -0
  40. 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
  }
@@ -1672,6 +1681,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
1672
1681
  * Set of generic interfaces to allow PowerSync compatibility with
1673
1682
  * different SQLite DB implementations.
1674
1683
  */
1684
+ /**
1685
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
1686
+ */
1687
+ function DBGetUtilsDefaultMixin(Base) {
1688
+ return class extends Base {
1689
+ async getAll(sql, parameters) {
1690
+ const res = await this.execute(sql, parameters);
1691
+ return res.rows?._array ?? [];
1692
+ }
1693
+ async getOptional(sql, parameters) {
1694
+ const res = await this.execute(sql, parameters);
1695
+ return res.rows?.item(0) ?? null;
1696
+ }
1697
+ async get(sql, parameters) {
1698
+ const res = await this.execute(sql, parameters);
1699
+ const first = res.rows?.item(0);
1700
+ if (!first) {
1701
+ throw new Error('Result set is empty');
1702
+ }
1703
+ return first;
1704
+ }
1705
+ async executeBatch(query, params = []) {
1706
+ // If this context can run batch statements natively, use that.
1707
+ // @ts-ignore
1708
+ if (super.executeBatch) {
1709
+ // @ts-ignore
1710
+ return super.executeBatch(query, params);
1711
+ }
1712
+ // Emulate executeBatch by running statements individually.
1713
+ let lastInsertId;
1714
+ let rowsAffected = 0;
1715
+ for (const set of params) {
1716
+ const result = await this.execute(query, set);
1717
+ lastInsertId = result.insertId;
1718
+ rowsAffected += result.rowsAffected;
1719
+ }
1720
+ return {
1721
+ rowsAffected,
1722
+ insertId: lastInsertId
1723
+ };
1724
+ }
1725
+ };
1726
+ }
1675
1727
  /**
1676
1728
  * Update table operation numbers from SQLite
1677
1729
  */
@@ -1681,6 +1733,89 @@ var RowUpdateType;
1681
1733
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
1682
1734
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
1683
1735
  })(RowUpdateType || (RowUpdateType = {}));
1736
+ /**
1737
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
1738
+ * {@link ConnectionPool.writeLock}.
1739
+ */
1740
+ function DBAdapterDefaultMixin(Base) {
1741
+ return class extends Base {
1742
+ readTransaction(fn, options) {
1743
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1744
+ }
1745
+ writeTransaction(fn, options) {
1746
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1747
+ }
1748
+ getAll(sql, parameters) {
1749
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
1750
+ }
1751
+ getOptional(sql, parameters) {
1752
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
1753
+ }
1754
+ get(sql, parameters) {
1755
+ return this.readLock((ctx) => ctx.get(sql, parameters));
1756
+ }
1757
+ execute(query, params) {
1758
+ return this.writeLock((ctx) => ctx.execute(query, params));
1759
+ }
1760
+ executeRaw(query, params) {
1761
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
1762
+ }
1763
+ executeBatch(query, params) {
1764
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
1765
+ }
1766
+ };
1767
+ }
1768
+ class BaseTransaction {
1769
+ inner;
1770
+ finalized = false;
1771
+ constructor(inner) {
1772
+ this.inner = inner;
1773
+ }
1774
+ async commit() {
1775
+ if (this.finalized) {
1776
+ return { rowsAffected: 0 };
1777
+ }
1778
+ this.finalized = true;
1779
+ return this.inner.execute('COMMIT');
1780
+ }
1781
+ async rollback() {
1782
+ if (this.finalized) {
1783
+ return { rowsAffected: 0 };
1784
+ }
1785
+ this.finalized = true;
1786
+ return this.inner.execute('ROLLBACK');
1787
+ }
1788
+ execute(query, params) {
1789
+ return this.inner.execute(query, params);
1790
+ }
1791
+ executeRaw(query, params) {
1792
+ return this.inner.executeRaw(query, params);
1793
+ }
1794
+ executeBatch(query, params) {
1795
+ return this.inner.executeBatch(query, params);
1796
+ }
1797
+ }
1798
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
1799
+ static async runWith(ctx, fn) {
1800
+ let tx = new TransactionImplementation(ctx);
1801
+ try {
1802
+ await ctx.execute('BEGIN IMMEDIATE');
1803
+ const result = await fn(tx);
1804
+ await tx.commit();
1805
+ return result;
1806
+ }
1807
+ catch (ex) {
1808
+ try {
1809
+ await tx.rollback();
1810
+ }
1811
+ catch (ex2) {
1812
+ // In rare cases, a rollback may fail.
1813
+ // Safe to ignore.
1814
+ }
1815
+ throw ex;
1816
+ }
1817
+ }
1818
+ }
1684
1819
  function isBatchedUpdateNotification(update) {
1685
1820
  return 'tables' in update;
1686
1821
  }
@@ -10446,7 +10581,7 @@ function requireDist () {
10446
10581
 
10447
10582
  var distExports = requireDist();
10448
10583
 
10449
- var version = "1.47.0";
10584
+ var version = "1.49.0";
10450
10585
  var PACKAGE = {
10451
10586
  version: version};
10452
10587
 
@@ -12479,7 +12614,7 @@ class TriggerManagerImpl {
12479
12614
  }
12480
12615
  async createDiffTrigger(options) {
12481
12616
  await this.db.waitForReady();
12482
- const { source, destination, columns, when, hooks,
12617
+ const { source, destination, columns, when, hooks, setupContext,
12483
12618
  // Fall back to the provided default if not given on this level
12484
12619
  useStorage = this.defaultConfig.useStorageByDefault } = options;
12485
12620
  const operations = Object.keys(when);
@@ -12534,13 +12669,20 @@ class TriggerManagerImpl {
12534
12669
  * we need to ensure we can cleanup the created resources.
12535
12670
  * We unfortunately cannot rely on transaction rollback.
12536
12671
  */
12537
- const cleanup = async () => {
12672
+ const cleanup = async (options) => {
12673
+ const { context } = options ?? {};
12538
12674
  disposeWarningListener();
12539
- return this.db.writeLock(async (tx) => {
12675
+ const doCleanup = async (tx) => {
12540
12676
  await this.removeTriggers(tx, triggerIds);
12541
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
12677
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
12542
12678
  await releaseStorageClaim?.();
12543
- });
12679
+ };
12680
+ if (context) {
12681
+ await doCleanup(context);
12682
+ }
12683
+ else {
12684
+ await this.db.writeLock(doCleanup);
12685
+ }
12544
12686
  };
12545
12687
  const setup = async (tx) => {
12546
12688
  // Allow user code to execute in this lock context before the trigger is created.
@@ -12614,12 +12756,17 @@ class TriggerManagerImpl {
12614
12756
  }
12615
12757
  };
12616
12758
  try {
12617
- await this.db.writeLock(setup);
12759
+ if (setupContext) {
12760
+ await setup(setupContext);
12761
+ }
12762
+ else {
12763
+ await this.db.writeLock(setup);
12764
+ }
12618
12765
  return cleanup;
12619
12766
  }
12620
12767
  catch (error) {
12621
12768
  try {
12622
- await cleanup();
12769
+ await cleanup(setupContext ? { context: setupContext } : undefined);
12623
12770
  }
12624
12771
  catch (cleanupError) {
12625
12772
  throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
@@ -14127,39 +14274,6 @@ class ConnectionClosedError extends Error {
14127
14274
  }
14128
14275
  }
14129
14276
 
14130
- /**
14131
- * Instructs PowerSync to sync data into a "raw" table.
14132
- *
14133
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
14134
- * using client-side table and column constraints.
14135
- *
14136
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
14137
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
14138
- * using raw tables.
14139
- *
14140
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
14141
- *
14142
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
14143
- * stability guarantees.
14144
- */
14145
- class RawTable {
14146
- /**
14147
- * The name of the table.
14148
- *
14149
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
14150
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
14151
- * appears in the source / backend database) are to be handled specially.
14152
- */
14153
- name;
14154
- put;
14155
- delete;
14156
- constructor(name, type) {
14157
- this.name = name;
14158
- this.put = type.put;
14159
- this.delete = type.delete;
14160
- }
14161
- }
14162
-
14163
14277
  /**
14164
14278
  * A schema is a collection of tables. It is used to define the structure of a database.
14165
14279
  */
@@ -14204,7 +14318,7 @@ class Schema {
14204
14318
  */
14205
14319
  withRawTables(tables) {
14206
14320
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
14207
- this.rawTables.push(new RawTable(name, rawTableDefinition));
14321
+ this.rawTables.push({ name, ...rawTableDefinition });
14208
14322
  }
14209
14323
  }
14210
14324
  validate() {
@@ -14215,9 +14329,31 @@ class Schema {
14215
14329
  toJSON() {
14216
14330
  return {
14217
14331
  tables: this.tables.map((t) => t.toJSON()),
14218
- raw_tables: this.rawTables
14332
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
14219
14333
  };
14220
14334
  }
14335
+ /**
14336
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
14337
+ *
14338
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
14339
+ * to define triggers for this table.
14340
+ */
14341
+ static rawTableToJson(table) {
14342
+ const serialized = {
14343
+ name: table.name,
14344
+ put: table.put,
14345
+ delete: table.delete,
14346
+ clear: table.clear
14347
+ };
14348
+ if ('schema' in table) {
14349
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
14350
+ const schema = table.schema;
14351
+ serialized.table_name = schema.tableName ?? table.name;
14352
+ serialized.synced_columns = schema.syncedColumns;
14353
+ Object.assign(serialized, encodeTableOptions(table.schema));
14354
+ }
14355
+ return serialized;
14356
+ }
14221
14357
  }
14222
14358
 
14223
14359
  /**
@@ -14375,5 +14511,5 @@ const parseQuery = (query, parameters) => {
14375
14511
  return { sqlStatement, parameters: parameters };
14376
14512
  };
14377
14513
 
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, 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 };
14514
+ export { ATTACHMENT_TABLE, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, 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 };
14379
14515
  //# sourceMappingURL=bundle.mjs.map