@naturalcycles/db-lib 9.4.1 → 9.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import { Transform } from 'node:stream';
3
- import { AnyObject, AsyncMapper, BaseDBEntity, CommonLogger, JsonSchemaObject, JsonSchemaRootObject, Saved, UnixTimestampMillisNumber, UnsavedId, ZodSchema } from '@naturalcycles/js-lib';
3
+ import { AnyObject, AsyncMapper, BaseDBEntity, CommonLogger, JsonSchemaObject, JsonSchemaRootObject, UnixTimestampMillisNumber, Unsaved, ZodSchema } from '@naturalcycles/js-lib';
4
4
  import { AjvSchema, ObjectSchema, ReadableTyped } from '@naturalcycles/nodejs-lib';
5
5
  import { CommonDBTransactionOptions, DBModelType, DBPatch, DBTransaction, RunQueryResult } from '../db.model';
6
6
  import { DBQuery, RunnableDBQuery } from '../query/dbQuery';
@@ -15,19 +15,19 @@ import { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveBa
15
15
  export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity = BM, TM extends AnyObject = BM> {
16
16
  cfg: CommonDaoCfg<BM, DBM, TM>;
17
17
  constructor(cfg: CommonDaoCfg<BM, DBM, TM>);
18
- create(part?: Partial<BM>, opt?: CommonDaoOptions): Saved<BM>;
18
+ create(part?: Partial<BM>, opt?: CommonDaoOptions): BM;
19
19
  getById(id: undefined | null, opt?: CommonDaoOptions): Promise<null>;
20
- getById(id?: string | null, opt?: CommonDaoOptions): Promise<Saved<BM> | null>;
21
- getByIdOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<Saved<BM>>;
22
- getByIdAsDBMOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<Saved<DBM>>;
20
+ getById(id?: string | null, opt?: CommonDaoOptions): Promise<BM | null>;
21
+ getByIdOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<BM>;
22
+ getByIdAsDBMOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<DBM>;
23
23
  getByIdAsDBM(id: undefined | null, opt?: CommonDaoOptions): Promise<null>;
24
- getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise<Saved<DBM> | null>;
24
+ getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise<DBM | null>;
25
25
  getByIdAsTM(id: undefined | null, opt?: CommonDaoOptions): Promise<null>;
26
26
  getByIdAsTM(id?: string | null, opt?: CommonDaoOptions): Promise<TM | null>;
27
- getByIds(ids: string[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
28
- getByIdsAsDBM(ids: string[], opt?: CommonDaoOptions): Promise<Saved<DBM>[]>;
29
- requireById(id: string, opt?: CommonDaoOptions): Promise<Saved<BM>>;
30
- requireByIdAsDBM(id: string, opt?: CommonDaoOptions): Promise<Saved<DBM>>;
27
+ getByIds(ids: string[], opt?: CommonDaoOptions): Promise<BM[]>;
28
+ getByIdsAsDBM(ids: string[], opt?: CommonDaoOptions): Promise<DBM[]>;
29
+ requireById(id: string, opt?: CommonDaoOptions): Promise<BM>;
30
+ requireByIdAsDBM(id: string, opt?: CommonDaoOptions): Promise<DBM>;
31
31
  private throwRequiredError;
32
32
  /**
33
33
  * Throws if readOnly is true
@@ -38,33 +38,33 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
38
38
  */
39
39
  private requireObjectMutability;
40
40
  private ensureUniqueId;
41
- getBy(by: keyof DBM, value: any, limit?: number, opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
42
- getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise<Saved<BM> | null>;
43
- getAll(opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
41
+ getBy(by: keyof DBM, value: any, limit?: number, opt?: CommonDaoOptions): Promise<BM[]>;
42
+ getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise<BM | null>;
43
+ getAll(opt?: CommonDaoOptions): Promise<BM[]>;
44
44
  /**
45
45
  * Pass `table` to override table
46
46
  */
47
47
  query(table?: string): RunnableDBQuery<BM, DBM, TM>;
48
- runQuery(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
48
+ runQuery(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<BM[]>;
49
49
  runQuerySingleColumn<T = any>(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<T[]>;
50
50
  /**
51
51
  * Convenience method that runs multiple queries in parallel and then merges their results together.
52
52
  * Does deduplication by id.
53
53
  * Order is not guaranteed, as queries run in parallel.
54
54
  */
55
- runUnionQueries(queries: DBQuery<DBM>[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
56
- runQueryExtended(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<BM>>>;
57
- runQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<Saved<DBM>[]>;
58
- runQueryExtendedAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<DBM>>>;
55
+ runUnionQueries(queries: DBQuery<DBM>[], opt?: CommonDaoOptions): Promise<BM[]>;
56
+ runQueryExtended(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<RunQueryResult<BM>>;
57
+ runQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<DBM[]>;
58
+ runQueryExtendedAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<RunQueryResult<DBM>>;
59
59
  runQueryAsTM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<TM[]>;
60
60
  runQueryExtendedAsTM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<RunQueryResult<TM>>;
61
61
  runQueryCount(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<number>;
62
- streamQueryForEach(q: DBQuery<DBM>, mapper: AsyncMapper<Saved<BM>, void>, opt?: CommonDaoStreamForEachOptions<Saved<BM>>): Promise<void>;
63
- streamQueryAsDBMForEach(q: DBQuery<DBM>, mapper: AsyncMapper<Saved<DBM>, void>, opt?: CommonDaoStreamForEachOptions<DBM>): Promise<void>;
62
+ streamQueryForEach(q: DBQuery<DBM>, mapper: AsyncMapper<BM, void>, opt?: CommonDaoStreamForEachOptions<BM>): Promise<void>;
63
+ streamQueryAsDBMForEach(q: DBQuery<DBM>, mapper: AsyncMapper<DBM, void>, opt?: CommonDaoStreamForEachOptions<DBM>): Promise<void>;
64
64
  /**
65
65
  * Stream as Readable, to be able to .pipe() it further with support of backpressure.
66
66
  */
67
- streamQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<Saved<DBM>>;
67
+ streamQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<DBM>;
68
68
  /**
69
69
  * Stream as Readable, to be able to .pipe() it further with support of backpressure.
70
70
  *
@@ -74,7 +74,7 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
74
74
  *
75
75
  * You can do `.pipe(transformNoOp)` to make it "valid again".
76
76
  */
77
- streamQuery(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions<Saved<BM>>): ReadableTyped<Saved<BM>>;
77
+ streamQuery(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions<BM>): ReadableTyped<BM>;
78
78
  queryIds(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<string[]>;
79
79
  streamQueryIds(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions<string>): ReadableTyped<string>;
80
80
  streamQueryIdsForEach(q: DBQuery<DBM>, mapper: AsyncMapper<string, void>, opt?: CommonDaoStreamForEachOptions<string>): Promise<void>;
@@ -86,7 +86,7 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
86
86
  /**
87
87
  * Mutates with id, created, updated
88
88
  */
89
- save(bm: UnsavedId<BM>, opt?: CommonDaoSaveOptions<BM, DBM>): Promise<Saved<BM>>;
89
+ save(bm: Unsaved<BM>, opt?: CommonDaoSaveOptions<BM, DBM>): Promise<BM>;
90
90
  /**
91
91
  * 1. Applies the patch
92
92
  * 2. If object is the same after patching - skips saving it
@@ -95,7 +95,7 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
95
95
  * Similar to `save` with skipIfEquals.
96
96
  * Similar to `patch`, but doesn't load the object from the Database.
97
97
  */
98
- savePatch(bm: BM, patch: Partial<BM>, opt: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
98
+ savePatch(bm: BM, patch: Partial<BM>, opt: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
99
99
  /**
100
100
  * Convenience method to replace 3 operations (loading+patching+saving) with one:
101
101
  *
@@ -105,25 +105,25 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
105
105
  * 2. Applies the patch on top of loaded data.
106
106
  * 3. Saves (as fast as possible since the read) with the Patch applied, but only if the data has changed.
107
107
  */
108
- patchById(id: string, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
108
+ patchById(id: string, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
109
109
  /**
110
110
  * Like patchById, but runs all operations within a Transaction.
111
111
  */
112
- patchByIdInTransaction(id: string, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
112
+ patchByIdInTransaction(id: string, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
113
113
  /**
114
114
  * Same as patchById, but takes the whole object as input.
115
115
  * This "whole object" is mutated with the patch and returned.
116
116
  * Otherwise, similar behavior as patchById.
117
117
  * It still loads the row from the DB.
118
118
  */
119
- patch(bm: BM, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
119
+ patch(bm: BM, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
120
120
  /**
121
121
  * Like patch, but runs all operations within a Transaction.
122
122
  */
123
- patchInTransaction(bm: BM, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
124
- saveAsDBM(dbm: UnsavedId<DBM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<DBM>>;
125
- saveBatch(bms: UnsavedId<BM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>[]>;
126
- saveBatchAsDBM(dbms: UnsavedId<DBM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<DBM>[]>;
123
+ patchInTransaction(bm: BM, patch: Partial<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
124
+ saveAsDBM(dbm: Unsaved<DBM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<DBM>;
125
+ saveBatch(bms: Unsaved<BM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM[]>;
126
+ saveBatchAsDBM(dbms: Unsaved<DBM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<DBM[]>;
127
127
  /**
128
128
  * "Streaming" is implemented by buffering incoming rows into **batches**
129
129
  * (of size opt.batchSize, which defaults to 500),
@@ -147,18 +147,18 @@ export declare class CommonDao<BM extends BaseDBEntity, DBM extends BaseDBEntity
147
147
  updateByIds(ids: string[], patch: DBPatch<DBM>, opt?: CommonDaoOptions): Promise<number>;
148
148
  updateByQuery(q: DBQuery<DBM>, patch: DBPatch<DBM>, opt?: CommonDaoOptions): Promise<number>;
149
149
  dbmToBM(_dbm: undefined, opt?: CommonDaoOptions): Promise<undefined>;
150
- dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise<Saved<BM>>;
151
- dbmsToBM(dbms: DBM[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
150
+ dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise<BM>;
151
+ dbmsToBM(dbms: DBM[], opt?: CommonDaoOptions): Promise<BM[]>;
152
152
  /**
153
153
  * Mutates object with properties: id, created, updated.
154
154
  * Returns DBM (new reference).
155
155
  */
156
156
  bmToDBM(bm: undefined, opt?: CommonDaoOptions): Promise<undefined>;
157
- bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<Saved<DBM>>;
158
- bmsToDBM(bms: BM[], opt?: CommonDaoOptions): Promise<Saved<DBM>[]>;
157
+ bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<DBM>;
158
+ bmsToDBM(bms: BM[], opt?: CommonDaoOptions): Promise<DBM[]>;
159
159
  anyToDBM(dbm: undefined, opt?: CommonDaoOptions): undefined;
160
- anyToDBM(dbm?: any, opt?: CommonDaoOptions): Saved<DBM>;
161
- anyToDBMs(entities: DBM[], opt?: CommonDaoOptions): Saved<DBM>[];
160
+ anyToDBM(dbm?: any, opt?: CommonDaoOptions): DBM;
161
+ anyToDBMs(entities: DBM[], opt?: CommonDaoOptions): DBM[];
162
162
  bmToTM(bm: undefined, opt?: CommonDaoOptions): TM | undefined;
163
163
  bmToTM(bm?: BM, opt?: CommonDaoOptions): TM;
164
164
  bmsToTM(bms: BM[], opt?: CommonDaoOptions): TM[];
@@ -199,10 +199,10 @@ export declare class CommonDaoTransaction {
199
199
  * Perform a graceful rollback without throwing/re-throwing any error.
200
200
  */
201
201
  rollback(): Promise<void>;
202
- getById<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, id?: string | null, opt?: CommonDaoOptions): Promise<Saved<BM> | null>;
203
- getByIds<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, ids: string[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
204
- save<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, bm: UnsavedId<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>>;
205
- saveBatch<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, bms: UnsavedId<BM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<Saved<BM>[]>;
202
+ getById<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, id?: string | null, opt?: CommonDaoOptions): Promise<BM | null>;
203
+ getByIds<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, ids: string[], opt?: CommonDaoOptions): Promise<BM[]>;
204
+ save<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, bm: Unsaved<BM>, opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM>;
205
+ saveBatch<BM extends BaseDBEntity, DBM extends BaseDBEntity>(dao: CommonDao<BM, DBM, any>, bms: Unsaved<BM>[], opt?: CommonDaoSaveBatchOptions<DBM>): Promise<BM[]>;
206
206
  deleteById(dao: CommonDao<any>, id?: string | null, opt?: CommonDaoOptions): Promise<number>;
207
207
  deleteByIds(dao: CommonDao<any>, ids: string[], opt?: CommonDaoOptions): Promise<number>;
208
208
  }
@@ -419,7 +419,7 @@ class CommonDao {
419
419
  return (stream
420
420
  // optimization: 1 validation is enough
421
421
  // .pipe(transformMap<any, DBM>(dbm => this.anyToDBM(dbm, opt), safeOpt))
422
- // .pipe(transformMap<DBM, Saved<BM>>(dbm => this.dbmToBM(dbm, opt), safeOpt))
422
+ // .pipe(transformMap<DBM, BM>(dbm => this.dbmToBM(dbm, opt), safeOpt))
423
423
  .on('error', err => stream.emit('error', err))
424
424
  .pipe((0, nodejs_lib_1.transformMap)(async (dbm) => {
425
425
  if (this.cfg.hooks.afterLoad) {
@@ -1117,7 +1117,7 @@ class CommonDaoTransaction {
1117
1117
  // dao: CommonDao<BM, DBM, any>,
1118
1118
  // q: DBQuery<DBM>,
1119
1119
  // opt?: CommonDaoOptions,
1120
- // ): Promise<Saved<BM>[]> {
1120
+ // ): Promise<BM[]> {
1121
1121
  // try {
1122
1122
  // return await dao.runQuery(q, { ...opt, tx: this.tx })
1123
1123
  // } catch (err) {
@@ -1,4 +1,4 @@
1
- import { AnyObject, BaseDBEntity, CommonLogger, ErrorMode, Promisable, Saved, ZodError, ZodSchema } from '@naturalcycles/js-lib';
1
+ import { AnyObject, BaseDBEntity, CommonLogger, ErrorMode, Promisable, ZodError, ZodSchema } from '@naturalcycles/js-lib';
2
2
  import { AjvSchema, AjvValidationError, JoiValidationError, ObjectSchema, TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
3
3
  import { CommonDB } from '../common.db';
4
4
  import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions } from '../db.model';
@@ -53,7 +53,7 @@ export interface CommonDaoHooks<BM extends BaseDBEntity, DBM extends BaseDBEntit
53
53
  *
54
54
  * You can do validations as needed here and throw errors, they will be propagated.
55
55
  */
56
- afterLoad?: (dbm: Saved<DBM>) => Promisable<Saved<DBM> | null>;
56
+ afterLoad?: (dbm: DBM) => Promisable<DBM | null>;
57
57
  /**
58
58
  * Allows to access the DBM just before it's supposed to be saved to the DB.
59
59
  *
@@ -67,7 +67,7 @@ export interface CommonDaoHooks<BM extends BaseDBEntity, DBM extends BaseDBEntit
67
67
  *
68
68
  * You can do validations as needed here and throw errors, they will be propagated.
69
69
  */
70
- beforeSave?: (dbm: Saved<DBM>) => Promisable<Saved<DBM> | null>;
70
+ beforeSave?: (dbm: DBM) => Promisable<DBM | null>;
71
71
  /**
72
72
  * Called in:
73
73
  * - dbmToBM (applied before DBM becomes BM)
@@ -1,4 +1,4 @@
1
- import { AsyncMapper, Saved, AnyObject, BaseDBEntity, ObjectWithId } from '@naturalcycles/js-lib';
1
+ import { AsyncMapper, AnyObject, BaseDBEntity, ObjectWithId } from '@naturalcycles/js-lib';
2
2
  import { ReadableTyped } from '@naturalcycles/nodejs-lib';
3
3
  import { CommonDaoOptions, CommonDaoStreamDeleteOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, DBPatch } from '..';
4
4
  import { CommonDao } from '../commondao/common.dao';
@@ -90,19 +90,19 @@ export declare class RunnableDBQuery<BM extends BaseDBEntity, DBM extends BaseDB
90
90
  * Pass `table` to override table.
91
91
  */
92
92
  constructor(dao: CommonDao<BM, DBM, TM>, table?: string);
93
- runQuery(opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
93
+ runQuery(opt?: CommonDaoOptions): Promise<BM[]>;
94
94
  runQuerySingleColumn<T = any>(opt?: CommonDaoOptions): Promise<T[]>;
95
- runQueryAsDBM(opt?: CommonDaoOptions): Promise<Saved<DBM>[]>;
95
+ runQueryAsDBM(opt?: CommonDaoOptions): Promise<DBM[]>;
96
96
  runQueryAsTM(opt?: CommonDaoOptions): Promise<TM[]>;
97
- runQueryExtended(opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<BM>>>;
98
- runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<DBM>>>;
97
+ runQueryExtended(opt?: CommonDaoOptions): Promise<RunQueryResult<BM>>;
98
+ runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise<RunQueryResult<DBM>>;
99
99
  runQueryExtendedAsTM(opt?: CommonDaoOptions): Promise<RunQueryResult<TM>>;
100
100
  runQueryCount(opt?: CommonDaoOptions): Promise<number>;
101
101
  updateByQuery(patch: DBPatch<DBM>, opt?: CommonDaoOptions): Promise<number>;
102
- streamQueryForEach(mapper: AsyncMapper<Saved<BM>, void>, opt?: CommonDaoStreamForEachOptions<Saved<BM>>): Promise<void>;
103
- streamQueryAsDBMForEach(mapper: AsyncMapper<Saved<DBM>, void>, opt?: CommonDaoStreamForEachOptions<DBM>): Promise<void>;
104
- streamQuery(opt?: CommonDaoStreamOptions<Saved<BM>>): ReadableTyped<Saved<BM>>;
105
- streamQueryAsDBM(opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<Saved<DBM>>;
102
+ streamQueryForEach(mapper: AsyncMapper<BM, void>, opt?: CommonDaoStreamForEachOptions<BM>): Promise<void>;
103
+ streamQueryAsDBMForEach(mapper: AsyncMapper<DBM, void>, opt?: CommonDaoStreamForEachOptions<DBM>): Promise<void>;
104
+ streamQuery(opt?: CommonDaoStreamOptions<BM>): ReadableTyped<BM>;
105
+ streamQueryAsDBM(opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<DBM>;
106
106
  queryIds(opt?: CommonDaoOptions): Promise<string[]>;
107
107
  streamQueryIds(opt?: CommonDaoStreamOptions<string>): ReadableTyped<string>;
108
108
  streamQueryIdsForEach(mapper: AsyncMapper<string, void>, opt?: CommonDaoStreamForEachOptions<string>): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { BaseDBEntity, Saved, JsonSchemaObject } from '@naturalcycles/js-lib';
2
+ import { BaseDBEntity, JsonSchemaObject } from '@naturalcycles/js-lib';
3
3
  export declare const TEST_TABLE = "TEST_TABLE";
4
4
  export interface TestItemBM extends BaseDBEntity {
5
5
  k1: string;
@@ -19,7 +19,7 @@ export declare const testItemDBMSchema: import("joi").ObjectSchema<TestItemDBM>;
19
19
  export declare const testItemTMSchema: import("joi").ObjectSchema<TestItemTM>;
20
20
  export declare const testItemBMJsonSchema: JsonSchemaObject<TestItemBM>;
21
21
  export declare const testItemDBMJsonSchema: JsonSchemaObject<TestItemDBM>;
22
- export declare function createTestItemDBM(num?: number): Saved<TestItemDBM>;
23
- export declare function createTestItemBM(num?: number): Saved<TestItemBM>;
24
- export declare function createTestItemsDBM(count?: number): Saved<TestItemDBM>[];
25
- export declare function createTestItemsBM(count?: number): Saved<TestItemBM>[];
22
+ export declare function createTestItemDBM(num?: number): TestItemDBM;
23
+ export declare function createTestItemBM(num?: number): TestItemBM;
24
+ export declare function createTestItemsDBM(count?: number): TestItemDBM[];
25
+ export declare function createTestItemsBM(count?: number): TestItemBM[];
@@ -25,7 +25,10 @@ exports.testItemTMSchema = (0, nodejs_lib_1.objectSchema)({
25
25
  });
26
26
  exports.testItemBMJsonSchema = js_lib_1.jsonSchema
27
27
  .rootObject({
28
+ // todo: figure out how to not copy-paste these 3 fields
28
29
  id: js_lib_1.jsonSchema.string(), // todo: not strictly needed here
30
+ created: js_lib_1.jsonSchema.unixTimestamp(),
31
+ updated: js_lib_1.jsonSchema.unixTimestamp(),
29
32
  k1: js_lib_1.jsonSchema.string(),
30
33
  k2: js_lib_1.jsonSchema.oneOf([js_lib_1.jsonSchema.string(), js_lib_1.jsonSchema.null()]).optional(),
31
34
  k3: js_lib_1.jsonSchema.number().optional(),
package/package.json CHANGED
@@ -40,7 +40,7 @@
40
40
  "engines": {
41
41
  "node": ">=18.12"
42
42
  },
43
- "version": "9.4.1",
43
+ "version": "9.4.2",
44
44
  "description": "Lowest Common Denominator API to supported Databases",
45
45
  "keywords": [
46
46
  "db",
@@ -4,7 +4,6 @@ import {
4
4
  CommonLogger,
5
5
  ErrorMode,
6
6
  Promisable,
7
- Saved,
8
7
  ZodError,
9
8
  ZodSchema,
10
9
  } from '@naturalcycles/js-lib'
@@ -76,7 +75,7 @@ export interface CommonDaoHooks<BM extends BaseDBEntity, DBM extends BaseDBEntit
76
75
  *
77
76
  * You can do validations as needed here and throw errors, they will be propagated.
78
77
  */
79
- afterLoad?: (dbm: Saved<DBM>) => Promisable<Saved<DBM> | null>
78
+ afterLoad?: (dbm: DBM) => Promisable<DBM | null>
80
79
 
81
80
  /**
82
81
  * Allows to access the DBM just before it's supposed to be saved to the DB.
@@ -91,7 +90,7 @@ export interface CommonDaoHooks<BM extends BaseDBEntity, DBM extends BaseDBEntit
91
90
  *
92
91
  * You can do validations as needed here and throw errors, they will be propagated.
93
92
  */
94
- beforeSave?: (dbm: Saved<DBM>) => Promisable<Saved<DBM> | null>
93
+ beforeSave?: (dbm: DBM) => Promisable<DBM | null>
95
94
 
96
95
  /**
97
96
  * Called in:
@@ -21,10 +21,9 @@ import {
21
21
  JsonSchemaRootObject,
22
22
  ObjectWithId,
23
23
  pMap,
24
- Saved,
25
24
  SKIP,
26
25
  UnixTimestampMillisNumber,
27
- UnsavedId,
26
+ Unsaved,
28
27
  ZodSchema,
29
28
  ZodValidationError,
30
29
  zSafeValidate,
@@ -115,7 +114,7 @@ export class CommonDao<
115
114
  }
116
115
 
117
116
  // CREATE
118
- create(part: Partial<BM> = {}, opt: CommonDaoOptions = {}): Saved<BM> {
117
+ create(part: Partial<BM> = {}, opt: CommonDaoOptions = {}): BM {
119
118
  const bm = this.cfg.hooks!.beforeCreate!(part)
120
119
  // First assignIdCreatedUpdated, then validate!
121
120
  this.assignIdCreatedUpdated(bm, opt)
@@ -124,14 +123,14 @@ export class CommonDao<
124
123
 
125
124
  // GET
126
125
  async getById(id: undefined | null, opt?: CommonDaoOptions): Promise<null>
127
- async getById(id?: string | null, opt?: CommonDaoOptions): Promise<Saved<BM> | null>
128
- async getById(id?: string | null, opt: CommonDaoOptions = {}): Promise<Saved<BM> | null> {
126
+ async getById(id?: string | null, opt?: CommonDaoOptions): Promise<BM | null>
127
+ async getById(id?: string | null, opt: CommonDaoOptions = {}): Promise<BM | null> {
129
128
  if (!id) return null
130
129
  const op = `getById(${id})`
131
130
  const table = opt.table || this.cfg.table
132
131
  const started = this.logStarted(op, table)
133
132
 
134
- let dbm = (await (opt.tx || this.cfg.db).getByIds<Saved<DBM>>(table, [id]))[0]
133
+ let dbm = (await (opt.tx || this.cfg.db).getByIds<DBM>(table, [id]))[0]
135
134
  if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) {
136
135
  dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined
137
136
  }
@@ -141,11 +140,7 @@ export class CommonDao<
141
140
  return bm || null
142
141
  }
143
142
 
144
- async getByIdOrEmpty(
145
- id: string,
146
- part: Partial<BM> = {},
147
- opt?: CommonDaoOptions,
148
- ): Promise<Saved<BM>> {
143
+ async getByIdOrEmpty(id: string, part: Partial<BM> = {}, opt?: CommonDaoOptions): Promise<BM> {
149
144
  const bm = await this.getById(id, opt)
150
145
  if (bm) return bm
151
146
 
@@ -156,7 +151,7 @@ export class CommonDao<
156
151
  id: string,
157
152
  part: Partial<BM> = {},
158
153
  opt?: CommonDaoOptions,
159
- ): Promise<Saved<DBM>> {
154
+ ): Promise<DBM> {
160
155
  const dbm = await this.getByIdAsDBM(id, opt)
161
156
  if (dbm) return dbm
162
157
 
@@ -165,13 +160,13 @@ export class CommonDao<
165
160
  }
166
161
 
167
162
  async getByIdAsDBM(id: undefined | null, opt?: CommonDaoOptions): Promise<null>
168
- async getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise<Saved<DBM> | null>
169
- async getByIdAsDBM(id?: string | null, opt: CommonDaoOptions = {}): Promise<Saved<DBM> | null> {
163
+ async getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise<DBM | null>
164
+ async getByIdAsDBM(id?: string | null, opt: CommonDaoOptions = {}): Promise<DBM | null> {
170
165
  if (!id) return null
171
166
  const op = `getByIdAsDBM(${id})`
172
167
  const table = opt.table || this.cfg.table
173
168
  const started = this.logStarted(op, table)
174
- let [dbm] = await (opt.tx || this.cfg.db).getByIds<Saved<DBM>>(table, [id])
169
+ let [dbm] = await (opt.tx || this.cfg.db).getByIds<DBM>(table, [id])
175
170
  if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) {
176
171
  dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined
177
172
  }
@@ -190,7 +185,7 @@ export class CommonDao<
190
185
  const op = `getByIdAsTM(${id})`
191
186
  const table = opt.table || this.cfg.table
192
187
  const started = this.logStarted(op, table)
193
- let [dbm] = await (opt.tx || this.cfg.db).getByIds<Saved<DBM>>(table, [id])
188
+ let [dbm] = await (opt.tx || this.cfg.db).getByIds<DBM>(table, [id])
194
189
  if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) {
195
190
  dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined
196
191
  }
@@ -205,12 +200,12 @@ export class CommonDao<
205
200
  return tm || null
206
201
  }
207
202
 
208
- async getByIds(ids: string[], opt: CommonDaoOptions = {}): Promise<Saved<BM>[]> {
203
+ async getByIds(ids: string[], opt: CommonDaoOptions = {}): Promise<BM[]> {
209
204
  if (!ids.length) return []
210
205
  const op = `getByIds ${ids.length} id(s) (${_truncate(ids.slice(0, 10).join(', '), 50)})`
211
206
  const table = opt.table || this.cfg.table
212
207
  const started = this.logStarted(op, table)
213
- let dbms = await (opt.tx || this.cfg.db).getByIds<Saved<DBM>>(table, ids)
208
+ let dbms = await (opt.tx || this.cfg.db).getByIds<DBM>(table, ids)
214
209
  if (!opt.raw && this.cfg.hooks!.afterLoad && dbms.length) {
215
210
  dbms = (await pMap(dbms, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter(
216
211
  _isTruthy,
@@ -222,12 +217,12 @@ export class CommonDao<
222
217
  return bms
223
218
  }
224
219
 
225
- async getByIdsAsDBM(ids: string[], opt: CommonDaoOptions = {}): Promise<Saved<DBM>[]> {
220
+ async getByIdsAsDBM(ids: string[], opt: CommonDaoOptions = {}): Promise<DBM[]> {
226
221
  if (!ids.length) return []
227
222
  const op = `getByIdsAsDBM ${ids.length} id(s) (${_truncate(ids.slice(0, 10).join(', '), 50)})`
228
223
  const table = opt.table || this.cfg.table
229
224
  const started = this.logStarted(op, table)
230
- let dbms = await (opt.tx || this.cfg.db).getByIds<Saved<DBM>>(table, ids)
225
+ let dbms = await (opt.tx || this.cfg.db).getByIds<DBM>(table, ids)
231
226
  if (!opt.raw && this.cfg.hooks!.afterLoad && dbms.length) {
232
227
  dbms = (await pMap(dbms, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter(
233
228
  _isTruthy,
@@ -238,7 +233,7 @@ export class CommonDao<
238
233
  return dbms
239
234
  }
240
235
 
241
- async requireById(id: string, opt: CommonDaoOptions = {}): Promise<Saved<BM>> {
236
+ async requireById(id: string, opt: CommonDaoOptions = {}): Promise<BM> {
242
237
  const r = await this.getById(id, opt)
243
238
  if (!r) {
244
239
  this.throwRequiredError(id, opt)
@@ -246,7 +241,7 @@ export class CommonDao<
246
241
  return r
247
242
  }
248
243
 
249
- async requireByIdAsDBM(id: string, opt: CommonDaoOptions = {}): Promise<Saved<DBM>> {
244
+ async requireByIdAsDBM(id: string, opt: CommonDaoOptions = {}): Promise<DBM> {
250
245
  const r = await this.getByIdAsDBM(id, opt)
251
246
  if (!r) {
252
247
  this.throwRequiredError(id, opt)
@@ -295,16 +290,16 @@ export class CommonDao<
295
290
  }
296
291
  }
297
292
 
298
- async getBy(by: keyof DBM, value: any, limit = 0, opt?: CommonDaoOptions): Promise<Saved<BM>[]> {
293
+ async getBy(by: keyof DBM, value: any, limit = 0, opt?: CommonDaoOptions): Promise<BM[]> {
299
294
  return await this.query().filterEq(by, value).limit(limit).runQuery(opt)
300
295
  }
301
296
 
302
- async getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise<Saved<BM> | null> {
297
+ async getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise<BM | null> {
303
298
  const [bm] = await this.query().filterEq(by, value).limit(1).runQuery(opt)
304
299
  return bm || null
305
300
  }
306
301
 
307
- async getAll(opt?: CommonDaoOptions): Promise<Saved<BM>[]> {
302
+ async getAll(opt?: CommonDaoOptions): Promise<BM[]> {
308
303
  return await this.query().runQuery(opt)
309
304
  }
310
305
 
@@ -316,7 +311,7 @@ export class CommonDao<
316
311
  return new RunnableDBQuery<BM, DBM, TM>(this, table)
317
312
  }
318
313
 
319
- async runQuery(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<Saved<BM>[]> {
314
+ async runQuery(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<BM[]> {
320
315
  const { rows } = await this.runQueryExtended(q, opt)
321
316
  return rows
322
317
  }
@@ -338,21 +333,18 @@ export class CommonDao<
338
333
  * Does deduplication by id.
339
334
  * Order is not guaranteed, as queries run in parallel.
340
335
  */
341
- async runUnionQueries(queries: DBQuery<DBM>[], opt?: CommonDaoOptions): Promise<Saved<BM>[]> {
336
+ async runUnionQueries(queries: DBQuery<DBM>[], opt?: CommonDaoOptions): Promise<BM[]> {
342
337
  const results = (
343
338
  await pMap(queries, async q => (await this.runQueryExtended(q, opt)).rows)
344
339
  ).flat()
345
340
  return _uniqBy(results, r => r.id)
346
341
  }
347
342
 
348
- async runQueryExtended(
349
- q: DBQuery<DBM>,
350
- opt: CommonDaoOptions = {},
351
- ): Promise<RunQueryResult<Saved<BM>>> {
343
+ async runQueryExtended(q: DBQuery<DBM>, opt: CommonDaoOptions = {}): Promise<RunQueryResult<BM>> {
352
344
  q.table = opt.table || q.table
353
345
  const op = `runQuery(${q.pretty()})`
354
346
  const started = this.logStarted(op, q.table)
355
- let { rows, ...queryResult } = await this.cfg.db.runQuery<Saved<DBM>>(q, opt)
347
+ let { rows, ...queryResult } = await this.cfg.db.runQuery<DBM>(q, opt)
356
348
  const partialQuery = !!q._selectedFieldNames
357
349
  if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) {
358
350
  rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter(
@@ -368,7 +360,7 @@ export class CommonDao<
368
360
  }
369
361
  }
370
362
 
371
- async runQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<Saved<DBM>[]> {
363
+ async runQueryAsDBM(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<DBM[]> {
372
364
  const { rows } = await this.runQueryExtendedAsDBM(q, opt)
373
365
  return rows
374
366
  }
@@ -376,11 +368,11 @@ export class CommonDao<
376
368
  async runQueryExtendedAsDBM(
377
369
  q: DBQuery<DBM>,
378
370
  opt: CommonDaoOptions = {},
379
- ): Promise<RunQueryResult<Saved<DBM>>> {
371
+ ): Promise<RunQueryResult<DBM>> {
380
372
  q.table = opt.table || q.table
381
373
  const op = `runQueryAsDBM(${q.pretty()})`
382
374
  const started = this.logStarted(op, q.table)
383
- let { rows, ...queryResult } = await this.cfg.db.runQuery<Saved<DBM>>(q, opt)
375
+ let { rows, ...queryResult } = await this.cfg.db.runQuery<DBM>(q, opt)
384
376
  if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) {
385
377
  rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter(
386
378
  _isTruthy,
@@ -405,7 +397,7 @@ export class CommonDao<
405
397
  q.table = opt.table || q.table
406
398
  const op = `runQueryAsTM(${q.pretty()})`
407
399
  const started = this.logStarted(op, q.table)
408
- let { rows, ...queryResult } = await this.cfg.db.runQuery<Saved<DBM>>(q, opt)
400
+ let { rows, ...queryResult } = await this.cfg.db.runQuery<DBM>(q, opt)
409
401
  if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) {
410
402
  rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter(
411
403
  _isTruthy,
@@ -435,8 +427,8 @@ export class CommonDao<
435
427
 
436
428
  async streamQueryForEach(
437
429
  q: DBQuery<DBM>,
438
- mapper: AsyncMapper<Saved<BM>, void>,
439
- opt: CommonDaoStreamForEachOptions<Saved<BM>> = {},
430
+ mapper: AsyncMapper<BM, void>,
431
+ opt: CommonDaoStreamForEachOptions<BM> = {},
440
432
  ): Promise<void> {
441
433
  q.table = opt.table || q.table
442
434
  opt.skipValidation = opt.skipValidation !== false // default true
@@ -450,7 +442,7 @@ export class CommonDao<
450
442
 
451
443
  await _pipeline([
452
444
  this.cfg.db.streamQuery<DBM>(q, opt),
453
- transformMap<Saved<DBM>, Saved<BM>>(
445
+ transformMap<DBM, BM>(
454
446
  async dbm => {
455
447
  count++
456
448
  if (partialQuery || opt.raw) return dbm as any
@@ -466,7 +458,7 @@ export class CommonDao<
466
458
  errorMode: opt.errorMode,
467
459
  },
468
460
  ),
469
- transformMap<Saved<BM>, void>(mapper, {
461
+ transformMap<BM, void>(mapper, {
470
462
  ...opt,
471
463
  predicate: _passthroughPredicate, // to be able to logProgress
472
464
  }),
@@ -485,7 +477,7 @@ export class CommonDao<
485
477
 
486
478
  async streamQueryAsDBMForEach(
487
479
  q: DBQuery<DBM>,
488
- mapper: AsyncMapper<Saved<DBM>, void>,
480
+ mapper: AsyncMapper<DBM, void>,
489
481
  opt: CommonDaoStreamForEachOptions<DBM> = {},
490
482
  ): Promise<void> {
491
483
  q.table = opt.table || q.table
@@ -516,7 +508,7 @@ export class CommonDao<
516
508
  errorMode: opt.errorMode,
517
509
  },
518
510
  ),
519
- transformMap<Saved<DBM>, void>(mapper, {
511
+ transformMap<DBM, void>(mapper, {
520
512
  ...opt,
521
513
  predicate: _passthroughPredicate, // to be able to logProgress
522
514
  }),
@@ -536,10 +528,7 @@ export class CommonDao<
536
528
  /**
537
529
  * Stream as Readable, to be able to .pipe() it further with support of backpressure.
538
530
  */
539
- streamQueryAsDBM(
540
- q: DBQuery<DBM>,
541
- opt: CommonDaoStreamOptions<DBM> = {},
542
- ): ReadableTyped<Saved<DBM>> {
531
+ streamQueryAsDBM(q: DBQuery<DBM>, opt: CommonDaoStreamOptions<DBM> = {}): ReadableTyped<DBM> {
543
532
  q.table = opt.table || q.table
544
533
  opt.skipValidation = opt.skipValidation !== false // default true
545
534
  opt.skipConversion = opt.skipConversion !== false // default true
@@ -553,7 +542,7 @@ export class CommonDao<
553
542
  return stream
554
543
  .on('error', err => stream.emit('error', err))
555
544
  .pipe(
556
- transformMap<any, Saved<DBM>>(
545
+ transformMap<any, DBM>(
557
546
  async dbm => {
558
547
  if (this.cfg.hooks!.afterLoad) {
559
548
  dbm = (await this.cfg.hooks!.afterLoad(dbm))!
@@ -578,10 +567,7 @@ export class CommonDao<
578
567
  *
579
568
  * You can do `.pipe(transformNoOp)` to make it "valid again".
580
569
  */
581
- streamQuery(
582
- q: DBQuery<DBM>,
583
- opt: CommonDaoStreamOptions<Saved<BM>> = {},
584
- ): ReadableTyped<Saved<BM>> {
570
+ streamQuery(q: DBQuery<DBM>, opt: CommonDaoStreamOptions<BM> = {}): ReadableTyped<BM> {
585
571
  q.table = opt.table || q.table
586
572
  opt.skipValidation = opt.skipValidation !== false // default true
587
573
  opt.skipConversion = opt.skipConversion !== false // default true
@@ -595,10 +581,10 @@ export class CommonDao<
595
581
  stream
596
582
  // optimization: 1 validation is enough
597
583
  // .pipe(transformMap<any, DBM>(dbm => this.anyToDBM(dbm, opt), safeOpt))
598
- // .pipe(transformMap<DBM, Saved<BM>>(dbm => this.dbmToBM(dbm, opt), safeOpt))
584
+ // .pipe(transformMap<DBM, BM>(dbm => this.dbmToBM(dbm, opt), safeOpt))
599
585
  .on('error', err => stream.emit('error', err))
600
586
  .pipe(
601
- transformMap<Saved<DBM>, Saved<BM>>(
587
+ transformMap<DBM, BM>(
602
588
  async dbm => {
603
589
  if (this.cfg.hooks!.afterLoad) {
604
590
  dbm = (await this.cfg.hooks!.afterLoad(dbm))!
@@ -632,7 +618,7 @@ export class CommonDao<
632
618
  .streamQuery<DBM>(q.select(['id']), opt)
633
619
  .on('error', err => stream.emit('error', err))
634
620
  .pipe(
635
- transformMapSimple<Saved<DBM>, string>(r => r.id, {
621
+ transformMapSimple<DBM, string>(r => r.id, {
636
622
  errorMode: ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors
637
623
  }),
638
624
  )
@@ -654,7 +640,7 @@ export class CommonDao<
654
640
 
655
641
  await _pipeline([
656
642
  this.cfg.db.streamQuery<DBM>(q.select(['id']), opt),
657
- transformMapSimple<Saved<DBM>, string>(r => {
643
+ transformMapSimple<DBM, string>(r => {
658
644
  count++
659
645
  return r.id
660
646
  }),
@@ -701,17 +687,17 @@ export class CommonDao<
701
687
  /**
702
688
  * Mutates with id, created, updated
703
689
  */
704
- async save(bm: UnsavedId<BM>, opt: CommonDaoSaveOptions<BM, DBM> = {}): Promise<Saved<BM>> {
690
+ async save(bm: Unsaved<BM>, opt: CommonDaoSaveOptions<BM, DBM> = {}): Promise<BM> {
705
691
  this.requireWriteAccess()
706
692
 
707
693
  if (opt.skipIfEquals && _deepJsonEquals(bm, opt.skipIfEquals)) {
708
694
  // Skipping the save operation
709
- return bm as Saved<BM>
695
+ return bm as BM
710
696
  }
711
697
 
712
698
  const idWasGenerated = !bm.id && this.cfg.generateId
713
699
  this.assignIdCreatedUpdated(bm, opt) // mutates
714
- _typeCast<Saved<BM>>(bm)
700
+ _typeCast<BM>(bm)
715
701
  let dbm = await this.bmToDBM(bm, opt)
716
702
 
717
703
  if (this.cfg.hooks!.beforeSave) {
@@ -751,11 +737,7 @@ export class CommonDao<
751
737
  * Similar to `save` with skipIfEquals.
752
738
  * Similar to `patch`, but doesn't load the object from the Database.
753
739
  */
754
- async savePatch(
755
- bm: BM,
756
- patch: Partial<BM>,
757
- opt: CommonDaoSaveBatchOptions<DBM>,
758
- ): Promise<Saved<BM>> {
740
+ async savePatch(bm: BM, patch: Partial<BM>, opt: CommonDaoSaveBatchOptions<DBM>): Promise<BM> {
759
741
  const patched: BM = {
760
742
  ...bm,
761
743
  ...patch,
@@ -763,7 +745,7 @@ export class CommonDao<
763
745
 
764
746
  if (_deepJsonEquals(bm, patched)) {
765
747
  // Skipping the save operation, as data is the same
766
- return bm as Saved<BM>
748
+ return bm
767
749
  }
768
750
 
769
751
  // Actually apply the patch by mutating the original object (by design)
@@ -785,7 +767,7 @@ export class CommonDao<
785
767
  id: string,
786
768
  patch: Partial<BM>,
787
769
  opt: CommonDaoSaveBatchOptions<DBM> = {},
788
- ): Promise<Saved<BM>> {
770
+ ): Promise<BM> {
789
771
  if (this.cfg.patchInTransaction && !opt.tx) {
790
772
  // patchInTransaction means that we should run this op in Transaction
791
773
  // But if opt.tx is passed - means that we are already in a Transaction,
@@ -793,7 +775,7 @@ export class CommonDao<
793
775
  return await this.patchByIdInTransaction(id, patch, opt)
794
776
  }
795
777
 
796
- let patched: Saved<BM>
778
+ let patched: BM
797
779
  const loaded = await this.getById(id, opt)
798
780
 
799
781
  if (loaded) {
@@ -817,7 +799,7 @@ export class CommonDao<
817
799
  id: string,
818
800
  patch: Partial<BM>,
819
801
  opt?: CommonDaoSaveBatchOptions<DBM>,
820
- ): Promise<Saved<BM>> {
802
+ ): Promise<BM> {
821
803
  return await this.runInTransaction(async daoTx => {
822
804
  return await this.patchById(id, patch, { ...opt, tx: daoTx.tx })
823
805
  })
@@ -829,11 +811,7 @@ export class CommonDao<
829
811
  * Otherwise, similar behavior as patchById.
830
812
  * It still loads the row from the DB.
831
813
  */
832
- async patch(
833
- bm: BM,
834
- patch: Partial<BM>,
835
- opt: CommonDaoSaveBatchOptions<DBM> = {},
836
- ): Promise<Saved<BM>> {
814
+ async patch(bm: BM, patch: Partial<BM>, opt: CommonDaoSaveBatchOptions<DBM> = {}): Promise<BM> {
837
815
  if (this.cfg.patchInTransaction && !opt.tx) {
838
816
  // patchInTransaction means that we should run this op in Transaction
839
817
  // But if opt.tx is passed - means that we are already in a Transaction,
@@ -848,7 +826,7 @@ export class CommonDao<
848
826
 
849
827
  if (_deepJsonEquals(loaded, bm)) {
850
828
  // Skipping the save operation, as data is the same
851
- return bm as Saved<BM>
829
+ return bm
852
830
  }
853
831
 
854
832
  // Make `bm` exactly the same as `loaded`
@@ -867,22 +845,19 @@ export class CommonDao<
867
845
  bm: BM,
868
846
  patch: Partial<BM>,
869
847
  opt?: CommonDaoSaveBatchOptions<DBM>,
870
- ): Promise<Saved<BM>> {
848
+ ): Promise<BM> {
871
849
  return await this.runInTransaction(async daoTx => {
872
850
  return await this.patch(bm, patch, { ...opt, tx: daoTx.tx })
873
851
  })
874
852
  }
875
853
 
876
- async saveAsDBM(
877
- dbm: UnsavedId<DBM>,
878
- opt: CommonDaoSaveBatchOptions<DBM> = {},
879
- ): Promise<Saved<DBM>> {
854
+ async saveAsDBM(dbm: Unsaved<DBM>, opt: CommonDaoSaveBatchOptions<DBM> = {}): Promise<DBM> {
880
855
  this.requireWriteAccess()
881
856
  const table = opt.table || this.cfg.table
882
857
 
883
858
  // assigning id in case it misses the id
884
859
  // will override/set `updated` field, unless opts.preserveUpdated is set
885
- let row = dbm as Saved<DBM>
860
+ let row = dbm as DBM
886
861
  if (!opt.raw) {
887
862
  const idWasGenerated = !dbm.id && this.cfg.generateId
888
863
  this.assignIdCreatedUpdated(dbm, opt) // mutates
@@ -899,7 +874,7 @@ export class CommonDao<
899
874
 
900
875
  if (this.cfg.hooks!.beforeSave) {
901
876
  row = (await this.cfg.hooks!.beforeSave(row))!
902
- if (row === null) return dbm as Saved<DBM>
877
+ if (row === null) return dbm as DBM
903
878
  }
904
879
 
905
880
  await (opt.tx || this.cfg.db).saveBatch(table, [row], {
@@ -916,10 +891,7 @@ export class CommonDao<
916
891
  return row
917
892
  }
918
893
 
919
- async saveBatch(
920
- bms: UnsavedId<BM>[],
921
- opt: CommonDaoSaveBatchOptions<DBM> = {},
922
- ): Promise<Saved<BM>[]> {
894
+ async saveBatch(bms: Unsaved<BM>[], opt: CommonDaoSaveBatchOptions<DBM> = {}): Promise<BM[]> {
923
895
  if (!bms.length) return []
924
896
  this.requireWriteAccess()
925
897
  const table = opt.table || this.cfg.table
@@ -960,20 +932,20 @@ export class CommonDao<
960
932
 
961
933
  this.logSaveResult(started, op, table)
962
934
 
963
- return bms as Saved<BM>[]
935
+ return bms as BM[]
964
936
  }
965
937
 
966
938
  async saveBatchAsDBM(
967
- dbms: UnsavedId<DBM>[],
939
+ dbms: Unsaved<DBM>[],
968
940
  opt: CommonDaoSaveBatchOptions<DBM> = {},
969
- ): Promise<Saved<DBM>[]> {
941
+ ): Promise<DBM[]> {
970
942
  if (!dbms.length) return []
971
943
  this.requireWriteAccess()
972
944
  const table = opt.table || this.cfg.table
973
- let rows = dbms as Saved<DBM>[]
945
+ let rows = dbms as DBM[]
974
946
  if (!opt.raw) {
975
947
  dbms.forEach(dbm => this.assignIdCreatedUpdated(dbm, opt)) // mutates
976
- rows = this.anyToDBMs(dbms as Saved<DBM>[], opt)
948
+ rows = this.anyToDBMs(dbms as DBM[], opt)
977
949
  if (opt.ensureUniqueId) throw new AppError('ensureUniqueId is not supported in saveBatch')
978
950
  }
979
951
  if (this.cfg.immutable && !opt.allowMutability && !opt.saveMethod) {
@@ -1034,7 +1006,7 @@ export class CommonDao<
1034
1006
  const { batchSize = 500, batchConcurrency = 16, errorMode } = opt
1035
1007
 
1036
1008
  return [
1037
- transformMap<BM, Saved<DBM>>(
1009
+ transformMap<BM, DBM>(
1038
1010
  async bm => {
1039
1011
  this.assignIdCreatedUpdated(bm, opt) // mutates
1040
1012
 
@@ -1191,8 +1163,8 @@ export class CommonDao<
1191
1163
  // CONVERSIONS
1192
1164
 
1193
1165
  async dbmToBM(_dbm: undefined, opt?: CommonDaoOptions): Promise<undefined>
1194
- async dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise<Saved<BM>>
1195
- async dbmToBM(_dbm?: DBM, opt: CommonDaoOptions = {}): Promise<Saved<BM> | undefined> {
1166
+ async dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise<BM>
1167
+ async dbmToBM(_dbm?: DBM, opt: CommonDaoOptions = {}): Promise<BM | undefined> {
1196
1168
  if (!_dbm) return
1197
1169
 
1198
1170
  // optimization: no need to run full joi DBM validation, cause BM validation will be run
@@ -1211,7 +1183,7 @@ export class CommonDao<
1211
1183
  return this.validateAndConvert(bm, this.cfg.bmSchema, DBModelType.BM, opt)
1212
1184
  }
1213
1185
 
1214
- async dbmsToBM(dbms: DBM[], opt: CommonDaoOptions = {}): Promise<Saved<BM>[]> {
1186
+ async dbmsToBM(dbms: DBM[], opt: CommonDaoOptions = {}): Promise<BM[]> {
1215
1187
  return await pMap(dbms, async dbm => await this.dbmToBM(dbm, opt))
1216
1188
  }
1217
1189
 
@@ -1220,8 +1192,8 @@ export class CommonDao<
1220
1192
  * Returns DBM (new reference).
1221
1193
  */
1222
1194
  async bmToDBM(bm: undefined, opt?: CommonDaoOptions): Promise<undefined>
1223
- async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<Saved<DBM>>
1224
- async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<Saved<DBM> | undefined> {
1195
+ async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<DBM>
1196
+ async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise<DBM | undefined> {
1225
1197
  if (bm === undefined) return
1226
1198
 
1227
1199
  // optimization: no need to run the BM validation, since DBM will be validated anyway
@@ -1240,14 +1212,14 @@ export class CommonDao<
1240
1212
  return this.validateAndConvert(dbm, this.cfg.dbmSchema, DBModelType.DBM, opt)
1241
1213
  }
1242
1214
 
1243
- async bmsToDBM(bms: BM[], opt: CommonDaoOptions = {}): Promise<Saved<DBM>[]> {
1215
+ async bmsToDBM(bms: BM[], opt: CommonDaoOptions = {}): Promise<DBM[]> {
1244
1216
  // try/catch?
1245
1217
  return await pMap(bms, async bm => await this.bmToDBM(bm, opt))
1246
1218
  }
1247
1219
 
1248
1220
  anyToDBM(dbm: undefined, opt?: CommonDaoOptions): undefined
1249
- anyToDBM(dbm?: any, opt?: CommonDaoOptions): Saved<DBM>
1250
- anyToDBM(dbm?: DBM, opt: CommonDaoOptions = {}): Saved<DBM> | undefined {
1221
+ anyToDBM(dbm?: any, opt?: CommonDaoOptions): DBM
1222
+ anyToDBM(dbm?: DBM, opt: CommonDaoOptions = {}): DBM | undefined {
1251
1223
  if (!dbm) return
1252
1224
 
1253
1225
  // this shouldn't be happening on load! but should on save!
@@ -1263,7 +1235,7 @@ export class CommonDao<
1263
1235
  return this.validateAndConvert(dbm, this.cfg.dbmSchema, DBModelType.DBM, opt)
1264
1236
  }
1265
1237
 
1266
- anyToDBMs(entities: DBM[], opt: CommonDaoOptions = {}): Saved<DBM>[] {
1238
+ anyToDBMs(entities: DBM[], opt: CommonDaoOptions = {}): DBM[] {
1267
1239
  return entities.map(entity => this.anyToDBM(entity, opt))
1268
1240
  }
1269
1241
 
@@ -1491,7 +1463,7 @@ export class CommonDaoTransaction {
1491
1463
  dao: CommonDao<BM, DBM, any>,
1492
1464
  id?: string | null,
1493
1465
  opt?: CommonDaoOptions,
1494
- ): Promise<Saved<BM> | null> {
1466
+ ): Promise<BM | null> {
1495
1467
  return await dao.getById(id, { ...opt, tx: this.tx })
1496
1468
  }
1497
1469
 
@@ -1499,7 +1471,7 @@ export class CommonDaoTransaction {
1499
1471
  dao: CommonDao<BM, DBM, any>,
1500
1472
  ids: string[],
1501
1473
  opt?: CommonDaoOptions,
1502
- ): Promise<Saved<BM>[]> {
1474
+ ): Promise<BM[]> {
1503
1475
  return await dao.getByIds(ids, { ...opt, tx: this.tx })
1504
1476
  }
1505
1477
 
@@ -1508,7 +1480,7 @@ export class CommonDaoTransaction {
1508
1480
  // dao: CommonDao<BM, DBM, any>,
1509
1481
  // q: DBQuery<DBM>,
1510
1482
  // opt?: CommonDaoOptions,
1511
- // ): Promise<Saved<BM>[]> {
1483
+ // ): Promise<BM[]> {
1512
1484
  // try {
1513
1485
  // return await dao.runQuery(q, { ...opt, tx: this.tx })
1514
1486
  // } catch (err) {
@@ -1519,17 +1491,17 @@ export class CommonDaoTransaction {
1519
1491
 
1520
1492
  async save<BM extends BaseDBEntity, DBM extends BaseDBEntity>(
1521
1493
  dao: CommonDao<BM, DBM, any>,
1522
- bm: UnsavedId<BM>,
1494
+ bm: Unsaved<BM>,
1523
1495
  opt?: CommonDaoSaveBatchOptions<DBM>,
1524
- ): Promise<Saved<BM>> {
1496
+ ): Promise<BM> {
1525
1497
  return (await this.saveBatch(dao, [bm], opt))[0]!
1526
1498
  }
1527
1499
 
1528
1500
  async saveBatch<BM extends BaseDBEntity, DBM extends BaseDBEntity>(
1529
1501
  dao: CommonDao<BM, DBM, any>,
1530
- bms: UnsavedId<BM>[],
1502
+ bms: Unsaved<BM>[],
1531
1503
  opt?: CommonDaoSaveBatchOptions<DBM>,
1532
- ): Promise<Saved<BM>[]> {
1504
+ ): Promise<BM[]> {
1533
1505
  return await dao.saveBatch(bms, { ...opt, tx: this.tx })
1534
1506
  }
1535
1507
 
@@ -10,7 +10,6 @@ import {
10
10
  localTime,
11
11
  JsonSchemaObject,
12
12
  BaseDBEntity,
13
- Saved,
14
13
  } from '@naturalcycles/js-lib'
15
14
  import {
16
15
  NDJsonStats,
@@ -217,7 +216,7 @@ export async function dbPipelineRestore(opt: DBPipelineRestoreOptions): Promise<
217
216
  }),
218
217
  transformLimit({ limit }),
219
218
  ...(sinceUpdated
220
- ? [transformFilterSync<Saved<BaseDBEntity>>(r => r.updated >= sinceUpdated)]
219
+ ? [transformFilterSync<BaseDBEntity>(r => r.updated >= sinceUpdated)]
221
220
  : []),
222
221
  transformMap(mapperPerTable[table] || _passthroughMapper, {
223
222
  errorMode,
@@ -1,7 +1,6 @@
1
1
  import {
2
2
  AsyncMapper,
3
3
  _truncate,
4
- Saved,
5
4
  AnyObject,
6
5
  _objectAssign,
7
6
  BaseDBEntity,
@@ -251,7 +250,7 @@ export class RunnableDBQuery<
251
250
  super(table || dao.cfg.table)
252
251
  }
253
252
 
254
- async runQuery(opt?: CommonDaoOptions): Promise<Saved<BM>[]> {
253
+ async runQuery(opt?: CommonDaoOptions): Promise<BM[]> {
255
254
  return await this.dao.runQuery(this, opt)
256
255
  }
257
256
 
@@ -259,7 +258,7 @@ export class RunnableDBQuery<
259
258
  return await this.dao.runQuerySingleColumn<T>(this, opt)
260
259
  }
261
260
 
262
- async runQueryAsDBM(opt?: CommonDaoOptions): Promise<Saved<DBM>[]> {
261
+ async runQueryAsDBM(opt?: CommonDaoOptions): Promise<DBM[]> {
263
262
  return await this.dao.runQueryAsDBM(this, opt)
264
263
  }
265
264
 
@@ -267,11 +266,11 @@ export class RunnableDBQuery<
267
266
  return await this.dao.runQueryAsTM(this, opt)
268
267
  }
269
268
 
270
- async runQueryExtended(opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<BM>>> {
269
+ async runQueryExtended(opt?: CommonDaoOptions): Promise<RunQueryResult<BM>> {
271
270
  return await this.dao.runQueryExtended(this, opt)
272
271
  }
273
272
 
274
- async runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise<RunQueryResult<Saved<DBM>>> {
273
+ async runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise<RunQueryResult<DBM>> {
275
274
  return await this.dao.runQueryExtendedAsDBM(this, opt)
276
275
  }
277
276
 
@@ -288,24 +287,24 @@ export class RunnableDBQuery<
288
287
  }
289
288
 
290
289
  async streamQueryForEach(
291
- mapper: AsyncMapper<Saved<BM>, void>,
292
- opt?: CommonDaoStreamForEachOptions<Saved<BM>>,
290
+ mapper: AsyncMapper<BM, void>,
291
+ opt?: CommonDaoStreamForEachOptions<BM>,
293
292
  ): Promise<void> {
294
293
  await this.dao.streamQueryForEach(this, mapper, opt)
295
294
  }
296
295
 
297
296
  async streamQueryAsDBMForEach(
298
- mapper: AsyncMapper<Saved<DBM>, void>,
297
+ mapper: AsyncMapper<DBM, void>,
299
298
  opt?: CommonDaoStreamForEachOptions<DBM>,
300
299
  ): Promise<void> {
301
300
  await this.dao.streamQueryAsDBMForEach(this, mapper, opt)
302
301
  }
303
302
 
304
- streamQuery(opt?: CommonDaoStreamOptions<Saved<BM>>): ReadableTyped<Saved<BM>> {
303
+ streamQuery(opt?: CommonDaoStreamOptions<BM>): ReadableTyped<BM> {
305
304
  return this.dao.streamQuery(this, opt)
306
305
  }
307
306
 
308
- streamQueryAsDBM(opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<Saved<DBM>> {
307
+ streamQueryAsDBM(opt?: CommonDaoStreamOptions<DBM>): ReadableTyped<DBM> {
309
308
  return this.dao.streamQueryAsDBM(this, opt)
310
309
  }
311
310
 
@@ -1,4 +1,4 @@
1
- import { jsonSchema, _range, BaseDBEntity, Saved, JsonSchemaObject } from '@naturalcycles/js-lib'
1
+ import { jsonSchema, _range, BaseDBEntity, JsonSchemaObject } from '@naturalcycles/js-lib'
2
2
  import {
3
3
  baseDBEntitySchema,
4
4
  binarySchema,
@@ -50,7 +50,10 @@ export const testItemTMSchema = objectSchema<TestItemTM>({
50
50
 
51
51
  export const testItemBMJsonSchema: JsonSchemaObject<TestItemBM> = jsonSchema
52
52
  .rootObject<TestItemBM>({
53
+ // todo: figure out how to not copy-paste these 3 fields
53
54
  id: jsonSchema.string(), // todo: not strictly needed here
55
+ created: jsonSchema.unixTimestamp(),
56
+ updated: jsonSchema.unixTimestamp(),
54
57
  k1: jsonSchema.string(),
55
58
  k2: jsonSchema.oneOf<string | null>([jsonSchema.string(), jsonSchema.null()]).optional(),
56
59
  k3: jsonSchema.number().optional(),
@@ -74,7 +77,7 @@ export const testItemDBMJsonSchema: JsonSchemaObject<TestItemDBM> = jsonSchema
74
77
  })
75
78
  .build()
76
79
 
77
- export function createTestItemDBM(num = 1): Saved<TestItemDBM> {
80
+ export function createTestItemDBM(num = 1): TestItemDBM {
78
81
  return {
79
82
  id: `id${num}`,
80
83
  k1: `v${num}`,
@@ -86,14 +89,14 @@ export function createTestItemDBM(num = 1): Saved<TestItemDBM> {
86
89
  }
87
90
  }
88
91
 
89
- export function createTestItemBM(num = 1): Saved<TestItemBM> {
92
+ export function createTestItemBM(num = 1): TestItemBM {
90
93
  return createTestItemDBM(num)
91
94
  }
92
95
 
93
- export function createTestItemsDBM(count = 1): Saved<TestItemDBM>[] {
96
+ export function createTestItemsDBM(count = 1): TestItemDBM[] {
94
97
  return _range(1, count + 1).map(num => createTestItemDBM(num))
95
98
  }
96
99
 
97
- export function createTestItemsBM(count = 1): Saved<TestItemBM>[] {
100
+ export function createTestItemsBM(count = 1): TestItemBM[] {
98
101
  return _range(1, count + 1).map(num => createTestItemBM(num))
99
102
  }