@powersync/common 1.48.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.
@@ -1530,6 +1530,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
1530
1530
  * Set of generic interfaces to allow PowerSync compatibility with
1531
1531
  * different SQLite DB implementations.
1532
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
+ }
1533
1576
  /**
1534
1577
  * Update table operation numbers from SQLite
1535
1578
  */
@@ -1539,6 +1582,89 @@ var RowUpdateType;
1539
1582
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
1540
1583
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
1541
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
+ }
1542
1668
  function isBatchedUpdateNotification(update) {
1543
1669
  return 'tables' in update;
1544
1670
  }
@@ -7933,7 +8059,7 @@ function requireDist () {
7933
8059
 
7934
8060
  var distExports = requireDist();
7935
8061
 
7936
- var version = "1.48.0";
8062
+ var version = "1.49.0";
7937
8063
  var PACKAGE = {
7938
8064
  version: version};
7939
8065
 
@@ -9966,7 +10092,7 @@ class TriggerManagerImpl {
9966
10092
  }
9967
10093
  async createDiffTrigger(options) {
9968
10094
  await this.db.waitForReady();
9969
- const { source, destination, columns, when, hooks,
10095
+ const { source, destination, columns, when, hooks, setupContext,
9970
10096
  // Fall back to the provided default if not given on this level
9971
10097
  useStorage = this.defaultConfig.useStorageByDefault } = options;
9972
10098
  const operations = Object.keys(when);
@@ -10021,13 +10147,20 @@ class TriggerManagerImpl {
10021
10147
  * we need to ensure we can cleanup the created resources.
10022
10148
  * We unfortunately cannot rely on transaction rollback.
10023
10149
  */
10024
- const cleanup = async () => {
10150
+ const cleanup = async (options) => {
10151
+ const { context } = options ?? {};
10025
10152
  disposeWarningListener();
10026
- return this.db.writeLock(async (tx) => {
10153
+ const doCleanup = async (tx) => {
10027
10154
  await this.removeTriggers(tx, triggerIds);
10028
- await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
10155
+ await tx.execute(`DROP TABLE IF EXISTS ${destination};`);
10029
10156
  await releaseStorageClaim?.();
10030
- });
10157
+ };
10158
+ if (context) {
10159
+ await doCleanup(context);
10160
+ }
10161
+ else {
10162
+ await this.db.writeLock(doCleanup);
10163
+ }
10031
10164
  };
10032
10165
  const setup = async (tx) => {
10033
10166
  // Allow user code to execute in this lock context before the trigger is created.
@@ -10101,12 +10234,17 @@ class TriggerManagerImpl {
10101
10234
  }
10102
10235
  };
10103
10236
  try {
10104
- await this.db.writeLock(setup);
10237
+ if (setupContext) {
10238
+ await setup(setupContext);
10239
+ }
10240
+ else {
10241
+ await this.db.writeLock(setup);
10242
+ }
10105
10243
  return cleanup;
10106
10244
  }
10107
10245
  catch (error) {
10108
10246
  try {
10109
- await cleanup();
10247
+ await cleanup(setupContext ? { context: setupContext } : undefined);
10110
10248
  }
10111
10249
  catch (cleanupError) {
10112
10250
  throw new AggregateError([error, cleanupError], 'Error during operation and cleanup');
@@ -11851,5 +11989,5 @@ const parseQuery = (query, parameters) => {
11851
11989
  return { sqlStatement, parameters: parameters };
11852
11990
  };
11853
11991
 
11854
- 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 };
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 };
11855
11993
  //# sourceMappingURL=bundle.node.mjs.map