@naturalcycles/db-lib 8.11.0 → 8.13.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 (58) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/adapter/cachedb/cache.db.d.ts +3 -3
  3. package/dist/adapter/cachedb/cache.db.js +4 -4
  4. package/dist/adapter/file/file.db.d.ts +2 -2
  5. package/dist/adapter/file/file.db.js +20 -18
  6. package/dist/adapter/file/inMemory.persistence.plugin.js +1 -1
  7. package/dist/adapter/file/localFile.persistence.plugin.js +9 -9
  8. package/dist/adapter/inmemory/inMemory.db.d.ts +3 -4
  9. package/dist/adapter/inmemory/inMemory.db.js +25 -23
  10. package/dist/adapter/inmemory/queryInMemory.js +1 -1
  11. package/dist/base.common.db.d.ts +3 -3
  12. package/dist/base.common.db.js +10 -4
  13. package/dist/common.db.d.ts +3 -3
  14. package/dist/commondao/common.dao.d.ts +7 -7
  15. package/dist/commondao/common.dao.js +56 -48
  16. package/dist/commondao/common.dao.model.d.ts +20 -27
  17. package/dist/db.model.js +2 -2
  18. package/dist/getDB.js +3 -3
  19. package/dist/index.d.ts +2 -4
  20. package/dist/index.js +1 -5
  21. package/dist/kv/commonKeyValueDao.js +4 -4
  22. package/dist/model.util.js +2 -2
  23. package/dist/pipeline/dbPipelineBackup.d.ts +0 -1
  24. package/dist/pipeline/dbPipelineBackup.js +14 -25
  25. package/dist/pipeline/dbPipelineCopy.js +11 -11
  26. package/dist/pipeline/dbPipelineRestore.js +20 -20
  27. package/dist/query/dbQuery.js +2 -2
  28. package/dist/testing/daoTest.js +23 -23
  29. package/dist/testing/dbTest.js +17 -17
  30. package/dist/testing/keyValueDBTest.js +18 -14
  31. package/dist/testing/keyValueDaoTest.js +18 -14
  32. package/dist/testing/test.model.d.ts +4 -2
  33. package/dist/testing/test.model.js +39 -8
  34. package/dist/testing/timeSeriesTest.util.js +1 -1
  35. package/dist/transaction/dbTransaction.util.js +2 -2
  36. package/dist/validation/index.js +9 -9
  37. package/package.json +1 -1
  38. package/readme.md +5 -4
  39. package/src/adapter/cachedb/cache.db.ts +9 -5
  40. package/src/adapter/file/file.db.ts +7 -4
  41. package/src/adapter/inmemory/inMemory.db.ts +20 -7
  42. package/src/base.common.db.ts +10 -4
  43. package/src/common.db.ts +3 -3
  44. package/src/commondao/common.dao.model.ts +24 -29
  45. package/src/commondao/common.dao.ts +35 -24
  46. package/src/index.ts +0 -7
  47. package/src/pipeline/dbPipelineBackup.ts +2 -15
  48. package/src/pipeline/dbPipelineRestore.ts +1 -1
  49. package/src/testing/dbTest.ts +1 -1
  50. package/src/testing/keyValueDBTest.ts +10 -6
  51. package/src/testing/keyValueDaoTest.ts +10 -6
  52. package/src/testing/test.model.ts +38 -4
  53. package/dist/schema/common.schema.d.ts +0 -38
  54. package/dist/schema/common.schema.js +0 -18
  55. package/dist/schema/commonSchemaGenerator.d.ts +0 -35
  56. package/dist/schema/commonSchemaGenerator.js +0 -151
  57. package/src/schema/common.schema.ts +0 -49
  58. package/src/schema/commonSchemaGenerator.ts +0 -200
@@ -7,7 +7,7 @@ const cnst_1 = require("../cnst");
7
7
  const db_model_1 = require("../db.model");
8
8
  const dbQuery_1 = require("../query/dbQuery");
9
9
  const common_dao_model_1 = require("./common.dao.model");
10
- const log = nodejs_lib_1.Debug('nc:db-lib:commondao');
10
+ const log = (0, nodejs_lib_1.Debug)('nc:db-lib:commondao');
11
11
  /* eslint-disable no-dupe-class-members */
12
12
  /**
13
13
  * Lowest common denominator API between supported Databases.
@@ -24,7 +24,7 @@ class CommonDao {
24
24
  createdUpdated: true,
25
25
  ...cfg,
26
26
  hooks: {
27
- createId: () => nodejs_lib_1.stringId(),
27
+ createId: () => (0, nodejs_lib_1.stringId)(),
28
28
  parseNaturalId: () => ({}),
29
29
  beforeCreate: bm => bm,
30
30
  beforeDBMValidate: dbm => dbm,
@@ -33,15 +33,13 @@ class CommonDao {
33
33
  beforeTMToBM: tm => tm,
34
34
  beforeBMToTM: bm => bm,
35
35
  anonymize: dbm => dbm,
36
+ onValidationError: err => err,
36
37
  ...cfg.hooks,
37
38
  },
38
39
  };
39
40
  }
40
41
  // CREATE
41
42
  create(input, opt = {}) {
42
- if (opt.throwOnError === undefined) {
43
- opt.throwOnError = this.cfg.throwOnDaoCreateObject;
44
- }
45
43
  let bm = this.cfg.hooks.beforeCreate(input);
46
44
  bm = this.validateAndConvert(bm, this.cfg.bmSchema, db_model_1.DBModelType.BM, opt);
47
45
  // If no SCHEMA - return as is
@@ -107,7 +105,7 @@ class CommonDao {
107
105
  return tm || null;
108
106
  }
109
107
  async getByIds(ids, opt = {}) {
110
- const op = `getByIds ${ids.length} id(s) (${js_lib_1._truncate(ids.slice(0, 10).join(', '), 50)})`;
108
+ const op = `getByIds ${ids.length} id(s) (${(0, js_lib_1._truncate)(ids.slice(0, 10).join(', '), 50)})`;
111
109
  const table = opt.table || this.cfg.table;
112
110
  const started = this.logStarted(op, table);
113
111
  const dbms = await this.cfg.db.getByIds(table, ids);
@@ -116,7 +114,7 @@ class CommonDao {
116
114
  return bms;
117
115
  }
118
116
  async getByIdsAsDBM(ids, opt = {}) {
119
- const op = `getByIdsAsDBM ${ids.length} id(s) (${js_lib_1._truncate(ids.slice(0, 10).join(', '), 50)})`;
117
+ const op = `getByIdsAsDBM ${ids.length} id(s) (${(0, js_lib_1._truncate)(ids.slice(0, 10).join(', '), 50)})`;
120
118
  const table = opt.table || this.cfg.table;
121
119
  const started = this.logStarted(op, table);
122
120
  const dbms = await this.cfg.db.getByIds(table, ids);
@@ -227,7 +225,7 @@ class CommonDao {
227
225
  const started = this.logStarted(op, q.table);
228
226
  const count = await this.cfg.db.runQueryCount(q, opt);
229
227
  if (this.cfg.logLevel >= common_dao_model_1.CommonDaoLogLevel.OPERATIONS) {
230
- log(`<< ${q.table}.${op}: ${count} row(s) in ${js_lib_1._since(started)}`);
228
+ log(`<< ${q.table}.${op}: ${count} row(s) in ${(0, js_lib_1._since)(started)}`);
231
229
  }
232
230
  return count;
233
231
  }
@@ -240,29 +238,29 @@ class CommonDao {
240
238
  const op = `streamQueryForEach(${q.pretty()})`;
241
239
  const started = this.logStarted(op, q.table, true);
242
240
  let count = 0;
243
- await nodejs_lib_1._pipeline([
241
+ await (0, nodejs_lib_1._pipeline)([
244
242
  this.cfg.db.streamQuery(q, opt),
245
243
  // optimization: 1 validation is enough
246
244
  // transformMap<any, DBM>(dbm => (partialQuery || opt.raw ? dbm : this.anyToDBM(dbm, opt)), opt),
247
- nodejs_lib_1.transformMapSync(dbm => {
245
+ (0, nodejs_lib_1.transformMapSync)(dbm => {
248
246
  count++;
249
247
  return partialQuery || opt.raw ? dbm : this.dbmToBM(dbm, opt);
250
248
  }, {
251
249
  errorMode: opt.errorMode,
252
250
  }),
253
- nodejs_lib_1.transformMap(mapper, {
251
+ (0, nodejs_lib_1.transformMap)(mapper, {
254
252
  ...opt,
255
253
  predicate: js_lib_1._passthroughPredicate, // to be able to logProgress
256
254
  }),
257
255
  // LogProgress should be AFTER the mapper, to be able to report correct stats
258
- nodejs_lib_1.transformLogProgress({
256
+ (0, nodejs_lib_1.transformLogProgress)({
259
257
  metric: q.table,
260
258
  ...opt,
261
259
  }),
262
- nodejs_lib_1.writableVoid(),
260
+ (0, nodejs_lib_1.writableVoid)(),
263
261
  ]);
264
262
  if (this.cfg.logLevel >= common_dao_model_1.CommonDaoLogLevel.OPERATIONS) {
265
- log(`<< ${q.table}.${op}: ${count} row(s) in ${js_lib_1._since(started)}`);
263
+ log(`<< ${q.table}.${op}: ${count} row(s) in ${(0, js_lib_1._since)(started)}`);
266
264
  }
267
265
  }
268
266
  async streamQueryAsDBMForEach(q, mapper, opt = {}) {
@@ -274,27 +272,27 @@ class CommonDao {
274
272
  const op = `streamQueryAsDBMForEach(${q.pretty()})`;
275
273
  const started = this.logStarted(op, q.table, true);
276
274
  let count = 0;
277
- await nodejs_lib_1._pipeline([
275
+ await (0, nodejs_lib_1._pipeline)([
278
276
  this.cfg.db.streamQuery(q, opt),
279
- nodejs_lib_1.transformMapSync(dbm => {
277
+ (0, nodejs_lib_1.transformMapSync)(dbm => {
280
278
  count++;
281
279
  return partialQuery || opt.raw ? dbm : this.anyToDBM(dbm, opt);
282
280
  }, {
283
281
  errorMode: opt.errorMode,
284
282
  }),
285
- nodejs_lib_1.transformMap(mapper, {
283
+ (0, nodejs_lib_1.transformMap)(mapper, {
286
284
  ...opt,
287
285
  predicate: js_lib_1._passthroughPredicate, // to be able to logProgress
288
286
  }),
289
287
  // LogProgress should be AFTER the mapper, to be able to report correct stats
290
- nodejs_lib_1.transformLogProgress({
288
+ (0, nodejs_lib_1.transformLogProgress)({
291
289
  metric: q.table,
292
290
  ...opt,
293
291
  }),
294
- nodejs_lib_1.writableVoid(),
292
+ (0, nodejs_lib_1.writableVoid)(),
295
293
  ]);
296
294
  if (this.cfg.logLevel >= common_dao_model_1.CommonDaoLogLevel.OPERATIONS) {
297
- log(`<< ${q.table}.${op}: ${count} row(s) in ${js_lib_1._since(started)}`);
295
+ log(`<< ${q.table}.${op}: ${count} row(s) in ${(0, js_lib_1._since)(started)}`);
298
296
  }
299
297
  }
300
298
  /**
@@ -309,7 +307,7 @@ class CommonDao {
309
307
  const stream = this.cfg.db.streamQuery(q, opt);
310
308
  if (partialQuery || opt.raw)
311
309
  return stream;
312
- return stream.pipe(nodejs_lib_1.transformMapSimple(dbm => this.anyToDBM(dbm, opt), {
310
+ return stream.pipe((0, nodejs_lib_1.transformMapSimple)(dbm => this.anyToDBM(dbm, opt), {
313
311
  errorMode: js_lib_1.ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors
314
312
  }));
315
313
  }
@@ -329,7 +327,7 @@ class CommonDao {
329
327
  // optimization: 1 validation is enough
330
328
  // .pipe(transformMap<any, DBM>(dbm => this.anyToDBM(dbm, opt), safeOpt))
331
329
  // .pipe(transformMap<DBM, Saved<BM>>(dbm => this.dbmToBM(dbm, opt), safeOpt))
332
- .pipe(nodejs_lib_1.transformMapSimple(dbm => this.dbmToBM(dbm, opt), {
330
+ .pipe((0, nodejs_lib_1.transformMapSimple)(dbm => this.dbmToBM(dbm, opt), {
333
331
  errorMode: js_lib_1.ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors
334
332
  })));
335
333
  }
@@ -341,7 +339,7 @@ class CommonDao {
341
339
  streamQueryIds(q, opt = {}) {
342
340
  q.table = opt.table || q.table;
343
341
  opt.errorMode || (opt.errorMode = js_lib_1.ErrorMode.SUPPRESS);
344
- return this.cfg.db.streamQuery(q.select(['id']), opt).pipe(nodejs_lib_1.transformMapSimple(objectWithId => objectWithId.id, {
342
+ return this.cfg.db.streamQuery(q.select(['id']), opt).pipe((0, nodejs_lib_1.transformMapSimple)(objectWithId => objectWithId.id, {
345
343
  errorMode: js_lib_1.ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors
346
344
  }));
347
345
  }
@@ -351,23 +349,23 @@ class CommonDao {
351
349
  const op = `streamQueryIdsForEach(${q.pretty()})`;
352
350
  const started = this.logStarted(op, q.table, true);
353
351
  let count = 0;
354
- await nodejs_lib_1._pipeline([
352
+ await (0, nodejs_lib_1._pipeline)([
355
353
  this.cfg.db.streamQuery(q.select(['id']), opt),
356
- nodejs_lib_1.transformMapSimple(objectWithId => objectWithId.id),
357
- nodejs_lib_1.transformTap(() => count++),
358
- nodejs_lib_1.transformMap(mapper, {
354
+ (0, nodejs_lib_1.transformMapSimple)(objectWithId => objectWithId.id),
355
+ (0, nodejs_lib_1.transformTap)(() => count++),
356
+ (0, nodejs_lib_1.transformMap)(mapper, {
359
357
  ...opt,
360
358
  predicate: js_lib_1._passthroughPredicate,
361
359
  }),
362
360
  // LogProgress should be AFTER the mapper, to be able to report correct stats
363
- nodejs_lib_1.transformLogProgress({
361
+ (0, nodejs_lib_1.transformLogProgress)({
364
362
  metric: q.table,
365
363
  ...opt,
366
364
  }),
367
- nodejs_lib_1.writableVoid(),
365
+ (0, nodejs_lib_1.writableVoid)(),
368
366
  ]);
369
367
  if (this.cfg.logLevel >= common_dao_model_1.CommonDaoLogLevel.OPERATIONS) {
370
- log(`<< ${q.table}.${op}: ${count} id(s) in ${js_lib_1._since(started)}`);
368
+ log(`<< ${q.table}.${op}: ${count} id(s) in ${(0, js_lib_1._since)(started)}`);
371
369
  }
372
370
  }
373
371
  assignIdCreatedUpdated(obj, opt = {}) {
@@ -466,7 +464,7 @@ class CommonDao {
466
464
  const dbms = this.bmsToDBM(bms, opt);
467
465
  if (opt.ensureUniqueId)
468
466
  throw new js_lib_1.AppError('ensureUniqueId is not supported in saveBatch');
469
- const op = `saveBatch ${dbms.length} row(s) (${js_lib_1._truncate(dbms
467
+ const op = `saveBatch ${dbms.length} row(s) (${(0, js_lib_1._truncate)(dbms
470
468
  .slice(0, 10)
471
469
  .map(bm => bm.id)
472
470
  .join(', '), 50)})`;
@@ -487,7 +485,7 @@ class CommonDao {
487
485
  if (opt.ensureUniqueId)
488
486
  throw new js_lib_1.AppError('ensureUniqueId is not supported in saveBatch');
489
487
  }
490
- const op = `saveBatchAsDBM ${dbms.length} row(s) (${js_lib_1._truncate(dbms
488
+ const op = `saveBatchAsDBM ${dbms.length} row(s) (${(0, js_lib_1._truncate)(dbms
491
489
  .slice(0, 10)
492
490
  .map(bm => bm.id)
493
491
  .join(', '), 50)})`;
@@ -613,14 +611,15 @@ class CommonDao {
613
611
  /**
614
612
  * Returns *converted value*.
615
613
  * Validates (unless `skipValidation=true` passed).
616
- * Throws only if `throwOnError=true` passed OR if `env().throwOnEntityValidationError`
614
+ *
615
+ * Does NOT mutate the object.
617
616
  */
618
617
  validateAndConvert(obj, schema, modelType, opt = {}) {
619
618
  // `raw` option completely bypasses any processing
620
619
  if (opt.raw)
621
620
  return obj;
622
621
  // Filter null and undefined values
623
- obj = js_lib_1._filterNullishValues(obj);
622
+ obj = (0, js_lib_1._filterNullishValues)(obj);
624
623
  // Pre-validation hooks
625
624
  if (modelType === db_model_1.DBModelType.DBM) {
626
625
  obj = this.cfg.hooks.beforeDBMValidate(obj);
@@ -631,27 +630,36 @@ class CommonDao {
631
630
  }
632
631
  // This will Convert and Validate
633
632
  const table = opt.table || this.cfg.table;
634
- const { value, error } = nodejs_lib_1.getValidationResult(obj, schema, table + (modelType || ''));
633
+ const objectName = table + (modelType || '');
634
+ let error;
635
+ let convertedValue;
636
+ if (schema instanceof nodejs_lib_1.AjvSchema) {
637
+ // Ajv schema
638
+ convertedValue = obj; // because Ajv mutates original object
639
+ error = schema.getValidationError(obj, {
640
+ objectName,
641
+ });
642
+ }
643
+ else {
644
+ // Joi
645
+ const vr = (0, nodejs_lib_1.getValidationResult)(obj, schema, objectName);
646
+ error = vr.error;
647
+ convertedValue = vr.value;
648
+ }
635
649
  // If we care about validation and there's an error
636
650
  if (error && !opt.skipValidation) {
637
- if (opt.throwOnError ||
638
- (this.cfg.throwOnEntityValidationError && opt.throwOnError === undefined)) {
639
- throw error;
640
- }
641
- else {
642
- // capture by Sentry and ignore the error
643
- // It will still *convert* the value and return.
644
- this.cfg.onValidationError?.(error);
645
- }
651
+ const processedError = this.cfg.hooks.onValidationError(error);
652
+ if (processedError)
653
+ throw processedError;
646
654
  }
647
- return value; // converted value
655
+ return convertedValue;
648
656
  }
649
657
  async getTableSchema() {
650
658
  return await this.cfg.db.getTableSchema(this.cfg.table);
651
659
  }
652
660
  async createTable(schema, opt) {
653
661
  this.requireWriteAccess();
654
- await this.cfg.db.createTable(schema, opt);
662
+ await this.cfg.db.createTable(this.cfg.table, schema, opt);
655
663
  }
656
664
  /**
657
665
  * Proxy to this.cfg.db.ping
@@ -684,12 +692,12 @@ class CommonDao {
684
692
  else {
685
693
  logRes = `undefined`;
686
694
  }
687
- log(...[`<< ${table}.${op}: ${logRes} in ${js_lib_1._since(started)}`].concat(args));
695
+ log(...[`<< ${table}.${op}: ${logRes} in ${(0, js_lib_1._since)(started)}`].concat(args));
688
696
  }
689
697
  logSaveResult(started, op, table) {
690
698
  if (!this.cfg.logLevel)
691
699
  return;
692
- log(`<< ${table}.${op} in ${js_lib_1._since(started)}`);
700
+ log(`<< ${table}.${op} in ${(0, js_lib_1._since)(started)}`);
693
701
  }
694
702
  logStarted(op, table, force = false) {
695
703
  if (this.cfg.logStarted || force) {
@@ -1,15 +1,15 @@
1
1
  import { ErrorMode } from '@naturalcycles/js-lib';
2
- import { JoiValidationError, ObjectSchemaTyped, TransformLogProgressOptions } from '@naturalcycles/nodejs-lib';
2
+ import { AjvSchema, AjvValidationError, JoiValidationError, ObjectSchemaTyped, TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
3
3
  import { CommonDB } from '../common.db';
4
4
  import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions, ObjectWithId } from '../db.model';
5
5
  export declare type CommonDaoCreateIdHook<BM, DBM> = (obj: DBM | BM) => string;
6
6
  export declare type CommonDaoParseNaturalIdHook<DBM> = (id: string) => Partial<DBM>;
7
7
  export declare type CommonDaoBeforeCreateHook<BM> = (bm: Partial<BM>) => BM;
8
- export declare type CommonDaoBeforeDBMValidateHook<DBM> = (dbm: DBM) => DBM;
9
- export declare type CommonDaoBeforeDBMToBMHook<BM, DBM> = (dbm: DBM) => BM;
10
- export declare type CommonDaoBeforeBMToDBMHook<BM, DBM> = (bm: BM) => DBM;
11
- export declare type CommonDaoBeforeTMToBMHook<BM, TM> = (tm: TM) => BM;
12
- export declare type CommonDaoBeforeBMToTMHook<BM, TM> = (bm: BM) => TM;
8
+ export declare type CommonDaoBeforeDBMValidateHook<DBM> = (dbm: Partial<DBM>) => Partial<DBM>;
9
+ export declare type CommonDaoBeforeDBMToBMHook<BM, DBM> = (dbm: DBM) => Partial<BM>;
10
+ export declare type CommonDaoBeforeBMToDBMHook<BM, DBM> = (bm: BM) => Partial<DBM>;
11
+ export declare type CommonDaoBeforeTMToBMHook<BM, TM> = (tm: TM) => Partial<BM>;
12
+ export declare type CommonDaoBeforeBMToTMHook<BM, TM> = (bm: BM) => Partial<TM>;
13
13
  export declare type CommonDaoAnonymizeHook<DBM> = (dbm: DBM) => DBM;
14
14
  interface CommonDaoHooks<BM, DBM, TM> {
15
15
  createId: CommonDaoCreateIdHook<BM, DBM>;
@@ -21,6 +21,13 @@ interface CommonDaoHooks<BM, DBM, TM> {
21
21
  beforeTMToBM: CommonDaoBeforeTMToBMHook<BM, TM>;
22
22
  beforeBMToTM: CommonDaoBeforeBMToTMHook<BM, TM>;
23
23
  anonymize: CommonDaoAnonymizeHook<DBM>;
24
+ /**
25
+ * If hook is defined - allows to prevent or modify the error thrown.
26
+ * Return `false` to prevent throwing an error.
27
+ * Return original `err` to pass the error through (will be thrown in CommonDao).
28
+ * Return modified/new `Error` if needed.
29
+ */
30
+ onValidationError: (err: JoiValidationError | AjvValidationError) => Error | false;
24
31
  }
25
32
  export declare enum CommonDaoLogLevel {
26
33
  /**
@@ -34,9 +41,12 @@ export declare enum CommonDaoLogLevel {
34
41
  export interface CommonDaoCfg<BM extends Partial<ObjectWithId>, DBM extends ObjectWithId, TM> {
35
42
  db: CommonDB;
36
43
  table: string;
37
- dbmSchema?: ObjectSchemaTyped<DBM>;
38
- bmSchema?: ObjectSchemaTyped<BM>;
39
- tmSchema?: ObjectSchemaTyped<TM>;
44
+ /**
45
+ * Joi or AjvSchema are supported.
46
+ */
47
+ dbmSchema?: ObjectSchemaTyped<DBM> | AjvSchema<DBM>;
48
+ bmSchema?: ObjectSchemaTyped<BM> | AjvSchema<BM>;
49
+ tmSchema?: ObjectSchemaTyped<TM> | AjvSchema<TM>;
40
50
  excludeFromIndexes?: string[];
41
51
  /**
42
52
  * @default to false
@@ -51,19 +61,6 @@ export interface CommonDaoCfg<BM extends Partial<ObjectWithId>, DBM extends Obje
51
61
  * @default false
52
62
  */
53
63
  logStarted?: boolean;
54
- /**
55
- * @default false
56
- */
57
- throwOnEntityValidationError?: boolean;
58
- /**
59
- * @default to throwOnEntityValidationError setting
60
- */
61
- throwOnDaoCreateObject?: boolean;
62
- /**
63
- * Called when validation error occurs.
64
- * Called ONLY when error is NOT thrown (when throwOnEntityValidationError is off)
65
- */
66
- onValidationError?: (err: JoiValidationError) => any;
67
64
  hooks?: Partial<CommonDaoHooks<BM, DBM, TM>>;
68
65
  /**
69
66
  * @default true
@@ -99,10 +96,6 @@ export interface CommonDaoOptions extends CommonDBOptions {
99
96
  * @default false
100
97
  */
101
98
  raw?: boolean;
102
- /**
103
- * @default inherited from CommonDaoCfg.throwOnEntityValidationError
104
- */
105
- throwOnError?: boolean;
106
99
  /**
107
100
  * @default false
108
101
  */
@@ -135,7 +128,7 @@ export interface CommonDaoSaveOptions extends CommonDaoOptions, CommonDBSaveOpti
135
128
  */
136
129
  ensureUniqueId?: boolean;
137
130
  }
138
- export interface CommonDaoStreamForEachOptions<IN> extends CommonDaoStreamOptions, TransformLogProgressOptions<IN> {
131
+ export interface CommonDaoStreamForEachOptions<IN> extends CommonDaoStreamOptions, TransformMapOptions<IN, any>, TransformLogProgressOptions<IN> {
139
132
  }
140
133
  export interface CommonDaoStreamOptions extends CommonDaoOptions {
141
134
  /**
package/dist/db.model.js CHANGED
@@ -13,13 +13,13 @@ var DBModelType;
13
13
  DBModelType["BM"] = "BM";
14
14
  DBModelType["TM"] = "TM";
15
15
  })(DBModelType = exports.DBModelType || (exports.DBModelType = {}));
16
- exports.baseDBEntitySchema = nodejs_lib_1.objectSchema({
16
+ exports.baseDBEntitySchema = (0, nodejs_lib_1.objectSchema)({
17
17
  id: nodejs_lib_1.stringSchema.optional(),
18
18
  created: nodejs_lib_1.unixTimestampSchema.optional(),
19
19
  updated: nodejs_lib_1.unixTimestampSchema.optional(),
20
20
  // _ver: verSchema.optional(),
21
21
  });
22
- exports.savedDBEntitySchema = nodejs_lib_1.objectSchema({
22
+ exports.savedDBEntitySchema = (0, nodejs_lib_1.objectSchema)({
23
23
  id: nodejs_lib_1.stringSchema,
24
24
  created: nodejs_lib_1.unixTimestampSchema,
25
25
  updated: nodejs_lib_1.unixTimestampSchema,
package/dist/getDB.js CHANGED
@@ -18,15 +18,15 @@ function getDB(index = 1) {
18
18
  }
19
19
  exports.getDB = getDB;
20
20
  // Extra function to provide index=1 as default (since memo doesn't work well with default arguments)
21
- const _getDB = js_lib_1._memoFn((index) => {
21
+ const _getDB = (0, js_lib_1._memoFn)((index) => {
22
22
  const libName = process.env[`DB${index}`];
23
23
  if (!libName) {
24
- throw new Error(`getDB(${colors_1.yellow(index)}), but process.env.${colors_1.white('DB' + index)} is not defined!`);
24
+ throw new Error(`getDB(${(0, colors_1.yellow)(index)}), but process.env.${(0, colors_1.white)('DB' + index)} is not defined!`);
25
25
  }
26
26
  const lib = require(libName);
27
27
  if (!lib.getDBAdapter) {
28
28
  throw new Error(`DB${index}=${libName}, but require('${libName}').getDBAdapter() is not defined`);
29
29
  }
30
- const cfg = nodejs_lib_1.secretOptional(`SECRET_DB${index}`);
30
+ const cfg = (0, nodejs_lib_1.secretOptional)(`SECRET_DB${index}`);
31
31
  return lib.getDBAdapter(cfg);
32
32
  });
package/dist/index.d.ts CHANGED
@@ -15,9 +15,7 @@ import { dbPipelineBackup, DBPipelineBackupOptions } from './pipeline/dbPipeline
15
15
  import { dbPipelineCopy, DBPipelineCopyOptions } from './pipeline/dbPipelineCopy';
16
16
  import { dbPipelineRestore, DBPipelineRestoreOptions } from './pipeline/dbPipelineRestore';
17
17
  import { DBQuery, DBQueryFilter, DBQueryFilterOperator, DBQueryFilterOperatorValues, DBQueryOrder, RunnableDBQuery } from './query/dbQuery';
18
- import { CommonSchema, CommonSchemaField, DATA_TYPE } from './schema/common.schema';
19
- import { CommonSchemaGenerator, CommonSchemaGeneratorCfg } from './schema/commonSchemaGenerator';
20
18
  import { DBTransaction, RunnableDBTransaction } from './transaction/dbTransaction';
21
19
  import { commitDBTransactionSimple, mergeDBOperations } from './transaction/dbTransaction.util';
22
- export type { DBQueryFilterOperator, DBQueryFilter, DBQueryOrder, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBCreateOptions, CommonDB, RunQueryResult, CreatedUpdated, CreatedUpdatedId, CreatedUpdatedVer, ObjectWithId, BaseDBEntity, SavedDBEntity, Saved, Unsaved, CommonDaoCfg, CommonDaoCreateIdHook, CommonDaoParseNaturalIdHook, CommonDaoBeforeCreateHook, CommonDaoBeforeDBMValidateHook, CommonDaoBeforeDBMToBMHook, CommonDaoBeforeBMToDBMHook, CommonDaoBeforeTMToBMHook, CommonDaoBeforeBMToTMHook, CommonDaoAnonymizeHook, InMemoryDBCfg, InMemoryKeyValueDBCfg, DBPipelineBackupOptions, DBPipelineRestoreOptions, DBPipelineCopyOptions, CommonSchema, CommonSchemaField, CommonSchemaGeneratorCfg, CommonDBAdapter, DBOperation, DBSaveBatchOperation, DBDeleteByIdsOperation, CommonKeyValueDB, CommonKeyValueDaoCfg, KeyValueDBTuple, };
23
- export { DBQuery, DBQueryFilterOperatorValues, RunnableDBQuery, CommonDaoLogLevel, DBRelation, DBModelType, baseDBEntitySchema, savedDBEntitySchema, CommonDao, createdUpdatedFields, createdUpdatedIdFields, idField, InMemoryDB, InMemoryKeyValueDB, queryInMemory, serializeJsonField, deserializeJsonField, dbPipelineBackup, dbPipelineRestore, dbPipelineCopy, DATA_TYPE, getDB, DBLibError, BaseCommonDB, DBTransaction, RunnableDBTransaction, mergeDBOperations, commitDBTransactionSimple, CommonSchemaGenerator, CommonKeyValueDao, };
20
+ export type { DBQueryFilterOperator, DBQueryFilter, DBQueryOrder, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBCreateOptions, CommonDB, RunQueryResult, CreatedUpdated, CreatedUpdatedId, CreatedUpdatedVer, ObjectWithId, BaseDBEntity, SavedDBEntity, Saved, Unsaved, CommonDaoCfg, CommonDaoCreateIdHook, CommonDaoParseNaturalIdHook, CommonDaoBeforeCreateHook, CommonDaoBeforeDBMValidateHook, CommonDaoBeforeDBMToBMHook, CommonDaoBeforeBMToDBMHook, CommonDaoBeforeTMToBMHook, CommonDaoBeforeBMToTMHook, CommonDaoAnonymizeHook, InMemoryDBCfg, InMemoryKeyValueDBCfg, DBPipelineBackupOptions, DBPipelineRestoreOptions, DBPipelineCopyOptions, CommonDBAdapter, DBOperation, DBSaveBatchOperation, DBDeleteByIdsOperation, CommonKeyValueDB, CommonKeyValueDaoCfg, KeyValueDBTuple, };
21
+ export { DBQuery, DBQueryFilterOperatorValues, RunnableDBQuery, CommonDaoLogLevel, DBRelation, DBModelType, baseDBEntitySchema, savedDBEntitySchema, CommonDao, createdUpdatedFields, createdUpdatedIdFields, idField, InMemoryDB, InMemoryKeyValueDB, queryInMemory, serializeJsonField, deserializeJsonField, dbPipelineBackup, dbPipelineRestore, dbPipelineCopy, getDB, DBLibError, BaseCommonDB, DBTransaction, RunnableDBTransaction, mergeDBOperations, commitDBTransactionSimple, CommonKeyValueDao, };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CommonKeyValueDao = exports.CommonSchemaGenerator = exports.commitDBTransactionSimple = exports.mergeDBOperations = exports.RunnableDBTransaction = exports.DBTransaction = exports.BaseCommonDB = exports.DBLibError = exports.getDB = exports.DATA_TYPE = exports.dbPipelineCopy = exports.dbPipelineRestore = exports.dbPipelineBackup = exports.deserializeJsonField = exports.serializeJsonField = exports.queryInMemory = exports.InMemoryKeyValueDB = exports.InMemoryDB = exports.idField = exports.createdUpdatedIdFields = exports.createdUpdatedFields = exports.CommonDao = exports.savedDBEntitySchema = exports.baseDBEntitySchema = exports.DBModelType = exports.DBRelation = exports.CommonDaoLogLevel = exports.RunnableDBQuery = exports.DBQueryFilterOperatorValues = exports.DBQuery = void 0;
3
+ exports.CommonKeyValueDao = exports.commitDBTransactionSimple = exports.mergeDBOperations = exports.RunnableDBTransaction = exports.DBTransaction = exports.BaseCommonDB = exports.DBLibError = exports.getDB = exports.dbPipelineCopy = exports.dbPipelineRestore = exports.dbPipelineBackup = exports.deserializeJsonField = exports.serializeJsonField = exports.queryInMemory = exports.InMemoryKeyValueDB = exports.InMemoryDB = exports.idField = exports.createdUpdatedIdFields = exports.createdUpdatedFields = exports.CommonDao = exports.savedDBEntitySchema = exports.baseDBEntitySchema = exports.DBModelType = exports.DBRelation = exports.CommonDaoLogLevel = exports.RunnableDBQuery = exports.DBQueryFilterOperatorValues = exports.DBQuery = void 0;
4
4
  const inMemory_db_1 = require("./adapter/inmemory/inMemory.db");
5
5
  Object.defineProperty(exports, "InMemoryDB", { enumerable: true, get: function () { return inMemory_db_1.InMemoryDB; } });
6
6
  const inMemoryKeyValueDB_1 = require("./adapter/inmemory/inMemoryKeyValueDB");
@@ -40,10 +40,6 @@ const dbQuery_1 = require("./query/dbQuery");
40
40
  Object.defineProperty(exports, "DBQuery", { enumerable: true, get: function () { return dbQuery_1.DBQuery; } });
41
41
  Object.defineProperty(exports, "DBQueryFilterOperatorValues", { enumerable: true, get: function () { return dbQuery_1.DBQueryFilterOperatorValues; } });
42
42
  Object.defineProperty(exports, "RunnableDBQuery", { enumerable: true, get: function () { return dbQuery_1.RunnableDBQuery; } });
43
- const common_schema_1 = require("./schema/common.schema");
44
- Object.defineProperty(exports, "DATA_TYPE", { enumerable: true, get: function () { return common_schema_1.DATA_TYPE; } });
45
- const commonSchemaGenerator_1 = require("./schema/commonSchemaGenerator");
46
- Object.defineProperty(exports, "CommonSchemaGenerator", { enumerable: true, get: function () { return commonSchemaGenerator_1.CommonSchemaGenerator; } });
47
43
  const dbTransaction_1 = require("./transaction/dbTransaction");
48
44
  Object.defineProperty(exports, "DBTransaction", { enumerable: true, get: function () { return dbTransaction_1.DBTransaction; } });
49
45
  Object.defineProperty(exports, "RunnableDBTransaction", { enumerable: true, get: function () { return dbTransaction_1.RunnableDBTransaction; } });
@@ -25,7 +25,7 @@ class CommonKeyValueDao {
25
25
  const entries = await this.cfg.db.getByIds(this.cfg.table, ids);
26
26
  if (!this.cfg.hooks?.mapBufferToValue)
27
27
  return entries;
28
- return await js_lib_1.pMap(entries, async ([id, buf]) => [
28
+ return await (0, js_lib_1.pMap)(entries, async ([id, buf]) => [
29
29
  id,
30
30
  await this.cfg.hooks.mapBufferToValue(buf),
31
31
  ]);
@@ -39,7 +39,7 @@ class CommonKeyValueDao {
39
39
  bufferEntries = entries;
40
40
  }
41
41
  else {
42
- bufferEntries = await js_lib_1.pMap(entries, async ([id, v]) => [
42
+ bufferEntries = await (0, js_lib_1.pMap)(entries, async ([id, v]) => [
43
43
  id,
44
44
  await this.cfg.hooks.mapValueToBuffer(v),
45
45
  ]);
@@ -58,7 +58,7 @@ class CommonKeyValueDao {
58
58
  }
59
59
  // todo: consider it when readableMap supports `errorMode: SUPPRESS`
60
60
  // readableMap(this.cfg.db.streamValues(this.cfg.table, limit), async buf => await this.cfg.hooks!.mapBufferToValue(buf))
61
- return this.cfg.db.streamValues(this.cfg.table, limit).pipe(nodejs_lib_1.transformMap(async (buf) => await this.cfg.hooks.mapBufferToValue(buf), {
61
+ return this.cfg.db.streamValues(this.cfg.table, limit).pipe((0, nodejs_lib_1.transformMap)(async (buf) => await this.cfg.hooks.mapBufferToValue(buf), {
62
62
  errorMode: js_lib_1.ErrorMode.SUPPRESS, // cause .pipe cannot propagate errors
63
63
  }));
64
64
  }
@@ -66,7 +66,7 @@ class CommonKeyValueDao {
66
66
  if (!this.cfg.hooks?.mapBufferToValue) {
67
67
  return this.cfg.db.streamEntries(this.cfg.table, limit);
68
68
  }
69
- return this.cfg.db.streamEntries(this.cfg.table, limit).pipe(nodejs_lib_1.transformMap(async ([id, buf]) => [id, await this.cfg.hooks.mapBufferToValue(buf)], {
69
+ return this.cfg.db.streamEntries(this.cfg.table, limit).pipe((0, nodejs_lib_1.transformMap)(async ([id, buf]) => [id, await this.cfg.hooks.mapBufferToValue(buf)], {
70
70
  errorMode: js_lib_1.ErrorMode.SUPPRESS, // cause .pipe cannot propagate errors
71
71
  }));
72
72
  }
@@ -14,14 +14,14 @@ function createdUpdatedIdFields(existingObject) {
14
14
  const now = Math.floor(Date.now() / 1000);
15
15
  return {
16
16
  created: existingObject?.created || now,
17
- id: existingObject?.id || nodejs_lib_1.stringId(),
17
+ id: existingObject?.id || (0, nodejs_lib_1.stringId)(),
18
18
  updated: now,
19
19
  };
20
20
  }
21
21
  exports.createdUpdatedIdFields = createdUpdatedIdFields;
22
22
  function idField(existingObject) {
23
23
  return {
24
- id: existingObject?.id || nodejs_lib_1.stringId(),
24
+ id: existingObject?.id || (0, nodejs_lib_1.stringId)(),
25
25
  };
26
26
  }
27
27
  exports.idField = idField;
@@ -76,7 +76,6 @@ export interface DBPipelineBackupOptions extends TransformLogProgressOptions {
76
76
  * @default false
77
77
  * If true - will use CommonSchemaGenerator to detect schema from input data.
78
78
  */
79
- emitSchemaFromData?: boolean;
80
79
  /**
81
80
  * @default false
82
81
  * If true - will use CommonDB.getTableSchema() and emit schema.
@@ -8,7 +8,6 @@ const time_lib_1 = require("@naturalcycles/time-lib");
8
8
  const fs = require("fs-extra");
9
9
  const zlib_1 = require("zlib");
10
10
  const index_1 = require("../index");
11
- const commonSchemaGenerator_1 = require("../schema/commonSchemaGenerator");
12
11
  // const log = Debug('nc:db-lib:pipeline')
13
12
  /**
14
13
  * Pipeline from input stream(s) to a NDJSON file (optionally gzipped).
@@ -20,19 +19,19 @@ const commonSchemaGenerator_1 = require("../schema/commonSchemaGenerator");
20
19
  * Optionally you can provide mapperPerTable and @param transformMapOptions (one for all mappers) - it will run for each table.
21
20
  */
22
21
  async function dbPipelineBackup(opt) {
23
- const { db, concurrency = 16, limit = 0, sinceUpdated, outputDirPath, protectFromOverwrite = false, zlibOptions, mapperPerTable = {}, transformMapOptions, errorMode = js_lib_1.ErrorMode.SUPPRESS, emitSchemaFromDB = false, emitSchemaFromData = false, sortObjects = false, } = opt;
22
+ const { db, concurrency = 16, limit = 0, sinceUpdated, outputDirPath, protectFromOverwrite = false, zlibOptions, mapperPerTable = {}, transformMapOptions, errorMode = js_lib_1.ErrorMode.SUPPRESS, emitSchemaFromDB = false, sortObjects = false, } = opt;
24
23
  const strict = errorMode !== js_lib_1.ErrorMode.SUPPRESS;
25
24
  const gzip = opt.gzip !== false; // default to true
26
25
  let { tables } = opt;
27
- const sinceUpdatedStr = sinceUpdated ? ' since ' + colors_1.grey(time_lib_1.dayjs.unix(sinceUpdated).toPretty()) : '';
28
- console.log(`>> ${colors_1.dimWhite('dbPipelineBackup')} started in ${colors_1.grey(outputDirPath)}...${sinceUpdatedStr}`);
26
+ const sinceUpdatedStr = sinceUpdated ? ' since ' + (0, colors_1.grey)(time_lib_1.dayjs.unix(sinceUpdated).toPretty()) : '';
27
+ console.log(`>> ${(0, colors_1.dimWhite)('dbPipelineBackup')} started in ${(0, colors_1.grey)(outputDirPath)}...${sinceUpdatedStr}`);
29
28
  fs.ensureDirSync(outputDirPath);
30
29
  if (!tables) {
31
30
  tables = await db.getTables();
32
31
  }
33
- console.log(`${colors_1.yellow(tables.length)} ${colors_1.boldWhite('table(s)')}:\n` + tables.join('\n'));
32
+ console.log(`${(0, colors_1.yellow)(tables.length)} ${(0, colors_1.boldWhite)('table(s)')}:\n` + tables.join('\n'));
34
33
  const statsPerTable = {};
35
- await js_lib_1.pMap(tables, async (table) => {
34
+ await (0, js_lib_1.pMap)(tables, async (table) => {
36
35
  let q = index_1.DBQuery.create(table).limit(limit);
37
36
  if (sinceUpdated) {
38
37
  q = q.filter('updated', '>=', sinceUpdated);
@@ -45,35 +44,30 @@ async function dbPipelineBackup(opt) {
45
44
  const started = Date.now();
46
45
  let rows = 0;
47
46
  await fs.ensureFile(filePath);
48
- console.log(`>> ${colors_1.grey(filePath)} started...`);
47
+ console.log(`>> ${(0, colors_1.grey)(filePath)} started...`);
49
48
  if (emitSchemaFromDB) {
50
49
  const schema = await db.getTableSchema(table);
51
50
  await fs.writeJson(schemaFilePath, schema, { spaces: 2 });
52
- console.log(`>> ${colors_1.grey(schemaFilePath)} saved (generated from DB)`);
51
+ console.log(`>> ${(0, colors_1.grey)(schemaFilePath)} saved (generated from DB)`);
53
52
  }
54
- const schemaGen = emitSchemaFromData
55
- ? new commonSchemaGenerator_1.CommonSchemaGenerator({ table, sortedFields: true })
56
- : undefined;
57
- await nodejs_lib_1._pipeline([
53
+ await (0, nodejs_lib_1._pipeline)([
58
54
  db.streamQuery(q),
59
- nodejs_lib_1.transformLogProgress({
55
+ (0, nodejs_lib_1.transformLogProgress)({
60
56
  logEvery: 1000,
61
57
  ...opt,
62
58
  metric: table,
63
59
  }),
64
- nodejs_lib_1.transformMap(mapperPerTable[table] || js_lib_1._passthroughMapper, {
60
+ (0, nodejs_lib_1.transformMap)(mapperPerTable[table] || js_lib_1._passthroughMapper, {
65
61
  errorMode,
66
62
  flattenArrayOutput: true,
67
63
  ...transformMapOptions,
68
64
  metric: table,
69
65
  }),
70
- nodejs_lib_1.transformTap(row => {
66
+ (0, nodejs_lib_1.transformTap)(() => {
71
67
  rows++;
72
- if (schemaGen)
73
- schemaGen.add(row);
74
68
  }),
75
- nodejs_lib_1.transformToNDJson({ strict, sortObjects }),
76
- ...(gzip ? [zlib_1.createGzip(zlibOptions)] : []),
69
+ (0, nodejs_lib_1.transformToNDJson)({ strict, sortObjects }),
70
+ ...(gzip ? [(0, zlib_1.createGzip)(zlibOptions)] : []),
77
71
  fs.createWriteStream(filePath),
78
72
  ]);
79
73
  const { size: sizeBytes } = await fs.stat(filePath);
@@ -82,12 +76,7 @@ async function dbPipelineBackup(opt) {
82
76
  rows,
83
77
  sizeBytes,
84
78
  });
85
- console.log(`>> ${colors_1.grey(filePath)}\n` + stats.toPretty());
86
- if (schemaGen) {
87
- const schema = schemaGen.generate();
88
- await fs.writeJson(schemaFilePath, schema, { spaces: 2 });
89
- console.log(`>> ${colors_1.grey(schemaFilePath)} saved (generated from data)`);
90
- }
79
+ console.log(`>> ${(0, colors_1.grey)(filePath)}\n` + stats.toPretty());
91
80
  statsPerTable[table] = stats;
92
81
  }, { concurrency, errorMode });
93
82
  const statsTotal = nodejs_lib_1.NDJsonStats.createCombined(Object.values(statsPerTable));