@naturalcycles/db-lib 10.0.2 → 10.1.1

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 +5 -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 +10 -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,8 +1,8 @@
1
1
  import type { BaseDBEntity, CommonLogger, ErrorMode, NumberOfMilliseconds, Promisable, UnixTimestamp } from '@naturalcycles/js-lib';
2
2
  import type { ZodError, ZodSchema } from '@naturalcycles/js-lib/dist/zod/index.js';
3
3
  import type { AjvSchema, AjvValidationError, JoiValidationError, ObjectSchema, TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
4
- import type { CommonDB } from '../common.db';
5
- import type { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions } from '../db.model';
4
+ import type { CommonDB } from '../common.db.js';
5
+ import type { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions } from '../db.model.js';
6
6
  export interface CommonDaoHooks<BM extends BaseDBEntity, DBM extends BaseDBEntity, ID = BM['id']> {
7
7
  /**
8
8
  * Allows to override the id generation function.
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CommonDaoLogLevel = void 0;
4
- var CommonDaoLogLevel;
1
+ export var CommonDaoLogLevel;
5
2
  (function (CommonDaoLogLevel) {
6
3
  /**
7
4
  * Same as undefined
@@ -19,4 +16,4 @@ var CommonDaoLogLevel;
19
16
  * Log EVERYTHING - all data passing in and out (max 10 rows). Very verbose!
20
17
  */
21
18
  CommonDaoLogLevel[CommonDaoLogLevel["DATA_FULL"] = 30] = "DATA_FULL";
22
- })(CommonDaoLogLevel || (exports.CommonDaoLogLevel = CommonDaoLogLevel = {}));
19
+ })(CommonDaoLogLevel || (CommonDaoLogLevel = {}));
@@ -1,5 +1,5 @@
1
1
  import type { ObjectWithId, UnixTimestamp } from '@naturalcycles/js-lib';
2
- import type { CommonDB } from './common.db';
2
+ import type { CommonDB } from './common.db.js';
3
3
  /**
4
4
  * Similar to SQL INSERT, UPDATE.
5
5
  * Insert will fail if row already exists.
@@ -23,6 +23,11 @@ export interface DBTransaction {
23
23
  getByIds: CommonDB['getByIds'];
24
24
  saveBatch: CommonDB['saveBatch'];
25
25
  deleteByIds: CommonDB['deleteByIds'];
26
+ /**
27
+ * Commit the transaction.
28
+ * May throw.
29
+ */
30
+ commit: () => Promise<void>;
26
31
  /**
27
32
  * Perform a graceful rollback.
28
33
  * It'll rollback the transaction and won't throw/re-throw any errors.
package/dist/db.model.js CHANGED
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DBModelType = exports.DBRelation = void 0;
4
- var DBRelation;
1
+ export var DBRelation;
5
2
  (function (DBRelation) {
6
3
  DBRelation["ONE_TO_ONE"] = "ONE_TO_ONE";
7
4
  DBRelation["ONE_TO_MANY"] = "ONE_TO_MANY";
8
- })(DBRelation || (exports.DBRelation = DBRelation = {}));
9
- var DBModelType;
5
+ })(DBRelation || (DBRelation = {}));
6
+ export var DBModelType;
10
7
  (function (DBModelType) {
11
8
  DBModelType["DBM"] = "DBM";
12
9
  DBModelType["BM"] = "BM";
13
- })(DBModelType || (exports.DBModelType = DBModelType = {}));
10
+ })(DBModelType || (DBModelType = {}));
package/dist/index.d.ts CHANGED
@@ -1,17 +1,17 @@
1
- export * from './adapter/inmemory/inMemory.db';
2
- export * from './adapter/inmemory/inMemoryKeyValueDB';
3
- export * from './adapter/inmemory/queryInMemory';
4
- export * from './base.common.db';
5
- export * from './common.db';
6
- export * from './commondao/common.dao';
7
- export * from './commondao/common.dao.model';
8
- export * from './db.model';
9
- export * from './kv/commonKeyValueDao';
10
- export * from './kv/commonKeyValueDaoMemoCache';
11
- export * from './kv/commonKeyValueDB';
12
- export * from './model.util';
13
- export * from './pipeline/dbPipelineBackup';
14
- export * from './pipeline/dbPipelineCopy';
15
- export * from './pipeline/dbPipelineRestore';
16
- export * from './query/dbQuery';
17
- export * from './transaction/dbTransaction.util';
1
+ export * from './adapter/inmemory/inMemory.db.js';
2
+ export * from './adapter/inmemory/inMemoryKeyValueDB.js';
3
+ export * from './adapter/inmemory/queryInMemory.js';
4
+ export * from './base.common.db.js';
5
+ export * from './common.db.js';
6
+ export * from './commondao/common.dao.js';
7
+ export * from './commondao/common.dao.model.js';
8
+ export * from './db.model.js';
9
+ export * from './kv/commonKeyValueDao.js';
10
+ export * from './kv/commonKeyValueDaoMemoCache.js';
11
+ export * from './kv/commonKeyValueDB.js';
12
+ export * from './model.util.js';
13
+ export * from './pipeline/dbPipelineBackup.js';
14
+ export * from './pipeline/dbPipelineCopy.js';
15
+ export * from './pipeline/dbPipelineRestore.js';
16
+ export * from './query/dbQuery.js';
17
+ export * from './transaction/dbTransaction.util.js';
package/dist/index.js CHANGED
@@ -1,20 +1,17 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./adapter/inmemory/inMemory.db"), exports);
5
- tslib_1.__exportStar(require("./adapter/inmemory/inMemoryKeyValueDB"), exports);
6
- tslib_1.__exportStar(require("./adapter/inmemory/queryInMemory"), exports);
7
- tslib_1.__exportStar(require("./base.common.db"), exports);
8
- tslib_1.__exportStar(require("./common.db"), exports);
9
- tslib_1.__exportStar(require("./commondao/common.dao"), exports);
10
- tslib_1.__exportStar(require("./commondao/common.dao.model"), exports);
11
- tslib_1.__exportStar(require("./db.model"), exports);
12
- tslib_1.__exportStar(require("./kv/commonKeyValueDao"), exports);
13
- tslib_1.__exportStar(require("./kv/commonKeyValueDaoMemoCache"), exports);
14
- tslib_1.__exportStar(require("./kv/commonKeyValueDB"), exports);
15
- tslib_1.__exportStar(require("./model.util"), exports);
16
- tslib_1.__exportStar(require("./pipeline/dbPipelineBackup"), exports);
17
- tslib_1.__exportStar(require("./pipeline/dbPipelineCopy"), exports);
18
- tslib_1.__exportStar(require("./pipeline/dbPipelineRestore"), exports);
19
- tslib_1.__exportStar(require("./query/dbQuery"), exports);
20
- tslib_1.__exportStar(require("./transaction/dbTransaction.util"), exports);
1
+ export * from './adapter/inmemory/inMemory.db.js';
2
+ export * from './adapter/inmemory/inMemoryKeyValueDB.js';
3
+ export * from './adapter/inmemory/queryInMemory.js';
4
+ export * from './base.common.db.js';
5
+ export * from './common.db.js';
6
+ export * from './commondao/common.dao.js';
7
+ export * from './commondao/common.dao.model.js';
8
+ export * from './db.model.js';
9
+ export * from './kv/commonKeyValueDao.js';
10
+ export * from './kv/commonKeyValueDaoMemoCache.js';
11
+ export * from './kv/commonKeyValueDB.js';
12
+ export * from './model.util.js';
13
+ export * from './pipeline/dbPipelineBackup.js';
14
+ export * from './pipeline/dbPipelineCopy.js';
15
+ export * from './pipeline/dbPipelineRestore.js';
16
+ export * from './query/dbQuery.js';
17
+ export * from './transaction/dbTransaction.util.js';
@@ -1,6 +1,6 @@
1
1
  import type { Integer, UnixTimestamp } from '@naturalcycles/js-lib';
2
2
  import type { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
- import type { CommonDBCreateOptions } from '../db.model';
3
+ import type { CommonDBCreateOptions } from '../db.model.js';
4
4
  /**
5
5
  * Common interface for Key-Value database implementations.
6
6
  *
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.commonKeyValueDBFullSupport = void 0;
4
- exports.commonKeyValueDBFullSupport = {
1
+ export const commonKeyValueDBFullSupport = {
5
2
  count: true,
6
3
  increment: true,
7
4
  };
@@ -1,8 +1,8 @@
1
1
  import type { CommonLogger, KeyValueTuple } from '@naturalcycles/js-lib';
2
2
  import type { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
- import type { CommonDaoLogLevel } from '../commondao/common.dao.model';
4
- import type { CommonDBCreateOptions } from '../db.model';
5
- import type { CommonKeyValueDB, CommonKeyValueDBSaveBatchOptions, IncrementTuple, KeyValueDBTuple } from './commonKeyValueDB';
3
+ import type { CommonDaoLogLevel } from '../commondao/common.dao.model.js';
4
+ import type { CommonDBCreateOptions } from '../db.model.js';
5
+ import type { CommonKeyValueDB, CommonKeyValueDBSaveBatchOptions, IncrementTuple, KeyValueDBTuple } from './commonKeyValueDB.js';
6
6
  export interface CommonKeyValueDaoCfg<V> {
7
7
  db: CommonKeyValueDB;
8
8
  table: string;
@@ -1,15 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CommonKeyValueDao = exports.commonKeyValueDaoDeflatedJsonTransformer = void 0;
4
- const js_lib_1 = require("@naturalcycles/js-lib");
5
- const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
- exports.commonKeyValueDaoDeflatedJsonTransformer = {
7
- valueToBuffer: async (v) => await (0, nodejs_lib_1.deflateString)(JSON.stringify(v)),
8
- bufferToValue: async (buf) => JSON.parse(await (0, nodejs_lib_1.inflateToString)(buf)),
1
+ import { AppError, pMap } from '@naturalcycles/js-lib';
2
+ import { deflateString, inflateToString } from '@naturalcycles/nodejs-lib';
3
+ export const commonKeyValueDaoDeflatedJsonTransformer = {
4
+ valueToBuffer: async (v) => await deflateString(JSON.stringify(v)),
5
+ bufferToValue: async (buf) => JSON.parse(await inflateToString(buf)),
9
6
  };
10
7
  // todo: logging
11
8
  // todo: readonly
12
- class CommonKeyValueDao {
9
+ export class CommonKeyValueDao {
13
10
  constructor(cfg) {
14
11
  this.cfg = {
15
12
  logger: console,
@@ -39,7 +36,7 @@ class CommonKeyValueDao {
39
36
  const [r] = await this.getByIds([id]);
40
37
  if (!r) {
41
38
  const { table } = this.cfg;
42
- throw new js_lib_1.AppError(`DB row required, but not found in ${table}`, {
39
+ throw new AppError(`DB row required, but not found in ${table}`, {
43
40
  table,
44
41
  id,
45
42
  });
@@ -50,7 +47,7 @@ class CommonKeyValueDao {
50
47
  const [r] = await this.cfg.db.getByIds(this.cfg.table, [id]);
51
48
  if (!r) {
52
49
  const { table } = this.cfg;
53
- throw new js_lib_1.AppError(`DB row required, but not found in ${table}`, {
50
+ throw new AppError(`DB row required, but not found in ${table}`, {
54
51
  table,
55
52
  id,
56
53
  });
@@ -61,7 +58,7 @@ class CommonKeyValueDao {
61
58
  const entries = await this.cfg.db.getByIds(this.cfg.table, ids);
62
59
  if (!this.cfg.transformer)
63
60
  return entries;
64
- return await (0, js_lib_1.pMap)(entries, async ([id, raw]) => [
61
+ return await pMap(entries, async ([id, raw]) => [
65
62
  id,
66
63
  await this.cfg.transformer.bufferToValue(raw),
67
64
  ]);
@@ -79,7 +76,7 @@ class CommonKeyValueDao {
79
76
  rawEntries = entries;
80
77
  }
81
78
  else {
82
- rawEntries = await (0, js_lib_1.pMap)(entries, async ([id, v]) => [id, await transformer.valueToBuffer(v)]);
79
+ rawEntries = await pMap(entries, async ([id, v]) => [id, await transformer.valueToBuffer(v)]);
83
80
  }
84
81
  await this.cfg.db.saveBatch(this.cfg.table, rawEntries, opt);
85
82
  }
@@ -149,4 +146,3 @@ class CommonKeyValueDao {
149
146
  return await this.cfg.db.incrementBatch(this.cfg.table, entries);
150
147
  }
151
148
  }
152
- exports.CommonKeyValueDao = CommonKeyValueDao;
@@ -1,6 +1,6 @@
1
1
  import type { AsyncMemoCache, NumberOfSeconds } from '@naturalcycles/js-lib';
2
2
  import { MISS } from '@naturalcycles/js-lib';
3
- import type { CommonKeyValueDao } from './commonKeyValueDao';
3
+ import type { CommonKeyValueDao } from './commonKeyValueDao.js';
4
4
  export interface CommonKeyValueDaoMemoCacheCfg<VALUE> {
5
5
  dao: CommonKeyValueDao<string, VALUE>;
6
6
  /**
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CommonKeyValueDaoMemoCache = void 0;
4
- const js_lib_1 = require("@naturalcycles/js-lib");
1
+ import { localTime, MISS } from '@naturalcycles/js-lib';
5
2
  /**
6
3
  * AsyncMemoCache implementation, backed by CommonKeyValueDao.
7
4
  *
@@ -10,17 +7,17 @@ const js_lib_1 = require("@naturalcycles/js-lib");
10
7
  * Also, does not support .clear(), as it's more dangerous than useful to actually
11
8
  * clear the whole table/cache.
12
9
  */
13
- class CommonKeyValueDaoMemoCache {
10
+ export class CommonKeyValueDaoMemoCache {
14
11
  cfg;
15
12
  constructor(cfg) {
16
13
  this.cfg = cfg;
17
14
  }
18
15
  async get(k) {
19
- return (await this.cfg.dao.getById(k)) || js_lib_1.MISS;
16
+ return (await this.cfg.dao.getById(k)) || MISS;
20
17
  }
21
18
  async set(k, v) {
22
19
  const opt = this.cfg.ttl
23
- ? { expireAt: (js_lib_1.localTime.nowUnix() + this.cfg.ttl) }
20
+ ? { expireAt: (localTime.nowUnix() + this.cfg.ttl) }
24
21
  : undefined;
25
22
  await this.cfg.dao.save(k, v, opt);
26
23
  }
@@ -28,4 +25,3 @@ class CommonKeyValueDaoMemoCache {
28
25
  throw new Error('CommonKeyValueDaoMemoCache.clear is not supported, because cache is expected to be persistent');
29
26
  }
30
27
  }
31
- exports.CommonKeyValueDaoMemoCache = CommonKeyValueDaoMemoCache;
@@ -1,30 +1,24 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createdUpdatedFields = createdUpdatedFields;
4
- exports.createdUpdatedIdFields = createdUpdatedIdFields;
5
- exports.deserializeJsonField = deserializeJsonField;
6
- exports.serializeJsonField = serializeJsonField;
7
- const js_lib_1 = require("@naturalcycles/js-lib");
8
- const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
9
- function createdUpdatedFields(existingObject) {
10
- const now = js_lib_1.localTime.nowUnix();
1
+ import { localTime } from '@naturalcycles/js-lib';
2
+ import { stringId } from '@naturalcycles/nodejs-lib';
3
+ export function createdUpdatedFields(existingObject) {
4
+ const now = localTime.nowUnix();
11
5
  return {
12
6
  created: existingObject?.created || now,
13
7
  updated: now,
14
8
  };
15
9
  }
16
- function createdUpdatedIdFields(existingObject) {
17
- const now = js_lib_1.localTime.nowUnix();
10
+ export function createdUpdatedIdFields(existingObject) {
11
+ const now = localTime.nowUnix();
18
12
  return {
19
13
  created: existingObject?.created || now,
20
- id: existingObject?.id || (0, nodejs_lib_1.stringId)(),
14
+ id: existingObject?.id || stringId(),
21
15
  updated: now,
22
16
  };
23
17
  }
24
- function deserializeJsonField(f) {
18
+ export function deserializeJsonField(f) {
25
19
  return JSON.parse(f || '{}');
26
20
  }
27
- function serializeJsonField(f) {
21
+ export function serializeJsonField(f) {
28
22
  if (f === undefined)
29
23
  return;
30
24
  return JSON.stringify(f);
@@ -2,8 +2,8 @@ import type { AsyncMapper, StringMap, UnixTimestamp } from '@naturalcycles/js-li
2
2
  import { ErrorMode } from '@naturalcycles/js-lib';
3
3
  import type { TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
4
4
  import { NDJsonStats } from '@naturalcycles/nodejs-lib';
5
- import type { CommonDB } from '../common.db';
6
- import { DBQuery } from '../index';
5
+ import type { CommonDB } from '../common.db.js';
6
+ import { DBQuery } from '../query/dbQuery.js';
7
7
  export interface DBPipelineBackupOptions extends TransformLogProgressOptions {
8
8
  /**
9
9
  * DB to dump data from.
@@ -1,9 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dbPipelineBackup = dbPipelineBackup;
4
- const js_lib_1 = require("@naturalcycles/js-lib");
5
- const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
- const index_1 = require("../index");
1
+ import { _passthroughMapper, AppError, ErrorMode, localTime, pMap } from '@naturalcycles/js-lib';
2
+ import { _pipeline, boldWhite, dimWhite, fs2, grey, NDJsonStats, transformLogProgress, transformMap, transformTap, yellow, } from '@naturalcycles/nodejs-lib';
3
+ import { DBQuery } from '../query/dbQuery.js';
7
4
  /**
8
5
  * Pipeline from input stream(s) to a NDJSON file (optionally gzipped).
9
6
  * File is overwritten (by default).
@@ -13,17 +10,17 @@ const index_1 = require("../index");
13
10
  *
14
11
  * Optionally you can provide mapperPerTable and @param transformMapOptions (one for all mappers) - it will run for each table.
15
12
  */
16
- async function dbPipelineBackup(opt) {
17
- const { db, concurrency = 16, limit = 0, outputDirPath, protectFromOverwrite = false, mapperPerTable = {}, queryPerTable = {}, logEveryPerTable = {}, transformMapOptions, errorMode = js_lib_1.ErrorMode.SUPPRESS, emitSchemaFromDB = false, } = opt;
13
+ export async function dbPipelineBackup(opt) {
14
+ const { db, concurrency = 16, limit = 0, outputDirPath, protectFromOverwrite = false, mapperPerTable = {}, queryPerTable = {}, logEveryPerTable = {}, transformMapOptions, errorMode = ErrorMode.SUPPRESS, emitSchemaFromDB = false, } = opt;
18
15
  const gzip = opt.gzip !== false; // default to true
19
16
  let { tables } = opt;
20
- console.log(`>> ${(0, nodejs_lib_1.dimWhite)('dbPipelineBackup')} started in ${(0, nodejs_lib_1.grey)(outputDirPath)}...`);
21
- nodejs_lib_1.fs2.ensureDir(outputDirPath);
17
+ console.log(`>> ${dimWhite('dbPipelineBackup')} started in ${grey(outputDirPath)}...`);
18
+ fs2.ensureDir(outputDirPath);
22
19
  tables ||= await db.getTables();
23
- console.log(`${(0, nodejs_lib_1.yellow)(tables.length)} ${(0, nodejs_lib_1.boldWhite)('table(s)')}:\n` + tables.join('\n'));
20
+ console.log(`${yellow(tables.length)} ${boldWhite('table(s)')}:\n` + tables.join('\n'));
24
21
  const statsPerTable = {};
25
- await (0, js_lib_1.pMap)(tables, async (table) => {
26
- let q = index_1.DBQuery.create(table).limit(limit);
22
+ await pMap(tables, async (table) => {
23
+ let q = DBQuery.create(table).limit(limit);
27
24
  const sinceUpdated = opt.sinceUpdatedPerTable?.[table] ?? opt.sinceUpdated;
28
25
  if (sinceUpdated) {
29
26
  q = q.filter('updated', '>=', sinceUpdated);
@@ -31,56 +28,56 @@ async function dbPipelineBackup(opt) {
31
28
  if (queryPerTable[table]) {
32
29
  // Override the Query with this Query, completely ingoring any of the other query-related options
33
30
  q = queryPerTable[table];
34
- console.log(`>> ${(0, nodejs_lib_1.grey)(table)} ${q.pretty()}`);
31
+ console.log(`>> ${grey(table)} ${q.pretty()}`);
35
32
  }
36
33
  else {
37
34
  const sinceUpdatedStr = sinceUpdated
38
- ? ' since ' + (0, nodejs_lib_1.grey)((0, js_lib_1.localTime)(sinceUpdated).toPretty())
35
+ ? ' since ' + grey(localTime(sinceUpdated).toPretty())
39
36
  : '';
40
- console.log(`>> ${(0, nodejs_lib_1.grey)(table)}${sinceUpdatedStr}`);
37
+ console.log(`>> ${grey(table)}${sinceUpdatedStr}`);
41
38
  }
42
39
  const filePath = `${outputDirPath}/${table}.ndjson` + (gzip ? '.gz' : '');
43
40
  const schemaFilePath = `${outputDirPath}/${table}.schema.json`;
44
- if (protectFromOverwrite && nodejs_lib_1.fs2.pathExists(filePath)) {
45
- throw new js_lib_1.AppError(`dbPipelineBackup: output file exists: ${filePath}`);
41
+ if (protectFromOverwrite && fs2.pathExists(filePath)) {
42
+ throw new AppError(`dbPipelineBackup: output file exists: ${filePath}`);
46
43
  }
47
44
  const started = Date.now();
48
45
  let rows = 0;
49
- nodejs_lib_1.fs2.ensureFile(filePath);
46
+ fs2.ensureFile(filePath);
50
47
  // console.log(`>> ${grey(filePath)} started...`)
51
48
  if (emitSchemaFromDB) {
52
49
  const schema = await db.getTableSchema(table);
53
- await nodejs_lib_1.fs2.writeJsonAsync(schemaFilePath, schema, { spaces: 2 });
54
- console.log(`>> ${(0, nodejs_lib_1.grey)(schemaFilePath)} saved (generated from DB)`);
50
+ await fs2.writeJsonAsync(schemaFilePath, schema, { spaces: 2 });
51
+ console.log(`>> ${grey(schemaFilePath)} saved (generated from DB)`);
55
52
  }
56
- await (0, nodejs_lib_1._pipeline)([
53
+ await _pipeline([
57
54
  db.streamQuery(q),
58
- (0, nodejs_lib_1.transformLogProgress)({
55
+ transformLogProgress({
59
56
  ...opt,
60
57
  logEvery: logEveryPerTable[table] ?? opt.logEvery ?? 1000,
61
58
  metric: table,
62
59
  }),
63
- (0, nodejs_lib_1.transformMap)(mapperPerTable[table] || js_lib_1._passthroughMapper, {
60
+ transformMap(mapperPerTable[table] || _passthroughMapper, {
64
61
  errorMode,
65
62
  flattenArrayOutput: true,
66
63
  ...transformMapOptions,
67
64
  metric: table,
68
65
  }),
69
- (0, nodejs_lib_1.transformTap)(() => {
66
+ transformTap(() => {
70
67
  rows++;
71
68
  }),
72
- ...nodejs_lib_1.fs2.createWriteStreamAsNDJSON(filePath),
69
+ ...fs2.createWriteStreamAsNDJSON(filePath),
73
70
  ]);
74
- const { size: sizeBytes } = await nodejs_lib_1.fs2.statAsync(filePath);
75
- const stats = nodejs_lib_1.NDJsonStats.create({
71
+ const { size: sizeBytes } = await fs2.statAsync(filePath);
72
+ const stats = NDJsonStats.create({
76
73
  tookMillis: Date.now() - started,
77
74
  rows,
78
75
  sizeBytes,
79
76
  });
80
- console.log(`>> ${(0, nodejs_lib_1.grey)(filePath)}\n` + stats.toPretty());
77
+ console.log(`>> ${grey(filePath)}\n` + stats.toPretty());
81
78
  statsPerTable[table] = stats;
82
79
  }, { concurrency, errorMode });
83
- const statsTotal = nodejs_lib_1.NDJsonStats.createCombined(Object.values(statsPerTable));
80
+ const statsTotal = NDJsonStats.createCombined(Object.values(statsPerTable));
84
81
  console.log(statsTotal.toPretty('total'));
85
82
  return statsTotal;
86
83
  }
@@ -2,8 +2,8 @@ import type { AsyncMapper, UnixTimestamp } from '@naturalcycles/js-lib';
2
2
  import { ErrorMode } from '@naturalcycles/js-lib';
3
3
  import type { TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
4
4
  import { NDJsonStats } from '@naturalcycles/nodejs-lib';
5
- import type { CommonDB } from '../common.db';
6
- import type { CommonDBSaveOptions } from '../db.model';
5
+ import type { CommonDB } from '../common.db.js';
6
+ import type { CommonDBSaveOptions } from '../db.model.js';
7
7
  export interface DBPipelineCopyOptions extends TransformLogProgressOptions {
8
8
  dbInput: CommonDB;
9
9
  dbOutput: CommonDB;
@@ -1,61 +1,58 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dbPipelineCopy = dbPipelineCopy;
4
- const js_lib_1 = require("@naturalcycles/js-lib");
5
- const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
- const dbQuery_1 = require("../query/dbQuery");
1
+ import { _passthroughMapper, ErrorMode, localTime, pMap } from '@naturalcycles/js-lib';
2
+ import { _pipeline, boldWhite, dimWhite, grey, NDJsonStats, transformChunk, transformLogProgress, transformMap, transformTap, writableForEach, yellow, } from '@naturalcycles/nodejs-lib';
3
+ import { DBQuery } from '../query/dbQuery.js';
7
4
  /**
8
5
  * Pipeline from input stream(s) to CommonDB .saveBatch().
9
6
  * Input stream can be a stream from CommonDB.streamQuery()
10
7
  * Allows to define a mapper and a predicate to map/filter objects between input and output.
11
8
  * Handles backpressure.
12
9
  */
13
- async function dbPipelineCopy(opt) {
14
- const { chunkSize = 100, dbInput, dbOutput, concurrency = 16, limit = 0, sinceUpdated, mapperPerTable = {}, saveOptionsPerTable = {}, transformMapOptions, errorMode = js_lib_1.ErrorMode.SUPPRESS, } = opt;
10
+ export async function dbPipelineCopy(opt) {
11
+ const { chunkSize = 100, dbInput, dbOutput, concurrency = 16, limit = 0, sinceUpdated, mapperPerTable = {}, saveOptionsPerTable = {}, transformMapOptions, errorMode = ErrorMode.SUPPRESS, } = opt;
15
12
  let { tables } = opt;
16
- const sinceUpdatedStr = sinceUpdated ? ' since ' + (0, nodejs_lib_1.grey)((0, js_lib_1.localTime)(sinceUpdated).toPretty()) : '';
17
- console.log(`>> ${(0, nodejs_lib_1.dimWhite)('dbPipelineCopy')} started...${sinceUpdatedStr}`);
13
+ const sinceUpdatedStr = sinceUpdated ? ' since ' + grey(localTime(sinceUpdated).toPretty()) : '';
14
+ console.log(`>> ${dimWhite('dbPipelineCopy')} started...${sinceUpdatedStr}`);
18
15
  tables ||= await dbInput.getTables();
19
- console.log(`${(0, nodejs_lib_1.yellow)(tables.length)} ${(0, nodejs_lib_1.boldWhite)('table(s)')}:\n` + tables.join('\n'));
16
+ console.log(`${yellow(tables.length)} ${boldWhite('table(s)')}:\n` + tables.join('\n'));
20
17
  const statsPerTable = {};
21
- await (0, js_lib_1.pMap)(tables, async (table) => {
22
- let q = dbQuery_1.DBQuery.create(table).limit(limit);
18
+ await pMap(tables, async (table) => {
19
+ let q = DBQuery.create(table).limit(limit);
23
20
  if (sinceUpdated) {
24
21
  q = q.filter('updated', '>=', sinceUpdated);
25
22
  }
26
23
  const saveOptions = saveOptionsPerTable[table] || {};
27
- const mapper = mapperPerTable[table] || js_lib_1._passthroughMapper;
24
+ const mapper = mapperPerTable[table] || _passthroughMapper;
28
25
  const stream = dbInput.streamQuery(q);
29
26
  const started = Date.now();
30
27
  let rows = 0;
31
- await (0, nodejs_lib_1._pipeline)([
28
+ await _pipeline([
32
29
  stream,
33
- (0, nodejs_lib_1.transformLogProgress)({
30
+ transformLogProgress({
34
31
  logEvery: 1000,
35
32
  ...opt,
36
33
  metric: table,
37
34
  }),
38
- (0, nodejs_lib_1.transformMap)(mapper, {
35
+ transformMap(mapper, {
39
36
  errorMode,
40
37
  flattenArrayOutput: true,
41
38
  ...transformMapOptions,
42
39
  metric: table,
43
40
  }),
44
- (0, nodejs_lib_1.transformTap)(() => rows++),
45
- (0, nodejs_lib_1.transformChunk)({ chunkSize }),
46
- (0, nodejs_lib_1.writableForEach)(async (dbms) => {
41
+ transformTap(() => rows++),
42
+ transformChunk({ chunkSize }),
43
+ writableForEach(async (dbms) => {
47
44
  await dbOutput.saveBatch(table, dbms, saveOptions);
48
45
  }),
49
46
  ]);
50
- const stats = nodejs_lib_1.NDJsonStats.create({
47
+ const stats = NDJsonStats.create({
51
48
  tookMillis: Date.now() - started,
52
49
  rows,
53
50
  sizeBytes: 0, // n/a
54
51
  });
55
- console.log(`>> ${(0, nodejs_lib_1.grey)(table)}\n` + stats.toPretty());
52
+ console.log(`>> ${grey(table)}\n` + stats.toPretty());
56
53
  statsPerTable[table] = stats;
57
54
  }, { concurrency, errorMode });
58
- const statsTotal = nodejs_lib_1.NDJsonStats.createCombined(Object.values(statsPerTable));
55
+ const statsTotal = NDJsonStats.createCombined(Object.values(statsPerTable));
59
56
  console.log(statsTotal.toPretty('total'));
60
57
  return statsTotal;
61
58
  }
@@ -2,8 +2,8 @@ import type { AsyncMapper, UnixTimestamp } from '@naturalcycles/js-lib';
2
2
  import { ErrorMode } from '@naturalcycles/js-lib';
3
3
  import type { TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
4
4
  import { NDJsonStats } from '@naturalcycles/nodejs-lib';
5
- import type { CommonDB } from '../common.db';
6
- import type { CommonDBSaveOptions } from '../index';
5
+ import type { CommonDB } from '../common.db.js';
6
+ import type { CommonDBSaveOptions } from '../db.model.js';
7
7
  export interface DBPipelineRestoreOptions extends TransformLogProgressOptions {
8
8
  /**
9
9
  * DB to save data to.