-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
914 lines (749 loc) · 19.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
const uniqid = require("uniqid");
const util = require("util");
const { toString } = require("./toString");
const { fieldResolve } = require("./fieldResolve");
class Select {
constructor() {
this._fields = [];
}
select(field, alias) {
// Resolve field name
let f = "";
if (
/^([A-Z][A-Z0-9_]*\s*\()((?:(?:"(?:\\"|[^"])*")|(?:'(?:\\'|[^'])*')|(?:`(?:\\`|[^`])*`)|[^'"\s]*))(?:\s*,\s*((?:(?:"(?:\\"|[^"])*")|(?:'(?:\\'|[^'])*')|(?:`(?:\\`|[^`])*`)|[^'"\s]*)))*\)$/i.test(
field
) ||
/^[a-zA-Z_1-9]+([.])(`)[a-zA-Z0-9-_]+(`)$/.test(field) ||
/^[a-zA-Z_1-9]+([.])([*])$/.test(field) ||
/^[A-Z ]+([(])[a-zA-Z0-9* _=<>(,&).`!']+([)])$/.test(field)
) {
f += `${field}`;
} else {
f += `\`${field}\``;
}
if (alias) f += ` AS ${alias}`;
this._fields.push(f);
return this;
}
render() {
var stm = "SELECT ";
if (this._fields.length === 0) stm = stm + "* ";
else
this._fields.forEach((element) => {
stm += `${element}, `;
});
return stm.slice(0, -2);
}
clone() {
let cp = new select();
cp._fields = this._fields;
return cp;
}
}
class Leaf {
constructor(link, field, operator, value, node) {
this._binding = [];
// Check if the value is a column or not
if (/^[`a-zA-Z_1-9]+([.])(`)[a-zA-Z0-9-_]+(`)$/.test(value))
this._value = value;
else {
if (
operator.toUpperCase() === "IN" ||
operator.toUpperCase() === "NOT IN"
) {
if (Array.isArray(value) && value.length > 0) {
this._value = "(";
value.forEach((element) => {
const key = uniqid();
this._value = this._value + `:${key}, `;
this._binding[key] = element;
});
this._value = this._value.slice(0, -2) + ")";
} else if (Array.isArray(value) && value.length === 0) {
this._value = "(FALSE)";
} else {
throw new Error(`Expect an array, got ${typeof value}`);
}
} else {
const key = uniqid();
this._binding[key] = toString(value);
this._value = `:${key}`;
}
}
this._link = link;
this._field = fieldResolve(field);
this._operator = operator.toUpperCase();
this._parent = node;
}
getBinding() {
return this._binding;
}
parent() {
return this._parent;
}
render() {
return `${this._link} ${this._field} ${this._operator} ${this._value}`;
}
clone(node) {
let cp = new Leaf("AND", "dummy", "=", "dummy"); // This is really dirty
cp._binding = this._binding;
cp._field = this._field;
cp._link = this._link;
cp._operator = this._operator;
cp._value = this._value;
cp._parent = node;
return cp;
}
}
class Node {
constructor(query) {
this._tree = [];
this._link = undefined;
this._parent = undefined;
this._query = query;
}
addLeaf(link, field, operator, value) {
this._tree.push(new Leaf(link, field, operator, value, this));
// Return this for chaining
return this;
}
addNode(node) {
node._parent = this;
this._tree.push(node);
return node;
}
/**
* This method will empty the tree
*/
empty() {
this._tree = [];
return this;
}
getLeafs() {
return this._tree.filter((e) => e.constructor.name === "Leaf");
}
getNodes() {
return this._tree.filter((e) => e.constructor.name === "Node");
}
isEmpty() {
return !this.getLeafs().length > 0 && !this.getNodes().length > 0;
}
findLeaf(link, field, operator, value) {
this._tree.forEach((element, index) => {
if (
element.constructor.name === "Leaf" &&
element._link === link &&
element._field === fieldResolve(field) &&
element._binding[field] === value
)
return element;
else return element.findLeaf(link, field, operator, value);
});
}
getBinding() {
let binding = {};
this._tree.forEach((element, index) => {
Object.assign(binding, element.getBinding());
});
return binding;
}
and(field, operator, value) {
this.addLeaf("AND", field, operator, value, this);
return this;
}
or(field, operator, value) {
this.addLeaf("OR", field, operator, value, this);
return this;
}
render() {
if (this._tree.length === 0) return "";
let statement = `${this._link} (`;
this._tree.forEach((element, index) => {
if (index === 0)
statement += ` ${element.render()}`.slice(this._link === "AND" ? 5 : 4);
else statement += ` ${element.render()}`;
});
statement += ")";
return statement;
}
// a "proxy" function to Query execute method
async execute(connection, releaseConnection = true) {
return await this._query.execute(connection, releaseConnection);
}
// a "proxy" function to Query load method
async load(connection, releaseConnection = true) {
return await this._query.load(connection, releaseConnection);
}
clone(query, parent) {
let cp = new Node(query);
cp._link = this._link;
cp._parent = parent;
cp._tree = this._tree.map((t) => {
if (t.constructor === Leaf) return t.clone(cp);
else return t.clone(query, cp);
});
return cp;
}
}
class Join {
constructor(query) {
this._joins = [];
this._query = query;
}
add(type, table, alias) {
this._joins.push({
type,
table,
alias: alias || table,
on: new Node(this._query),
});
return this;
}
on(column, operator, referencedColumn) {
if (this._joins.length === 0) throw new Error("Invalid call");
let node = this._joins[this._joins.length - 1]["on"];
node._link = "ON";
node.addLeaf("AND", column, operator, referencedColumn, node);
return node;
}
render() {
if (this._joins.length === 0) return "";
let stm = "";
this._joins.forEach((join) => {
stm += `${join.type} ${join.table} AS ${join.alias} ${join.on.render()} `;
Object.assign(this._query._binding, join.on.getBinding());
});
return stm;
}
clone(query) {
let cp = new Join(query);
cp._joins = this._joins;
return cp;
}
}
class Where extends Node {
constructor(query) {
super(query);
}
render() {
Object.assign(this._query._binding, this.getBinding());
let render = super.render();
if (render === "") return "";
else return "WHERE " + render.slice(4);
}
andWhere(field, operator, value) {
let node = new Node(this._query);
node._link = "AND";
node._parent = this;
node.addLeaf("AND", field, operator, value, this);
this.addNode(node);
return node;
}
orWhere(field, operator, value) {
let node = new Node(this._query);
node._link = "OR";
node._parent = this;
node.addLeaf("OR", field, operator, value, this);
this.addNode(node);
return node;
}
clone(query) {
let cp = new Where(query);
cp._link = this._link;
cp._tree = this._tree.map((t) => {
if (t.constructor === Leaf) return t.clone(cp);
else return t.clone(query, cp);
});
return cp;
}
}
class Having extends Node {
constructor(query) {
super();
this._query = query;
this._link = "HAVING";
}
render() {
Object.assign(this._query._binding, this.getBinding());
return super.render();
}
clone(query) {
let cp = new this.constructor(query);
cp._tree = this._tree.map((t) => {
if (t.constructor === Leaf) return t.clone(cp);
else return t.clone(query, cp);
});
return cp;
}
}
class Limit {
constructor(offset = null, limit = null) {
this._offset = offset;
this._limit = limit;
}
render() {
if ((this._offset === this._limit) === null) return "";
return `LIMIT ${+this._offset || 0}, ${
this._limit === null ? 1000000000 : this._limit
}`;
}
clone() {
return new this.constructor(this._offset, this._limit);
}
}
class GroupBy {
constructor() {
this._fields = [];
}
add(field) {
this._fields.push(fieldResolve(field));
return this;
}
render() {
if (this._fields.length === 0) return "";
return `GROUP BY ${this._fields.join(",")}`;
}
clone() {
let cp = new GroupBy();
cp._fields = [...this._fields];
return cp;
}
}
class OrderBy {
constructor() {
this._field = null;
this._direction = "DESC";
}
add(field, direction) {
this._field = field;
this._direction = direction == null ? "DESC" : direction;
return this;
}
render() {
if (this._field === null) return "";
return `ORDER BY ${this._field} ${this._direction}`;
}
clone() {
let cp = new this.constructor();
cp._field = this._field;
cp._direction = this._direction;
return cp;
}
}
class Query {
constructor() {
this._where = new Where(this);
this._binding = [];
}
/**
* @returns {Where|Node}
*/
where(field, operator, value) {
// This method will reset the `_where` object. Call `andWhere` or `orWhere` if you want to add more condition
this._where = new Where(this);
this._where._link = "AND";
this._where.addLeaf("AND", field, operator, value, this._where);
return this._where;
}
andWhere(field, operator, value) {
if (this._where.isEmpty() === true)
return this.where(field, operator, value);
return this._where.andWhere(field, operator, value);
}
orWhere(field, operator, value) {
if (this._where.isEmpty() === true)
return this.where(field, operator, value);
return this._where.orWhere(field, operator, value);
}
getWhere() {
return this._where;
}
getBinding() {
return this._binding;
}
async execute(connection, releaseConnection = true) {
let sql = await this.sql(connection);
let binding = [];
for (let key in this._binding) {
if (this._binding.hasOwnProperty(key)) {
sql = sql.replace(`:${key}`, "?");
binding.push(this._binding[key]);
}
}
const fn = util.promisify(connection.query).bind(connection);
let result = await fn(sql, binding);
if (releaseConnection) release(connection);
return result;
}
}
class SelectQuery extends Query {
constructor() {
super();
this._table = undefined;
this._alias = undefined;
this._select = new Select();
this._having = new Having(this);
this._join = new Join(this);
this._limit = new Limit();
this._groupBy = new GroupBy();
this._orderBy = new OrderBy();
}
select(field, alias) {
this._select.select(field, alias);
return this;
}
from(table, alias) {
this._table = table;
this._alias = alias;
return this;
}
having(field, operator, value) {
this._having.and(field, operator, value);
return this._having;
}
leftJoin(table, alias) {
this._join.add("LEFT JOIN", table, alias);
return this._join;
}
rightJoin(table, alias) {
this._join.add("RIGHT JOIN", table, alias);
return this._join;
}
innerJoin(table, alias) {
this._join.add("INNER JOIN", table, alias);
return this._join;
}
limit(offset, limit) {
this._limit = new Limit(offset, limit);
return this;
}
groupBy() {
let args = [].slice.call(arguments);
args.forEach((element) => {
this._groupBy.add(String(element));
});
return this;
}
orderBy(field, direction = "ASC") {
this._orderBy.add(field, direction);
return this;
}
sql() {
if (!this._table)
throw Error("You must specific table by calling `from` method");
let from = `\`${this._table}\``;
if (this._alias) from += ` AS \`${this._alias}\``;
return [
this._select.render().trim(),
"FROM",
from.trim(),
this._join.render().trim(),
this._where.render().trim(),
this._groupBy.render().trim(),
this._having.render().trim(),
this._orderBy.render().trim(),
this._limit.render().trim(),
]
.filter((e) => e !== "")
.join(" ");
}
async load(connection, releaseConnection = true) {
this.limit(0, 1);
let results = await this.execute(connection, releaseConnection);
return results[0] || null;
}
async execute(connection, releaseConnection = true) {
if (connection.constructor.name === "Pool") {
connection = await getConnection(connection);
}
let sql = await this.sql(connection);
let binding = [];
for (var key in this._binding) {
if (this._binding.hasOwnProperty(key)) {
sql = sql.replace(`:${key}`, "?");
binding.push(this._binding[key]);
}
}
const fn = util.promisify(connection.query).bind(connection);
try {
let result = await fn(sql, binding);
if (releaseConnection) release(connection);
return result;
} catch (e) {
if (e.errno === 1054) {
this.orderBy(null);
return await super.execute(connection, releaseConnection);
} else {
if (releaseConnection) release(connection);
throw e;
}
}
}
clone() {
let cp = new SelectQuery();
cp._table = this._table;
cp._alias = this._alias;
cp._where = this._where.clone(cp);
cp._having = this._having.clone(cp);
cp._join = this._join.clone(cp);
cp._limit = this._limit.clone();
cp._groupBy = this._groupBy.clone();
cp._orderBy = this._orderBy.clone();
return cp;
}
}
class UpdateQuery extends Query {
constructor(table) {
// Private
super();
this._table = table;
this._data = {};
}
given(data) {
if (typeof data !== "object" || data === null) {
throw new Error("Data must be an object and not null");
}
let copy = {};
Object.keys(data).forEach((key) => {
copy[key] = toString(data[key]);
});
this._data = copy;
return this;
}
prime(field, value) {
this._data[field] = toString(value);
return this;
}
async sql(connection) {
if (!this._table) throw Error("You need to call specific method first");
if (Object.keys(this._data).length === 0)
throw Error("You need provide data first");
const query = util.promisify(connection.query).bind(connection);
let fields = await query(`DESCRIBE \`${this._table}\``);
let set = [];
fields.forEach((field) => {
if (field["Extra"] === "auto_increment") return;
if (this._data[field["Field"]] === undefined) return;
let key = uniqid();
set.push(`\`${field["Field"]}\` = :${key}`);
this._binding[key] = this._data[field["Field"]];
});
if (set.length === 0) throw new Error("No data was provided" + this._table);
var sql = [
"UPDATE",
`\`${this._table}\``,
"SET",
set.join(", "),
this._where.render(),
]
.filter((e) => e !== "")
.join(" ");
return sql;
}
}
class InsertQuery extends Query {
constructor(table) {
// Private
super();
this._table = table;
this._data = {};
}
given(data) {
if (typeof data !== "object" || data === null) {
throw new Error("Data must be an object and not null");
}
let copy = {};
Object.keys(data).forEach((key) => {
copy[key] = toString(data[key]);
});
this._data = copy;
return this;
}
prime(field, value) {
this._data[field] = toString(value);
return this;
}
async sql(connection) {
if (!this._table) throw Error("You need to call specific method first");
if (Object.keys(this._data).length === 0)
throw Error("You need provide data first");
const query = util.promisify(connection.query).bind(connection);
let fields = await query(`DESCRIBE \`${this._table}\``);
let fs = [],
vs = [];
fields.forEach((field) => {
if (field["Extra"] === "auto_increment") return;
if (this._data[field["Field"]] === undefined) return;
let key = uniqid();
fs.push(`\`${field["Field"]}\``);
vs.push(`:${key}`);
this._binding[key] = this._data[field["Field"]];
});
let sql = [
"INSERT INTO",
`\`${this._table}\``,
"(",
fs.join(", "),
")",
"VALUES",
"(",
vs.join(", "),
")",
]
.filter((e) => e !== "")
.join(" ");
return sql;
}
}
class InsertOnUpdateQuery extends Query {
constructor(table) {
// Private
super();
this._table = table;
this._data = [];
}
given(data) {
if (typeof data !== "object" || data === null) {
throw new Error("Data must be an object and not null");
}
let copy = {};
Object.keys(data).forEach((key) => {
copy[key] = toString(data[key]);
});
this._data = copy;
return this;
}
prime(field, value) {
this._data[field] = toString(value);
return this;
}
async sql(connection) {
if (!this._table) throw Error("You need to call specific method first");
if (Object.keys(this._data).length === 0)
throw Error("You need provide data first");
const query = util.promisify(connection.query).bind(connection);
let fields = await query(`DESCRIBE \`${this._table}\``);
let fs = [],
vs = [],
us = [],
usp = [];
fields.forEach((field) => {
if (field["Extra"] === "auto_increment") return;
if (this._data[field["Field"]] === undefined) return;
let key = uniqid();
let ukey = uniqid();
fs.push(`\`${field["Field"]}\``);
vs.push(`:${key}`);
us.push(`\`${field["Field"]}\` = :${ukey}`);
usp[ukey] = this._data[field["Field"]];
this._binding[key] = this._data[field["Field"]];
});
this._binding = { ...this._binding, ...usp };
let sql = [
"INSERT INTO",
`\`${this._table}\``,
"(",
fs.join(", "),
")",
"VALUES",
"(",
vs.join(", "),
")",
"ON DUPLICATE KEY UPDATE",
us.join(", "),
]
.filter((e) => e !== "")
.join(" ");
return sql;
}
}
class DeleteQuery extends Query {
constructor(table) {
// Private
super();
this._table = table;
}
sql() {
if (!this._table) throw Error("You need to call specific method first");
return [
"DELETE FROM",
`\`${this._table}\``,
this._where.render().trim(),
].join(" ");
}
}
module.exports = {
select,
insert,
update,
node,
del,
insertOnUpdate,
getConnection,
startTransaction,
commit,
rollback,
release,
execute,
};
function select() {
let select = new SelectQuery();
let args = [...arguments];
if (args[0] === "*") return select;
args.forEach((arg) => {
if (typeof arg == "string") select.select(arg);
});
return select;
}
function insert(table) {
return new InsertQuery(table);
}
function insertOnUpdate(table) {
return new InsertOnUpdateQuery(table);
}
function update(table) {
return new UpdateQuery(table);
}
function del(table) {
return new DeleteQuery(table);
}
function node(link) {
let node = new Node();
node._link = link;
return node;
}
/* Create a connection from a pool */
async function getConnection(pool) {
return await util.promisify(pool.getConnection).bind(pool)();
}
async function startTransaction(connection) {
await util.promisify(connection.query).bind(connection)(
"SET TRANSACTION ISOLATION LEVEL READ COMMITTED"
);
await util.promisify(connection.query).bind(connection)("SET autocommit = 0");
await util.promisify(connection.query).bind(connection)("START TRANSACTION");
connection.INTRANSACTION = true;
connection.COMMITTED = false;
}
async function commit(connection) {
await util.promisify(connection.query).bind(connection)("COMMIT");
await util.promisify(connection.query).bind(connection)("SET autocommit = 1");
connection.INTRANSACTION = false;
connection.COMMITTED = true;
release(connection);
}
async function rollback(connection) {
await util.promisify(connection.query).bind(connection)("ROLLBACK");
await connection.destroy();
}
function release(connection) {
if (connection.INTRANSACTION === true) {
return;
}
if (connection._pool) {
connection._pool.releaseConnection(connection);
}
}
async function execute(connection, query) {
return await util.promisify(connection.query).bind(connection)(query);
}