@naturalcycles/db-lib 10.0.2 → 10.1.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 (110) hide show
  1. package/dist/adapter/cachedb/cache.db.d.ts +5 -5
  2. package/dist/adapter/cachedb/cache.db.js +8 -12
  3. package/dist/adapter/cachedb/cache.db.model.d.ts +2 -2
  4. package/dist/adapter/cachedb/cache.db.model.js +1 -2
  5. package/dist/adapter/cachedb/index.d.ts +2 -2
  6. package/dist/adapter/cachedb/index.js +2 -5
  7. package/dist/adapter/file/file.db.d.ts +5 -6
  8. package/dist/adapter/file/file.db.js +25 -27
  9. package/dist/adapter/file/file.db.model.d.ts +2 -2
  10. package/dist/adapter/file/file.db.model.js +1 -2
  11. package/dist/adapter/file/inMemory.persistence.plugin.d.ts +2 -2
  12. package/dist/adapter/file/inMemory.persistence.plugin.js +3 -7
  13. package/dist/adapter/file/index.d.ts +3 -3
  14. package/dist/adapter/file/index.js +3 -7
  15. package/dist/adapter/file/localFile.persistence.plugin.d.ts +2 -2
  16. package/dist/adapter/file/localFile.persistence.plugin.js +11 -15
  17. package/dist/adapter/file/noop.persistence.plugin.d.ts +2 -2
  18. package/dist/adapter/file/noop.persistence.plugin.js +1 -5
  19. package/dist/adapter/inmemory/inMemory.db.d.ts +5 -4
  20. package/dist/adapter/inmemory/inMemory.db.js +43 -41
  21. package/dist/adapter/inmemory/inMemoryKeyValueDB.d.ts +2 -2
  22. package/dist/adapter/inmemory/inMemoryKeyValueDB.js +7 -11
  23. package/dist/adapter/inmemory/queryInMemory.d.ts +1 -1
  24. package/dist/adapter/inmemory/queryInMemory.js +4 -7
  25. package/dist/base.common.db.d.ts +6 -4
  26. package/dist/base.common.db.js +8 -9
  27. package/dist/cnst.js +2 -5
  28. package/dist/common.db.d.ts +8 -2
  29. package/dist/common.db.js +3 -6
  30. package/dist/commondao/common.dao.d.ts +11 -4
  31. package/dist/commondao/common.dao.js +120 -113
  32. package/dist/commondao/common.dao.model.d.ts +2 -2
  33. package/dist/commondao/common.dao.model.js +2 -5
  34. package/dist/db.model.d.ts +6 -1
  35. package/dist/db.model.js +4 -7
  36. package/dist/index.d.ts +17 -17
  37. package/dist/index.js +17 -20
  38. package/dist/kv/commonKeyValueDB.d.ts +1 -1
  39. package/dist/kv/commonKeyValueDB.js +1 -4
  40. package/dist/kv/commonKeyValueDao.d.ts +3 -3
  41. package/dist/kv/commonKeyValueDao.js +10 -14
  42. package/dist/kv/commonKeyValueDaoMemoCache.d.ts +1 -1
  43. package/dist/kv/commonKeyValueDaoMemoCache.js +4 -8
  44. package/dist/model.util.js +9 -15
  45. package/dist/pipeline/dbPipelineBackup.d.ts +2 -2
  46. package/dist/pipeline/dbPipelineBackup.js +27 -30
  47. package/dist/pipeline/dbPipelineCopy.d.ts +2 -2
  48. package/dist/pipeline/dbPipelineCopy.js +20 -23
  49. package/dist/pipeline/dbPipelineRestore.d.ts +2 -2
  50. package/dist/pipeline/dbPipelineRestore.js +27 -30
  51. package/dist/query/dbQuery.d.ts +3 -3
  52. package/dist/query/dbQuery.js +7 -12
  53. package/dist/testing/{dbTest.d.ts → commonDBTest.d.ts} +1 -1
  54. package/dist/testing/{dbTest.js → commonDBTest.js} +81 -62
  55. package/dist/testing/commonDaoTest.d.ts +3 -0
  56. package/dist/testing/{daoTest.js → commonDaoTest.js} +101 -38
  57. package/dist/testing/index.d.ts +7 -7
  58. package/dist/testing/index.js +6 -20
  59. package/dist/testing/keyValueDBTest.d.ts +1 -1
  60. package/dist/testing/keyValueDBTest.js +28 -31
  61. package/dist/testing/keyValueDaoTest.d.ts +1 -1
  62. package/dist/testing/keyValueDaoTest.js +8 -11
  63. package/dist/testing/test.model.js +30 -37
  64. package/dist/testing/timeSeriesTest.util.d.ts +1 -1
  65. package/dist/testing/timeSeriesTest.util.js +3 -6
  66. package/dist/timeseries/commonTimeSeriesDao.d.ts +1 -1
  67. package/dist/timeseries/commonTimeSeriesDao.js +5 -9
  68. package/dist/timeseries/timeSeries.model.d.ts +1 -1
  69. package/dist/timeseries/timeSeries.model.js +1 -2
  70. package/dist/transaction/dbTransaction.util.d.ts +3 -2
  71. package/dist/transaction/dbTransaction.util.js +2 -5
  72. package/dist/validation/index.d.ts +2 -2
  73. package/dist/validation/index.js +25 -28
  74. package/package.json +3 -3
  75. package/src/adapter/cachedb/cache.db.model.ts +2 -2
  76. package/src/adapter/cachedb/cache.db.ts +6 -6
  77. package/src/adapter/cachedb/index.ts +2 -2
  78. package/src/adapter/file/file.db.model.ts +2 -2
  79. package/src/adapter/file/file.db.ts +8 -6
  80. package/src/adapter/file/inMemory.persistence.plugin.ts +2 -2
  81. package/src/adapter/file/index.ts +3 -3
  82. package/src/adapter/file/localFile.persistence.plugin.ts +2 -2
  83. package/src/adapter/file/noop.persistence.plugin.ts +2 -2
  84. package/src/adapter/inmemory/inMemory.db.ts +15 -10
  85. package/src/adapter/inmemory/inMemoryKeyValueDB.ts +7 -3
  86. package/src/adapter/inmemory/queryInMemory.ts +1 -1
  87. package/src/base.common.db.ts +9 -5
  88. package/src/common.db.ts +10 -2
  89. package/src/commondao/common.dao.model.ts +2 -2
  90. package/src/commondao/common.dao.ts +20 -6
  91. package/src/db.model.ts +7 -1
  92. package/src/index.ts +17 -17
  93. package/src/kv/commonKeyValueDB.ts +1 -1
  94. package/src/kv/commonKeyValueDao.ts +3 -3
  95. package/src/kv/commonKeyValueDaoMemoCache.ts +1 -1
  96. package/src/pipeline/dbPipelineBackup.ts +2 -2
  97. package/src/pipeline/dbPipelineCopy.ts +3 -3
  98. package/src/pipeline/dbPipelineRestore.ts +2 -2
  99. package/src/query/dbQuery.ts +3 -3
  100. package/src/testing/{dbTest.ts → commonDBTest.ts} +34 -6
  101. package/src/testing/{daoTest.ts → commonDaoTest.ts} +89 -11
  102. package/src/testing/index.ts +7 -7
  103. package/src/testing/keyValueDBTest.ts +2 -2
  104. package/src/testing/keyValueDaoTest.ts +3 -3
  105. package/src/testing/timeSeriesTest.util.ts +1 -1
  106. package/src/timeseries/commonTimeSeriesDao.ts +2 -2
  107. package/src/timeseries/timeSeries.model.ts +1 -1
  108. package/src/transaction/dbTransaction.util.ts +3 -2
  109. package/src/validation/index.ts +8 -3
  110. package/dist/testing/daoTest.d.ts +0 -3
@@ -1,14 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InMemoryDBTransaction = exports.InMemoryDB = void 0;
4
- const node_stream_1 = require("node:stream");
5
- const js_lib_1 = require("@naturalcycles/js-lib");
6
- const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
7
- const __1 = require("../..");
8
- class InMemoryDB {
9
- dbType = __1.CommonDBType.document;
1
+ import { Readable } from 'node:stream';
2
+ import { _assert, _by, _deepCopy, _isEmptyObject, _since, _sortObjectDeep, _stringMapEntries, _stringMapValues, generateJsonSchemaFromData, localTime, pMap, } from '@naturalcycles/js-lib';
3
+ import { _pipeline, bufferReviver, dimGrey, fs2, yellow } from '@naturalcycles/nodejs-lib';
4
+ import { commonDBFullSupport, CommonDBType } from '../../common.db.js';
5
+ import { queryInMemory } from './queryInMemory.js';
6
+ export class InMemoryDB {
7
+ dbType = CommonDBType.document;
10
8
  support = {
11
- ...__1.commonDBFullSupport,
9
+ ...commonDBFullSupport,
12
10
  timeMachine: false,
13
11
  };
14
12
  constructor(cfg) {
@@ -31,7 +29,7 @@ class InMemoryDB {
31
29
  * Deterministic - jsonSorted.
32
30
  */
33
31
  getDataSnapshot() {
34
- return (0, js_lib_1._sortObjectDeep)(this.data);
32
+ return _sortObjectDeep(this.data);
35
33
  }
36
34
  async ping() { }
37
35
  /**
@@ -57,7 +55,7 @@ class InMemoryDB {
57
55
  async getTableSchema(_table) {
58
56
  const table = this.cfg.tablesPrefix + _table;
59
57
  return {
60
- ...(0, js_lib_1.generateJsonSchemaFromData)((0, js_lib_1._stringMapValues)(this.data[table] || {})),
58
+ ...generateJsonSchemaFromData(_stringMapValues(this.data[table] || {})),
61
59
  $id: `${table}.schema.json`,
62
60
  };
63
61
  }
@@ -92,14 +90,14 @@ class InMemoryDB {
92
90
  // JSON parse/stringify (deep clone) is to:
93
91
  // 1. Not store values "by reference" (avoid mutation bugs)
94
92
  // 2. Simulate real DB that would do something like that in a transport layer anyway
95
- this.data[table][r.id] = JSON.parse(JSON.stringify(r), nodejs_lib_1.bufferReviver);
93
+ this.data[table][r.id] = JSON.parse(JSON.stringify(r), bufferReviver);
96
94
  });
97
95
  }
98
96
  async deleteByQuery(q, _opt) {
99
97
  const table = this.cfg.tablesPrefix + q.table;
100
98
  if (!this.data[table])
101
99
  return 0;
102
- const ids = (0, __1.queryInMemory)(q, Object.values(this.data[table])).map(r => r.id);
100
+ const ids = queryInMemory(q, Object.values(this.data[table])).map(r => r.id);
103
101
  return await this.deleteByIds(q.table, ids);
104
102
  }
105
103
  async deleteByIds(_table, ids, _opt) {
@@ -116,24 +114,24 @@ class InMemoryDB {
116
114
  return count;
117
115
  }
118
116
  async patchByQuery(q, patch) {
119
- if ((0, js_lib_1._isEmptyObject)(patch))
117
+ if (_isEmptyObject(patch))
120
118
  return 0;
121
119
  const table = this.cfg.tablesPrefix + q.table;
122
- const rows = (0, __1.queryInMemory)(q, Object.values(this.data[table] || {}));
120
+ const rows = queryInMemory(q, Object.values(this.data[table] || {}));
123
121
  rows.forEach(row => Object.assign(row, patch));
124
122
  return rows.length;
125
123
  }
126
124
  async runQuery(q, _opt) {
127
125
  const table = this.cfg.tablesPrefix + q.table;
128
- return { rows: (0, __1.queryInMemory)(q, Object.values(this.data[table] || {})) };
126
+ return { rows: queryInMemory(q, Object.values(this.data[table] || {})) };
129
127
  }
130
128
  async runQueryCount(q, _opt) {
131
129
  const table = this.cfg.tablesPrefix + q.table;
132
- return (0, __1.queryInMemory)(q, Object.values(this.data[table] || {})).length;
130
+ return queryInMemory(q, Object.values(this.data[table] || {})).length;
133
131
  }
134
132
  streamQuery(q, _opt) {
135
133
  const table = this.cfg.tablesPrefix + q.table;
136
- return node_stream_1.Readable.from((0, __1.queryInMemory)(q, Object.values(this.data[table] || {})));
134
+ return Readable.from(queryInMemory(q, Object.values(this.data[table] || {})));
137
135
  }
138
136
  async runInTransaction(fn, opt = {}) {
139
137
  const tx = new InMemoryDBTransaction(this, {
@@ -149,11 +147,17 @@ class InMemoryDB {
149
147
  throw err;
150
148
  }
151
149
  }
150
+ async createTransaction(opt = {}) {
151
+ return new InMemoryDBTransaction(this, {
152
+ readOnly: false,
153
+ ...opt,
154
+ });
155
+ }
152
156
  async incrementBatch(table, prop, incrementMap, _opt) {
153
157
  const tbl = this.cfg.tablesPrefix + table;
154
158
  this.data[tbl] ||= {};
155
159
  const result = {};
156
- for (const [id, by] of (0, js_lib_1._stringMapEntries)(incrementMap)) {
160
+ for (const [id, by] of _stringMapEntries(incrementMap)) {
157
161
  this.data[tbl][id] ||= { id };
158
162
  const newValue = (this.data[tbl][id][prop] || 0) + by;
159
163
  this.data[tbl][id][prop] = newValue;
@@ -165,44 +169,43 @@ class InMemoryDB {
165
169
  * Flushes all tables (all namespaces) at once.
166
170
  */
167
171
  async flushToDisk() {
168
- (0, js_lib_1._assert)(this.cfg.persistenceEnabled, 'flushToDisk() called but persistenceEnabled=false');
172
+ _assert(this.cfg.persistenceEnabled, 'flushToDisk() called but persistenceEnabled=false');
169
173
  const { persistentStoragePath, persistZip } = this.cfg;
170
- const started = js_lib_1.localTime.nowUnixMillis();
171
- await nodejs_lib_1.fs2.emptyDirAsync(persistentStoragePath);
174
+ const started = localTime.nowUnixMillis();
175
+ await fs2.emptyDirAsync(persistentStoragePath);
172
176
  let tables = 0;
173
177
  // infinite concurrency for now
174
- await (0, js_lib_1.pMap)(Object.keys(this.data), async (table) => {
178
+ await pMap(Object.keys(this.data), async (table) => {
175
179
  const rows = Object.values(this.data[table]);
176
180
  if (rows.length === 0)
177
181
  return; // 0 rows
178
182
  tables++;
179
183
  const fname = `${persistentStoragePath}/${table}.ndjson${persistZip ? '.gz' : ''}`;
180
- await (0, nodejs_lib_1._pipeline)([node_stream_1.Readable.from(rows), ...nodejs_lib_1.fs2.createWriteStreamAsNDJSON(fname)]);
184
+ await _pipeline([Readable.from(rows), ...fs2.createWriteStreamAsNDJSON(fname)]);
181
185
  });
182
- this.cfg.logger.log(`flushToDisk took ${(0, nodejs_lib_1.dimGrey)((0, js_lib_1._since)(started))} to save ${(0, nodejs_lib_1.yellow)(tables)} tables`);
186
+ this.cfg.logger.log(`flushToDisk took ${dimGrey(_since(started))} to save ${yellow(tables)} tables`);
183
187
  }
184
188
  /**
185
189
  * Restores all tables (all namespaces) at once.
186
190
  */
187
191
  async restoreFromDisk() {
188
- (0, js_lib_1._assert)(this.cfg.persistenceEnabled, 'restoreFromDisk() called but persistenceEnabled=false');
192
+ _assert(this.cfg.persistenceEnabled, 'restoreFromDisk() called but persistenceEnabled=false');
189
193
  const { persistentStoragePath } = this.cfg;
190
- const started = js_lib_1.localTime.nowUnixMillis();
191
- await nodejs_lib_1.fs2.ensureDirAsync(persistentStoragePath);
194
+ const started = localTime.nowUnixMillis();
195
+ await fs2.ensureDirAsync(persistentStoragePath);
192
196
  this.data = {}; // empty it in the beginning!
193
- const files = (await nodejs_lib_1.fs2.readdirAsync(persistentStoragePath)).filter(f => f.includes('.ndjson'));
197
+ const files = (await fs2.readdirAsync(persistentStoragePath)).filter(f => f.includes('.ndjson'));
194
198
  // infinite concurrency for now
195
- await (0, js_lib_1.pMap)(files, async (file) => {
199
+ await pMap(files, async (file) => {
196
200
  const fname = `${persistentStoragePath}/${file}`;
197
201
  const table = file.split('.ndjson')[0];
198
- const rows = await nodejs_lib_1.fs2.createReadStreamAsNDJSON(fname).toArray();
199
- this.data[table] = (0, js_lib_1._by)(rows, r => r.id);
202
+ const rows = await fs2.createReadStreamAsNDJSON(fname).toArray();
203
+ this.data[table] = _by(rows, r => r.id);
200
204
  });
201
- this.cfg.logger.log(`restoreFromDisk took ${(0, nodejs_lib_1.dimGrey)((0, js_lib_1._since)(started))} to read ${(0, nodejs_lib_1.yellow)(files.length)} tables`);
205
+ this.cfg.logger.log(`restoreFromDisk took ${dimGrey(_since(started))} to read ${yellow(files.length)} tables`);
202
206
  }
203
207
  }
204
- exports.InMemoryDB = InMemoryDB;
205
- class InMemoryDBTransaction {
208
+ export class InMemoryDBTransaction {
206
209
  db;
207
210
  opt;
208
211
  constructor(db, opt) {
@@ -214,12 +217,12 @@ class InMemoryDBTransaction {
214
217
  writeOperationHappened = false;
215
218
  async getByIds(table, ids, opt) {
216
219
  if (this.db.cfg.forbidTransactionReadAfterWrite) {
217
- (0, js_lib_1._assert)(!this.writeOperationHappened, `InMemoryDBTransaction: read operation attempted after write operation`);
220
+ _assert(!this.writeOperationHappened, `InMemoryDBTransaction: read operation attempted after write operation`);
218
221
  }
219
222
  return await this.db.getByIds(table, ids, opt);
220
223
  }
221
224
  async saveBatch(table, rows, opt) {
222
- (0, js_lib_1._assert)(!this.opt.readOnly, `InMemoryDBTransaction: saveBatch(${table}) called in readOnly mode`);
225
+ _assert(!this.opt.readOnly, `InMemoryDBTransaction: saveBatch(${table}) called in readOnly mode`);
223
226
  this.writeOperationHappened = true;
224
227
  this.ops.push({
225
228
  type: 'saveBatch',
@@ -229,7 +232,7 @@ class InMemoryDBTransaction {
229
232
  });
230
233
  }
231
234
  async deleteByIds(table, ids, opt) {
232
- (0, js_lib_1._assert)(!this.opt.readOnly, `InMemoryDBTransaction: deleteByIds(${table}) called in readOnly mode`);
235
+ _assert(!this.opt.readOnly, `InMemoryDBTransaction: deleteByIds(${table}) called in readOnly mode`);
233
236
  this.writeOperationHappened = true;
234
237
  this.ops.push({
235
238
  type: 'deleteByIds',
@@ -240,7 +243,7 @@ class InMemoryDBTransaction {
240
243
  return ids.length;
241
244
  }
242
245
  async commit() {
243
- const backup = (0, js_lib_1._deepCopy)(this.db.data);
246
+ const backup = _deepCopy(this.db.data);
244
247
  try {
245
248
  for (const op of this.ops) {
246
249
  if (op.type === 'saveBatch') {
@@ -267,4 +270,3 @@ class InMemoryDBTransaction {
267
270
  this.ops = [];
268
271
  }
269
272
  }
270
- exports.InMemoryDBTransaction = InMemoryDBTransaction;
@@ -1,7 +1,7 @@
1
1
  import type { StringMap } from '@naturalcycles/js-lib';
2
2
  import type { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
- import type { CommonDBCreateOptions } from '../../db.model';
4
- import type { CommonKeyValueDB, IncrementTuple, KeyValueDBTuple } from '../../kv/commonKeyValueDB';
3
+ import type { CommonDBCreateOptions } from '../../db.model.js';
4
+ import type { CommonKeyValueDB, IncrementTuple, KeyValueDBTuple } from '../../kv/commonKeyValueDB.js';
5
5
  export interface InMemoryKeyValueDBCfg {
6
6
  }
7
7
  export declare class InMemoryKeyValueDB implements CommonKeyValueDB {
@@ -1,15 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InMemoryKeyValueDB = void 0;
4
- const node_stream_1 = require("node:stream");
5
- const commonKeyValueDB_1 = require("../../kv/commonKeyValueDB");
6
- class InMemoryKeyValueDB {
1
+ import { Readable } from 'node:stream';
2
+ import { commonKeyValueDBFullSupport } from '../../kv/commonKeyValueDB.js';
3
+ export class InMemoryKeyValueDB {
7
4
  cfg;
8
5
  constructor(cfg = {}) {
9
6
  this.cfg = cfg;
10
7
  }
11
8
  support = {
12
- ...commonKeyValueDB_1.commonKeyValueDBFullSupport,
9
+ ...commonKeyValueDBFullSupport,
13
10
  };
14
11
  // data[table][id] => any (can be Buffer, or number)
15
12
  data = {};
@@ -28,13 +25,13 @@ class InMemoryKeyValueDB {
28
25
  entries.forEach(([id, v]) => (this.data[table][id] = v));
29
26
  }
30
27
  streamIds(table, limit) {
31
- return node_stream_1.Readable.from(Object.keys(this.data[table] || {}).slice(0, limit));
28
+ return Readable.from(Object.keys(this.data[table] || {}).slice(0, limit));
32
29
  }
33
30
  streamValues(table, limit) {
34
- return node_stream_1.Readable.from(Object.values(this.data[table] || {}).slice(0, limit));
31
+ return Readable.from(Object.values(this.data[table] || {}).slice(0, limit));
35
32
  }
36
33
  streamEntries(table, limit) {
37
- return node_stream_1.Readable.from(Object.entries(this.data[table] || {}).slice(0, limit));
34
+ return Readable.from(Object.entries(this.data[table] || {}).slice(0, limit));
38
35
  }
39
36
  async count(table) {
40
37
  this.data[table] ||= {};
@@ -49,4 +46,3 @@ class InMemoryKeyValueDB {
49
46
  });
50
47
  }
51
48
  }
52
- exports.InMemoryKeyValueDB = InMemoryKeyValueDB;
@@ -1,3 +1,3 @@
1
1
  import type { ObjectWithId } from '@naturalcycles/js-lib';
2
- import type { DBQuery } from '../../query/dbQuery';
2
+ import type { DBQuery } from '../../query/dbQuery.js';
3
3
  export declare function queryInMemory<ROW extends ObjectWithId>(q: DBQuery<ROW>, rows?: ROW[]): ROW[];
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.queryInMemory = queryInMemory;
4
- const js_lib_1 = require("@naturalcycles/js-lib");
1
+ import { _get, _pick } from '@naturalcycles/js-lib';
5
2
  const FILTER_FNS = {
6
3
  '==': (v, val) => v === val,
7
4
  '!=': (v, val) => v !== val,
@@ -16,18 +13,18 @@ const FILTER_FNS = {
16
13
  };
17
14
  // Important: q.table is not used in this function, so tablesPrefix is not needed.
18
15
  // But should be careful here..
19
- function queryInMemory(q, rows = []) {
16
+ export function queryInMemory(q, rows = []) {
20
17
  // .filter
21
18
  // eslint-disable-next-line unicorn/no-array-reduce
22
19
  rows = q._filters.reduce((rows, filter) => {
23
20
  return rows.filter(row => {
24
- const value = (0, js_lib_1._get)(row, filter.name);
21
+ const value = _get(row, filter.name);
25
22
  return FILTER_FNS[filter.op](value, filter.val);
26
23
  });
27
24
  }, rows);
28
25
  // .select(fieldNames)
29
26
  if (q._selectedFieldNames) {
30
- rows = rows.map(row => (0, js_lib_1._pick)(row, q._selectedFieldNames));
27
+ rows = rows.map(row => _pick(row, q._selectedFieldNames));
31
28
  }
32
29
  // todo: only one order is supported (first)
33
30
  const [order] = q._orders;
@@ -1,9 +1,10 @@
1
1
  import type { JsonSchemaObject, JsonSchemaRootObject, ObjectWithId, StringMap } from '@naturalcycles/js-lib';
2
2
  import type { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
- import type { CommonDB, CommonDBSupport } from './common.db';
4
- import { CommonDBType } from './common.db';
5
- import type { CommonDBOptions, CommonDBSaveOptions, CommonDBTransactionOptions, DBTransactionFn, RunQueryResult } from './db.model';
6
- import type { DBQuery } from './query/dbQuery';
3
+ import type { CommonDB, CommonDBSupport } from './common.db.js';
4
+ import { CommonDBType } from './common.db.js';
5
+ import type { CommonDBOptions, CommonDBSaveOptions, CommonDBTransactionOptions, DBTransactionFn, RunQueryResult } from './db.model.js';
6
+ import type { DBQuery } from './query/dbQuery.js';
7
+ import { FakeDBTransaction } from './transaction/dbTransaction.util.js';
7
8
  /**
8
9
  * No-op implementation of CommonDB interface.
9
10
  * To be extended by actual implementations.
@@ -24,5 +25,6 @@ export declare class BaseCommonDB implements CommonDB {
24
25
  streamQuery<ROW extends ObjectWithId>(_q: DBQuery<ROW>): ReadableTyped<ROW>;
25
26
  deleteByIds(_table: string, _ids: string[], _opt?: CommonDBOptions): Promise<number>;
26
27
  runInTransaction(fn: DBTransactionFn, _opt?: CommonDBTransactionOptions): Promise<void>;
28
+ createTransaction(_opt?: CommonDBTransactionOptions): Promise<FakeDBTransaction>;
27
29
  incrementBatch(_table: string, _prop: string, _incrementMap: StringMap<number>, _opt?: CommonDBOptions): Promise<StringMap<number>>;
28
30
  }
@@ -1,14 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseCommonDB = void 0;
4
- const common_db_1 = require("./common.db");
5
- const dbTransaction_util_1 = require("./transaction/dbTransaction.util");
1
+ import { CommonDBType } from './common.db.js';
2
+ import { FakeDBTransaction } from './transaction/dbTransaction.util.js';
6
3
  /**
7
4
  * No-op implementation of CommonDB interface.
8
5
  * To be extended by actual implementations.
9
6
  */
10
- class BaseCommonDB {
11
- dbType = common_db_1.CommonDBType.document;
7
+ export class BaseCommonDB {
8
+ dbType = CommonDBType.document;
12
9
  support = {};
13
10
  async ping() {
14
11
  throw new Error('ping is not implemented');
@@ -47,12 +44,14 @@ class BaseCommonDB {
47
44
  throw new Error('deleteByIds is not implemented');
48
45
  }
49
46
  async runInTransaction(fn, _opt) {
50
- const tx = new dbTransaction_util_1.FakeDBTransaction(this);
47
+ const tx = new FakeDBTransaction(this);
51
48
  await fn(tx);
52
49
  // there's no try/catch and rollback, as there's nothing to rollback
53
50
  }
51
+ async createTransaction(_opt) {
52
+ return new FakeDBTransaction(this);
53
+ }
54
54
  async incrementBatch(_table, _prop, _incrementMap, _opt) {
55
55
  throw new Error('incrementBatch is not implemented');
56
56
  }
57
57
  }
58
- exports.BaseCommonDB = BaseCommonDB;
package/dist/cnst.js CHANGED
@@ -1,10 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DBLibError = void 0;
4
- var DBLibError;
1
+ export var DBLibError;
5
2
  (function (DBLibError) {
6
3
  DBLibError["DB_ROW_REQUIRED"] = "DB_ROW_REQUIRED";
7
4
  DBLibError["DAO_IS_READ_ONLY"] = "DAO_IS_READ_ONLY";
8
5
  DBLibError["NON_UNIQUE_ID"] = "NON_UNIQUE_ID";
9
6
  DBLibError["OBJECT_IS_IMMUTABLE"] = "OBJECT_IS_IMMUTABLE";
10
- })(DBLibError || (exports.DBLibError = DBLibError = {}));
7
+ })(DBLibError || (DBLibError = {}));
@@ -1,7 +1,7 @@
1
1
  import type { JsonSchemaObject, JsonSchemaRootObject, ObjectWithId, StringMap } from '@naturalcycles/js-lib';
2
2
  import type { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
- import type { CommonDBCreateOptions, CommonDBOptions, CommonDBReadOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBTransactionOptions, DBTransactionFn, RunQueryResult } from './db.model';
4
- import type { DBQuery } from './query/dbQuery';
3
+ import type { CommonDBCreateOptions, CommonDBOptions, CommonDBReadOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBTransactionOptions, DBTransaction, DBTransactionFn, RunQueryResult } from './db.model.js';
4
+ import type { DBQuery } from './query/dbQuery.js';
5
5
  export declare enum CommonDBType {
6
6
  'document' = "document",
7
7
  'relational' = "relational"
@@ -87,6 +87,12 @@ export interface CommonDB {
87
87
  * unless specified as readOnly in CommonDBTransactionOptions.
88
88
  */
89
89
  runInTransaction: (fn: DBTransactionFn, opt?: CommonDBTransactionOptions) => Promise<void>;
90
+ /**
91
+ * Experimental API to support more manual transaction control.
92
+ *
93
+ * @experimental
94
+ */
95
+ createTransaction: (opt?: CommonDBTransactionOptions) => Promise<DBTransaction>;
90
96
  /**
91
97
  * Increments a value of a property by a given amount.
92
98
  * This is a batch operation, so it allows to increment multiple rows at once.
package/dist/common.db.js CHANGED
@@ -1,12 +1,9 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.commonDBFullSupport = exports.CommonDBType = void 0;
4
- var CommonDBType;
1
+ export var CommonDBType;
5
2
  (function (CommonDBType) {
6
3
  CommonDBType["document"] = "document";
7
4
  CommonDBType["relational"] = "relational";
8
- })(CommonDBType || (exports.CommonDBType = CommonDBType = {}));
9
- exports.commonDBFullSupport = {
5
+ })(CommonDBType || (CommonDBType = {}));
6
+ export const commonDBFullSupport = {
10
7
  queries: true,
11
8
  dbQueryFilter: true,
12
9
  dbQueryFilterIn: true,
@@ -3,10 +3,10 @@ import type { AsyncMapper, BaseDBEntity, CommonLogger, JsonSchemaObject, JsonSch
3
3
  import { ZodSchema } from '@naturalcycles/js-lib/dist/zod/index.js';
4
4
  import type { ObjectSchema, ReadableTyped } from '@naturalcycles/nodejs-lib';
5
5
  import { AjvSchema } from '@naturalcycles/nodejs-lib';
6
- import type { CommonDBTransactionOptions, DBTransaction, RunQueryResult } from '../db.model';
7
- import type { DBQuery } from '../query/dbQuery';
8
- import { RunnableDBQuery } from '../query/dbQuery';
9
- import type { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoPatchByIdOptions, CommonDaoPatchOptions, CommonDaoReadOptions, CommonDaoSaveBatchOptions, CommonDaoSaveOptions, CommonDaoStreamDeleteOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDaoStreamSaveOptions } from './common.dao.model';
6
+ import type { CommonDBTransactionOptions, DBTransaction, RunQueryResult } from '../db.model.js';
7
+ import type { DBQuery } from '../query/dbQuery.js';
8
+ import { RunnableDBQuery } from '../query/dbQuery.js';
9
+ import type { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoPatchByIdOptions, CommonDaoPatchOptions, CommonDaoReadOptions, CommonDaoSaveBatchOptions, CommonDaoSaveOptions, CommonDaoStreamDeleteOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDaoStreamSaveOptions } from './common.dao.model.js';
10
10
  /**
11
11
  * Lowest common denominator API between supported Databases.
12
12
  *
@@ -168,6 +168,7 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
168
168
  * Proxy to this.cfg.db.ping
169
169
  */
170
170
  ping(): Promise<void>;
171
+ createTransaction(opt?: CommonDBTransactionOptions): Promise<CommonDaoTransaction>;
171
172
  runInTransaction<T = void>(fn: CommonDaoTransactionFn<T>, opt?: CommonDBTransactionOptions): Promise<T>;
172
173
  /**
173
174
  * Throws if query uses a property that is in `excludeFromIndexes` list.
@@ -192,8 +193,14 @@ export declare class CommonDaoTransaction {
192
193
  tx: DBTransaction;
193
194
  private logger;
194
195
  constructor(tx: DBTransaction, logger: CommonLogger);
196
+ /**
197
+ * Commits the underlying DBTransaction.
198
+ * May throw.
199
+ */
200
+ commit(): Promise<void>;
195
201
  /**
196
202
  * Perform a graceful rollback without throwing/re-throwing any error.
203
+ * Never throws.
197
204
  */
198
205
  rollback(): Promise<void>;
199
206
  getById<BM extends BaseDBEntity, DBM extends BaseDBEntity, ID = BM['id']>(dao: CommonDao<BM, DBM, ID>, id?: ID | null, opt?: CommonDaoReadOptions): Promise<BM | null>;