query-core 0.1.20 → 0.1.23

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,4 +1,17 @@
1
1
  "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ extendStatics(d, b);
11
+ function __() { this.constructor = d; }
12
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
+ };
14
+ })();
2
15
  Object.defineProperty(exports, "__esModule", { value: true });
3
16
  var build_1 = require("./build");
4
17
  var query_1 = require("./query");
@@ -27,20 +40,20 @@ var SearchBuilder = (function () {
27
40
  this.excluding = (excluding && excluding.length > 0 ? excluding : 'excluding');
28
41
  this.search = this.search.bind(this);
29
42
  if (buildParam) {
30
- this.buildParam = buildParam;
43
+ this.param = buildParam;
31
44
  }
32
45
  else {
33
46
  if (provider === search_1.oracle) {
34
- this.buildParam = query_1.buildOracleParam;
47
+ this.param = query_1.buildOracleParam;
35
48
  }
36
49
  else if (provider === exports.postgres) {
37
- this.buildParam = query_1.buildDollarParam;
50
+ this.param = query_1.buildDollarParam;
38
51
  }
39
52
  else if (provider === exports.mssql) {
40
- this.buildParam = query_1.buildMsSQLParam;
53
+ this.param = query_1.buildMsSQLParam;
41
54
  }
42
55
  else {
43
- this.buildParam = build_1.param;
56
+ this.param = build_1.param;
44
57
  }
45
58
  }
46
59
  this.total = (total && total.length > 0 ? total : 'total');
@@ -53,7 +66,7 @@ var SearchBuilder = (function () {
53
66
  var st = (this.sort ? this.sort : 'sort');
54
67
  var sn = s[st];
55
68
  delete s[st];
56
- var x = (this.provider === exports.postgres ? 'ilike' : this.buildParam);
69
+ var x = (this.provider === exports.postgres ? 'ilike' : this.param);
57
70
  var q2 = this.buildQuery(s, x, sn, this.buildSort, this.attributes, this.table, fields, this.q, this.excluding);
58
71
  if (!q2) {
59
72
  throw new Error('Cannot build query');
@@ -77,3 +90,58 @@ var SearchBuilder = (function () {
77
90
  return SearchBuilder;
78
91
  }());
79
92
  exports.SearchBuilder = SearchBuilder;
93
+ var Query = (function (_super) {
94
+ __extends(Query, _super);
95
+ function Query(query, table, attributes, provider, buildQ, fromDB, sort, q, excluding, buildSort, buildParam, total) {
96
+ var _this = _super.call(this, query, table, attributes, provider, buildQ, fromDB, sort, q, excluding, buildSort, buildParam, total) || this;
97
+ var m = build_1.metadata(attributes);
98
+ _this.primaryKeys = m.keys;
99
+ _this.map = m.map;
100
+ _this.bools = m.bools;
101
+ if (_this.metadata) {
102
+ _this.metadata = _this.metadata.bind(_this);
103
+ }
104
+ _this.all = _this.all.bind(_this);
105
+ _this.load = _this.load.bind(_this);
106
+ _this.exist = _this.exist.bind(_this);
107
+ return _this;
108
+ }
109
+ Query.prototype.metadata = function () {
110
+ return this.attributes;
111
+ };
112
+ Query.prototype.all = function () {
113
+ var sql = "select * from " + this.table;
114
+ return this.query(sql, [], this.map);
115
+ };
116
+ Query.prototype.load = function (id, ctx) {
117
+ var stmt = build_1.select(id, this.table, this.primaryKeys, this.param);
118
+ if (!stmt) {
119
+ throw new Error('cannot build query by id');
120
+ }
121
+ var fn = this.fromDB;
122
+ if (fn) {
123
+ return this.query(stmt.query, stmt.params, this.map, ctx).then(function (res) {
124
+ if (!res || res.length === 0) {
125
+ return null;
126
+ }
127
+ else {
128
+ var obj = res[0];
129
+ return fn(obj);
130
+ }
131
+ });
132
+ }
133
+ else {
134
+ return this.query(stmt.query, stmt.params, this.map).then(function (res) { return (!res || res.length === 0) ? null : res[0]; });
135
+ }
136
+ };
137
+ Query.prototype.exist = function (id, ctx) {
138
+ var field = (this.primaryKeys[0].column ? this.primaryKeys[0].column : this.primaryKeys[0].name);
139
+ var stmt = build_1.exist(id, this.table, this.primaryKeys, this.param, field);
140
+ if (!stmt) {
141
+ throw new Error('cannot build query by id');
142
+ }
143
+ return this.query(stmt.query, stmt.params, this.map, undefined, ctx).then(function (res) { return (!res || res.length === 0) ? false : true; });
144
+ };
145
+ return Query;
146
+ }(SearchBuilder));
147
+ exports.Query = Query;
package/lib/index.js CHANGED
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  var health_1 = require("./health");
7
7
  exports.SqlChecker = health_1.Checker;
8
8
  var services_1 = require("./services");
9
- exports.SqlLoadRepository = services_1.SqlLoader;
10
9
  exports.SqlViewRepository = services_1.SqlLoader;
11
10
  exports.SqlLoadService = services_1.SqlLoader;
12
11
  exports.SqlViewService = services_1.SqlLoader;
package/lib/services.js CHANGED
@@ -14,16 +14,16 @@ var __extends = (this && this.__extends) || (function () {
14
14
  })();
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  var build_1 = require("./build");
17
- function useGet(table, q, attrs, param, fromDB) {
18
- var l = new SqlLoader(table, q, attrs, param, fromDB);
17
+ function useGet(q, table, attrs, param, fromDB) {
18
+ var l = new SqlLoader(q, table, attrs, param, fromDB);
19
19
  return l.load;
20
20
  }
21
21
  exports.useGet = useGet;
22
22
  exports.useLoad = useGet;
23
23
  var SqlLoader = (function () {
24
- function SqlLoader(table, query, attrs, param, fromDB) {
25
- this.table = table;
24
+ function SqlLoader(query, table, attrs, param, fromDB) {
26
25
  this.query = query;
26
+ this.table = table;
27
27
  this.param = param;
28
28
  this.fromDB = fromDB;
29
29
  if (Array.isArray(attrs)) {
@@ -83,10 +83,144 @@ var SqlLoader = (function () {
83
83
  return SqlLoader;
84
84
  }());
85
85
  exports.SqlLoader = SqlLoader;
86
+ var SqlLoadRepository = (function () {
87
+ function SqlLoadRepository(query, table, attrs, param, id1Field, id2Field, fromDB, id1Col, id2Col) {
88
+ this.query = query;
89
+ this.table = table;
90
+ this.param = param;
91
+ this.id1Field = id1Field;
92
+ this.id2Field = id2Field;
93
+ this.fromDB = fromDB;
94
+ var m = build_1.metadata(attrs);
95
+ this.attributes = attrs;
96
+ this.map = m.map;
97
+ this.bools = m.bools;
98
+ if (this.metadata) {
99
+ this.metadata = this.metadata.bind(this);
100
+ }
101
+ this.all = this.all.bind(this);
102
+ this.load = this.load.bind(this);
103
+ this.exist = this.exist.bind(this);
104
+ if (id1Col && id1Col.length > 0) {
105
+ this.id1Col = id1Col;
106
+ }
107
+ else {
108
+ var c = attrs[this.id1Field];
109
+ if (c) {
110
+ this.id1Col = (c.column && c.column.length > 0 ? c.column : this.id1Field);
111
+ }
112
+ else {
113
+ this.id1Col = this.id1Field;
114
+ }
115
+ }
116
+ if (id2Col && id2Col.length > 0) {
117
+ this.id2Col = id2Col;
118
+ }
119
+ else {
120
+ var c = attrs[this.id2Field];
121
+ if (c) {
122
+ this.id2Col = (c.column && c.column.length > 0 ? c.column : this.id2Field);
123
+ }
124
+ else {
125
+ this.id2Col = this.id2Field;
126
+ }
127
+ }
128
+ }
129
+ SqlLoadRepository.prototype.metadata = function () {
130
+ return this.attributes;
131
+ };
132
+ SqlLoadRepository.prototype.all = function () {
133
+ var sql = "select * from " + this.table;
134
+ return this.query(sql, [], this.map);
135
+ };
136
+ SqlLoadRepository.prototype.load = function (id1, id2, ctx) {
137
+ var _this = this;
138
+ return this.query("select * from " + this.table + " where " + this.id1Col + " = " + this.param(1) + " and " + this.id2Col + " = " + this.param(2), [id1, id2], this.map, undefined, ctx).then(function (objs) {
139
+ if (!objs || objs.length == 0) {
140
+ return null;
141
+ }
142
+ else {
143
+ var fn = _this.fromDB;
144
+ if (fn) {
145
+ return fn(objs[0]);
146
+ }
147
+ else {
148
+ return objs[0];
149
+ }
150
+ }
151
+ });
152
+ };
153
+ SqlLoadRepository.prototype.exist = function (id1, id2, ctx) {
154
+ return this.query("select " + this.id1Col + " from " + this.table + " where " + this.id1Col + " = " + this.param(1) + " and " + this.id2Col + " = " + this.param(2), [id1, id2], undefined, undefined, ctx).then(function (objs) {
155
+ return (objs && objs.length > 0 ? true : false);
156
+ });
157
+ };
158
+ return SqlLoadRepository;
159
+ }());
160
+ exports.SqlLoadRepository = SqlLoadRepository;
161
+ var GenericRepository = (function (_super) {
162
+ __extends(GenericRepository, _super);
163
+ function GenericRepository(manager, table, attrs, id1Field, id2Field, toDB, fromDB, id1Col, id2Col) {
164
+ var _this = _super.call(this, manager.query, table, attrs, manager.param, id1Field, id2Field, fromDB, id1Col, id2Col) || this;
165
+ _this.toDB = toDB;
166
+ var x = build_1.version(attrs);
167
+ _this.exec = manager.exec;
168
+ _this.execBatch = manager.execBatch;
169
+ if (x) {
170
+ _this.version = x.name;
171
+ }
172
+ _this.insert = _this.insert.bind(_this);
173
+ _this.update = _this.update.bind(_this);
174
+ _this.patch = _this.patch.bind(_this);
175
+ _this.delete = _this.delete.bind(_this);
176
+ return _this;
177
+ }
178
+ GenericRepository.prototype.insert = function (obj, ctx) {
179
+ var obj2 = obj;
180
+ if (this.toDB) {
181
+ obj2 = this.toDB(obj);
182
+ }
183
+ var stmt = build_1.buildToInsert(obj2, this.table, this.attributes, this.param, this.version);
184
+ if (stmt) {
185
+ return this.exec(stmt.query, stmt.params, ctx).catch(function (err) {
186
+ if (err && err.error === 'duplicate') {
187
+ return 0;
188
+ }
189
+ else {
190
+ throw err;
191
+ }
192
+ });
193
+ }
194
+ else {
195
+ return Promise.resolve(0);
196
+ }
197
+ };
198
+ GenericRepository.prototype.update = function (obj, ctx) {
199
+ var obj2 = obj;
200
+ if (this.toDB) {
201
+ obj2 = this.toDB(obj);
202
+ }
203
+ var stmt = build_1.buildToUpdate(obj2, this.table, this.attributes, this.param, this.version);
204
+ if (stmt) {
205
+ return this.exec(stmt.query, stmt.params, ctx);
206
+ }
207
+ else {
208
+ return Promise.resolve(0);
209
+ }
210
+ };
211
+ GenericRepository.prototype.patch = function (obj, ctx) {
212
+ return this.update(obj, ctx);
213
+ };
214
+ GenericRepository.prototype.delete = function (id1, id2, ctx) {
215
+ return this.exec("delete from " + this.table + " where " + this.id1Col + " = " + this.param(1) + " and " + this.id2Col + " = " + this.param(2), [id1, id2], ctx);
216
+ };
217
+ return GenericRepository;
218
+ }(SqlLoadRepository));
219
+ exports.GenericRepository = GenericRepository;
86
220
  var SqlSearchLoader = (function (_super) {
87
221
  __extends(SqlSearchLoader, _super);
88
- function SqlSearchLoader(find, table, query, attrs, param, fromDB) {
89
- var _this = _super.call(this, table, query, attrs, param, fromDB) || this;
222
+ function SqlSearchLoader(find, query, table, attrs, param, fromDB) {
223
+ var _this = _super.call(this, query, table, attrs, param, fromDB) || this;
90
224
  _this.find = find;
91
225
  _this.search = _this.search.bind(_this);
92
226
  return _this;
@@ -145,8 +279,36 @@ var LogManager = (function () {
145
279
  return this.db.param(i);
146
280
  };
147
281
  LogManager.prototype.exec = function (sql, args, ctx) {
282
+ var _this = this;
148
283
  var t1 = new Date();
149
- return this.db.exec(sql, args, ctx);
284
+ return this.db.exec(sql, args, ctx).then(function (v) {
285
+ setTimeout(function () {
286
+ if (_this.log) {
287
+ var d = diff(t1);
288
+ var obj = {};
289
+ if (_this.sql.length > 0) {
290
+ obj[_this.sql] = getString(sql, args);
291
+ }
292
+ if (_this.return.length > 0) {
293
+ obj[_this.return] = v;
294
+ }
295
+ obj[_this.duration] = d;
296
+ _this.log('query', obj);
297
+ }
298
+ }, 0);
299
+ return v;
300
+ }).catch(function (er) {
301
+ setTimeout(function () {
302
+ var d = diff(t1);
303
+ var obj = {};
304
+ if (_this.sql.length > 0) {
305
+ obj[_this.sql] = getString(sql, args);
306
+ }
307
+ obj[_this.duration] = d;
308
+ _this.error('error query: ' + buildString(er));
309
+ }, 0);
310
+ throw er;
311
+ });
150
312
  };
151
313
  LogManager.prototype.execBatch = function (statements, firstSuccess, ctx) {
152
314
  var _this = this;
@@ -346,7 +508,7 @@ exports.diff = diff;
346
508
  var SqlWriter = (function (_super) {
347
509
  __extends(SqlWriter, _super);
348
510
  function SqlWriter(manager, table, attrs, toDB, fromDB) {
349
- var _this = _super.call(this, table, manager.query, attrs, manager.param, fromDB) || this;
511
+ var _this = _super.call(this, manager.query, table, attrs, manager.param, fromDB) || this;
350
512
  _this.toDB = toDB;
351
513
  var x = build_1.version(attrs);
352
514
  _this.exec = manager.exec;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "query-core",
3
- "version": "0.1.20",
3
+ "version": "0.1.23",
4
4
  "description": "query",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./src/index.ts",
@@ -1,4 +1,4 @@
1
- import {metadata, param} from './build';
1
+ import {exist, metadata, param, select} from './build';
2
2
  import {Attribute, Attributes, Statement, StringMap} from './metadata';
3
3
  import {buildDollarParam, buildMsSQLParam, buildOracleParam, buildQuery, buildSort as bs, LikeType} from './query';
4
4
  import {buildFromQuery, oracle, SearchResult} from './search';
@@ -14,9 +14,10 @@ export class SearchBuilder<T, S> {
14
14
  q?: string;
15
15
  excluding?: string;
16
16
  buildSort?: (sort?: string, map?: Attributes|StringMap) => string;
17
- buildParam: (i: number) => string;
17
+ param: (i: number) => string;
18
18
  total?: string;
19
- constructor(public query: (sql: string, args?: any[], m?: StringMap, bools?: Attribute[]) => Promise<T[]>, public table: string,
19
+ constructor(public query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
20
+ public table: string,
20
21
  public attributes?: Attributes,
21
22
  public provider?: string,
22
23
  buildQ?: (s: S, bparam: LikeType|((i: number ) => string), sort?: string, buildSort3?: (sort?: string, map?: Attributes|StringMap) => string, attrs?: Attributes, table?: string, fields?: string[], sq?: string, strExcluding?: string) => Statement|undefined,
@@ -39,16 +40,16 @@ export class SearchBuilder<T, S> {
39
40
  this.excluding = (excluding && excluding.length > 0 ? excluding : 'excluding');
40
41
  this.search = this.search.bind(this);
41
42
  if (buildParam) {
42
- this.buildParam = buildParam;
43
+ this.param = buildParam;
43
44
  } else {
44
45
  if (provider === oracle) {
45
- this.buildParam = buildOracleParam;
46
+ this.param = buildOracleParam;
46
47
  } else if (provider === postgres) {
47
- this.buildParam = buildDollarParam;
48
+ this.param = buildDollarParam;
48
49
  } else if (provider === mssql) {
49
- this.buildParam = buildMsSQLParam;
50
+ this.param = buildMsSQLParam;
50
51
  } else {
51
- this.buildParam = param;
52
+ this.param = param;
52
53
  }
53
54
  }
54
55
  this.total = (total && total.length > 0 ? total : 'total');
@@ -61,14 +62,14 @@ export class SearchBuilder<T, S> {
61
62
  const st = (this.sort ? this.sort : 'sort');
62
63
  const sn = (s as any)[st] as string;
63
64
  delete (s as any)[st];
64
- const x = (this.provider === postgres ? 'ilike' : this.buildParam);
65
+ const x = (this.provider === postgres ? 'ilike' : this.param);
65
66
  const q2 = this.buildQuery(s, x, sn, this.buildSort, this.attributes, this.table, fields, this.q, this.excluding);
66
67
  if (!q2) {
67
68
  throw new Error('Cannot build query');
68
69
  }
69
70
  const fn = this.fromDB;
70
71
  if (fn) {
71
- return buildFromQuery(this.query, q2.query, q2.params, limit, skip, this.map, this.bools, this.provider, this.total).then(r => {
72
+ return buildFromQuery<T>(this.query, q2.query, q2.params, limit, skip, this.map, this.bools, this.provider, this.total).then(r => {
72
73
  if (r.list && r.list.length > 0) {
73
74
  r.list = r.list.map(o => fn(o));
74
75
  return r;
@@ -81,3 +82,69 @@ export class SearchBuilder<T, S> {
81
82
  }
82
83
  }
83
84
  }
85
+ // tslint:disable-next-line:max-classes-per-file
86
+ export class Query<T, ID, S> extends SearchBuilder<T, S> {
87
+ primaryKeys: Attribute[];
88
+ map?: StringMap;
89
+ // attributes: Attributes;
90
+ bools?: Attribute[];
91
+ constructor(
92
+ query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
93
+ table: string,
94
+ attributes: Attributes,
95
+ provider?: string,
96
+ buildQ?: (s: S, bparam: LikeType|((i: number ) => string), sort?: string, buildSort3?: (sort?: string, map?: Attributes|StringMap) => string, attrs?: Attributes, table?: string, fields?: string[], sq?: string, strExcluding?: string) => Statement|undefined,
97
+ fromDB?: (v: T) => T,
98
+ sort?: string,
99
+ q?: string,
100
+ excluding?: string,
101
+ buildSort?: (sort?: string, map?: Attributes|StringMap) => string,
102
+ buildParam?: (i: number) => string,
103
+ total?: string) {
104
+ super(query, table, attributes, provider, buildQ, fromDB, sort, q, excluding, buildSort, buildParam, total);
105
+ const m = metadata(attributes);
106
+ this.primaryKeys = m.keys;
107
+ this.map = m.map;
108
+ this.bools = m.bools;
109
+ if (this.metadata) {
110
+ this.metadata = this.metadata.bind(this);
111
+ }
112
+ this.all = this.all.bind(this);
113
+ this.load = this.load.bind(this);
114
+ this.exist = this.exist.bind(this);
115
+ }
116
+ metadata?(): Attributes|undefined {
117
+ return this.attributes;
118
+ }
119
+ all(): Promise<T[]> {
120
+ const sql = `select * from ${this.table}`;
121
+ return this.query(sql, [], this.map);
122
+ }
123
+ load(id: ID, ctx?: any): Promise<T|null> {
124
+ const stmt = select<ID>(id, this.table, this.primaryKeys, this.param);
125
+ if (!stmt) {
126
+ throw new Error('cannot build query by id');
127
+ }
128
+ const fn = this.fromDB;
129
+ if (fn) {
130
+ return this.query<T>(stmt.query, stmt.params, this.map, ctx).then(res => {
131
+ if (!res || res.length === 0) {
132
+ return null;
133
+ } else {
134
+ const obj = res[0];
135
+ return fn(obj);
136
+ }
137
+ });
138
+ } else {
139
+ return this.query<T>(stmt.query, stmt.params, this.map).then(res => (!res || res.length === 0) ? null : res[0]);
140
+ }
141
+ }
142
+ exist(id: ID, ctx?: any): Promise<boolean> {
143
+ const field = (this.primaryKeys[0].column ? this.primaryKeys[0].column : this.primaryKeys[0].name);
144
+ const stmt = exist<ID>(id, this.table, this.primaryKeys, this.param, field);
145
+ if (!stmt) {
146
+ throw new Error('cannot build query by id');
147
+ }
148
+ return this.query(stmt.query, stmt.params, this.map, undefined, ctx).then(res => (!res || res.length === 0) ? false : true);
149
+ }
150
+ }
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export {Checker as SqlChecker};
3
3
 
4
4
  import {Attribute, StringMap} from './metadata';
5
5
  import {SqlLoader, SqlSearchLoader, SqlSearchWriter, SqlWriter} from './services';
6
- export {SqlLoader as SqlLoadRepository};
6
+ // export {SqlLoader as SqlLoadRepository};
7
7
  export {SqlLoader as SqlViewRepository};
8
8
  export {SqlWriter as SqlGenericRepository};
9
9
  export {SqlWriter as Repository};
package/src/search.ts CHANGED
@@ -4,9 +4,9 @@ export interface SearchResult<T> {
4
4
  list: T[];
5
5
  total?: number;
6
6
  }
7
- export function buildFromQuery<T>(query: (sql: string, args?: any[], m?: StringMap, bools?: Attribute[]) => Promise<T[]>, sql: string, params?: any[], limit?: number, offset?: number, mp?: StringMap, bools?: Attribute[], provider?: string, totalCol?: string): Promise<SearchResult<T>> {
7
+ export function buildFromQuery<T>(query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[]) => Promise<K[]>, sql: string, params?: any[], limit?: number, offset?: number, mp?: StringMap, bools?: Attribute[], provider?: string, totalCol?: string): Promise<SearchResult<T>> {
8
8
  if (!limit || limit <= 0) {
9
- return query(sql, params, mp, bools).then(list => {
9
+ return query<T>(sql, params, mp, bools).then(list => {
10
10
  const total = (list ? list.length : undefined);
11
11
  return {list, total};
12
12
  });
@@ -20,8 +20,8 @@ export function buildFromQuery<T>(query: (sql: string, args?: any[], m?: StringM
20
20
  } else {
21
21
  const sql2 = buildPagingQuery(sql, limit, offset);
22
22
  const countQuery = buildCountQuery(sql);
23
- const resultPromise = query(sql2, params, mp, bools);
24
- const countPromise = query(countQuery, params).then(r => {
23
+ const resultPromise = query<T>(sql2, params, mp, bools);
24
+ const countPromise = query<T>(countQuery, params).then(r => {
25
25
  if (!r || r.length === 0) {
26
26
  return 0;
27
27
  } else {
@@ -37,11 +37,11 @@ export function buildFromQuery<T>(query: (sql: string, args?: any[], m?: StringM
37
37
  }
38
38
  }
39
39
  }
40
- export function queryAndCount<T>(query: (sql: string, args?: any[], m?: StringMap, bools?: Attribute[]) => Promise<T[]>, sql: string, params: any[]|undefined, total: string, mp?: StringMap, bools?: Attribute[]): Promise<SearchResult<T>> {
40
+ export function queryAndCount<T>(query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[]) => Promise<K[]>, sql: string, params: any[]|undefined, total: string, mp?: StringMap, bools?: Attribute[]): Promise<SearchResult<T>> {
41
41
  if (!total || total.length === 0) {
42
42
  total = 'total';
43
43
  }
44
- return query(sql, params, mp, bools).then(list => {
44
+ return query<T>(sql, params, mp, bools).then(list => {
45
45
  if (!list || list.length === 0) {
46
46
  return {list: [], total: 0};
47
47
  }
package/src/services.ts CHANGED
@@ -9,12 +9,13 @@ export interface Filter {
9
9
  }
10
10
  export type Load<T, ID> = (id: ID, ctx?: any) => Promise<T|null>;
11
11
  export type Get<T, ID> = Load<T, ID>;
12
- export function useGet<T, ID>(table: string,
12
+ export function useGet<T, ID>(
13
13
  q: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
14
+ table: string,
14
15
  attrs: Attributes|string[],
15
16
  param: (i: number) => string,
16
17
  fromDB?: (v: T) => T): Load<T, ID> {
17
- const l = new SqlLoader<T, ID>(table, q, attrs, param, fromDB);
18
+ const l = new SqlLoader<T, ID>(q, table, attrs, param, fromDB);
18
19
  return l.load;
19
20
  }
20
21
  export const useLoad = useGet;
@@ -23,8 +24,9 @@ export class SqlLoader<T, ID> {
23
24
  map?: StringMap;
24
25
  attributes: Attributes;
25
26
  bools?: Attribute[];
26
- constructor(public table: string,
27
+ constructor(
27
28
  public query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
29
+ public table: string,
28
30
  attrs: Attributes|string[],
29
31
  public param: (i: number) => string,
30
32
  public fromDB?: (v: T) => T) {
@@ -81,15 +83,154 @@ export class SqlLoader<T, ID> {
81
83
  }
82
84
  }
83
85
  // tslint:disable-next-line:max-classes-per-file
86
+ export class SqlLoadRepository<T, K1, K2> {
87
+ map?: StringMap;
88
+ attributes: Attributes;
89
+ bools?: Attribute[];
90
+ id1Col: string;
91
+ id2Col: string;
92
+ constructor(
93
+ public query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
94
+ public table: string,
95
+ attrs: Attributes,
96
+ public param: (i: number) => string,
97
+ public id1Field: string,
98
+ public id2Field: string,
99
+ public fromDB?: (v: T) => T,
100
+ id1Col?: string,
101
+ id2Col?: string) {
102
+
103
+ const m = metadata(attrs);
104
+ this.attributes = attrs;
105
+ this.map = m.map;
106
+ this.bools = m.bools;
107
+
108
+ if (this.metadata) {
109
+ this.metadata = this.metadata.bind(this);
110
+ }
111
+ this.all = this.all.bind(this);
112
+ this.load = this.load.bind(this);
113
+ this.exist = this.exist.bind(this);
114
+ if (id1Col && id1Col.length > 0) {
115
+ this.id1Col = id1Col;
116
+ } else {
117
+ const c = attrs[this.id1Field];
118
+ if (c) {
119
+ this.id1Col = (c.column && c.column.length > 0 ? c.column : this.id1Field);
120
+ } else {
121
+ this.id1Col = this.id1Field;
122
+ }
123
+ }
124
+ if (id2Col && id2Col.length > 0) {
125
+ this.id2Col = id2Col;
126
+ } else {
127
+ const c = attrs[this.id2Field];
128
+ if (c) {
129
+ this.id2Col = (c.column && c.column.length > 0 ? c.column : this.id2Field);
130
+ } else {
131
+ this.id2Col = this.id2Field;
132
+ }
133
+ }
134
+ }
135
+ metadata?(): Attributes|undefined {
136
+ return this.attributes;
137
+ }
138
+ all(): Promise<T[]> {
139
+ const sql = `select * from ${this.table}`;
140
+ return this.query(sql, [], this.map);
141
+ }
142
+ load(id1: K1, id2: K2, ctx?: any): Promise<T|null> {
143
+ 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 => {
144
+ if (!objs || objs.length == 0) {
145
+ return null;
146
+ } else {
147
+ const fn = this.fromDB;
148
+ if (fn) {
149
+ return fn(objs[0]);
150
+ } else {
151
+ return objs[0];
152
+ }
153
+ }
154
+ });
155
+ }
156
+ exist(id1: K1, id2: K2, ctx?: any): Promise<boolean> {
157
+ 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 => {
158
+ return (objs && objs.length > 0 ? true : false);
159
+ });
160
+ }
161
+ }
162
+ // tslint:disable-next-line:max-classes-per-file
163
+ export class GenericRepository<T, K1, K2> extends SqlLoadRepository<T, K1, K2> {
164
+ version?: string;
165
+ exec: (sql: string, args?: any[], ctx?: any) => Promise<number>;
166
+ execBatch: (statements: Statement[], firstSuccess?: boolean, ctx?: any) => Promise<number>;
167
+ constructor(manager: Manager, table: string,
168
+ attrs: Attributes,
169
+ id1Field: string,
170
+ id2Field: string,
171
+ public toDB?: (v: T) => T,
172
+ fromDB?: (v: T) => T,
173
+ id1Col?: string,
174
+ id2Col?: string) {
175
+ super(manager.query, table, attrs, manager.param, id1Field, id2Field, fromDB, id1Col, id2Col);
176
+ const x = version(attrs);
177
+ this.exec = manager.exec;
178
+ this.execBatch = manager.execBatch;
179
+ if (x) {
180
+ this.version = x.name;
181
+ }
182
+ this.insert = this.insert.bind(this);
183
+ this.update = this.update.bind(this);
184
+ this.patch = this.patch.bind(this);
185
+ this.delete = this.delete.bind(this);
186
+ }
187
+ insert(obj: T, ctx?: any): Promise<number> {
188
+ let obj2 = obj;
189
+ if (this.toDB) {
190
+ obj2 = this.toDB(obj);
191
+ }
192
+ const stmt = buildToInsert(obj2, this.table, this.attributes, this.param, this.version);
193
+ if (stmt) {
194
+ return this.exec(stmt.query, stmt.params, ctx).catch(err => {
195
+ if (err && err.error === 'duplicate') {
196
+ return 0;
197
+ } else {
198
+ throw err;
199
+ }
200
+ });
201
+ } else {
202
+ return Promise.resolve(0);
203
+ }
204
+ }
205
+ update(obj: T, ctx?: any): Promise<number> {
206
+ let obj2 = obj;
207
+ if (this.toDB) {
208
+ obj2 = this.toDB(obj);
209
+ }
210
+ const stmt = buildToUpdate(obj2, this.table, this.attributes, this.param, this.version);
211
+ if (stmt) {
212
+ return this.exec(stmt.query, stmt.params, ctx);
213
+ } else {
214
+ return Promise.resolve(0);
215
+ }
216
+ }
217
+ patch(obj: Partial<T>, ctx?: any): Promise<number> {
218
+ return this.update(obj as any, ctx);
219
+ }
220
+ delete(id1: K1, id2: K2, ctx?: any): Promise<number> {
221
+ return this.exec(`delete from ${this.table} where ${this.id1Col} = ${this.param(1)} and ${this.id2Col} = ${this.param(2)}`, [id1, id2], ctx);
222
+ }
223
+ }
224
+ // tslint:disable-next-line:max-classes-per-file
84
225
  export class SqlSearchLoader<T, ID, S extends Filter> extends SqlLoader<T, ID> {
85
226
  constructor(
86
227
  protected find: (s: S, limit?: number, offset?: number|string, fields?: string[]) => Promise<SearchResult<T>>,
87
- table: string,
88
228
  query: <K>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any) => Promise<K[]>,
229
+ table: string,
89
230
  attrs: Attributes|string[],
90
231
  param: (i: number) => string,
91
232
  fromDB?: (v: T) => T) {
92
- super(table, query, attrs, param, fromDB);
233
+ super(query, table, attrs, param, fromDB);
93
234
  this.search = this.search.bind(this);
94
235
  }
95
236
  search(s: S, limit?: number, offset?: number|string, fields?: string[]): Promise<SearchResult<T>> {
@@ -181,7 +322,34 @@ export class LogManager implements ExtManager {
181
322
  }
182
323
  exec(sql: string, args?: any[], ctx?: any): Promise<number> {
183
324
  const t1 = new Date();
184
- return this.db.exec(sql, args, ctx);
325
+ return this.db.exec(sql, args, ctx).then(v => {
326
+ setTimeout(() => {
327
+ if (this.log) {
328
+ const d = diff(t1);
329
+ const obj: SimpleMap = {} ;
330
+ if (this.sql.length > 0) {
331
+ obj[this.sql] = getString(sql, args);
332
+ }
333
+ if (this.return.length > 0) {
334
+ obj[this.return] = v;
335
+ }
336
+ obj[this.duration] = d;
337
+ this.log('query', obj);
338
+ }
339
+ }, 0);
340
+ return v;
341
+ }).catch(er => {
342
+ setTimeout(() => {
343
+ const d = diff(t1);
344
+ const obj: SimpleMap = {};
345
+ if (this.sql.length > 0) {
346
+ obj[this.sql] = getString(sql, args);
347
+ }
348
+ obj[this.duration] = d;
349
+ this.error('error query: ' + buildString(er));
350
+ }, 0);
351
+ throw er;
352
+ });
185
353
  }
186
354
  execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number> {
187
355
  const t1 = new Date();
@@ -385,7 +553,7 @@ export class SqlWriter<T, ID> extends SqlLoader<T, ID> {
385
553
  attrs: Attributes,
386
554
  public toDB?: (v: T) => T,
387
555
  fromDB?: (v: T) => T) {
388
- super(table, manager.query, attrs, manager.param, fromDB);
556
+ super(manager.query, table, attrs, manager.param, fromDB);
389
557
  const x = version(attrs);
390
558
  this.exec = manager.exec;
391
559
  this.execBatch = manager.execBatch;