@naturalcycles/db-lib 8.12.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 (39) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/adapter/cachedb/cache.db.d.ts +3 -3
  3. package/dist/adapter/cachedb/cache.db.js +3 -3
  4. package/dist/adapter/file/file.db.d.ts +2 -2
  5. package/dist/adapter/file/file.db.js +4 -2
  6. package/dist/adapter/inmemory/inMemory.db.d.ts +3 -4
  7. package/dist/adapter/inmemory/inMemory.db.js +6 -4
  8. package/dist/base.common.db.d.ts +3 -3
  9. package/dist/base.common.db.js +9 -3
  10. package/dist/common.db.d.ts +3 -3
  11. package/dist/commondao/common.dao.d.ts +3 -4
  12. package/dist/commondao/common.dao.js +1 -1
  13. package/dist/index.d.ts +2 -4
  14. package/dist/index.js +1 -5
  15. package/dist/pipeline/dbPipelineBackup.d.ts +0 -1
  16. package/dist/pipeline/dbPipelineBackup.js +2 -13
  17. package/dist/pipeline/dbPipelineRestore.js +1 -1
  18. package/dist/testing/dbTest.js +1 -1
  19. package/dist/testing/test.model.d.ts +2 -2
  20. package/dist/testing/test.model.js +13 -2
  21. package/package.json +1 -1
  22. package/readme.md +5 -4
  23. package/src/adapter/cachedb/cache.db.ts +9 -5
  24. package/src/adapter/file/file.db.ts +7 -4
  25. package/src/adapter/inmemory/inMemory.db.ts +20 -7
  26. package/src/base.common.db.ts +10 -4
  27. package/src/common.db.ts +3 -3
  28. package/src/commondao/common.dao.ts +4 -4
  29. package/src/index.ts +0 -7
  30. package/src/pipeline/dbPipelineBackup.ts +2 -15
  31. package/src/pipeline/dbPipelineRestore.ts +1 -1
  32. package/src/testing/dbTest.ts +1 -1
  33. package/src/testing/test.model.ts +16 -4
  34. package/dist/schema/common.schema.d.ts +0 -38
  35. package/dist/schema/common.schema.js +0 -18
  36. package/dist/schema/commonSchemaGenerator.d.ts +0 -35
  37. package/dist/schema/commonSchemaGenerator.js +0 -151
  38. package/src/schema/common.schema.ts +0 -49
  39. package/src/schema/commonSchemaGenerator.ts +0 -200
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ # [8.13.0](https://github.com/NaturalCycles/db-lib/compare/v8.12.0...v8.13.0) (2021-10-01)
2
+
3
+
4
+ ### Features
5
+
6
+ * remove CommonSchema in favor of JsonSchema ([1827ec5](https://github.com/NaturalCycles/db-lib/commit/1827ec5709053b97a6b9e131f2ec0b40176c3e23))
7
+
1
8
  # [8.12.0](https://github.com/NaturalCycles/db-lib/compare/v8.11.2...v8.12.0) (2021-09-10)
2
9
 
3
10
 
@@ -1,11 +1,11 @@
1
1
  /// <reference types="node" />
2
+ import { JsonSchemaObject } from '@naturalcycles/js-lib';
2
3
  import { IDebugger } from '@naturalcycles/nodejs-lib';
3
4
  import { Readable } from 'stream';
4
5
  import { BaseCommonDB } from '../../base.common.db';
5
6
  import { CommonDB } from '../../common.db';
6
7
  import { ObjectWithId, RunQueryResult } from '../../db.model';
7
8
  import { DBQuery } from '../../query/dbQuery';
8
- import { CommonSchema } from '../../schema/common.schema';
9
9
  import { CacheDBCfg, CacheDBCreateOptions, CacheDBOptions, CacheDBStreamOptions } from './cache.db.model';
10
10
  /**
11
11
  * CommonDB implementation that proxies requests to downstream CommonDB
@@ -22,8 +22,8 @@ export declare class CacheDB extends BaseCommonDB implements CommonDB {
22
22
  * Resets InMemory DB data
23
23
  */
24
24
  getTables(): Promise<string[]>;
25
- getTableSchema<ROW extends ObjectWithId>(table: string): Promise<CommonSchema<ROW>>;
26
- createTable(schema: CommonSchema, opt?: CacheDBCreateOptions): Promise<void>;
25
+ getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>>;
26
+ createTable(table: string, schema: JsonSchemaObject, opt?: CacheDBCreateOptions): Promise<void>;
27
27
  getByIds<ROW extends ObjectWithId>(table: string, ids: string[], opt?: CacheDBOptions): Promise<ROW[]>;
28
28
  deleteByIds(table: string, ids: string[], opt?: CacheDBOptions): Promise<number>;
29
29
  saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], opt?: CacheDBOptions): Promise<void>;
@@ -33,12 +33,12 @@ class CacheDB extends base_common_db_1.BaseCommonDB {
33
33
  async getTableSchema(table) {
34
34
  return await this.cfg.downstreamDB.getTableSchema(table);
35
35
  }
36
- async createTable(schema, opt = {}) {
36
+ async createTable(table, schema, opt = {}) {
37
37
  if (!opt.onlyCache && !this.cfg.onlyCache) {
38
- await this.cfg.downstreamDB.createTable(schema, opt);
38
+ await this.cfg.downstreamDB.createTable(table, schema, opt);
39
39
  }
40
40
  if (!opt.skipCache && !this.cfg.skipCache) {
41
- await this.cfg.cacheDB.createTable(schema, opt);
41
+ await this.cfg.cacheDB.createTable(table, schema, opt);
42
42
  }
43
43
  }
44
44
  async getByIds(table, ids, opt = {}) {
@@ -1,6 +1,6 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib';
1
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib';
2
3
  import { BaseCommonDB, DBSaveBatchOperation, ObjectWithId } from '../..';
3
- import { CommonSchema } from '../..';
4
4
  import { CommonDB } from '../../common.db';
5
5
  import { CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, RunQueryResult } from '../../db.model';
6
6
  import { DBQuery } from '../../query/dbQuery';
@@ -32,7 +32,7 @@ export declare class FileDB extends BaseCommonDB implements CommonDB {
32
32
  streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CommonDBStreamOptions): ReadableTyped<ROW>;
33
33
  deleteByIds<ROW extends ObjectWithId>(table: string, ids: string[], _opt?: CommonDBOptions): Promise<number>;
34
34
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
35
- getTableSchema<ROW extends ObjectWithId>(table: string): Promise<CommonSchema<ROW>>;
35
+ getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>>;
36
36
  loadFile<ROW extends ObjectWithId>(table: string): Promise<ROW[]>;
37
37
  saveFile<ROW extends ObjectWithId>(table: string, _rows: ROW[]): Promise<void>;
38
38
  saveFiles(ops: DBSaveBatchOperation[]): Promise<void>;
@@ -5,7 +5,6 @@ const js_lib_1 = require("@naturalcycles/js-lib");
5
5
  const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
6
  const colors_1 = require("@naturalcycles/nodejs-lib/dist/colors");
7
7
  const __1 = require("../..");
8
- const __2 = require("../..");
9
8
  const log = (0, nodejs_lib_1.Debug)('nc:db-lib:filedb');
10
9
  /**
11
10
  * Provides barebone implementation for "whole file" based CommonDB.
@@ -140,7 +139,10 @@ class FileDB extends __1.BaseCommonDB {
140
139
  }
141
140
  async getTableSchema(table) {
142
141
  const rows = await this.loadFile(table);
143
- return __2.CommonSchemaGenerator.generateFromRows({ table }, rows);
142
+ return {
143
+ ...(0, js_lib_1.generateJsonSchemaFromData)(rows),
144
+ $id: `${table}.schema.json`,
145
+ };
144
146
  }
145
147
  // wrapper, to handle logging
146
148
  async loadFile(table) {
@@ -1,7 +1,6 @@
1
- import { StringMap } from '@naturalcycles/js-lib';
1
+ import { JsonSchemaObject, StringMap } from '@naturalcycles/js-lib';
2
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
3
  import { CommonDB, DBTransaction, ObjectWithId } from '../..';
4
- import { CommonSchema } from '../..';
5
4
  import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions, RunQueryResult } from '../../db.model';
6
5
  import { DBQuery } from '../../query/dbQuery';
7
6
  export interface InMemoryDBCfg {
@@ -47,8 +46,8 @@ export declare class InMemoryDB implements CommonDB {
47
46
  */
48
47
  resetCache(_table?: string): Promise<void>;
49
48
  getTables(): Promise<string[]>;
50
- getTableSchema<ROW extends ObjectWithId>(_table: string): Promise<CommonSchema<ROW>>;
51
- createTable(schema: CommonSchema, opt?: CommonDBCreateOptions): Promise<void>;
49
+ getTableSchema<ROW extends ObjectWithId>(_table: string): Promise<JsonSchemaObject<ROW>>;
50
+ createTable(_table: string, _schema: JsonSchemaObject, opt?: CommonDBCreateOptions): Promise<void>;
52
51
  getByIds<ROW extends ObjectWithId>(_table: string, ids: string[], _opt?: CommonDBOptions): Promise<ROW[]>;
53
52
  saveBatch<ROW extends ObjectWithId>(_table: string, rows: ROW[], _opt?: CommonDBSaveOptions): Promise<void>;
54
53
  deleteByIds(_table: string, ids: string[], _opt?: CommonDBOptions): Promise<number>;
@@ -8,7 +8,6 @@ const fs = require("fs-extra");
8
8
  const stream_1 = require("stream");
9
9
  const zlib_1 = require("zlib");
10
10
  const __1 = require("../..");
11
- const __2 = require("../..");
12
11
  const log = (0, nodejs_lib_1.Debug)('nc:db-lib:inmemorydb');
13
12
  class InMemoryDB {
14
13
  constructor(cfg) {
@@ -53,10 +52,13 @@ class InMemoryDB {
53
52
  }
54
53
  async getTableSchema(_table) {
55
54
  const table = this.cfg.tablesPrefix + _table;
56
- return __2.CommonSchemaGenerator.generateFromRows({ table }, Object.values(this.data[table] || {}));
55
+ return {
56
+ ...(0, js_lib_1.generateJsonSchemaFromData)(Object.values(this.data[table] || {})),
57
+ $id: `${table}.schema.json`,
58
+ };
57
59
  }
58
- async createTable(schema, opt = {}) {
59
- const table = this.cfg.tablesPrefix + schema.table;
60
+ async createTable(_table, _schema, opt = {}) {
61
+ const table = this.cfg.tablesPrefix + _table;
60
62
  if (opt.dropIfExists) {
61
63
  this.data[table] = {};
62
64
  }
@@ -1,8 +1,8 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib';
1
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib';
2
3
  import { CommonDB } from './common.db';
3
4
  import { CommonDBSaveOptions, ObjectWithId, RunQueryResult } from './db.model';
4
5
  import { DBQuery } from './query/dbQuery';
5
- import { CommonSchema } from './schema/common.schema';
6
6
  import { DBTransaction } from './transaction/dbTransaction';
7
7
  /**
8
8
  * No-op implementation of CommonDB interface.
@@ -11,8 +11,8 @@ import { DBTransaction } from './transaction/dbTransaction';
11
11
  export declare class BaseCommonDB implements CommonDB {
12
12
  ping(): Promise<void>;
13
13
  getTables(): Promise<string[]>;
14
- getTableSchema<ROW>(table: string): Promise<CommonSchema<ROW>>;
15
- createTable(_schema: CommonSchema): Promise<void>;
14
+ getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>>;
15
+ createTable(_table: string, _schema: JsonSchemaObject): Promise<void>;
16
16
  deleteByIds(_table: string, _ids: string[]): Promise<number>;
17
17
  deleteByQuery<ROW extends ObjectWithId>(_q: DBQuery<ROW>): Promise<number>;
18
18
  getByIds<ROW extends ObjectWithId>(_table: string, _ids: string[]): Promise<ROW[]>;
@@ -13,9 +13,15 @@ class BaseCommonDB {
13
13
  return [];
14
14
  }
15
15
  async getTableSchema(table) {
16
- return { table, fields: [] };
17
- }
18
- async createTable(_schema) { }
16
+ return {
17
+ $id: `${table}.schema.json`,
18
+ type: 'object',
19
+ additionalProperties: true,
20
+ properties: {},
21
+ required: [],
22
+ };
23
+ }
24
+ async createTable(_table, _schema) { }
19
25
  async deleteByIds(_table, _ids) {
20
26
  return 0;
21
27
  }
@@ -1,7 +1,7 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib';
1
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib';
2
3
  import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, ObjectWithId, RunQueryResult } from './db.model';
3
4
  import { DBQuery } from './query/dbQuery';
4
- import { CommonSchema } from './schema/common.schema';
5
5
  import { DBTransaction } from './transaction/dbTransaction';
6
6
  export interface CommonDB {
7
7
  /**
@@ -15,12 +15,12 @@ export interface CommonDB {
15
15
  * Return all tables (table names) available in this DB.
16
16
  */
17
17
  getTables(): Promise<string[]>;
18
- getTableSchema<ROW extends ObjectWithId>(table: string): Promise<CommonSchema<ROW>>;
18
+ getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>>;
19
19
  /**
20
20
  * Will do like `create table ...` for mysql.
21
21
  * Caution! dropIfExists defaults to false. If set to true - will actually DROP the table!
22
22
  */
23
- createTable(schema: CommonSchema, opt?: CommonDBCreateOptions): Promise<void>;
23
+ createTable(table: string, schema: JsonSchemaObject, opt?: CommonDBCreateOptions): Promise<void>;
24
24
  /**
25
25
  * Order of items returned is not guaranteed to match order of ids.
26
26
  * (Such limitation exists because Datastore doesn't support it).
@@ -1,8 +1,7 @@
1
- import { AsyncMapper } from '@naturalcycles/js-lib';
1
+ import { AsyncMapper, JsonSchemaObject } from '@naturalcycles/js-lib';
2
2
  import { AjvSchema, ObjectSchemaTyped, ReadableTyped } from '@naturalcycles/nodejs-lib';
3
3
  import { DBModelType, ObjectWithId, RunQueryResult, Saved } from '../db.model';
4
4
  import { DBQuery, RunnableDBQuery } from '../query/dbQuery';
5
- import { CommonSchema } from '../schema/common.schema';
6
5
  import { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions } from './common.dao.model';
7
6
  /**
8
7
  * Lowest common denominator API between supported Databases.
@@ -120,8 +119,8 @@ export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends Obj
120
119
  * Does NOT mutate the object.
121
120
  */
122
121
  validateAndConvert<IN, OUT = IN>(obj: IN, schema?: ObjectSchemaTyped<IN> | AjvSchema<IN>, modelType?: DBModelType, opt?: CommonDaoOptions): OUT;
123
- getTableSchema(): Promise<CommonSchema>;
124
- createTable(schema: CommonSchema, opt?: CommonDaoCreateOptions): Promise<void>;
122
+ getTableSchema(): Promise<JsonSchemaObject<DBM>>;
123
+ createTable(schema: JsonSchemaObject<DBM>, opt?: CommonDaoCreateOptions): Promise<void>;
125
124
  /**
126
125
  * Proxy to this.cfg.db.ping
127
126
  */
@@ -659,7 +659,7 @@ class CommonDao {
659
659
  }
660
660
  async createTable(schema, opt) {
661
661
  this.requireWriteAccess();
662
- await this.cfg.db.createTable(schema, opt);
662
+ await this.cfg.db.createTable(this.cfg.table, schema, opt);
663
663
  }
664
664
  /**
665
665
  * Proxy to this.cfg.db.ping
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; } });
@@ -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,7 +19,7 @@ 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;
@@ -51,9 +50,6 @@ async function dbPipelineBackup(opt) {
51
50
  await fs.writeJson(schemaFilePath, schema, { spaces: 2 });
52
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
53
  await (0, nodejs_lib_1._pipeline)([
58
54
  db.streamQuery(q),
59
55
  (0, nodejs_lib_1.transformLogProgress)({
@@ -67,10 +63,8 @@ async function dbPipelineBackup(opt) {
67
63
  ...transformMapOptions,
68
64
  metric: table,
69
65
  }),
70
- (0, nodejs_lib_1.transformTap)(row => {
66
+ (0, nodejs_lib_1.transformTap)(() => {
71
67
  rows++;
72
- if (schemaGen)
73
- schemaGen.add(row);
74
68
  }),
75
69
  (0, nodejs_lib_1.transformToNDJson)({ strict, sortObjects }),
76
70
  ...(gzip ? [(0, zlib_1.createGzip)(zlibOptions)] : []),
@@ -83,11 +77,6 @@ async function dbPipelineBackup(opt) {
83
77
  sizeBytes,
84
78
  });
85
79
  console.log(`>> ${(0, 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(`>> ${(0, colors_1.grey)(schemaFilePath)} saved (generated from data)`);
90
- }
91
80
  statsPerTable[table] = stats;
92
81
  }, { concurrency, errorMode });
93
82
  const statsTotal = nodejs_lib_1.NDJsonStats.createCombined(Object.values(statsPerTable));
@@ -56,7 +56,7 @@ async function dbPipelineRestore(opt) {
56
56
  return;
57
57
  }
58
58
  const schema = await fs.readJson(schemaFilePath);
59
- await db.createTable(schema, { dropIfExists: true });
59
+ await db.createTable(table, schema, { dropIfExists: true });
60
60
  });
61
61
  }
62
62
  await (0, js_lib_1.pMap)(tables, async (table) => {
@@ -28,7 +28,7 @@ function runCommonDBTest(db, features = {}, quirks = {}) {
28
28
  // CREATE TABLE, DROP
29
29
  if (createTable) {
30
30
  test('createTable, dropIfExists=true', async () => {
31
- await db.createTable((0, test_model_1.getTestItemSchema)(), { dropIfExists: true });
31
+ await db.createTable(test_model_1.TEST_TABLE, (0, test_model_1.getTestItemSchema)(), { dropIfExists: true });
32
32
  });
33
33
  }
34
34
  if (querying) {
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { CommonSchema } from '..';
2
+ import { JsonSchemaObject } from '@naturalcycles/js-lib';
3
3
  import { BaseDBEntity, Saved } from '../db.model';
4
4
  export declare const TEST_TABLE = "TEST_TABLE";
5
5
  export interface TestItemBM extends BaseDBEntity {
@@ -24,4 +24,4 @@ export declare function createTestItemDBM(num?: number): TestItemDBM;
24
24
  export declare function createTestItemBM(num?: number): Saved<TestItemBM>;
25
25
  export declare function createTestItemsDBM(count?: number): TestItemDBM[];
26
26
  export declare function createTestItemsBM(count?: number): Saved<TestItemBM>[];
27
- export declare function getTestItemSchema(): CommonSchema<TestItemDBM>;
27
+ export declare function getTestItemSchema(): JsonSchemaObject<TestItemDBM>;
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getTestItemSchema = exports.createTestItemsBM = exports.createTestItemsDBM = exports.createTestItemBM = exports.createTestItemDBM = exports.testItemDBMJsonSchema = exports.testItemBMJsonSchema = exports.testItemTMSchema = exports.testItemDBMSchema = exports.testItemBMSchema = exports.TEST_TABLE = void 0;
4
4
  const js_lib_1 = require("@naturalcycles/js-lib");
5
5
  const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
- const __1 = require("..");
7
6
  const db_model_1 = require("../db.model");
8
7
  const MOCK_TS_2018_06_21 = 1529539200;
9
8
  exports.TEST_TABLE = 'TEST_TABLE';
@@ -69,7 +68,19 @@ function createTestItemsBM(count = 1) {
69
68
  return (0, js_lib_1._range)(1, count + 1).map(num => createTestItemBM(num));
70
69
  }
71
70
  exports.createTestItemsBM = createTestItemsBM;
71
+ const testItemJsonSchema = js_lib_1.jsonSchema
72
+ .object({
73
+ id: js_lib_1.jsonSchema.string(),
74
+ k1: js_lib_1.jsonSchema.string(),
75
+ k2: js_lib_1.jsonSchema.string(),
76
+ k3: js_lib_1.jsonSchema.number(),
77
+ even: js_lib_1.jsonSchema.boolean(),
78
+ created: js_lib_1.jsonSchema.unixTimestamp(),
79
+ updated: js_lib_1.jsonSchema.unixTimestamp(),
80
+ })
81
+ .build();
72
82
  function getTestItemSchema() {
73
- return __1.CommonSchemaGenerator.generateFromRows({ table: exports.TEST_TABLE }, createTestItemsDBM());
83
+ // return CommonSchemaGenerator.generateFromRows({ table: TEST_TABLE }, createTestItemsDBM())
84
+ return testItemJsonSchema;
74
85
  }
75
86
  exports.getTestItemSchema = getTestItemSchema;
package/package.json CHANGED
@@ -42,7 +42,7 @@
42
42
  "engines": {
43
43
  "node": ">=12.13"
44
44
  },
45
- "version": "8.12.0",
45
+ "version": "8.13.0",
46
46
  "description": "Lowest Common Denominator API to supported Databases",
47
47
  "keywords": [
48
48
  "db",
package/readme.md CHANGED
@@ -216,19 +216,20 @@ await db.getTables()
216
216
 
217
217
  ###### getTableSchema
218
218
 
219
- `getTableSchema(table: string): Promise<CommonSchema>`
219
+ `getTableSchema(table: string): Promise<JsonSchemaObject>`
220
220
 
221
221
  ```typescript
222
222
  await db.getTableSchema('table1')
223
- // todo: describe CommonSchema example
224
223
  ```
225
224
 
225
+ Returns a JsonSchema, generated from the table.
226
+
226
227
  ###### createTable
227
228
 
228
- `createTable(schema: CommonSchema): Promise<void>`
229
+ `createTable(table: string, schema: JsonSchemaObject): Promise<void>`
229
230
 
230
231
  Applicable to Relational DBs, like MySQL. Will invoke smth like `create table Table1 ... ;`. Takes a
231
- `CommonSchema` as an argument.
232
+ `JsonSchema` as an argument.
232
233
 
233
234
  # DBQuery
234
235
 
@@ -1,10 +1,10 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib'
1
2
  import { Debug, IDebugger } from '@naturalcycles/nodejs-lib'
2
3
  import { Readable } from 'stream'
3
4
  import { BaseCommonDB } from '../../base.common.db'
4
5
  import { CommonDB } from '../../common.db'
5
6
  import { ObjectWithId, RunQueryResult } from '../../db.model'
6
7
  import { DBQuery } from '../../query/dbQuery'
7
- import { CommonSchema } from '../../schema/common.schema'
8
8
  import {
9
9
  CacheDBCfg,
10
10
  CacheDBCreateOptions,
@@ -45,17 +45,21 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
45
45
 
46
46
  override async getTableSchema<ROW extends ObjectWithId>(
47
47
  table: string,
48
- ): Promise<CommonSchema<ROW>> {
48
+ ): Promise<JsonSchemaObject<ROW>> {
49
49
  return await this.cfg.downstreamDB.getTableSchema<ROW>(table)
50
50
  }
51
51
 
52
- override async createTable(schema: CommonSchema, opt: CacheDBCreateOptions = {}): Promise<void> {
52
+ override async createTable(
53
+ table: string,
54
+ schema: JsonSchemaObject,
55
+ opt: CacheDBCreateOptions = {},
56
+ ): Promise<void> {
53
57
  if (!opt.onlyCache && !this.cfg.onlyCache) {
54
- await this.cfg.downstreamDB.createTable(schema, opt)
58
+ await this.cfg.downstreamDB.createTable(table, schema, opt)
55
59
  }
56
60
 
57
61
  if (!opt.skipCache && !this.cfg.skipCache) {
58
- await this.cfg.cacheDB.createTable(schema, opt)
62
+ await this.cfg.cacheDB.createTable(table, schema, opt)
59
63
  }
60
64
  }
61
65
 
@@ -1,4 +1,6 @@
1
1
  import {
2
+ generateJsonSchemaFromData,
3
+ JsonSchemaObject,
2
4
  pMap,
3
5
  StringMap,
4
6
  _by,
@@ -12,8 +14,6 @@ import {
12
14
  import { Debug, readableCreate, ReadableTyped } from '@naturalcycles/nodejs-lib'
13
15
  import { dimGrey } from '@naturalcycles/nodejs-lib/dist/colors'
14
16
  import { BaseCommonDB, DBSaveBatchOperation, ObjectWithId, queryInMemory } from '../..'
15
- import { CommonSchema } from '../..'
16
- import { CommonSchemaGenerator } from '../..'
17
17
  import { CommonDB } from '../../common.db'
18
18
  import {
19
19
  CommonDBOptions,
@@ -213,9 +213,12 @@ export class FileDB extends BaseCommonDB implements CommonDB {
213
213
 
214
214
  override async getTableSchema<ROW extends ObjectWithId>(
215
215
  table: string,
216
- ): Promise<CommonSchema<ROW>> {
216
+ ): Promise<JsonSchemaObject<ROW>> {
217
217
  const rows = await this.loadFile(table)
218
- return CommonSchemaGenerator.generateFromRows({ table }, rows)
218
+ return {
219
+ ...generateJsonSchemaFromData(rows),
220
+ $id: `${table}.schema.json`,
221
+ } as JsonSchemaObject<ROW>
219
222
  }
220
223
 
221
224
  // wrapper, to handle logging
@@ -1,4 +1,12 @@
1
- import { pMap, StringMap, _by, _since, _sortObjectDeep } from '@naturalcycles/js-lib'
1
+ import {
2
+ generateJsonSchemaFromData,
3
+ JsonSchemaObject,
4
+ pMap,
5
+ StringMap,
6
+ _by,
7
+ _since,
8
+ _sortObjectDeep,
9
+ } from '@naturalcycles/js-lib'
2
10
  import {
3
11
  bufferReviver,
4
12
  Debug,
@@ -14,8 +22,6 @@ import * as fs from 'fs-extra'
14
22
  import { Readable } from 'stream'
15
23
  import { createGzip, createUnzip } from 'zlib'
16
24
  import { CommonDB, DBTransaction, ObjectWithId, queryInMemory } from '../..'
17
- import { CommonSchema } from '../..'
18
- import { CommonSchemaGenerator } from '../..'
19
25
  import {
20
26
  CommonDBCreateOptions,
21
27
  CommonDBOptions,
@@ -105,13 +111,20 @@ export class InMemoryDB implements CommonDB {
105
111
  return Object.keys(this.data).filter(t => t.startsWith(this.cfg.tablesPrefix))
106
112
  }
107
113
 
108
- async getTableSchema<ROW extends ObjectWithId>(_table: string): Promise<CommonSchema<ROW>> {
114
+ async getTableSchema<ROW extends ObjectWithId>(_table: string): Promise<JsonSchemaObject<ROW>> {
109
115
  const table = this.cfg.tablesPrefix + _table
110
- return CommonSchemaGenerator.generateFromRows({ table }, Object.values(this.data[table] || {}))
116
+ return {
117
+ ...generateJsonSchemaFromData(Object.values(this.data[table] || {})),
118
+ $id: `${table}.schema.json`,
119
+ } as JsonSchemaObject<ROW>
111
120
  }
112
121
 
113
- async createTable(schema: CommonSchema, opt: CommonDBCreateOptions = {}): Promise<void> {
114
- const table = this.cfg.tablesPrefix + schema.table
122
+ async createTable(
123
+ _table: string,
124
+ _schema: JsonSchemaObject,
125
+ opt: CommonDBCreateOptions = {},
126
+ ): Promise<void> {
127
+ const table = this.cfg.tablesPrefix + _table
115
128
  if (opt.dropIfExists) {
116
129
  this.data[table] = {}
117
130
  } else {
@@ -1,9 +1,9 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib'
1
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib'
2
3
  import { Readable } from 'stream'
3
4
  import { CommonDB } from './common.db'
4
5
  import { CommonDBSaveOptions, ObjectWithId, RunQueryResult } from './db.model'
5
6
  import { DBQuery } from './query/dbQuery'
6
- import { CommonSchema } from './schema/common.schema'
7
7
  import { DBTransaction } from './transaction/dbTransaction'
8
8
  import { commitDBTransactionSimple } from './transaction/dbTransaction.util'
9
9
 
@@ -18,11 +18,17 @@ export class BaseCommonDB implements CommonDB {
18
18
  return []
19
19
  }
20
20
 
21
- async getTableSchema<ROW>(table: string): Promise<CommonSchema<ROW>> {
22
- return { table, fields: [] }
21
+ async getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>> {
22
+ return {
23
+ $id: `${table}.schema.json`,
24
+ type: 'object',
25
+ additionalProperties: true,
26
+ properties: {} as any,
27
+ required: [],
28
+ }
23
29
  }
24
30
 
25
- async createTable(_schema: CommonSchema): Promise<void> {}
31
+ async createTable(_table: string, _schema: JsonSchemaObject): Promise<void> {}
26
32
 
27
33
  async deleteByIds(_table: string, _ids: string[]): Promise<number> {
28
34
  return 0
package/src/common.db.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { JsonSchemaObject } from '@naturalcycles/js-lib'
1
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib'
2
3
  import {
3
4
  CommonDBCreateOptions,
@@ -8,7 +9,6 @@ import {
8
9
  RunQueryResult,
9
10
  } from './db.model'
10
11
  import { DBQuery } from './query/dbQuery'
11
- import { CommonSchema } from './schema/common.schema'
12
12
  import { DBTransaction } from './transaction/dbTransaction'
13
13
 
14
14
  export interface CommonDB {
@@ -25,13 +25,13 @@ export interface CommonDB {
25
25
  */
26
26
  getTables(): Promise<string[]>
27
27
 
28
- getTableSchema<ROW extends ObjectWithId>(table: string): Promise<CommonSchema<ROW>>
28
+ getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaObject<ROW>>
29
29
 
30
30
  /**
31
31
  * Will do like `create table ...` for mysql.
32
32
  * Caution! dropIfExists defaults to false. If set to true - will actually DROP the table!
33
33
  */
34
- createTable(schema: CommonSchema, opt?: CommonDBCreateOptions): Promise<void>
34
+ createTable(table: string, schema: JsonSchemaObject, opt?: CommonDBCreateOptions): Promise<void>
35
35
 
36
36
  // GET
37
37
  /**