@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
@@ -105,6 +105,21 @@ class Index {
105
105
  }
106
106
  }
107
107
 
108
+ /**
109
+ * @internal Not exported from `index.ts`.
110
+ */
111
+ function encodeTableOptions(options) {
112
+ const trackPrevious = options.trackPrevious;
113
+ return {
114
+ local_only: options.localOnly,
115
+ insert_only: options.insertOnly,
116
+ include_old: trackPrevious && (trackPrevious.columns ?? true),
117
+ include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
118
+ include_metadata: options.trackMetadata,
119
+ ignore_empty_update: options.ignoreEmptyUpdates
120
+ };
121
+ }
122
+
108
123
  const DEFAULT_TABLE_OPTIONS = {
109
124
  indexes: [],
110
125
  insertOnly: false,
@@ -294,18 +309,12 @@ class Table {
294
309
  }
295
310
  }
296
311
  toJSON() {
297
- const trackPrevious = this.trackPrevious;
298
312
  return {
299
313
  name: this.name,
300
314
  view_name: this.viewName,
301
- local_only: this.localOnly,
302
- insert_only: this.insertOnly,
303
- include_old: trackPrevious && (trackPrevious.columns ?? true),
304
- include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
305
- include_metadata: this.trackMetadata,
306
- ignore_empty_update: this.ignoreEmptyUpdates,
307
315
  columns: this.columns.map((c) => c.toJSON()),
308
- indexes: this.indexes.map((e) => e.toJSON(this))
316
+ indexes: this.indexes.map((e) => e.toJSON(this)),
317
+ ...encodeTableOptions(this)
309
318
  };
310
319
  }
311
320
  }
@@ -1523,6 +1532,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
1523
1532
  * Set of generic interfaces to allow PowerSync compatibility with
1524
1533
  * different SQLite DB implementations.
1525
1534
  */
1535
+ /**
1536
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
1537
+ */
1538
+ function DBGetUtilsDefaultMixin(Base) {
1539
+ return class extends Base {
1540
+ async getAll(sql, parameters) {
1541
+ const res = await this.execute(sql, parameters);
1542
+ return res.rows?._array ?? [];
1543
+ }
1544
+ async getOptional(sql, parameters) {
1545
+ const res = await this.execute(sql, parameters);
1546
+ return res.rows?.item(0) ?? null;
1547
+ }
1548
+ async get(sql, parameters) {
1549
+ const res = await this.execute(sql, parameters);
1550
+ const first = res.rows?.item(0);
1551
+ if (!first) {
1552
+ throw new Error('Result set is empty');
1553
+ }
1554
+ return first;
1555
+ }
1556
+ async executeBatch(query, params = []) {
1557
+ // If this context can run batch statements natively, use that.
1558
+ // @ts-ignore
1559
+ if (super.executeBatch) {
1560
+ // @ts-ignore
1561
+ return super.executeBatch(query, params);
1562
+ }
1563
+ // Emulate executeBatch by running statements individually.
1564
+ let lastInsertId;
1565
+ let rowsAffected = 0;
1566
+ for (const set of params) {
1567
+ const result = await this.execute(query, set);
1568
+ lastInsertId = result.insertId;
1569
+ rowsAffected += result.rowsAffected;
1570
+ }
1571
+ return {
1572
+ rowsAffected,
1573
+ insertId: lastInsertId
1574
+ };
1575
+ }
1576
+ };
1577
+ }
1526
1578
  /**
1527
1579
  * Update table operation numbers from SQLite
1528
1580
  */
@@ -1532,6 +1584,89 @@ exports.RowUpdateType = void 0;
1532
1584
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
1533
1585
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
1534
1586
  })(exports.RowUpdateType || (exports.RowUpdateType = {}));
1587
+ /**
1588
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
1589
+ * {@link ConnectionPool.writeLock}.
1590
+ */
1591
+ function DBAdapterDefaultMixin(Base) {
1592
+ return class extends Base {
1593
+ readTransaction(fn, options) {
1594
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1595
+ }
1596
+ writeTransaction(fn, options) {
1597
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
1598
+ }
1599
+ getAll(sql, parameters) {
1600
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
1601
+ }
1602
+ getOptional(sql, parameters) {
1603
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
1604
+ }
1605
+ get(sql, parameters) {
1606
+ return this.readLock((ctx) => ctx.get(sql, parameters));
1607
+ }
1608
+ execute(query, params) {
1609
+ return this.writeLock((ctx) => ctx.execute(query, params));
1610
+ }
1611
+ executeRaw(query, params) {
1612
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
1613
+ }
1614
+ executeBatch(query, params) {
1615
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
1616
+ }
1617
+ };
1618
+ }
1619
+ class BaseTransaction {
1620
+ inner;
1621
+ finalized = false;
1622
+ constructor(inner) {
1623
+ this.inner = inner;
1624
+ }
1625
+ async commit() {
1626
+ if (this.finalized) {
1627
+ return { rowsAffected: 0 };
1628
+ }
1629
+ this.finalized = true;
1630
+ return this.inner.execute('COMMIT');
1631
+ }
1632
+ async rollback() {
1633
+ if (this.finalized) {
1634
+ return { rowsAffected: 0 };
1635
+ }
1636
+ this.finalized = true;
1637
+ return this.inner.execute('ROLLBACK');
1638
+ }
1639
+ execute(query, params) {
1640
+ return this.inner.execute(query, params);
1641
+ }
1642
+ executeRaw(query, params) {
1643
+ return this.inner.executeRaw(query, params);
1644
+ }
1645
+ executeBatch(query, params) {
1646
+ return this.inner.executeBatch(query, params);
1647
+ }
1648
+ }
1649
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
1650
+ static async runWith(ctx, fn) {
1651
+ let tx = new TransactionImplementation(ctx);
1652
+ try {
1653
+ await ctx.execute('BEGIN IMMEDIATE');
1654
+ const result = await fn(tx);
1655
+ await tx.commit();
1656
+ return result;
1657
+ }
1658
+ catch (ex) {
1659
+ try {
1660
+ await tx.rollback();
1661
+ }
1662
+ catch (ex2) {
1663
+ // In rare cases, a rollback may fail.
1664
+ // Safe to ignore.
1665
+ }
1666
+ throw ex;
1667
+ }
1668
+ }
1669
+ }
1535
1670
  function isBatchedUpdateNotification(update) {
1536
1671
  return 'tables' in update;
1537
1672
  }
@@ -7926,7 +8061,7 @@ function requireDist () {
7926
8061
 
7927
8062
  var distExports = requireDist();
7928
8063
 
7929
- var version = "1.47.0";
8064
+ var version = "1.49.0";
7930
8065
  var PACKAGE = {
7931
8066
  version: version};
7932
8067
 
@@ -9959,7 +10094,7 @@ class TriggerManagerImpl {
9959
10094
  }
9960
10095
  async createDiffTrigger(options) {
9961
10096
  await this.db.waitForReady();
9962
- const { source, destination, columns, when, hooks,
10097
+ const { source, destination, columns, when, hooks, setupContext,
9963
10098
  // Fall back to the provided default if not given on this level
9964
10099
  useStorage = this.defaultConfig.useStorageByDefault } = options;
9965
10100
  const operations = Object.keys(when);
@@ -10014,13 +10149,20 @@ class TriggerManagerImpl {
10014
10149
  * we need to ensure we can cleanup the created resources.
10015
10150
  * We unfortunately cannot rely on transaction rollback.
10016
10151
  */
10017
- const cleanup = async () => {
10152
+ const cleanup = async (options) => {
10153
+ const { context } = options ?? {};
10018
10154
  disposeWarningListener();
10019
- return this.db.writeLock(async (tx) => {
10155
+ const doCleanup = async (tx) => {
10020
10156
  await this.removeTriggers(tx, triggerIds);
10021
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10157
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
10022
10158
  await releaseStorageClaim?.();
10023
- });
10159
+ };
10160
+ if (context) {
10161
+ await doCleanup(context);
10162
+ }
10163
+ else {
10164
+ await this.db.writeLock(doCleanup);
10165
+ }
10024
10166
  };
10025
10167
  const setup = async (tx) => {
10026
10168
  // Allow user code to execute in this lock context before the trigger is created.
@@ -10094,12 +10236,17 @@ class TriggerManagerImpl {
10094
10236
  }
10095
10237
  };
10096
10238
  try {
10097
- await this.db.writeLock(setup);
10239
+ if (setupContext) {
10240
+ await setup(setupContext);
10241
+ }
10242
+ else {
10243
+ await this.db.writeLock(setup);
10244
+ }
10098
10245
  return cleanup;
10099
10246
  }
10100
10247
  catch (error) {
10101
10248
  try {
10102
- await cleanup();
10249
+ await cleanup(setupContext ? { context: setupContext } : undefined);
10103
10250
  }
10104
10251
  catch (cleanupError) {
10105
10252
  throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
@@ -11607,39 +11754,6 @@ class ConnectionClosedError extends Error {
11607
11754
  }
11608
11755
  }
11609
11756
 
11610
- /**
11611
- * Instructs PowerSync to sync data into a "raw" table.
11612
- *
11613
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
11614
- * using client-side table and column constraints.
11615
- *
11616
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
11617
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
11618
- * using raw tables.
11619
- *
11620
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
11621
- *
11622
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
11623
- * stability guarantees.
11624
- */
11625
- class RawTable {
11626
- /**
11627
- * The name of the table.
11628
- *
11629
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
11630
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
11631
- * appears in the source / backend database) are to be handled specially.
11632
- */
11633
- name;
11634
- put;
11635
- delete;
11636
- constructor(name, type) {
11637
- this.name = name;
11638
- this.put = type.put;
11639
- this.delete = type.delete;
11640
- }
11641
- }
11642
-
11643
11757
  /**
11644
11758
  * A schema is a collection of tables. It is used to define the structure of a database.
11645
11759
  */
@@ -11684,7 +11798,7 @@ class Schema {
11684
11798
  */
11685
11799
  withRawTables(tables) {
11686
11800
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
11687
- this.rawTables.push(new RawTable(name, rawTableDefinition));
11801
+ this.rawTables.push({ name, ...rawTableDefinition });
11688
11802
  }
11689
11803
  }
11690
11804
  validate() {
@@ -11695,9 +11809,31 @@ class Schema {
11695
11809
  toJSON() {
11696
11810
  return {
11697
11811
  tables: this.tables.map((t) => t.toJSON()),
11698
- raw_tables: this.rawTables
11812
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
11699
11813
  };
11700
11814
  }
11815
+ /**
11816
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
11817
+ *
11818
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
11819
+ * to define triggers for this table.
11820
+ */
11821
+ static rawTableToJson(table) {
11822
+ const serialized = {
11823
+ name: table.name,
11824
+ put: table.put,
11825
+ delete: table.delete,
11826
+ clear: table.clear
11827
+ };
11828
+ if ('schema' in table) {
11829
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
11830
+ const schema = table.schema;
11831
+ serialized.table_name = schema.tableName ?? table.name;
11832
+ serialized.synced_columns = schema.syncedColumns;
11833
+ Object.assign(serialized, encodeTableOptions(table.schema));
11834
+ }
11835
+ return serialized;
11836
+ }
11701
11837
  }
11702
11838
 
11703
11839
  /**
@@ -11875,6 +12011,8 @@ exports.ControlledExecutor = ControlledExecutor;
11875
12011
  exports.CrudBatch = CrudBatch;
11876
12012
  exports.CrudEntry = CrudEntry;
11877
12013
  exports.CrudTransaction = CrudTransaction;
12014
+ exports.DBAdapterDefaultMixin = DBAdapterDefaultMixin;
12015
+ exports.DBGetUtilsDefaultMixin = DBGetUtilsDefaultMixin;
11878
12016
  exports.DEFAULT_CRUD_BATCH_LIMIT = DEFAULT_CRUD_BATCH_LIMIT;
11879
12017
  exports.DEFAULT_CRUD_UPLOAD_THROTTLE_MS = DEFAULT_CRUD_UPLOAD_THROTTLE_MS;
11880
12018
  exports.DEFAULT_INDEX_COLUMN_OPTIONS = DEFAULT_INDEX_COLUMN_OPTIONS;
@@ -11909,7 +12047,6 @@ exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
11909
12047
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
11910
12048
  exports.OpType = OpType;
11911
12049
  exports.OplogEntry = OplogEntry;
11912
- exports.RawTable = RawTable;
11913
12050
  exports.Schema = Schema;
11914
12051
  exports.SqliteBucketStorage = SqliteBucketStorage;
11915
12052
  exports.SyncDataBatch = SyncDataBatch;