@saltcorn/postgres 1.5.0-beta.1 → 1.5.0-beta.2

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 (2) hide show
  1. package/package.json +2 -2
  2. package/postgres.js +44 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saltcorn/postgres",
3
- "version": "1.5.0-beta.1",
3
+ "version": "1.5.0-beta.2",
4
4
  "description": "Postgres structures for Saltcorn, open-source no-code platform",
5
5
  "homepage": "https://saltcorn.com",
6
6
  "scripts": {
@@ -12,7 +12,7 @@
12
12
  "license": "MIT",
13
13
  "main": "index.js",
14
14
  "dependencies": {
15
- "@saltcorn/db-common": "1.5.0-beta.1",
15
+ "@saltcorn/db-common": "1.5.0-beta.2",
16
16
  "@saltcorn/plain-date": "0.2.5",
17
17
  "pg": "^8.13.1",
18
18
  "pg-copy-streams": "^6.0.6",
package/postgres.js CHANGED
@@ -632,6 +632,48 @@ const tryCatchInTransaction = async (f, onError) => {
632
632
  }
633
633
  };
634
634
 
635
+ /**
636
+ * Should be used for code that is sometimes called from within a withTransaction block
637
+ * and sometimes not.
638
+ * @param {Function} f logic to execute
639
+ * @param {Function} onError error handler
640
+ * @returns
641
+ */
642
+ const openOrUseTransaction = async (f, onError) => {
643
+ const reqCon = getRequestContext();
644
+ if (reqCon?.client) return await f();
645
+ else return await withTransaction(f, onError);
646
+ };
647
+
648
+ /**
649
+ * Wait some time until current transaction COMMITs,
650
+ * then open another transaction.
651
+ * @param {Function} f logic to execute
652
+ * @param {Function} onError error handler
653
+ * @returns
654
+ */
655
+ const whenTransactionisFree = (f, onError) => {
656
+ return new Promise((resolve, reject) => {
657
+ // wait until transaction is free
658
+ let counter = 0;
659
+ const interval = setInterval(async () => {
660
+ const reqCon = getRequestContext();
661
+ if (!reqCon?.client) {
662
+ clearInterval(interval);
663
+ try {
664
+ resolve(await withTransaction(f, onError));
665
+ } catch (e) {
666
+ reject(e);
667
+ }
668
+ }
669
+ if (++counter > 100) {
670
+ clearInterval(interval);
671
+ reject(new Error("Timeout waiting for transaction to be free"));
672
+ }
673
+ }, 200);
674
+ });
675
+ };
676
+
635
677
  const query = (text, params) => {
636
678
  sql_log(text, params);
637
679
  return getMyClient().query(text, params);
@@ -682,6 +724,8 @@ const postgresExports = {
682
724
  truncate,
683
725
  withTransaction,
684
726
  tryCatchInTransaction,
727
+ openOrUseTransaction,
728
+ whenTransactionisFree,
685
729
  commitAndBeginNewTransaction,
686
730
  };
687
731