mysql2-core 0.2.2 → 0.2.4

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/index.ts CHANGED
@@ -1,684 +1,728 @@
1
- import { Connection, createPool as createPool2, FieldPacket, format, OkPacket, Pool, PoolConnection, ResultSetHeader } from 'mysql2';
2
- import { buildToSave, buildToSaveBatch } from './build';
3
- import { Attribute, Attributes, Manager, Statement, StringMap } from './metadata';
1
+ import { Connection, createPool as createPool2, FieldPacket, format, Pool, PoolConnection, ResultSetHeader } from "mysql2"
2
+ import { buildToSave, buildToSaveBatch } from "./build"
3
+ import { Attribute, Attributes, Manager, Statement, StringMap } from "./metadata"
4
4
 
5
- export * from './metadata';
6
- export * from './build';
5
+ export * from "./build"
6
+ export * from "./metadata"
7
7
 
8
8
  // tslint:disable-next-line:class-name
9
9
  export class resource {
10
- static string?: boolean;
10
+ static string?: boolean
11
11
  }
12
12
  export interface Config {
13
- host?: string | undefined;
14
- port?: number;
15
- server?: string | undefined;
16
- database?: string | undefined;
17
- user?: string | undefined;
18
- password?: string | undefined;
19
- multipleStatements?: boolean | undefined;
20
- connectionLimit?: number | undefined;
21
- max?: number | undefined;
22
- min?: number | undefined;
23
- idleTimeoutMillis?: number | undefined;
13
+ host?: string | undefined
14
+ port?: number
15
+ server?: string | undefined
16
+ database?: string | undefined
17
+ user?: string | undefined
18
+ password?: string | undefined
19
+ multipleStatements?: boolean | undefined
20
+ connectionLimit?: number | undefined
21
+ max?: number | undefined
22
+ min?: number | undefined
23
+ idleTimeoutMillis?: number | undefined
24
24
  }
25
25
  export function createPool(conf: Config): Pool {
26
26
  if (conf.max && conf.max > 0 && !conf.connectionLimit) {
27
- conf.connectionLimit = conf.max;
27
+ conf.connectionLimit = conf.max
28
28
  }
29
- const pool = createPool2({...conf, rowsAsArray: true});
30
- return pool;
29
+ const pool = createPool2({ ...conf, rowsAsArray: true })
30
+ return pool
31
31
  }
32
32
 
33
33
  // tslint:disable-next-line:max-classes-per-file
34
34
  export class PoolManager implements Manager {
35
35
  constructor(public pool: Pool) {
36
- this.param = this.param.bind(this);
37
- this.exec = this.exec.bind(this);
38
- this.execBatch = this.execBatch.bind(this);
39
- this.query = this.query.bind(this);
40
- this.queryOne = this.queryOne.bind(this);
41
- this.execScalar = this.execScalar.bind(this);
42
- this.count = this.count.bind(this);
43
- }
44
- driver = 'mysql';
36
+ this.param = this.param.bind(this)
37
+ this.exec = this.exec.bind(this)
38
+ this.execBatch = this.execBatch.bind(this)
39
+ this.query = this.query.bind(this)
40
+ this.queryOne = this.queryOne.bind(this)
41
+ this.execScalar = this.execScalar.bind(this)
42
+ this.count = this.count.bind(this)
43
+ }
44
+ driver = "mysql"
45
45
  param(i: number): string {
46
- return '?';
46
+ return "?"
47
47
  }
48
48
  exec(sql: string, args?: any[], ctx?: any): Promise<number> {
49
- const p = (ctx ? ctx : this.pool);
50
- return exec(p, sql, args);
49
+ const p = ctx ? ctx : this.pool
50
+ return exec(p, sql, args)
51
51
  }
52
52
  execBatch(statements: Statement[], firstSuccess?: boolean, ctx?: any): Promise<number> {
53
- const p = (ctx ? ctx : this.pool);
54
- return execBatch(p, statements, firstSuccess);
53
+ const p = ctx ? ctx : this.pool
54
+ return execBatch(p, statements, firstSuccess)
55
55
  }
56
56
  query<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T[]> {
57
- const p = (ctx ? ctx : this.pool);
58
- return query(p, sql, args, m, bools);
57
+ const p = ctx ? ctx : this.pool
58
+ return query(p, sql, args, m, bools)
59
59
  }
60
60
  queryOne<T>(sql: string, args?: any[], m?: StringMap, bools?: Attribute[], ctx?: any): Promise<T | null> {
61
- const p = (ctx ? ctx : this.pool);
62
- return queryOne(p, sql, args, m, bools);
61
+ const p = ctx ? ctx : this.pool
62
+ return queryOne(p, sql, args, m, bools)
63
63
  }
64
64
  execScalar<T>(sql: string, args?: any[], ctx?: any): Promise<T> {
65
- const p = (ctx ? ctx : this.pool);
66
- return execScalar<T>(p, sql, args);
65
+ const p = ctx ? ctx : this.pool
66
+ return execScalar<T>(p, sql, args)
67
67
  }
68
68
  count(sql: string, args?: any[], ctx?: any): Promise<number> {
69
- const p = (ctx ? ctx : this.pool);
70
- return count(p, sql, args);
69
+ const p = ctx ? ctx : this.pool
70
+ return count(p, sql, args)
71
71
  }
72
72
  }
73
73
  export function execBatch(pool: Pool, statements: Statement[], firstSuccess?: boolean): Promise<number> {
74
74
  if (!statements || statements.length === 0) {
75
- return Promise.resolve(0);
75
+ return Promise.resolve(0)
76
76
  } else if (statements.length === 1) {
77
- return exec(pool, statements[0].query, statements[0].params);
77
+ return exec(pool, statements[0].query, statements[0].params)
78
78
  }
79
79
  if (firstSuccess) {
80
80
  return new Promise<number>((resolve, reject) => {
81
81
  pool.getConnection((er0, connection) => {
82
82
  if (er0) {
83
- return reject(er0);
83
+ return reject(er0)
84
84
  }
85
- connection.beginTransaction(er1 => {
85
+ connection.beginTransaction((er1) => {
86
86
  if (er1) {
87
87
  connection.rollback(() => {
88
- return reject(er1);
89
- });
88
+ return reject(er1)
89
+ })
90
90
  } else {
91
- let query0 = '';
92
- const queries: string[] = [];
93
- const l = statements.length;
91
+ let query0 = ""
92
+ const queries: string[] = []
93
+ const l = statements.length
94
94
  for (let j = 0; j < l; j++) {
95
- const item = statements[j];
95
+ const item = statements[j]
96
96
  if (j === 0) {
97
- query0 = format(item.query, toArray(item.params));
97
+ query0 = format(item.query, toArray(item.params))
98
98
  } else {
99
- if (item.query.endsWith(';')) {
100
- queries.push(format(item.query, toArray(item.params)));
99
+ if (item.query.endsWith(";")) {
100
+ queries.push(format(item.query, toArray(item.params)))
101
101
  } else {
102
- queries.push(format(item.query + ';', toArray(item.params)));
102
+ queries.push(format(item.query + ";", toArray(item.params)))
103
103
  }
104
104
  }
105
105
  }
106
- connection.query<ResultSetHeader>(query0, (er2a, results0) => {
106
+ connection.execute<ResultSetHeader>(query0, (er2a, results0) => {
107
107
  if (er2a) {
108
108
  connection.rollback(() => {
109
- return reject(er2a);
110
- });
109
+ return reject(er2a)
110
+ })
111
111
  } else {
112
112
  if (results0 && results0.affectedRows === 0) {
113
- return 0;
113
+ return 0
114
114
  } else {
115
- connection.query<OkPacket[]>(queries.join(''), (er2, results) => {
115
+ connection.execute<ResultSetHeader>(queries.join(""), (er2, results) => {
116
116
  if (er2) {
117
117
  connection.rollback(() => {
118
- return reject(er2);
119
- });
118
+ return reject(er2)
119
+ })
120
120
  } else {
121
121
  connection.commit((er3) => {
122
122
  if (er3) {
123
123
  connection.rollback(() => {
124
- return reject(er3);
125
- });
124
+ return reject(er3)
125
+ })
126
126
  }
127
- });
128
- let c = 0;
129
- c += results0.affectedRows + results.reduce((prev, item) => prev + item.affectedRows, 0);
130
- return resolve(c);
127
+ })
128
+ let c = 0
129
+ c += results0.affectedRows + results.affectedRows
130
+ return resolve(c)
131
131
  }
132
- });
132
+ })
133
133
  }
134
134
  }
135
- });
135
+ })
136
136
  }
137
- });
138
- });
139
- });
137
+ })
138
+ })
139
+ })
140
140
  } else {
141
141
  return new Promise<number>((resolve, reject) => {
142
142
  pool.getConnection((er0, connection) => {
143
143
  if (er0) {
144
- return reject(er0);
144
+ return reject(er0)
145
145
  }
146
- connection.beginTransaction(er1 => {
146
+ connection.beginTransaction((er1) => {
147
147
  if (er1) {
148
148
  connection.rollback(() => {
149
- return reject(er1);
150
- });
149
+ return reject(er1)
150
+ })
151
151
  } else {
152
- const queries: string[] = [];
153
- statements.forEach(item => {
154
- if (item.query.endsWith(';')) {
155
- queries.push(format(item.query, toArray(item.params)));
152
+ const queries: string[] = []
153
+ statements.forEach((item) => {
154
+ if (item.query.endsWith(";")) {
155
+ queries.push(format(item.query, toArray(item.params)))
156
156
  } else {
157
- queries.push(format(item.query + ';', toArray(item.params)));
157
+ queries.push(format(item.query + ";", toArray(item.params)))
158
158
  }
159
- });
160
- connection.query<OkPacket[]>(queries.join(''), (er2, results) => {
159
+ })
160
+ connection.execute<ResultSetHeader>(queries.join(""), (er2, results) => {
161
161
  if (er2) {
162
162
  connection.rollback(() => {
163
- buildError(er2);
164
- return reject(er2);
165
- });
163
+ buildError(er2)
164
+ return reject(er2)
165
+ })
166
166
  } else {
167
167
  connection.commit((er3) => {
168
168
  if (er3) {
169
169
  connection.rollback(() => {
170
- return reject(er3);
171
- });
170
+ return reject(er3)
171
+ })
172
172
  }
173
- });
174
- return resolve(results.reduce((prev, item) => prev + item.affectedRows, 0));
173
+ })
174
+ return resolve(results.affectedRows)
175
175
  }
176
- });
176
+ })
177
177
  }
178
- });
179
- });
180
- });
178
+ })
179
+ })
180
+ })
181
181
  }
182
182
  }
183
183
  function buildError(err: any): any {
184
- if (err.errno === 1062 && err.code === 'ER_DUP_ENTRY') {
185
- err.error = 'duplicate';
184
+ if (err.errno === 1062 && err.code === "ER_DUP_ENTRY") {
185
+ err.error = "duplicate"
186
186
  }
187
- return err;
187
+ return err
188
188
  }
189
189
 
190
- export async function exec(pool: Pool, sql: string, args?: any[]): Promise<number> {
191
- const p = toArray(args);
190
+ export async function exec(pool: Pool | PoolConnection, sql: string, args?: any[]): Promise<number> {
191
+ const p = toArray(args)
192
192
  return new Promise<number>((resolve, reject) => {
193
193
  return pool.execute<ResultSetHeader>(sql, p, (err, res) => {
194
194
  if (err) {
195
- buildError(err);
196
- return reject(err);
195
+ buildError(err)
196
+ return reject(err)
197
197
  } else {
198
- return resolve(res.affectedRows);
198
+ return resolve(res.affectedRows)
199
199
  }
200
- });
201
- });
200
+ })
201
+ })
202
202
  }
203
203
  export async function query<T>(pool: Pool | PoolConnection, sql: string, args?: any[], m?: StringMap, bools?: Attribute[]): Promise<T[]> {
204
- const p = toArray(args);
204
+ const p = toArray(args)
205
205
  return new Promise((resolve, reject) => {
206
206
  return pool.query<T[] & ResultSetHeader>(sql, p, (err, results, fields) => {
207
207
  if (err) {
208
- return reject(err);
208
+ return reject(err)
209
209
  } else {
210
210
  if (results.length > 0) {
211
- const arrayResult = results.map(item => {
212
- if(Array.isArray(item)) {
213
- return formatData<T>(fields, item);
211
+ const arrayResult = results.map((item) => {
212
+ if (Array.isArray(item)) {
213
+ return formatData<T>(fields, item)
214
214
  } else {
215
215
  return item
216
216
  }
217
- });
218
- return resolve(handleResults(arrayResult, m, bools));
217
+ })
218
+ return resolve(handleResults(arrayResult, m, bools))
219
219
  } else {
220
- resolve([]);
220
+ resolve([])
221
221
  }
222
222
  }
223
- });
224
- });
223
+ })
224
+ })
225
225
  }
226
226
 
227
- export function queryOne<T>(pool: Pool, sql: string, args?: any[], m?: StringMap, bools?: Attribute[]): Promise<T | null> {
228
- return query<T>(pool, sql, args, m, bools).then(r => {
229
- return (r && r.length > 0 ? r[0] : null);
230
- });
227
+ export function queryOne<T>(pool: Pool | PoolConnection, sql: string, args?: any[], m?: StringMap, bools?: Attribute[]): Promise<T | null> {
228
+ return query<T>(pool, sql, args, m, bools).then((r) => {
229
+ return r && r.length > 0 ? r[0] : null
230
+ })
231
231
  }
232
- export function execScalar<T>(pool: Pool, sql: string, args?: any[]): Promise<T> {
233
- return queryOne<T>(pool, sql, args).then(r => {
232
+ export function execScalar<T>(pool: Pool | PoolConnection, sql: string, args?: any[]): Promise<T> {
233
+ return queryOne<T>(pool, sql, args).then((r) => {
234
234
  if (!r) {
235
- return null;
235
+ return null
236
236
  } else {
237
- const keys = Object.keys(r);
238
- return (r as any)[keys[0]];
237
+ const keys = Object.keys(r)
238
+ return (r as any)[keys[0]]
239
239
  }
240
- });
240
+ })
241
241
  }
242
242
 
243
- export function count(pool: Pool, sql: string, args?: any[]): Promise<number> {
244
- return execScalar<number>(pool, sql, args);
243
+ export function count(pool: Pool | PoolConnection, sql: string, args?: any[]): Promise<number> {
244
+ return execScalar<number>(pool, sql, args)
245
245
  }
246
246
 
247
- export function save<T>(pool: Pool | ((sql: string, args?: any[]) => Promise<number>), obj: T, table: string, attrs: Attributes, ver?: string, buildParam?: (i: number) => string, i?: number): Promise<number> {
248
- const s = buildToSave(obj, table, attrs, ver, buildParam);
247
+ export function save<T>(
248
+ pool: Pool | PoolConnection | ((sql: string, args?: any[]) => Promise<number>),
249
+ obj: T,
250
+ table: string,
251
+ attrs: Attributes,
252
+ ver?: string,
253
+ buildParam?: (i: number) => string,
254
+ i?: number,
255
+ ): Promise<number> {
256
+ const s = buildToSave(obj, table, attrs, ver, buildParam)
249
257
  if (!s) {
250
- return Promise.resolve(-1);
258
+ return Promise.resolve(-1)
251
259
  }
252
- if (typeof pool === 'function') {
253
- return pool(s.query, s.params);
260
+ if (typeof pool === "function") {
261
+ return pool(s.query, s.params)
254
262
  } else {
255
- return exec(pool, s.query, s.params);
256
- }
257
- }
258
- export function saveBatch<T>(pool: Pool | ((statements: Statement[]) => Promise<number>), objs: T[], table: string, attrs: Attributes, ver?: string, buildParam?: (i: number) => string): Promise<number> {
259
- const s = buildToSaveBatch(objs, table, attrs, ver, buildParam);
260
- if (typeof pool === 'function') {
261
- return pool(s);
263
+ return exec(pool, s.query, s.params)
264
+ }
265
+ }
266
+ export function saveBatch<T>(
267
+ pool: Pool | ((statements: Statement[]) => Promise<number>),
268
+ objs: T[],
269
+ table: string,
270
+ attrs: Attributes,
271
+ ver?: string,
272
+ buildParam?: (i: number) => string,
273
+ ): Promise<number> {
274
+ const s = buildToSaveBatch(objs, table, attrs, ver, buildParam)
275
+ if (typeof pool === "function") {
276
+ return pool(s)
262
277
  } else {
263
- return execBatch(pool, s);
278
+ return execBatch(pool, s)
264
279
  }
265
280
  }
266
281
  export function toArray(arr?: any[]): any[] {
267
282
  if (!arr || arr.length === 0) {
268
- return [];
283
+ return []
269
284
  }
270
- const p: any[] = [];
271
- const l = arr.length;
285
+ const p: any[] = []
286
+ const l = arr.length
272
287
  for (let i = 0; i < l; i++) {
273
288
  if (arr[i] === undefined || arr[i] == null) {
274
- p.push(null);
289
+ p.push(null)
275
290
  } else {
276
- if (typeof arr[i] === 'object') {
291
+ if (typeof arr[i] === "object") {
277
292
  if (arr[i] instanceof Date) {
278
- p.push(arr[i]);
293
+ p.push(arr[i])
279
294
  } else {
280
295
  if (resource.string) {
281
- const s: string = JSON.stringify(arr[i]);
282
- p.push(s);
296
+ const s: string = JSON.stringify(arr[i])
297
+ p.push(s)
283
298
  } else {
284
- p.push(arr[i]);
299
+ p.push(arr[i])
285
300
  }
286
301
  }
287
302
  } else {
288
- p.push(arr[i]);
303
+ p.push(arr[i])
289
304
  }
290
305
  }
291
306
  }
292
- return p;
307
+ return p
293
308
  }
294
309
  export function handleResults<T>(r: T[], m?: StringMap, bools?: Attribute[]) {
295
310
  if (m) {
296
- const res = mapArray(r, m);
311
+ const res = mapArray(r, m)
297
312
  if (bools && bools.length > 0) {
298
- return handleBool(res, bools);
313
+ return handleBool(res, bools)
299
314
  } else {
300
- return res;
315
+ return res
301
316
  }
302
317
  } else {
303
318
  if (bools && bools.length > 0) {
304
- return handleBool(r, bools);
319
+ return handleBool(r, bools)
305
320
  } else {
306
- return r;
321
+ return r
307
322
  }
308
323
  }
309
324
  }
310
325
  export function handleBool<T>(objs: T[], bools: Attribute[]) {
311
326
  if (!bools || bools.length === 0 || !objs) {
312
- return objs;
327
+ return objs
313
328
  }
314
329
  for (const obj of objs) {
315
- const o: any = obj;
330
+ const o: any = obj
316
331
  for (const field of bools) {
317
332
  if (field.name) {
318
- const v = o[field.name];
319
- if (typeof v !== 'boolean' && v != null && v !== undefined) {
320
- const b = field.true;
333
+ const v = o[field.name]
334
+ if (typeof v !== "boolean" && v != null && v !== undefined) {
335
+ const b = field.true
321
336
  if (b == null || b === undefined) {
322
337
  // tslint:disable-next-line:triple-equals
323
- o[field.name] = ('1' == v || 'T' == v || 'Y' == v || 'true' == v || 'on' == v);
338
+ o[field.name] = "1" == v || "T" == v || "Y" == v || "true" == v || "on" == v
324
339
  } else {
325
340
  // tslint:disable-next-line:triple-equals
326
- o[field.name] = (v == b ? true : false);
341
+ o[field.name] = v == b ? true : false
327
342
  }
328
343
  }
329
344
  }
330
345
  }
331
346
  }
332
- return objs;
347
+ return objs
333
348
  }
334
349
  export function formatData<T>(nameColumn: FieldPacket[], data: any, m?: StringMap): T {
335
- const result: any = {};
350
+ const result: any = {}
336
351
  nameColumn.forEach((item, index) => {
337
- let key = item.name;
352
+ let key = item.name
338
353
  if (m) {
339
- key = m[item.name];
354
+ key = m[item.name]
340
355
  }
341
- result[key] = data[index];
342
- });
343
- return result;
356
+ result[key] = data[index]
357
+ })
358
+ return result
344
359
  }
345
360
  export function map<T>(obj: T, m?: StringMap): any {
346
361
  if (!m) {
347
- return obj;
362
+ return obj
348
363
  }
349
- const mkeys = Object.keys(m);
364
+ const mkeys = Object.keys(m)
350
365
  if (mkeys.length === 0) {
351
- return obj;
366
+ return obj
352
367
  }
353
- const o: any = {};
354
- const keys = Object.keys(obj as any);
368
+ const o: any = {}
369
+ const keys = Object.keys(obj as any)
355
370
  for (const key of keys) {
356
- let k0 = m[key];
371
+ let k0 = m[key]
357
372
  if (!k0) {
358
- k0 = key;
373
+ k0 = key
359
374
  }
360
- o[k0] = (obj as any)[key];
375
+ o[k0] = (obj as any)[key]
361
376
  }
362
- return o;
377
+ return o
363
378
  }
364
379
  export function mapArray<T>(results: T[], m?: StringMap): T[] {
365
380
  if (!m) {
366
- return results;
381
+ return results
367
382
  }
368
- const mkeys = Object.keys(m);
383
+ const mkeys = Object.keys(m)
369
384
  if (mkeys.length === 0) {
370
- return results;
385
+ return results
371
386
  }
372
- const objs = [];
373
- const length = results.length;
387
+ const objs = []
388
+ const length = results.length
374
389
  for (let i = 0; i < length; i++) {
375
- const obj = results[i];
376
- const obj2: any = {};
377
- const keys = Object.keys(obj as any);
390
+ const obj = results[i]
391
+ const obj2: any = {}
392
+ const keys = Object.keys(obj as any)
378
393
  for (const key of keys) {
379
- let k0 = m[key];
394
+ let k0 = m[key]
380
395
  if (!k0) {
381
- k0 = key;
396
+ k0 = key
382
397
  }
383
- obj2[k0] = (obj as any)[key];
398
+ obj2[k0] = (obj as any)[key]
384
399
  }
385
- objs.push(obj2);
400
+ objs.push(obj2)
386
401
  }
387
- return objs;
402
+ return objs
388
403
  }
389
404
  export function getFields(fields: string[], all?: string[]): string[] | undefined {
390
405
  if (!fields || fields.length === 0) {
391
- return undefined;
406
+ return undefined
392
407
  }
393
- const ext: string[] = [];
408
+ const ext: string[] = []
394
409
  if (all) {
395
410
  for (const s of fields) {
396
411
  if (all.includes(s)) {
397
- ext.push(s);
412
+ ext.push(s)
398
413
  }
399
414
  }
400
415
  if (ext.length === 0) {
401
- return undefined;
416
+ return undefined
402
417
  } else {
403
- return ext;
418
+ return ext
404
419
  }
405
420
  } else {
406
- return fields;
421
+ return fields
407
422
  }
408
423
  }
409
424
  export function buildFields(fields: string[], all?: string[]): string {
410
- const s = getFields(fields, all);
425
+ const s = getFields(fields, all)
411
426
  if (!s || s.length === 0) {
412
- return '*';
427
+ return "*"
413
428
  } else {
414
- return s.join(',');
429
+ return s.join(",")
415
430
  }
416
431
  }
417
432
  export function getMapField(name: string, mp?: StringMap): string {
418
433
  if (!mp) {
419
- return name;
434
+ return name
420
435
  }
421
- const x = mp[name];
436
+ const x = mp[name]
422
437
  if (!x) {
423
- return name;
438
+ return name
424
439
  }
425
- if (typeof x === 'string') {
426
- return x;
440
+ if (typeof x === "string") {
441
+ return x
427
442
  }
428
- return name;
443
+ return name
429
444
  }
430
445
  export function isEmpty(s: string): boolean {
431
- return !(s && s.length > 0);
446
+ return !(s && s.length > 0)
432
447
  }
433
448
  // tslint:disable-next-line:max-classes-per-file
434
449
  export class StringService {
435
- constructor(protected pool: Pool, public table: string, public column: string) {
436
- this.load = this.load.bind(this);
437
- this.save = this.save.bind(this);
450
+ constructor(
451
+ protected pool: Pool | PoolConnection,
452
+ public table: string,
453
+ public column: string,
454
+ ) {
455
+ this.load = this.load.bind(this)
456
+ this.save = this.save.bind(this)
438
457
  }
439
458
  load(key: string, max: number): Promise<string[]> {
440
- const s = `select ${this.column} from ${this.table} where ${this.column} like ? order by ${this.column} limit ${max}`;
441
- return query(this.pool, s, ['' + key + '%']).then(arr => {
442
- return arr.map(i => (i as any)[this.column] as string);
443
- });
459
+ const s = `select ${this.column} from ${this.table} where ${this.column} like ? order by ${this.column} limit ${max}`
460
+ return query(this.pool, s, ["" + key + "%"]).then((arr) => {
461
+ return arr.map((i) => (i as any)[this.column] as string)
462
+ })
444
463
  }
445
464
  save(values: string[]): Promise<number> {
446
465
  if (!values || values.length === 0) {
447
- return Promise.resolve(0);
466
+ return Promise.resolve(0)
448
467
  }
449
- const arr: string[] = [];
468
+ const arr: string[] = []
450
469
  for (let i = 1; i <= values.length; i++) {
451
- arr.push('(?)');
470
+ arr.push("(?)")
452
471
  }
453
- const s = `insert ignore into ${this.table}(${this.column})values${arr.join(',')}`;
454
- return exec(this.pool, s, values);
472
+ const s = `insert ignore into ${this.table}(${this.column})values${arr.join(",")}`
473
+ return exec(this.pool, s, values)
455
474
  }
456
475
  }
457
476
 
458
477
  export function version(attrs: Attributes): Attribute | undefined {
459
- const ks = Object.keys(attrs);
478
+ const ks = Object.keys(attrs)
460
479
  for (const k of ks) {
461
- const attr = attrs[k];
480
+ const attr = attrs[k]
462
481
  if (attr.version) {
463
- attr.name = k;
464
- return attr;
482
+ attr.name = k
483
+ return attr
465
484
  }
466
485
  }
467
- return undefined;
486
+ return undefined
468
487
  }
469
488
  // tslint:disable-next-line:max-classes-per-file
470
489
  export class MySQLWriter<T> {
471
- pool?: Pool;
472
- version?: string;
473
- exec?: (sql: string, args?: any[]) => Promise<number>;
474
- map?: (v: T) => T;
475
- param?: (i: number) => string;
476
- constructor(pool: Pool | ((sql: string, args?: any[]) => Promise<number>), public table: string, public attributes: Attributes, public oneIfSuccess?: boolean, toDB?: (v: T) => T, buildParam?: (i: number) => string) {
477
- this.write = this.write.bind(this);
478
- if (typeof pool === 'function') {
479
- this.exec = pool;
490
+ pool?: Pool | PoolConnection
491
+ version?: string
492
+ exec?: (sql: string, args?: any[]) => Promise<number>
493
+ map?: (v: T) => T
494
+ param?: (i: number) => string
495
+ constructor(
496
+ pool: Pool | PoolConnection | ((sql: string, args?: any[]) => Promise<number>),
497
+ public table: string,
498
+ public attributes: Attributes,
499
+ public oneIfSuccess?: boolean,
500
+ toDB?: (v: T) => T,
501
+ buildParam?: (i: number) => string,
502
+ ) {
503
+ this.write = this.write.bind(this)
504
+ if (typeof pool === "function") {
505
+ this.exec = pool
480
506
  } else {
481
- this.pool = pool;
507
+ this.pool = pool
482
508
  }
483
- this.param = buildParam;
484
- this.map = toDB;
485
- const x = version(attributes);
509
+ this.param = buildParam
510
+ this.map = toDB
511
+ const x = version(attributes)
486
512
  if (x) {
487
- this.version = x.name;
513
+ this.version = x.name
488
514
  }
489
515
  }
490
516
  write(obj: T): Promise<number> {
491
517
  if (!obj) {
492
- return Promise.resolve(0);
518
+ return Promise.resolve(0)
493
519
  }
494
- let obj2: NonNullable<T> | T = obj;
520
+ let obj2: NonNullable<T> | T = obj
495
521
  if (this.map) {
496
- obj2 = this.map(obj);
522
+ obj2 = this.map(obj)
497
523
  }
498
- const stmt = buildToSave(obj2, this.table, this.attributes, this.version, this.param);
524
+ const stmt = buildToSave(obj2, this.table, this.attributes, this.version, this.param)
499
525
  if (stmt) {
500
526
  if (this.exec) {
501
527
  if (this.oneIfSuccess) {
502
- return this.exec(stmt.query, stmt.params).then(ct => ct > 0 ? 1 : 0);
528
+ return this.exec(stmt.query, stmt.params).then((ct) => (ct > 0 ? 1 : 0))
503
529
  } else {
504
- return this.exec(stmt.query, stmt.params);
530
+ return this.exec(stmt.query, stmt.params)
505
531
  }
506
532
  } else {
507
533
  if (this.oneIfSuccess) {
508
- return exec(this.pool as any, stmt.query, stmt.params).then(ct => ct > 0 ? 1 : 0);
534
+ return exec(this.pool as any, stmt.query, stmt.params).then((ct) => (ct > 0 ? 1 : 0))
509
535
  } else {
510
- return exec(this.pool as any, stmt.query, stmt.params);
536
+ return exec(this.pool as any, stmt.query, stmt.params)
511
537
  }
512
538
  }
513
539
  } else {
514
- return Promise.resolve(0);
540
+ return Promise.resolve(0)
515
541
  }
516
542
  }
517
543
  }
518
544
  // tslint:disable-next-line:max-classes-per-file
519
545
  export class MySQLStreamWriter<T> {
520
- list: T[] = [];
521
- size = 0;
522
- pool?: Pool;
523
- version?: string;
524
- execBatch?: (statements: Statement[]) => Promise<number>;
525
- map?: (v: T) => T;
526
- param?: (i: number) => string;
527
- constructor(pool: Pool | ((statements: Statement[]) => Promise<number>), public table: string, public attributes: Attributes, size?: number, toDB?: (v: T) => T, buildParam?: (i: number) => string) {
528
- this.write = this.write.bind(this);
529
- this.flush = this.flush.bind(this);
530
- if (typeof pool === 'function') {
531
- this.execBatch = pool;
546
+ list: T[] = []
547
+ size = 0
548
+ pool?: Pool
549
+ version?: string
550
+ execBatch?: (statements: Statement[]) => Promise<number>
551
+ map?: (v: T) => T
552
+ param?: (i: number) => string
553
+ constructor(
554
+ pool: Pool | ((statements: Statement[]) => Promise<number>),
555
+ public table: string,
556
+ public attributes: Attributes,
557
+ size?: number,
558
+ toDB?: (v: T) => T,
559
+ buildParam?: (i: number) => string,
560
+ ) {
561
+ this.write = this.write.bind(this)
562
+ this.flush = this.flush.bind(this)
563
+ if (typeof pool === "function") {
564
+ this.execBatch = pool
532
565
  } else {
533
- this.pool = pool;
566
+ this.pool = pool
534
567
  }
535
- this.param = buildParam;
536
- this.map = toDB;
537
- const x = version(attributes);
568
+ this.param = buildParam
569
+ this.map = toDB
570
+ const x = version(attributes)
538
571
  if (x) {
539
- this.version = x.name;
572
+ this.version = x.name
540
573
  }
541
574
  if (size) {
542
- this.size = size;
575
+ this.size = size
543
576
  }
544
577
  }
545
578
  write(obj: T): Promise<number> {
546
579
  if (!obj) {
547
- return Promise.resolve(0);
580
+ return Promise.resolve(0)
548
581
  }
549
- let obj2: NonNullable<T> | T = obj;
582
+ let obj2: NonNullable<T> | T = obj
550
583
  if (this.map) {
551
- obj2 = this.map(obj);
552
- this.list.push(obj2);
584
+ obj2 = this.map(obj)
585
+ this.list.push(obj2)
553
586
  } else {
554
- this.list.push(obj);
587
+ this.list.push(obj)
555
588
  }
556
589
  if (this.list.length < this.size) {
557
- return Promise.resolve(0);
590
+ return Promise.resolve(0)
558
591
  } else {
559
- return this.flush();
592
+ return this.flush()
560
593
  }
561
594
  }
562
595
  flush(): Promise<number> {
563
596
  if (!this.list || this.list.length === 0) {
564
- return Promise.resolve(0);
597
+ return Promise.resolve(0)
565
598
  } else {
566
- const total = this.list.length;
567
- const stmt = buildToSaveBatch(this.list, this.table, this.attributes, this.version, this.param);
599
+ const total = this.list.length
600
+ const stmt = buildToSaveBatch(this.list, this.table, this.attributes, this.version, this.param)
568
601
  if (stmt) {
569
602
  if (this.execBatch) {
570
- return this.execBatch(stmt).then(r => {
571
- this.list = [];
572
- return total;
573
- });
603
+ return this.execBatch(stmt).then((r) => {
604
+ this.list = []
605
+ return total
606
+ })
574
607
  } else {
575
- return execBatch(this.pool as any, stmt).then(r => {
576
- this.list = [];
577
- return total;
578
- });
608
+ return execBatch(this.pool as any, stmt).then((r) => {
609
+ this.list = []
610
+ return total
611
+ })
579
612
  }
580
613
  } else {
581
- return Promise.resolve(0);
614
+ return Promise.resolve(0)
582
615
  }
583
616
  }
584
617
  }
585
618
  }
586
619
  // tslint:disable-next-line:max-classes-per-file
587
620
  export class MySQLBatchWriter<T> {
588
- pool?: Pool;
589
- version?: string;
590
- execute?: (statements: Statement[]) => Promise<number>;
591
- map?: (v: T) => T;
592
- param?: (i: number) => string;
593
- constructor(pool: Pool | ((statements: Statement[]) => Promise<number>), public table: string, public attributes: Attributes, public oneIfSuccess?: boolean, toDB?: (v: T) => T, buildParam?: (i: number) => string) {
594
- this.write = this.write.bind(this);
595
- if (typeof pool === 'function') {
596
- this.execute = pool;
621
+ pool?: Pool
622
+ version?: string
623
+ execute?: (statements: Statement[]) => Promise<number>
624
+ map?: (v: T) => T
625
+ param?: (i: number) => string
626
+ constructor(
627
+ pool: Pool | ((statements: Statement[]) => Promise<number>),
628
+ public table: string,
629
+ public attributes: Attributes,
630
+ public oneIfSuccess?: boolean,
631
+ toDB?: (v: T) => T,
632
+ buildParam?: (i: number) => string,
633
+ ) {
634
+ this.write = this.write.bind(this)
635
+ if (typeof pool === "function") {
636
+ this.execute = pool
597
637
  } else {
598
- this.pool = pool;
638
+ this.pool = pool
599
639
  }
600
- this.param = buildParam;
601
- this.map = toDB;
602
- const x = version(attributes);
640
+ this.param = buildParam
641
+ this.map = toDB
642
+ const x = version(attributes)
603
643
  if (x) {
604
- this.version = x.name;
644
+ this.version = x.name
605
645
  }
606
646
  }
607
647
  write(objs: T[]): Promise<number> {
608
648
  if (!objs || objs.length === 0) {
609
- return Promise.resolve(0);
649
+ return Promise.resolve(0)
610
650
  }
611
- let list = objs;
651
+ let list = objs
612
652
  if (this.map) {
613
- list = [];
653
+ list = []
614
654
  for (const obj of objs) {
615
- const obj2 = this.map(obj);
616
- list.push(obj2);
655
+ const obj2 = this.map(obj)
656
+ list.push(obj2)
617
657
  }
618
658
  }
619
- const stmts = buildToSaveBatch(list, this.table, this.attributes, this.version, this.param);
659
+ const stmts = buildToSaveBatch(list, this.table, this.attributes, this.version, this.param)
620
660
  if (stmts && stmts.length > 0) {
621
661
  if (this.execute) {
622
662
  if (this.oneIfSuccess) {
623
- return this.execute(stmts).then(ct => stmts.length);
663
+ return this.execute(stmts).then((ct) => stmts.length)
624
664
  } else {
625
- return this.execute(stmts);
665
+ return this.execute(stmts)
626
666
  }
627
667
  } else {
628
668
  if (this.oneIfSuccess) {
629
- return execBatch(this.pool as any, stmts).then(ct => stmts.length);
669
+ return execBatch(this.pool as any, stmts).then((ct) => stmts.length)
630
670
  } else {
631
- return execBatch(this.pool as any, stmts);
671
+ return execBatch(this.pool as any, stmts)
632
672
  }
633
673
  }
634
674
  } else {
635
- return Promise.resolve(0);
675
+ return Promise.resolve(0)
636
676
  }
637
677
  }
638
678
  }
639
679
 
640
680
  export interface AnyMap {
641
- [key: string]: any;
681
+ [key: string]: any
642
682
  }
643
683
  // tslint:disable-next-line:max-classes-per-file
644
684
  export class MySQLChecker {
645
- timeout: number;
646
- service: string;
647
- constructor(private pool: Pool, service?: string, timeout?: number) {
648
- this.timeout = (timeout ? timeout : 4200);
649
- this.service = (service ? service : 'mysql');
650
- this.check = this.check.bind(this);
651
- this.name = this.name.bind(this);
652
- this.build = this.build.bind(this);
685
+ timeout: number
686
+ service: string
687
+ constructor(
688
+ private pool: Pool,
689
+ service?: string,
690
+ timeout?: number,
691
+ ) {
692
+ this.timeout = timeout ? timeout : 4200
693
+ this.service = service ? service : "mysql"
694
+ this.check = this.check.bind(this)
695
+ this.name = this.name.bind(this)
696
+ this.build = this.build.bind(this)
653
697
  }
654
698
  async check(): Promise<AnyMap> {
655
- const obj = {} as AnyMap;
699
+ const obj = {} as AnyMap
656
700
  const promise = new Promise<any>((resolve, reject) => {
657
- this.pool.query('select current_time', (err, result) => {
701
+ this.pool.query("select current_time", (err, result) => {
658
702
  if (err) {
659
- return reject(err);
703
+ return reject(err)
660
704
  } else {
661
- resolve(obj);
705
+ resolve(obj)
662
706
  }
663
- });
664
- });
707
+ })
708
+ })
665
709
  if (this.timeout > 0) {
666
- return promiseTimeOut(this.timeout, promise);
710
+ return promiseTimeOut(this.timeout, promise)
667
711
  } else {
668
- return promise;
712
+ return promise
669
713
  }
670
714
  }
671
715
  name(): string {
672
- return this.service;
716
+ return this.service
673
717
  }
674
718
  build(data: AnyMap, err: any): AnyMap {
675
719
  if (err) {
676
720
  if (!data) {
677
- data = {} as AnyMap;
721
+ data = {} as AnyMap
678
722
  }
679
- data['error'] = err;
723
+ data["error"] = err
680
724
  }
681
- return data;
725
+ return data
682
726
  }
683
727
  }
684
728
 
@@ -687,21 +731,21 @@ function promiseTimeOut(timeoutInMilliseconds: number, promise: Promise<any>): P
687
731
  promise,
688
732
  new Promise((resolve, reject) => {
689
733
  setTimeout(() => {
690
- reject(`Timed out in: ${timeoutInMilliseconds} milliseconds!`);
691
- }, timeoutInMilliseconds);
692
- })
693
- ]);
734
+ reject(`Timed out in: ${timeoutInMilliseconds} milliseconds!`)
735
+ }, timeoutInMilliseconds)
736
+ }),
737
+ ])
694
738
  }
695
739
  export interface Formatter<T> {
696
- format: (row: T) => string;
740
+ format: (row: T) => string
697
741
  }
698
742
  export interface FileWriter {
699
- write(chunk: string): boolean;
700
- flush?(cb?: () => void): void;
701
- end?(cb?: () => void): void;
743
+ write(chunk: string): boolean
744
+ flush?(cb?: () => void): void
745
+ end?(cb?: () => void): void
702
746
  }
703
747
  export interface QueryBuilder {
704
- build(ctx?: any): Promise<Statement>;
748
+ build(ctx?: any): Promise<Statement>
705
749
  }
706
750
  // tslint:disable-next-line:max-classes-per-file
707
751
  export class Exporter<T> {
@@ -711,58 +755,58 @@ export class Exporter<T> {
711
755
  ft: (row: T) => string,
712
756
  public write: (chunk: string) => boolean,
713
757
  public end: (cb?: () => void) => void,
714
- public attributes?: Attributes
758
+ public attributes?: Attributes,
715
759
  ) {
716
- this.format = ft;
760
+ this.format = ft
717
761
  if (attributes) {
718
- this.map = buildMap(attributes);
762
+ this.map = buildMap(attributes)
719
763
  }
720
- this.export = this.export.bind(this);
764
+ this.export = this.export.bind(this)
721
765
  }
722
- map?: StringMap;
723
- format: (row: T) => string;
766
+ map?: StringMap
767
+ format: (row: T) => string
724
768
  async export(ctx?: any): Promise<number> {
725
- let idx = 0;
726
- const stmt = await this.buildQuery(ctx);
727
- const reader = this.connection.query(stmt.query, stmt.params);
728
- let er: any;
729
- reader.on('error', (err) => er = err);
769
+ let idx = 0
770
+ const stmt = await this.buildQuery(ctx)
771
+ const reader = this.connection.query(stmt.query, stmt.params)
772
+ let er: any
773
+ reader.on("error", (err) => (er = err))
730
774
  // (D2) WRITE ROW-BY-ROW
731
775
  if (this.map) {
732
- reader.on('result', async (row: any) => {
733
- ++idx;
734
- this.connection.pause();
735
- const obj = mapOne<T>(row, this.map);
736
- const data = this.format(obj);
737
- this.write(data);
738
- this.connection.resume();
739
- });
776
+ reader.on("result", async (row: any) => {
777
+ ++idx
778
+ this.connection.pause()
779
+ const obj = mapOne<T>(row, this.map)
780
+ const data = this.format(obj)
781
+ this.write(data)
782
+ this.connection.resume()
783
+ })
740
784
  } else {
741
- reader.on('result', async (row: any) => {
742
- ++idx;
743
- this.connection.pause();
744
- const data = this.format(row as T);
745
- this.write(data);
746
- this.connection.resume();
747
- });
785
+ reader.on("result", async (row: any) => {
786
+ ++idx
787
+ this.connection.pause()
788
+ const data = this.format(row as T)
789
+ this.write(data)
790
+ this.connection.resume()
791
+ })
748
792
  }
749
793
  // (D3) CLOSE CONNECTION + FILE
750
794
  return new Promise<number>((resolve, reject) => {
751
- reader.on('end', () => {
752
- this.end();
795
+ reader.on("end", () => {
796
+ this.end()
753
797
  if (er) {
754
- reject(er);
798
+ reject(er)
755
799
  } else {
756
800
  this.connection.end((err) => {
757
801
  if (err) {
758
- reject(err);
802
+ reject(err)
759
803
  } else {
760
- resolve(idx);
804
+ resolve(idx)
761
805
  }
762
- });
806
+ })
763
807
  }
764
- });
765
- });
808
+ })
809
+ })
766
810
  }
767
811
  }
768
812
  // tslint:disable-next-line:max-classes-per-file
@@ -772,109 +816,109 @@ export class ExportService<T> {
772
816
  public queryBuilder: QueryBuilder,
773
817
  public formatter: Formatter<T>,
774
818
  public writer: FileWriter,
775
- public attributes?: Attributes
819
+ public attributes?: Attributes,
776
820
  ) {
777
821
  if (attributes) {
778
- this.map = buildMap(attributes);
822
+ this.map = buildMap(attributes)
779
823
  }
780
- this.export = this.export.bind(this);
824
+ this.export = this.export.bind(this)
781
825
  }
782
- map?: StringMap;
826
+ map?: StringMap
783
827
  async export(ctx?: any): Promise<number> {
784
- let idx = 0;
785
- const stmt = await this.queryBuilder.build(ctx);
786
- const reader = this.connection.query(stmt.query, stmt.params);
787
- let er: any;
788
- reader.on('error', (err) => er = err);
828
+ let idx = 0
829
+ const stmt = await this.queryBuilder.build(ctx)
830
+ const reader = this.connection.query(stmt.query, stmt.params)
831
+ let er: any
832
+ reader.on("error", (err) => (er = err))
789
833
  // (D2) WRITE ROW-BY-ROW
790
834
  if (this.map) {
791
- reader.on('result', async (row: any) => {
792
- ++idx;
793
- this.connection.pause();
794
- const obj = mapOne<T>(row, this.map);
795
- const data = this.formatter.format(obj);
796
- this.writer.write(data);
797
- this.connection.resume();
798
- });
835
+ reader.on("result", async (row: any) => {
836
+ ++idx
837
+ this.connection.pause()
838
+ const obj = mapOne<T>(row, this.map)
839
+ const data = this.formatter.format(obj)
840
+ this.writer.write(data)
841
+ this.connection.resume()
842
+ })
799
843
  } else {
800
- reader.on('result', async (row: any) => {
801
- ++idx;
802
- this.connection.pause();
803
- const data = this.formatter.format(row as T);
804
- this.writer.write(data);
805
- this.connection.resume();
806
- });
844
+ reader.on("result", async (row: any) => {
845
+ ++idx
846
+ this.connection.pause()
847
+ const data = this.formatter.format(row as T)
848
+ this.writer.write(data)
849
+ this.connection.resume()
850
+ })
807
851
  }
808
852
  // (D3) CLOSE CONNECTION + FILE
809
853
  return new Promise<number>((resolve, reject) => {
810
- reader.on('end', () => {
854
+ reader.on("end", () => {
811
855
  if (this.writer.end) {
812
- this.writer.end();
856
+ this.writer.end()
813
857
  } else if (this.writer.flush) {
814
- this.writer.flush();
858
+ this.writer.flush()
815
859
  }
816
860
  if (er) {
817
- reject(er);
861
+ reject(er)
818
862
  } else {
819
863
  this.connection.end((err) => {
820
864
  if (err) {
821
- reject(err);
865
+ reject(err)
822
866
  } else {
823
- resolve(idx);
867
+ resolve(idx)
824
868
  }
825
- });
869
+ })
826
870
  }
827
- });
828
- });
871
+ })
872
+ })
829
873
  }
830
874
  }
831
875
  export function mapOne<T>(results: any, m?: StringMap): T {
832
- const obj: any = results;
876
+ const obj: any = results
833
877
  if (!m) {
834
- return obj;
878
+ return obj
835
879
  }
836
- const mkeys = Object.keys(m as any);
880
+ const mkeys = Object.keys(m as any)
837
881
  if (mkeys.length === 0) {
838
- return obj;
882
+ return obj
839
883
  }
840
- const obj2: any = {};
841
- const keys = Object.keys(obj);
884
+ const obj2: any = {}
885
+ const keys = Object.keys(obj)
842
886
  for (const key of keys) {
843
- let k0 = m[key];
887
+ let k0 = m[key]
844
888
  if (!k0) {
845
- k0 = key;
889
+ k0 = key
846
890
  }
847
- obj2[k0] = (obj)[key];
891
+ obj2[k0] = obj[key]
848
892
  }
849
- return obj2;
893
+ return obj2
850
894
  }
851
- export function buildMap(attrs: Attributes): StringMap|undefined {
852
- const mp: StringMap = {};
853
- const ks = Object.keys(attrs);
854
- let isMap = false;
895
+ export function buildMap(attrs: Attributes): StringMap | undefined {
896
+ const mp: StringMap = {}
897
+ const ks = Object.keys(attrs)
898
+ let isMap = false
855
899
  for (const k of ks) {
856
- const attr = attrs[k];
857
- attr.name = k;
858
- const field = (attr.column ? attr.column : k);
859
- const s = field.toLowerCase();
900
+ const attr = attrs[k]
901
+ attr.name = k
902
+ const field = attr.column ? attr.column : k
903
+ const s = field.toLowerCase()
860
904
  if (s !== k) {
861
- mp[s] = k;
862
- isMap = true;
905
+ mp[s] = k
906
+ isMap = true
863
907
  }
864
908
  }
865
909
  if (isMap) {
866
- return mp;
910
+ return mp
867
911
  }
868
- return undefined;
912
+ return undefined
869
913
  }
870
914
  export function select(table: string, attrs: Attributes): string {
871
- const cols: string[] = [];
872
- const ks = Object.keys(attrs);
915
+ const cols: string[] = []
916
+ const ks = Object.keys(attrs)
873
917
  for (const k of ks) {
874
- const attr = attrs[k];
875
- attr.name = k;
876
- const field = (attr.column ? attr.column : k);
877
- cols.push(field);
918
+ const attr = attrs[k]
919
+ attr.name = k
920
+ const field = attr.column ? attr.column : k
921
+ cols.push(field)
878
922
  }
879
- return `select ${cols.join(',')} from ${table}`;
923
+ return `select ${cols.join(",")} from ${table}`
880
924
  }