@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
@@ -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
  }
@@ -1521,6 +1530,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
1521
1530
  * Set of generic interfaces to allow PowerSync compatibility with
1522
1531
  * different SQLite DB implementations.
1523
1532
  */
1533
+ /**
1534
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
1535
+ */
1536
+ function DBGetUtilsDefaultMixin(Base) {
1537
+ return class extends Base {
1538
+ async getAll(sql, parameters) {
1539
+ const res = await this.execute(sql, parameters);
1540
+ return res.rows?._array ?? [];
1541
+ }
1542
+ async getOptional(sql, parameters) {
1543
+ const res = await this.execute(sql, parameters);
1544
+ return res.rows?.item(0) ?? null;
1545
+ }
1546
+ async get(sql, parameters) {
1547
+ const res = await this.execute(sql, parameters);
1548
+ const first = res.rows?.item(0);
1549
+ if (!first) {
1550
+ throw new Error('Result set is empty');
1551
+ }
1552
+ return first;
1553
+ }
1554
+ async executeBatch(query, params = []) {
1555
+ // If this context can run batch statements natively, use that.
1556
+ // @ts-ignore
1557
+ if (super.executeBatch) {
1558
+ // @ts-ignore
1559
+ return super.executeBatch(query, params);
1560
+ }
1561
+ // Emulate executeBatch by running statements individually.
1562
+ let lastInsertId;
1563
+ let rowsAffected = 0;
1564
+ for (const set of params) {
1565
+ const result = await this.execute(query, set);
1566
+ lastInsertId = result.insertId;
1567
+ rowsAffected += result.rowsAffected;
1568
+ }
1569
+ return {
1570
+ rowsAffected,
1571
+ insertId: lastInsertId
1572
+ };
1573
+ }
1574
+ };
1575
+ }
1524
1576
  /**
1525
1577
  * Update table operation numbers from SQLite
1526
1578
  */
@@ -1530,6 +1582,89 @@ var RowUpdateType;
1530
1582
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
1531
1583
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
1532
1584
  })(RowUpdateType || (RowUpdateType = {}));
1585
+ /**
1586
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
1587
+ * {@link ConnectionPool.writeLock}.
1588
+ */
1589
+ function DBAdapterDefaultMixin(Base) {
1590
+ return class extends Base {
1591
+ readTransaction(fn, options) {
1592
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1593
+ }
1594
+ writeTransaction(fn, options) {
1595
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1596
+ }
1597
+ getAll(sql, parameters) {
1598
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
1599
+ }
1600
+ getOptional(sql, parameters) {
1601
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
1602
+ }
1603
+ get(sql, parameters) {
1604
+ return this.readLock((ctx) => ctx.get(sql, parameters));
1605
+ }
1606
+ execute(query, params) {
1607
+ return this.writeLock((ctx) => ctx.execute(query, params));
1608
+ }
1609
+ executeRaw(query, params) {
1610
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
1611
+ }
1612
+ executeBatch(query, params) {
1613
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
1614
+ }
1615
+ };
1616
+ }
1617
+ class BaseTransaction {
1618
+ inner;
1619
+ finalized = false;
1620
+ constructor(inner) {
1621
+ this.inner = inner;
1622
+ }
1623
+ async commit() {
1624
+ if (this.finalized) {
1625
+ return { rowsAffected: 0 };
1626
+ }
1627
+ this.finalized = true;
1628
+ return this.inner.execute('COMMIT');
1629
+ }
1630
+ async rollback() {
1631
+ if (this.finalized) {
1632
+ return { rowsAffected: 0 };
1633
+ }
1634
+ this.finalized = true;
1635
+ return this.inner.execute('ROLLBACK');
1636
+ }
1637
+ execute(query, params) {
1638
+ return this.inner.execute(query, params);
1639
+ }
1640
+ executeRaw(query, params) {
1641
+ return this.inner.executeRaw(query, params);
1642
+ }
1643
+ executeBatch(query, params) {
1644
+ return this.inner.executeBatch(query, params);
1645
+ }
1646
+ }
1647
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
1648
+ static async runWith(ctx, fn) {
1649
+ let tx = new TransactionImplementation(ctx);
1650
+ try {
1651
+ await ctx.execute('BEGIN IMMEDIATE');
1652
+ const result = await fn(tx);
1653
+ await tx.commit();
1654
+ return result;
1655
+ }
1656
+ catch (ex) {
1657
+ try {
1658
+ await tx.rollback();
1659
+ }
1660
+ catch (ex2) {
1661
+ // In rare cases, a rollback may fail.
1662
+ // Safe to ignore.
1663
+ }
1664
+ throw ex;
1665
+ }
1666
+ }
1667
+ }
1533
1668
  function isBatchedUpdateNotification(update) {
1534
1669
  return 'tables' in update;
1535
1670
  }
@@ -7924,7 +8059,7 @@ function requireDist () {
7924
8059
 
7925
8060
  var distExports = requireDist();
7926
8061
 
7927
- var version = "1.47.0";
8062
+ var version = "1.49.0";
7928
8063
  var PACKAGE = {
7929
8064
  version: version};
7930
8065
 
@@ -9957,7 +10092,7 @@ class TriggerManagerImpl {
9957
10092
  }
9958
10093
  async createDiffTrigger(options) {
9959
10094
  await this.db.waitForReady();
9960
- const { source, destination, columns, when, hooks,
10095
+ const { source, destination, columns, when, hooks, setupContext,
9961
10096
  // Fall back to the provided default if not given on this level
9962
10097
  useStorage = this.defaultConfig.useStorageByDefault } = options;
9963
10098
  const operations = Object.keys(when);
@@ -10012,13 +10147,20 @@ class TriggerManagerImpl {
10012
10147
  * we need to ensure we can cleanup the created resources.
10013
10148
  * We unfortunately cannot rely on transaction rollback.
10014
10149
  */
10015
- const cleanup = async () => {
10150
+ const cleanup = async (options) => {
10151
+ const { context } = options ?? {};
10016
10152
  disposeWarningListener();
10017
- return this.db.writeLock(async (tx) => {
10153
+ const doCleanup = async (tx) => {
10018
10154
  await this.removeTriggers(tx, triggerIds);
10019
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10155
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
10020
10156
  await releaseStorageClaim?.();
10021
- });
10157
+ };
10158
+ if (context) {
10159
+ await doCleanup(context);
10160
+ }
10161
+ else {
10162
+ await this.db.writeLock(doCleanup);
10163
+ }
10022
10164
  };
10023
10165
  const setup = async (tx) => {
10024
10166
  // Allow user code to execute in this lock context before the trigger is created.
@@ -10092,12 +10234,17 @@ class TriggerManagerImpl {
10092
10234
  }
10093
10235
  };
10094
10236
  try {
10095
- await this.db.writeLock(setup);
10237
+ if (setupContext) {
10238
+ await setup(setupContext);
10239
+ }
10240
+ else {
10241
+ await this.db.writeLock(setup);
10242
+ }
10096
10243
  return cleanup;
10097
10244
  }
10098
10245
  catch (error) {
10099
10246
  try {
10100
- await cleanup();
10247
+ await cleanup(setupContext ? { context: setupContext } : undefined);
10101
10248
  }
10102
10249
  catch (cleanupError) {
10103
10250
  throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
@@ -11605,39 +11752,6 @@ class ConnectionClosedError extends Error {
11605
11752
  }
11606
11753
  }
11607
11754
 
11608
- /**
11609
- * Instructs PowerSync to sync data into a "raw" table.
11610
- *
11611
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
11612
- * using client-side table and column constraints.
11613
- *
11614
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
11615
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
11616
- * using raw tables.
11617
- *
11618
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
11619
- *
11620
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
11621
- * stability guarantees.
11622
- */
11623
- class RawTable {
11624
- /**
11625
- * The name of the table.
11626
- *
11627
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
11628
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
11629
- * appears in the source / backend database) are to be handled specially.
11630
- */
11631
- name;
11632
- put;
11633
- delete;
11634
- constructor(name, type) {
11635
- this.name = name;
11636
- this.put = type.put;
11637
- this.delete = type.delete;
11638
- }
11639
- }
11640
-
11641
11755
  /**
11642
11756
  * A schema is a collection of tables. It is used to define the structure of a database.
11643
11757
  */
@@ -11682,7 +11796,7 @@ class Schema {
11682
11796
  */
11683
11797
  withRawTables(tables) {
11684
11798
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
11685
- this.rawTables.push(new RawTable(name, rawTableDefinition));
11799
+ this.rawTables.push({ name, ...rawTableDefinition });
11686
11800
  }
11687
11801
  }
11688
11802
  validate() {
@@ -11693,9 +11807,31 @@ class Schema {
11693
11807
  toJSON() {
11694
11808
  return {
11695
11809
  tables: this.tables.map((t) => t.toJSON()),
11696
- raw_tables: this.rawTables
11810
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
11697
11811
  };
11698
11812
  }
11813
+ /**
11814
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
11815
+ *
11816
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
11817
+ * to define triggers for this table.
11818
+ */
11819
+ static rawTableToJson(table) {
11820
+ const serialized = {
11821
+ name: table.name,
11822
+ put: table.put,
11823
+ delete: table.delete,
11824
+ clear: table.clear
11825
+ };
11826
+ if ('schema' in table) {
11827
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
11828
+ const schema = table.schema;
11829
+ serialized.table_name = schema.tableName ?? table.name;
11830
+ serialized.synced_columns = schema.syncedColumns;
11831
+ Object.assign(serialized, encodeTableOptions(table.schema));
11832
+ }
11833
+ return serialized;
11834
+ }
11699
11835
  }
11700
11836
 
11701
11837
  /**
@@ -11853,5 +11989,5 @@ const parseQuery = (query, parameters) => {
11853
11989
  return { sqlStatement, parameters: parameters };
11854
11990
  };
11855
11991
 
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, 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 };
11992
+ 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 };
11857
11993
  //# sourceMappingURL=bundle.node.mjs.map