query-core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/services.ts CHANGED
@@ -1,122 +1,124 @@
1
- import {attributes, buildToDelete, buildToInsert, buildToUpdate, exist, metadata, select, version} from './build';
2
- import {Attribute, Attributes, Statement, StringMap} from './metadata';
3
- import {SearchResult} from './search';
1
+ import { attributes, buildToDelete, buildToInsert, buildToUpdate, exist, metadata, select, version } from "./build"
2
+ import { Attribute, Attributes, Statement, StringMap } from "./metadata"
3
+ import { SearchResult } from "./search"
4
4
 
5
5
  export interface Filter {
6
- fields?: string[];
7
- sort?: string;
8
- q?: string;
6
+ fields?: string[]
7
+ sort?: string
8
+ q?: string
9
9
  }
10
- export type Load<T, ID> = (id: ID, ctx?: any) => Promise<T|null>;
11
- export type Get<T, ID> = Load<T, ID>;
10
+ export type Load<T, ID> = (id: ID, ctx?: any) => Promise<T | null>
11
+ export type Get<T, ID> = Load<T, ID>
12
12
  export function useGet<T, ID>(
13
13
  q: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
14
14
  table: string,
15
- attrs: Attributes|string[],
15
+ attrs: Attributes | string[],
16
16
  param: (i: number) => string,
17
- fromDB?: (v: T) => T): Load<T, ID> {
18
- const l = new SqlLoader<T, ID>(q, table, attrs, param, fromDB);
19
- return l.load;
17
+ fromDB?: (v: T) => T,
18
+ ): Load<T, ID> {
19
+ const l = new SqlLoader<T, ID>(q, table, attrs, param, fromDB)
20
+ return l.load
20
21
  }
21
- export const useLoad = useGet;
22
+ export const useLoad = useGet
22
23
  export class SqlLoader<T, ID> {
23
- primaryKeys: Attribute[];
24
- map?: StringMap;
25
- attributes: Attributes;
26
- bools?: Attribute[];
24
+ primaryKeys: Attribute[]
25
+ map?: StringMap
26
+ attributes: Attributes
27
+ bools?: Attribute[]
27
28
  constructor(
28
29
  public query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
29
30
  public table: string,
30
- attrs: Attributes|string[],
31
+ attrs: Attributes | string[],
31
32
  public param: (i: number) => string,
32
- public fromDB?: (v: T) => T) {
33
+ public fromDB?: (v: T) => T,
34
+ ) {
33
35
  if (Array.isArray(attrs)) {
34
- this.primaryKeys = attributes(attrs);
35
- this.attributes = {} as any;
36
+ this.primaryKeys = attributes(attrs)
37
+ this.attributes = {} as any
36
38
  } else {
37
- const m = metadata(attrs);
38
- this.attributes = attrs;
39
- this.primaryKeys = m.keys;
40
- this.map = m.map;
41
- this.bools = m.bools;
39
+ const m = metadata(attrs)
40
+ this.attributes = attrs
41
+ this.primaryKeys = m.keys
42
+ this.map = m.map
43
+ this.bools = m.bools
42
44
  }
43
45
  if (this.metadata) {
44
- this.metadata = this.metadata.bind(this);
46
+ this.metadata = this.metadata.bind(this)
45
47
  }
46
- this.all = this.all.bind(this);
47
- this.load = this.load.bind(this);
48
- this.exist = this.exist.bind(this);
48
+ this.all = this.all.bind(this)
49
+ this.load = this.load.bind(this)
50
+ this.exist = this.exist.bind(this)
49
51
  }
50
- metadata?(): Attributes|undefined {
51
- return this.attributes;
52
+ metadata?(): Attributes | undefined {
53
+ return this.attributes
52
54
  }
53
55
  all(): Promise<T[]> {
54
- const sql = `select * from ${this.table}`;
55
- return this.query(sql, [], this.map);
56
+ const sql = `select * from ${this.table}`
57
+ return this.query(sql, [], this.map)
56
58
  }
57
- load(id: ID, ctx?: any): Promise<T|null> {
58
- const stmt = select<ID>(id, this.table, this.primaryKeys, this.param);
59
+ load(id: ID, ctx?: any): Promise<T | null> {
60
+ const stmt = select<ID>(id, this.table, this.primaryKeys, this.param)
59
61
  if (!stmt) {
60
- throw new Error('cannot build query by id');
62
+ throw new Error("cannot build query by id")
61
63
  }
62
- const fn = this.fromDB;
64
+ const fn = this.fromDB
63
65
  if (fn) {
64
- return this.query<T>(stmt.query, stmt.params, this.map, ctx).then(res => {
66
+ return this.query<T>(stmt.query, stmt.params, this.map, ctx).then((res) => {
65
67
  if (!res || res.length === 0) {
66
- return null;
68
+ return null
67
69
  } else {
68
- const obj = res[0];
69
- return fn(obj);
70
+ const obj = res[0]
71
+ return fn(obj)
70
72
  }
71
- });
73
+ })
72
74
  } else {
73
- return this.query<T>(stmt.query, stmt.params, this.map).then(res => (!res || res.length === 0) ? null : res[0]);
75
+ return this.query<T>(stmt.query, stmt.params, this.map).then((res) => (!res || res.length === 0 ? null : res[0]))
74
76
  }
75
77
  }
76
78
  exist(id: ID, ctx?: any): Promise<boolean> {
77
- const field = (this.primaryKeys[0].column ? this.primaryKeys[0].column : this.primaryKeys[0].name);
78
- const stmt = exist<ID>(id, this.table, this.primaryKeys, this.param, field);
79
+ const field = this.primaryKeys[0].column ? this.primaryKeys[0].column : this.primaryKeys[0].name
80
+ const stmt = exist<ID>(id, this.table, this.primaryKeys, this.param, field)
79
81
  if (!stmt) {
80
- throw new Error('cannot build query by id');
82
+ throw new Error("cannot build query by id")
81
83
  }
82
- return this.query(stmt.query, stmt.params, this.map, undefined, ctx).then(res => (!res || res.length === 0) ? false : true);
84
+ return this.query(stmt.query, stmt.params, this.map, undefined, ctx).then((res) => (!res || res.length === 0 ? false : true))
83
85
  }
84
86
  }
85
87
  // tslint:disable-next-line:max-classes-per-file
86
88
  export class QueryRepository<T, ID> {
87
89
  constructor(public db: DB, public table: string, public attrs: Attributes, public sort?: string, id?: string) {
88
- this.id = (id && id.length > 0 ? id : 'id');
89
- this.query = this.query.bind(this);
90
- const m = metadata(attrs);
91
- this.map = m.map;
92
- this.bools = m.bools;
93
- }
94
- id: string;
95
- map?: StringMap;
96
- bools?: Attribute[];
90
+ this.id = id && id.length > 0 ? id : "id"
91
+ this.query = this.query.bind(this)
92
+ const m = metadata(attrs)
93
+ this.map = m.map
94
+ this.bools = m.bools
95
+ }
96
+ id: string
97
+ map?: StringMap
98
+ bools?: Attribute[]
97
99
  query(ids: ID[]): Promise<T[]> {
98
100
  if (!ids || ids.length === 0) {
99
- return Promise.resolve([]);
101
+ return Promise.resolve([])
100
102
  }
101
- const ps: string[] = [];
102
- const length = ids.length;
103
+ const ps: string[] = []
104
+ const length = ids.length
103
105
  for (let i = 1; i <= length; i++) {
104
- ps.push(this.db.param(i));
106
+ ps.push(this.db.param(i))
105
107
  }
106
- let sql = `select * from ${this.table} where ${this.id} in (${ps.join(',')})`;
108
+ let sql = `select * from ${this.table} where ${this.id} in (${ps.join(",")})`
107
109
  if (this.sort && this.sort.length > 0) {
108
- sql = sql + ' order by ' + this.sort;
110
+ sql = sql + " order by " + this.sort
109
111
  }
110
- return this.db.query<T>(sql, ids, this.map, this.bools);
112
+ return this.db.query<T>(sql, ids, this.map, this.bools)
111
113
  }
112
114
  }
113
115
  // tslint:disable-next-line:max-classes-per-file
114
116
  export class SqlLoadRepository<T, K1, K2> {
115
- map?: StringMap;
116
- attributes: Attributes;
117
- bools?: Attribute[];
118
- id1Col: string;
119
- id2Col: string;
117
+ map?: StringMap
118
+ attributes: Attributes
119
+ bools?: Attribute[]
120
+ id1Col: string
121
+ id2Col: string
120
122
  constructor(
121
123
  public query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
122
124
  public table: string,
@@ -126,443 +128,494 @@ export class SqlLoadRepository<T, K1, K2> {
126
128
  public id2Field: string,
127
129
  public fromDB?: (v: T) => T,
128
130
  id1Col?: string,
129
- id2Col?: string) {
130
-
131
- const m = metadata(attrs);
132
- this.attributes = attrs;
133
- this.map = m.map;
134
- this.bools = m.bools;
131
+ id2Col?: string,
132
+ ) {
133
+ const m = metadata(attrs)
134
+ this.attributes = attrs
135
+ this.map = m.map
136
+ this.bools = m.bools
135
137
 
136
138
  if (this.metadata) {
137
- this.metadata = this.metadata.bind(this);
139
+ this.metadata = this.metadata.bind(this)
138
140
  }
139
- this.all = this.all.bind(this);
140
- this.load = this.load.bind(this);
141
- this.exist = this.exist.bind(this);
141
+ this.all = this.all.bind(this)
142
+ this.load = this.load.bind(this)
143
+ this.exist = this.exist.bind(this)
142
144
  if (id1Col && id1Col.length > 0) {
143
- this.id1Col = id1Col;
145
+ this.id1Col = id1Col
144
146
  } else {
145
- const c = attrs[this.id1Field];
147
+ const c = attrs[this.id1Field]
146
148
  if (c) {
147
- this.id1Col = (c.column && c.column.length > 0 ? c.column : this.id1Field);
149
+ this.id1Col = c.column && c.column.length > 0 ? c.column : this.id1Field
148
150
  } else {
149
- this.id1Col = this.id1Field;
151
+ this.id1Col = this.id1Field
150
152
  }
151
153
  }
152
154
  if (id2Col && id2Col.length > 0) {
153
- this.id2Col = id2Col;
155
+ this.id2Col = id2Col
154
156
  } else {
155
- const c = attrs[this.id2Field];
157
+ const c = attrs[this.id2Field]
156
158
  if (c) {
157
- this.id2Col = (c.column && c.column.length > 0 ? c.column : this.id2Field);
159
+ this.id2Col = c.column && c.column.length > 0 ? c.column : this.id2Field
158
160
  } else {
159
- this.id2Col = this.id2Field;
161
+ this.id2Col = this.id2Field
160
162
  }
161
163
  }
162
164
  }
163
- metadata?(): Attributes|undefined {
164
- return this.attributes;
165
+ metadata?(): Attributes | undefined {
166
+ return this.attributes
165
167
  }
166
168
  all(): Promise<T[]> {
167
- const sql = `select * from ${this.table}`;
168
- return this.query(sql, [], this.map);
169
- }
170
- load(id1: K1, id2: K2, ctx?: any): Promise<T|null> {
171
- return this.query<T>(`select * from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`, [id1, id2], this.map, undefined, ctx).then(objs => {
169
+ const sql = `select * from ${this.table}`
170
+ return this.query(sql, [], this.map)
171
+ }
172
+ load(id1: K1, id2: K2, ctx?: any): Promise<T | null> {
173
+ return this.query<T>(
174
+ `select * from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`,
175
+ [id1, id2],
176
+ this.map,
177
+ undefined,
178
+ ctx,
179
+ ).then((objs) => {
172
180
  if (!objs || objs.length === 0) {
173
- return null;
181
+ return null
174
182
  } else {
175
- const fn = this.fromDB;
183
+ const fn = this.fromDB
176
184
  if (fn) {
177
- return fn(objs[0]);
185
+ return fn(objs[0])
178
186
  } else {
179
- return objs[0];
187
+ return objs[0]
180
188
  }
181
189
  }
182
- });
190
+ })
183
191
  }
184
192
  exist(id1: K1, id2: K2, ctx?: any): Promise<boolean> {
185
- return this.query<T>(`select ${this.id1Col} from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`, [id1, id2], undefined, undefined, ctx).then(objs => {
186
- return (objs && objs.length > 0 ? true : false);
187
- });
193
+ return this.query<T>(
194
+ `select ${this.id1Col} from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`,
195
+ [id1, id2],
196
+ undefined,
197
+ undefined,
198
+ ctx,
199
+ ).then((objs) => {
200
+ return objs && objs.length > 0 ? true : false
201
+ })
188
202
  }
189
203
  }
190
204
  // tslint:disable-next-line:max-classes-per-file
191
205
  export class GenericRepository<T, K1, K2> extends SqlLoadRepository<T, K1, K2> {
192
- version?: string;
193
- exec: (sql: string, args?: any[], ctx?: any) => Promise<number>;
194
- execBatch: (statements: Statement[], firstSuccess?: boolean, ctx?: any) => Promise<number>;
195
- constructor(manager: Manager, table: string,
206
+ version?: string
207
+ exec: (sql: string, args?: any[], ctx?: any) => Promise<number>
208
+ execBatch: (statements: Statement[], firstSuccess?: boolean, ctx?: any) => Promise<number>
209
+ constructor(
210
+ manager: Manager,
211
+ table: string,
196
212
  attrs: Attributes,
197
213
  id1Field: string,
198
214
  id2Field: string,
199
215
  public toDB?: (v: T) => T,
200
216
  fromDB?: (v: T) => T,
201
217
  id1Col?: string,
202
- id2Col?: string) {
203
- super(manager.query, table, attrs, manager.param, id1Field, id2Field, fromDB, id1Col, id2Col);
204
- const x = version(attrs);
205
- this.exec = manager.exec;
206
- this.execBatch = manager.execBatch;
218
+ id2Col?: string,
219
+ ) {
220
+ super(manager.query, table, attrs, manager.param, id1Field, id2Field, fromDB, id1Col, id2Col)
221
+ const x = version(attrs)
222
+ this.exec = manager.exec
223
+ this.execBatch = manager.execBatch
207
224
  if (x) {
208
- this.version = x.name;
225
+ this.version = x.name
209
226
  }
210
- this.create = this.create.bind(this);
211
- this.update = this.update.bind(this);
212
- this.patch = this.patch.bind(this);
213
- this.delete = this.delete.bind(this);
227
+ this.create = this.create.bind(this)
228
+ this.update = this.update.bind(this)
229
+ this.patch = this.patch.bind(this)
230
+ this.delete = this.delete.bind(this)
214
231
  }
215
232
  create(obj: T, ctx?: any): Promise<number> {
216
- let obj2 = obj;
233
+ let obj2 = obj
217
234
  if (this.toDB) {
218
- obj2 = this.toDB(obj);
235
+ obj2 = this.toDB(obj)
219
236
  }
220
- const stmt = buildToInsert(obj2, this.table, this.attributes, this.param, this.version);
237
+ const stmt = buildToInsert(obj2, this.table, this.attributes, this.param, this.version)
221
238
  if (stmt) {
222
- return this.exec(stmt.query, stmt.params, ctx).catch(err => {
223
- if (err && err.error === 'duplicate') {
224
- return 0;
239
+ return this.exec(stmt.query, stmt.params, ctx).catch((err) => {
240
+ if (err && err.error === "duplicate") {
241
+ return 0
225
242
  } else {
226
- throw err;
243
+ throw err
227
244
  }
228
- });
245
+ })
229
246
  } else {
230
- return Promise.resolve(0);
247
+ return Promise.resolve(0)
231
248
  }
232
249
  }
233
250
  update(obj: T, ctx?: any): Promise<number> {
234
- let obj2 = obj;
251
+ let obj2 = obj
235
252
  if (this.toDB) {
236
- obj2 = this.toDB(obj);
253
+ obj2 = this.toDB(obj)
237
254
  }
238
- const stmt = buildToUpdate(obj2, this.table, this.attributes, this.param, this.version);
255
+ const stmt = buildToUpdate(obj2, this.table, this.attributes, this.param, this.version)
239
256
  if (stmt) {
240
- return this.exec(stmt.query, stmt.params, ctx);
257
+ return this.exec(stmt.query, stmt.params, ctx)
241
258
  } else {
242
- return Promise.resolve(0);
259
+ return Promise.resolve(0)
243
260
  }
244
261
  }
245
262
  patch(obj: Partial<T>, ctx?: any): Promise<number> {
246
- return this.update(obj as any, ctx);
263
+ return this.update(obj as any, ctx)
247
264
  }
248
265
  delete(id1: K1, id2: K2, ctx?: any): Promise<number> {
249
- return this.exec(`delete from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`, [id1, id2], ctx);
266
+ return this.exec(`delete from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`, [id1, id2], ctx)
250
267
  }
251
268
  }
252
269
  // tslint:disable-next-line:max-classes-per-file
253
270
  export class SqlSearchLoader<T, ID, S extends Filter> extends SqlLoader<T, ID> {
254
271
  constructor(
255
- protected find: (s: S, limit?: number, offset?: number|string, fields?: string[]) => Promise<SearchResult<T>>,
256
- query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
257
- table: string,
258
- attrs: Attributes|string[],
259
- param: (i: number) => string,
260
- fromDB?: (v: T) => T) {
261
- super(query, table, attrs, param, fromDB);
262
- this.search = this.search.bind(this);
263
- }
264
- search(s: S, limit?: number, offset?: number|string, fields?: string[]): Promise<SearchResult<T>> {
265
- return this.find(s, limit, offset, fields);
272
+ protected find: (s: S, limit?: number, offset?: number | string, fields?: string[]) => Promise<SearchResult<T>>,
273
+ query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
274
+ table: string,
275
+ attrs: Attributes | string[],
276
+ param: (i: number) => string,
277
+ fromDB?: (v: T) => T,
278
+ ) {
279
+ super(query, table, attrs, param, fromDB)
280
+ this.search = this.search.bind(this)
281
+ }
282
+ search(s: S, limit?: number, offset?: number | string, fields?: string[]): Promise<SearchResult<T>> {
283
+ return this.find(s, limit, offset, fields)
266
284
  }
267
285
  }
268
286
  export interface Manager {
269
- driver: string;
270
- param(i: number): string;
271
- exec(sql: string, args?: any[], ctx?: any): Promise<number>;
272
- execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number>;
273
- query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]>;
287
+ driver: string
288
+ param(i: number): string
289
+ exec(sql: string, args?: any[], ctx?: any): Promise<number>
290
+ execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number>
291
+ query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]>
274
292
  }
275
- export type DB = Manager;
293
+ export type DB = Manager
276
294
  export interface ExtManager {
277
- driver: string;
278
- param(i: number): string;
279
- exec(sql: string, args?: any[], ctx?: any): Promise<number>;
280
- execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number>;
281
- query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]>;
282
- queryOne<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T|null>;
283
- execScalar<T>(sql: string, args?: any[], ctx?: any): Promise<T>;
284
- count(sql: string, args?: any[], ctx?: any): Promise<number>;
295
+ driver: string
296
+ param(i: number): string
297
+ exec(sql: string, args?: any[], ctx?: any): Promise<number>
298
+ execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number>
299
+ query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]>
300
+ queryOne<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T | null>
301
+ execScalar<T>(sql: string, args?: any[], ctx?: any): Promise<T>
302
+ count(sql: string, args?: any[], ctx?: any): Promise<number>
285
303
  }
286
304
  export interface SimpleMap {
287
- [key: string]: string|number|boolean|Date;
305
+ [key: string]: string | number | boolean | Date
288
306
  }
289
307
  export interface Logger {
290
- level: number;
291
- debug(msg: string, m?: SimpleMap, ctx?: any): void;
292
- info(msg: string, m?: SimpleMap, ctx?: any): void;
293
- error(msg: string, m?: SimpleMap, ctx?: any): void;
294
- isDebugEnabled(): boolean;
295
- isInfoEnabled(): boolean;
308
+ level: number
309
+ debug(msg: string, m?: SimpleMap, ctx?: any): void
310
+ info(msg: string, m?: SimpleMap, ctx?: any): void
311
+ error(msg: string, m?: SimpleMap, ctx?: any): void
312
+ isDebugEnabled(): boolean
313
+ isInfoEnabled(): boolean
296
314
  }
297
- export function log(db: ExtManager, isLog: boolean|undefined|null, logger: Logger, q?: string, result?: string, r?: string, duration?: string): ExtManager {
315
+ export function log(db: ExtManager, isLog: boolean | undefined | null, logger: Logger, q?: string, result?: string, r?: string, duration?: string): ExtManager {
298
316
  if (!isLog) {
299
- return db;
317
+ return db
300
318
  }
301
319
  if (q !== undefined && q != null && q.length > 0) {
302
320
  if (!logger.isDebugEnabled()) {
303
- return db;
321
+ return db
304
322
  }
305
- return new LogManager(db, logger.error, logger.debug, q, result, r, duration);
323
+ return new LogManager(db, logger.error, logger.debug, q, result, r, duration)
306
324
  }
307
325
  if (!logger.isInfoEnabled()) {
308
- return db;
326
+ return db
309
327
  }
310
- return new LogManager(db, logger.error, logger.info, q, result, r, duration);
328
+ return new LogManager(db, logger.error, logger.info, q, result, r, duration)
311
329
  }
312
- export function useLog(db: ExtManager, isLog: boolean|undefined|null, err: ((msg: string, m?: SimpleMap) => void)|undefined, lg?: (msg: string, m?: SimpleMap) => void, q?: string, result?: string, r?: string, duration?: string): ExtManager {
330
+ export function useLog(
331
+ db: ExtManager,
332
+ isLog: boolean | undefined | null,
333
+ err: ((msg: string, m?: SimpleMap) => void) | undefined,
334
+ lg?: (msg: string, m?: SimpleMap) => void,
335
+ q?: string,
336
+ result?: string,
337
+ r?: string,
338
+ duration?: string,
339
+ ): ExtManager {
313
340
  if (!isLog) {
314
- return db;
341
+ return db
315
342
  }
316
343
  if (err) {
317
- return new LogManager(db, err, lg, q, result, r, duration);
344
+ return new LogManager(db, err, lg, q, result, r, duration)
318
345
  }
319
- return db;
346
+ return db
320
347
  }
321
348
  // tslint:disable-next-line:max-classes-per-file
322
349
  export class LogManager implements ExtManager {
323
- constructor(public db: ExtManager, err: (msg: string, m?: SimpleMap) => void, lg?: (msg: string, m?: SimpleMap) => void, q?: string, result?: string, r?: string, duration?: string) {
324
- this.driver = db.driver;
325
- this.duration = (duration && duration.length > 0 ? duration : 'duration');
326
- this.sql = (q === undefined ? '' : q);
327
- this.return = (r !== undefined && r != null ? r : 'count');
328
- this.result = (result !== undefined && result != null ? result : '');
350
+ constructor(
351
+ public db: ExtManager,
352
+ err: (msg: string, m?: SimpleMap) => void,
353
+ lg?: (msg: string, m?: SimpleMap) => void,
354
+ q?: string,
355
+ result?: string,
356
+ r?: string,
357
+ duration?: string,
358
+ ) {
359
+ this.driver = db.driver
360
+ this.duration = duration && duration.length > 0 ? duration : "duration"
361
+ this.sql = q === undefined ? "" : q
362
+ this.return = r !== undefined && r != null ? r : "count"
363
+ this.result = result !== undefined && result != null ? result : ""
329
364
  // this.err = (er ? er : 'error');
330
- this.log = lg;
331
- this.error = err;
332
- this.param = this.param.bind(this);
333
- this.exec = this.exec.bind(this);
334
- this.execBatch = this.execBatch.bind(this);
335
- this.query = this.query.bind(this);
336
- this.queryOne = this.queryOne.bind(this);
337
- this.execScalar = this.execScalar.bind(this);
338
- this.count = this.count.bind(this);
339
- }
340
- log?: (msg: string, m?: SimpleMap, ctx?: any) => void;
341
- error: (msg: string, m?: SimpleMap, ctx?: any) => void;
342
- driver: string;
343
- duration: string;
344
- sql: string;
345
- return: string;
346
- result: string;
365
+ this.log = lg
366
+ this.error = err
367
+ this.param = this.param.bind(this)
368
+ this.exec = this.exec.bind(this)
369
+ this.execBatch = this.execBatch.bind(this)
370
+ this.query = this.query.bind(this)
371
+ this.queryOne = this.queryOne.bind(this)
372
+ this.execScalar = this.execScalar.bind(this)
373
+ this.count = this.count.bind(this)
374
+ }
375
+ log?: (msg: string, m?: SimpleMap, ctx?: any) => void
376
+ error: (msg: string, m?: SimpleMap, ctx?: any) => void
377
+ driver: string
378
+ duration: string
379
+ sql: string
380
+ return: string
381
+ result: string
347
382
  // err: string;
348
383
  param(i: number): string {
349
- return this.db.param(i);
384
+ return this.db.param(i)
350
385
  }
351
386
  exec(sql: string, args?: any[], ctx?: any): Promise<number> {
352
- const t1 = new Date();
353
- return this.db.exec(sql, args, ctx).then(v => {
354
- setTimeout(() => {
355
- if (this.log) {
356
- const d = diff(t1);
357
- const obj: SimpleMap = {} ;
358
- if (this.sql.length > 0) {
359
- obj[this.sql] = getString(sql, args);
387
+ const t1 = new Date()
388
+ return this.db
389
+ .exec(sql, args, ctx)
390
+ .then((v) => {
391
+ setTimeout(() => {
392
+ if (this.log) {
393
+ const d = diff(t1)
394
+ const obj: SimpleMap = {}
395
+ if (this.sql.length > 0) {
396
+ obj[this.sql] = getString(sql, args)
397
+ }
398
+ if (this.return.length > 0) {
399
+ obj[this.return] = v
400
+ }
401
+ obj[this.duration] = d
402
+ this.log("query", obj)
360
403
  }
361
- if (this.return.length > 0) {
362
- obj[this.return] = v;
404
+ }, 0)
405
+ return v
406
+ })
407
+ .catch((er) => {
408
+ setTimeout(() => {
409
+ const d = diff(t1)
410
+ const obj: SimpleMap = {}
411
+ if (this.sql.length > 0) {
412
+ obj[this.sql] = getString(sql, args)
363
413
  }
364
- obj[this.duration] = d;
365
- this.log('query', obj);
366
- }
367
- }, 0);
368
- return v;
369
- }).catch(er => {
370
- setTimeout(() => {
371
- const d = diff(t1);
372
- const obj: SimpleMap = {};
373
- if (this.sql.length > 0) {
374
- obj[this.sql] = getString(sql, args);
375
- }
376
- obj[this.duration] = d;
377
- this.error('error query: ' + buildString(er));
378
- }, 0);
379
- throw er;
380
- });
414
+ obj[this.duration] = d
415
+ this.error("error query: " + buildString(er))
416
+ }, 0)
417
+ throw er
418
+ })
381
419
  }
382
420
  execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number> {
383
- const t1 = new Date();
384
- return this.db.execBatch(statements, firstSuccess, ctx).then(v => {
385
- setTimeout(() => {
386
- if (this.log) {
387
- const d = diff(t1);
388
- const obj: SimpleMap = {} ;
389
- if (this.sql.length > 0) {
390
- obj[this.sql] = JSON.stringify(statements);
421
+ const t1 = new Date()
422
+ return this.db
423
+ .execBatch(statements, firstSuccess, ctx)
424
+ .then((v) => {
425
+ setTimeout(() => {
426
+ if (this.log) {
427
+ const d = diff(t1)
428
+ const obj: SimpleMap = {}
429
+ if (this.sql.length > 0) {
430
+ obj[this.sql] = JSON.stringify(statements)
431
+ }
432
+ if (this.return.length > 0) {
433
+ obj[this.return] = v
434
+ }
435
+ obj[this.duration] = d
436
+ this.log("exec batch", obj)
391
437
  }
392
- if (this.return.length > 0) {
393
- obj[this.return] = v;
438
+ }, 0)
439
+ return v
440
+ })
441
+ .catch((er) => {
442
+ setTimeout(() => {
443
+ const d = diff(t1)
444
+ const obj: SimpleMap = {}
445
+ if (this.sql.length > 0) {
446
+ obj[this.sql] = JSON.stringify(statements)
394
447
  }
395
- obj[this.duration] = d;
396
- this.log('exec batch', obj);
397
- }
398
- }, 0);
399
- return v;
400
- }).catch(er => {
401
- setTimeout(() => {
402
- const d = diff(t1);
403
- const obj: SimpleMap = {};
404
- if (this.sql.length > 0) {
405
- obj[this.sql] = JSON.stringify(statements);
406
- }
407
- obj[this.duration] = d;
408
- this.error('error exec batch: ' + buildString(er));
409
- }, 0);
410
- throw er;
411
- });
448
+ obj[this.duration] = d
449
+ this.error("error exec batch: " + buildString(er))
450
+ }, 0)
451
+ throw er
452
+ })
412
453
  }
413
454
  query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]> {
414
- const t1 = new Date();
415
- return this.db.query<T>(sql, args, m, bools, ctx).then(v => {
416
- setTimeout(() => {
417
- if (this.log) {
418
- const d = diff(t1);
419
- const obj: SimpleMap = {} ;
420
- if (this.sql.length > 0) {
421
- obj[this.sql] = getString(sql, args);
422
- }
423
- if (this.result.length > 0) {
424
- if (v && v.length > 0) {
425
- obj[this.result] = JSON.stringify(v);
455
+ const t1 = new Date()
456
+ return this.db
457
+ .query<T>(sql, args, m, bools, ctx)
458
+ .then((v) => {
459
+ setTimeout(() => {
460
+ if (this.log) {
461
+ const d = diff(t1)
462
+ const obj: SimpleMap = {}
463
+ if (this.sql.length > 0) {
464
+ obj[this.sql] = getString(sql, args)
426
465
  }
466
+ if (this.result.length > 0) {
467
+ if (v && v.length > 0) {
468
+ obj[this.result] = JSON.stringify(v)
469
+ }
470
+ }
471
+ if (this.return.length > 0) {
472
+ obj[this.return] = v ? v.length : 0
473
+ }
474
+ obj[this.duration] = d
475
+ this.log("query", obj)
427
476
  }
428
- if (this.return.length > 0) {
429
- obj[this.return] = v ? v.length : 0;
430
- }
431
- obj[this.duration] = d;
432
- this.log('query', obj);
433
- }
434
- }, 0);
435
- return v;
436
- }).catch(er => {
437
- setTimeout(() => {
438
- const d = diff(t1);
439
- const obj: SimpleMap = {};
440
- if (this.sql.length > 0) {
441
- obj[this.sql] = getString(sql, args);
442
- }
443
- obj[this.duration] = d;
444
- this.error('error query: ' + buildString(er));
445
- }, 0);
446
- throw er;
447
- });
448
- }
449
- queryOne<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T|null> {
450
- const t1 = new Date();
451
- return this.db.queryOne<T>(sql, args, m, bools, ctx).then(v => {
452
- setTimeout(() => {
453
- if (this.log) {
454
- const d = diff(t1);
455
- const obj: SimpleMap = {} ;
477
+ }, 0)
478
+ return v
479
+ })
480
+ .catch((er) => {
481
+ setTimeout(() => {
482
+ const d = diff(t1)
483
+ const obj: SimpleMap = {}
456
484
  if (this.sql.length > 0) {
457
- obj[this.sql] = getString(sql, args);
485
+ obj[this.sql] = getString(sql, args)
458
486
  }
459
- if (this.result.length > 0) {
460
- obj[this.result] = v ? JSON.stringify(v) : 'null';
487
+ obj[this.duration] = d
488
+ this.error("error query: " + buildString(er))
489
+ }, 0)
490
+ throw er
491
+ })
492
+ }
493
+ queryOne<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T | null> {
494
+ const t1 = new Date()
495
+ return this.db
496
+ .queryOne<T>(sql, args, m, bools, ctx)
497
+ .then((v) => {
498
+ setTimeout(() => {
499
+ if (this.log) {
500
+ const d = diff(t1)
501
+ const obj: SimpleMap = {}
502
+ if (this.sql.length > 0) {
503
+ obj[this.sql] = getString(sql, args)
504
+ }
505
+ if (this.result.length > 0) {
506
+ obj[this.result] = v ? JSON.stringify(v) : "null"
507
+ }
508
+ if (this.return.length > 0) {
509
+ obj[this.return] = v ? 1 : 0
510
+ }
511
+ obj[this.duration] = d
512
+ this.log("query one", obj)
461
513
  }
462
- if (this.return.length > 0) {
463
- obj[this.return] = v ? 1 : 0;
514
+ }, 0)
515
+ return v
516
+ })
517
+ .catch((er) => {
518
+ setTimeout(() => {
519
+ const d = diff(t1)
520
+ const obj: SimpleMap = {}
521
+ if (this.sql.length > 0) {
522
+ obj[this.sql] = getString(sql, args)
464
523
  }
465
- obj[this.duration] = d;
466
- this.log('query one', obj);
467
- }
468
- }, 0);
469
- return v;
470
- }).catch(er => {
471
- setTimeout(() => {
472
- const d = diff(t1);
473
- const obj: SimpleMap = {};
474
- if (this.sql.length > 0) {
475
- obj[this.sql] = getString(sql, args);
476
- }
477
- obj[this.duration] = d;
478
- this.error('error query one: ' + buildString(er));
479
- }, 0);
480
- throw er;
481
- });
524
+ obj[this.duration] = d
525
+ this.error("error query one: " + buildString(er))
526
+ }, 0)
527
+ throw er
528
+ })
482
529
  }
483
530
  execScalar<T>(sql: string, args?: any[], ctx?: any): Promise<T> {
484
- const t1 = new Date();
485
- return this.db.execScalar<T>(sql, args, ctx).then(v => {
486
- setTimeout(() => {
487
- if (this.log) {
488
- const d = diff(t1);
489
- const obj: SimpleMap = {} ;
490
- if (this.sql.length > 0) {
491
- obj[this.sql] = getString(sql, args);
492
- }
493
- if (this.result.length > 0) {
494
- obj[this.result] = v ? buildString(v) : 'null';
531
+ const t1 = new Date()
532
+ return this.db
533
+ .execScalar<T>(sql, args, ctx)
534
+ .then((v) => {
535
+ setTimeout(() => {
536
+ if (this.log) {
537
+ const d = diff(t1)
538
+ const obj: SimpleMap = {}
539
+ if (this.sql.length > 0) {
540
+ obj[this.sql] = getString(sql, args)
541
+ }
542
+ if (this.result.length > 0) {
543
+ obj[this.result] = v ? buildString(v) : "null"
544
+ }
545
+ if (this.return.length > 0) {
546
+ obj[this.return] = v ? 1 : 0
547
+ }
548
+ obj[this.duration] = d
549
+ this.log("exec scalar", obj)
495
550
  }
496
- if (this.return.length > 0) {
497
- obj[this.return] = v ? 1 : 0;
551
+ }, 0)
552
+ return v
553
+ })
554
+ .catch((er) => {
555
+ setTimeout(() => {
556
+ const d = diff(t1)
557
+ const obj: SimpleMap = {}
558
+ if (this.sql.length > 0) {
559
+ obj[this.sql] = getString(sql, args)
498
560
  }
499
- obj[this.duration] = d;
500
- this.log('exec scalar', obj);
501
- }
502
- }, 0);
503
- return v;
504
- }).catch(er => {
505
- setTimeout(() => {
506
- const d = diff(t1);
507
- const obj: SimpleMap = {};
508
- if (this.sql.length > 0) {
509
- obj[this.sql] = getString(sql, args);
510
- }
511
- obj[this.duration] = d;
512
- this.error('error exec scalar: ' + buildString(er));
513
- }, 0);
514
- throw er;
515
- });
561
+ obj[this.duration] = d
562
+ this.error("error exec scalar: " + buildString(er))
563
+ }, 0)
564
+ throw er
565
+ })
516
566
  }
517
567
  count(sql: string, args?: any[], ctx?: any): Promise<number> {
518
- const t1 = new Date();
519
- return this.db.count(sql, args).then(v => {
520
- setTimeout(() => {
521
- if (this.log) {
522
- const d = diff(t1);
523
- const obj: SimpleMap = {} ;
524
- if (this.sql.length > 0) {
525
- obj[this.sql] = getString(sql, args);
568
+ const t1 = new Date()
569
+ return this.db
570
+ .count(sql, args)
571
+ .then((v) => {
572
+ setTimeout(() => {
573
+ if (this.log) {
574
+ const d = diff(t1)
575
+ const obj: SimpleMap = {}
576
+ if (this.sql.length > 0) {
577
+ obj[this.sql] = getString(sql, args)
578
+ }
579
+ if (this.return.length > 0) {
580
+ obj[this.return] = v
581
+ }
582
+ obj[this.duration] = d
583
+ this.log("count", obj)
526
584
  }
527
- if (this.return.length > 0) {
528
- obj[this.return] = v;
585
+ }, 0)
586
+ return v
587
+ })
588
+ .catch((er) => {
589
+ setTimeout(() => {
590
+ const d = diff(t1)
591
+ const obj: SimpleMap = {}
592
+ if (this.sql.length > 0) {
593
+ obj[this.sql] = getString(sql, args)
529
594
  }
530
- obj[this.duration] = d;
531
- this.log('count', obj);
532
- }
533
- }, 0);
534
- return v;
535
- }).catch(er => {
536
- setTimeout(() => {
537
- const d = diff(t1);
538
- const obj: SimpleMap = {};
539
- if (this.sql.length > 0) {
540
- obj[this.sql] = getString(sql, args);
541
- }
542
- obj[this.duration] = d;
543
- this.error('error count: ' + buildString(er));
544
- }, 0);
545
- throw er;
546
- });
595
+ obj[this.duration] = d
596
+ this.error("error count: " + buildString(er))
597
+ }, 0)
598
+ throw er
599
+ })
547
600
  }
548
601
  }
549
602
  function buildString(v: any): string {
550
- if (typeof v === 'string') {
551
- return v;
603
+ if (typeof v === "string") {
604
+ return v
552
605
  } else {
553
- return JSON.stringify(v);
606
+ return JSON.stringify(v)
554
607
  }
555
608
  }
556
609
  function getString(sql: string, args?: any[]): string {
557
610
  if (args && args.length > 0) {
558
- return sql + ' ' + JSON.stringify(args);
611
+ return sql + " " + JSON.stringify(args)
559
612
  } else {
560
- return sql;
613
+ return sql
561
614
  }
562
615
  }
563
616
  export function diff(d1: Date): number {
564
- const d2 = new Date();
565
- return d2.getTime() - d1.getTime();
617
+ const d2 = new Date()
618
+ return d2.getTime() - d1.getTime()
566
619
  }
567
620
  /*
568
621
  const NS_PER_SEC = 1e9;
@@ -574,80 +627,78 @@ const getDurationInMilliseconds = (start: [number, number] | undefined) => {
574
627
  */
575
628
  // tslint:disable-next-line:max-classes-per-file
576
629
  export class SqlWriter<T, ID> extends SqlLoader<T, ID> {
577
- version?: string;
578
- exec: (sql: string, args?: any[], ctx?: any) => Promise<number>;
579
- execBatch: (statements: Statement[], firstSuccess?: boolean, ctx?: any) => Promise<number>;
580
- constructor(manager: Manager, table: string,
581
- attrs: Attributes,
582
- public toDB?: (v: T) => T,
583
- fromDB?: (v: T) => T) {
584
- super(manager.query, table, attrs, manager.param, fromDB);
585
- const x = version(attrs);
586
- this.exec = manager.exec;
587
- this.execBatch = manager.execBatch;
630
+ version?: string
631
+ exec: (sql: string, args?: any[], ctx?: any) => Promise<number>
632
+ execBatch: (statements: Statement[], firstSuccess?: boolean, ctx?: any) => Promise<number>
633
+ constructor(manager: Manager, table: string, attrs: Attributes, public toDB?: (v: T) => T, fromDB?: (v: T) => T) {
634
+ super(manager.query, table, attrs, manager.param, fromDB)
635
+ const x = version(attrs)
636
+ this.exec = manager.exec
637
+ this.execBatch = manager.execBatch
588
638
  if (x) {
589
- this.version = x.name;
639
+ this.version = x.name
590
640
  }
591
- this.create = this.create.bind(this);
592
- this.update = this.update.bind(this);
593
- this.patch = this.patch.bind(this);
594
- this.delete = this.delete.bind(this);
641
+ this.create = this.create.bind(this)
642
+ this.update = this.update.bind(this)
643
+ this.patch = this.patch.bind(this)
644
+ this.delete = this.delete.bind(this)
595
645
  }
596
646
  create(obj: T, ctx?: any): Promise<number> {
597
- let obj2 = obj;
647
+ let obj2 = obj
598
648
  if (this.toDB) {
599
- obj2 = this.toDB(obj);
649
+ obj2 = this.toDB(obj)
600
650
  }
601
- const stmt = buildToInsert(obj2, this.table, this.attributes, this.param, this.version);
651
+ const stmt = buildToInsert(obj2, this.table, this.attributes, this.param, this.version)
602
652
  if (stmt) {
603
- return this.exec(stmt.query, stmt.params, ctx).catch(err => {
604
- if (err && err.error === 'duplicate') {
605
- return 0;
653
+ return this.exec(stmt.query, stmt.params, ctx).catch((err) => {
654
+ if (err && err.error === "duplicate") {
655
+ return 0
606
656
  } else {
607
- throw err;
657
+ throw err
608
658
  }
609
- });
659
+ })
610
660
  } else {
611
- return Promise.resolve(0);
661
+ return Promise.resolve(0)
612
662
  }
613
663
  }
614
664
  update(obj: T, ctx?: any): Promise<number> {
615
- let obj2 = obj;
665
+ let obj2 = obj
616
666
  if (this.toDB) {
617
- obj2 = this.toDB(obj);
667
+ obj2 = this.toDB(obj)
618
668
  }
619
- const stmt = buildToUpdate(obj2, this.table, this.attributes, this.param, this.version);
669
+ const stmt = buildToUpdate(obj2, this.table, this.attributes, this.param, this.version)
620
670
  if (stmt) {
621
- return this.exec(stmt.query, stmt.params, ctx);
671
+ return this.exec(stmt.query, stmt.params, ctx)
622
672
  } else {
623
- return Promise.resolve(0);
673
+ return Promise.resolve(0)
624
674
  }
625
675
  }
626
676
  patch(obj: Partial<T>, ctx?: any): Promise<number> {
627
- return this.update(obj as any, ctx);
677
+ return this.update(obj as any, ctx)
628
678
  }
629
679
  delete(id: ID, ctx?: any): Promise<number> {
630
- const stmt = buildToDelete<ID>(id, this.table, this.primaryKeys, this.param);
680
+ const stmt = buildToDelete<ID>(id, this.table, this.primaryKeys, this.param)
631
681
  if (stmt) {
632
- return this.exec(stmt.query, stmt.params, ctx);
682
+ return this.exec(stmt.query, stmt.params, ctx)
633
683
  } else {
634
- return Promise.resolve(0);
684
+ return Promise.resolve(0)
635
685
  }
636
686
  }
637
687
  }
638
688
  // tslint:disable-next-line:max-classes-per-file
639
689
  export class SqlSearchWriter<T, ID, S extends Filter> extends SqlWriter<T, ID> {
640
690
  constructor(
641
- protected find: (s: S, limit?: number, offset?: number|string, fields?: string[]) => Promise<SearchResult<T>>,
642
- manager: Manager,
643
- table: string,
644
- attrs: Attributes,
645
- toDB?: (v: T) => T,
646
- fromDB?: (v: T) => T) {
647
- super(manager, table, attrs, toDB, fromDB);
648
- this.search = this.search.bind(this);
649
- }
650
- search(s: S, limit?: number, offset?: number|string, fields?: string[]): Promise<SearchResult<T>> {
651
- return this.find(s, limit, offset, fields);
691
+ protected find: (s: S, limit?: number, offset?: number | string, fields?: string[]) => Promise<SearchResult<T>>,
692
+ manager: Manager,
693
+ table: string,
694
+ attrs: Attributes,
695
+ toDB?: (v: T) => T,
696
+ fromDB?: (v: T) => T,
697
+ ) {
698
+ super(manager, table, attrs, toDB, fromDB)
699
+ this.search = this.search.bind(this)
700
+ }
701
+ search(s: S, limit?: number, offset?: number | string, fields?: string[]): Promise<SearchResult<T>> {
702
+ return this.find(s, limit, offset, fields)
652
703
  }
653
704
  }