-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundle.js
2933 lines (2600 loc) · 94.3 KB
/
bundle.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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const sql2json = require('./sql2json');
const Json2sql = sql2json.json2sql;
const Sql2json = sql2json.sql2json;
// NOTE module hangs on semicolon
// obj = new Sql2json("select height, weight, color from item;");
/*
* newTable returns a new name for tables, maintains it's own internal state
*/
var newNameConstructor = function(beginningCharCode) {
var nameCharCodes = [beginningCharCode - 1];
return function() {
var leastSignificantDigit = nameCharCodes.pop()
leastSignificantDigit += 1;
if (leastSignificantDigit > beginningCharCode + 25) {
nameCharCodes.push(beginningCharCode)
nameCharCodes.push(beginningCharCode)
} else {
nameCharCodes.push(leastSignificantDigit)
}
return String.fromCharCode(...nameCharCodes);
}
};
var obfuscate = function() {
// reset obfuscators between runs
var newColumnName = newNameConstructor(97);
var newTableName = newNameConstructor(65);
var newTempWhereColumnName = newNameConstructor(97);
/*
* parseWhereBranch traverses a branch recursively and replaces any column names
* TODO build lookup table of replacements to properly obfuscate where clause,
* for now we naively replace where-clause literals linearly
* TODO factor out from obfuscate, nested due to dependency on newTempWhereColumnName
*/
var parseWhereBranch = function(node) {
if (node.type === 'operator') {
parseWhereBranch(node.left);
parseWhereBranch(node.right);
} else {
node.value = newTempWhereColumnName();
}
};
// get input
var inputArea = document.getElementById('input');
var inputString = inputArea.value;
if (inputString === '') {
// user did not provide input, obfuscate placeholder text instead
inputString = inputArea.placeholder;
}
// TODO remove when parsing properly handles trailing semicolon
inputString = inputString.trim()
if (inputString.endsWith(';')) {
inputString = inputString.slice(0, -1);
}
// obfuscate input
try {
obj = new Sql2json(inputString);
json = obj.toJSON();
json.select.forEach((selection) => {
selection.value = newColumnName()
})
json.from = 'A'
if(json.where) {
parseWhereBranch(json.where.left)
parseWhereBranch(json.where.right)
}
var result = Json2sql.toSQL(json) + ';';
} catch (e) {
var result = 'Could not parse sql! If you believe this is a bug please open an issue on github.com/morenoh149/sql-obfuscator';
}
// put result in DOM
var resultArea = document.getElementById('translation');
resultArea.innerHTML = result;
}
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById('submit').onclick = obfuscate;
});
},{"./sql2json":5}],2:[function(require,module,exports){
},{}],3:[function(require,module,exports){
(function (process){(function (){
// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
// backported and transplited with Babel, with backwards-compat fixes
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function (path) {
if (typeof path !== 'string') path = path + '';
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) {
// return '//';
// Backwards-compat fix:
return '/';
}
return path.slice(0, end);
};
function basename(path) {
if (typeof path !== 'string') path = path + '';
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
// Uses a mixed approach for backwards-compatibility, as ext behavior changed
// in new Node.js versions, so only basename() above is backported here
exports.basename = function (path, ext) {
var f = basename(path);
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function (path) {
if (typeof path !== 'string') path = path + '';
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this)}).call(this,require('_process'))
},{"_process":4}],4:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],5:[function(require,module,exports){
module.exports.json2sql = require('./lib/json2sql');
module.exports.sql2json = require('./lib/sql2json');
},{"./lib/json2sql":6,"./lib/sql2json":7}],6:[function(require,module,exports){
function json2sql() {}
const parseFunction = (nodeFun) => {
const args = [];
for (let i = 0, length = nodeFun.arguments.length; i < length; i++) {
const node = nodeFun.arguments[i];
switch (node.type) {
case 'literal':
args.push(node.value);
break;
case 'string':
args.push(`'${node.value}'`);
break;
case 'wildcard':
args.push(`*`);
break;
case 'number':
args.push(node.value);
break;
case 'math':
args.push(parseMath(node));
break;
case 'function':
args.push(parseFunction(node));
break;
default:
break;
}
}
return `${nodeFun.value}(${args.join(',')})${nodeFun.alias ? ` AS ${nodeFun.alias}` : ''}`;
};
const parseMath = (nodeFun) => {
const args = [];
for (let i = 0, length = nodeFun.arguments.length; i < length; i++) {
const node = nodeFun.arguments[i];
switch (node.type) {
case 'literal':
args.push(node.value);
break;
case 'string':
args.push(`'${node.value}'`);
break;
case 'number':
args.push(node.value);
break;
case 'function':
args.push(parseFunction(node));
break;
default:
break;
}
}
return `${args[0]} ${nodeFun.value} ${args[1]}${nodeFun.alias ? ` AS ${nodeFun.alias}` : ''}`;
};
const parseSelect = (select) => {
const responses = [];
if (select) {
for (let i = 0, length = select.length; i < length; i++) {
const node = select[i];
switch (node.type) {
case 'wildcard':
responses.push(`*`);
break;
case 'literal':
responses.push(`${node.value}${node.alias ? ` AS ${node.alias}` : ''}`);
break;
case 'string':
responses.push(`${node.value}${node.alias ? ` AS ${node.alias}` : ''}`);
break;
case 'function':
responses.push(parseFunction(node));
break;
case 'number':
responses.push(`${node.value}${node.alias ? ` AS ${node.alias}` : ''}`);
break;
case 'math':
responses.push(parseMath(node));
break;
case 'distinct':
responses.push(`DISTINCT ${parseSelect(node.arguments)}`);
break;
default:
break;
}
}
}
return responses.join(', ');
};
const parseNodeWhere = (node) => {
let args = [];
switch (node.type) {
case 'literal':
case 'number':
return node.value;
case 'string':
return `${node.value}`;
case 'operator':
return `${parseNodeWhere(node.left)} ${node.value} ${parseNodeWhere(node.right)}`;
case 'conditional':
return `${parseNodeWhere(node.left)} ${node.value} ${parseNodeWhere(node.right)}`;
case 'bracket':
return `(${parseNodeWhere(node.value)})`;
case 'in':
args = [];
if (node.arguments) {
for (let i = 0, length = node.arguments.length; i < length; i++) {
args.push(parseNodeWhere(node.arguments[i]));
}
}
return `${node.value} IN (${args.join(', ')})`;
case 'between':
args = [];
if (node.arguments) {
for (let i = 0, length = node.arguments.length; i < length; i++) {
args.push(parseNodeWhere(node.arguments[i]));
}
}
return `${node.value} BETWEEN ${parseNodeWhere(node.arguments[0])} AND ${parseNodeWhere(node.arguments[1])}`;
case 'function':
args = [];
if (node.arguments) {
for (let i = 0, length = node.arguments.length; i < length; i++) {
args.push(parseNodeWhere(node.arguments[i]));
}
}
return `${node.value}(${args.join(', ')})`;
default:
return node.value;
}
};
const parseWhere = (node) => {
if (node) {
return `WHERE ${parseNodeWhere(node)}`;
}
return '';
};
const parseOrderBy = (orderBy) => {
if (orderBy) {
const responses = [];
for (let i = 0, length = orderBy.length; i < length; i++) {
if (orderBy[i].type === 'function') {
responses.push(`${parseFunction(orderBy[i])}${orderBy[i].direction ? ` ${orderBy[i].direction}` : ''}`)
} else {
responses.push(`${orderBy[i].value}${orderBy[i].direction ? ` ${orderBy[i].direction}` : ''}`);
}
}
return `ORDER BY ${responses.join(', ')}`;
}
return '';
};
const parseGroupBy = (group) => {
if (group) {
const result = [];
for (let i = 0, length = group.length; i < length; i++) {
const node = group[i];
switch (node.type) {
case 'literal':
result.push(`${node.value}`);
break;
case 'number':
result.push(`${node.value}`);
break;
case 'function':
result.push(parseFunction(node));
break;
default:
break;
}
}
return `GROUP BY ${result.join(', ')}`;
}
return '';
};
json2sql.toSQL = (data) => {
if (!data) {
throw new Error('JSON required');
}
if (!data.delete) {
return `SELECT ${parseSelect(data.select)} FROM ${data.from}${data.where ? ` ${parseWhere(data.where)}` : ''}${data.group ? ` ${parseGroupBy(data.group)}` : ''}${data.orderBy ? ` ${parseOrderBy(data.orderBy)}` : ''}${data.limit ? ` LIMIT ${data.limit}` : ''}${data.offset ? ` OFFSET ${data.offset}` : ''}`.trim();
} else {
return `DELETE FROM ${data.from}${data.where ? ` ${parseWhere(data.where)}` : ''}${data.group ? ` ${parseGroupBy(data.group)}` : ''}${data.orderBy ? ` ${parseOrderBy(data.orderBy)}` : ''}${data.limit ? ` LIMIT ${data.limit}` : ''}${data.offset ? ` OFFSET ${data.offset}` : ''}`.trim();
}
};
json2sql.parseNodeWhere = parseNodeWhere;
json2sql.parseFunction = parseFunction;
module.exports = json2sql;
},{}],7:[function(require,module,exports){
const lexer = require('sql-parser').lexer;
const postgisFunctions = /^(ST_SummaryStatsAgg|ST_value|st_valueCount|st_transform|ST_Intersects|st_buffer|ST_AsGeoJson|ST_SetSRID|ST_GeomFromGeoJSON|ST_METADATA|ST_SUMMARYSTATS|ST_HISTOGRAM|TO_NUMBER|TO_CHAR|ST_GeoHash|first|last|ST_BANDMETADATA|st_centroid|round|trunc|abs|ceil|exp|floor|power|sqrt|acos|asin|atan|atan2|cos|cot|sin|tan|to_timestamp|ST_X|ST_Y|CF_[a-zA-Z0-9_-])$/gi;
const between = /^between$/gi;
const sqlStatements = /^delete$/gi;
const obtainType = function (token) {
postgisFunctions.lastIndex = 0;
between.lastIndex = 0;
sqlStatements.lastIndex = 0;
if (token[0] === 'LITERAL' && postgisFunctions.test(token[1])) {
return 'FUNCTION';
} else if (token[0] === 'LITERAL' && between.test(token[1])) {
return 'BETWEEN';
} else if (token[0] === 'LITERAL' && sqlStatements.test(token[1])) {
return 'DELETE';
}
return token[0];
};
function sql2json(sql, experimental=false) {
if (!sql) {
throw new Error('Sql required');
}
this.sql = sql;
this.experimental = experimental;
this.tokens = lexer.tokenize(this.sql);
this.index = 0;
this.stack = [];
this.parsed = {};
}
sql2json.prototype.hasNext = function () {
return this.index < this.tokens.length;
};
sql2json.prototype.next = function () {
return this.tokens[this.index++];
};
sql2json.prototype.parseFunction = function (functionName, isInSelect) {
const stack = [];
let findParen = false;
while (this.hasNext()) {
const token = this.next();
switch (obtainType(token)) {
case 'LITERAL':
stack.push({
value: token[1],
type: 'literal'
});
break;
case 'FUNCTION':
stack.push(this.parseFunction(token[1], isInSelect));
break;
case 'SEPARATOR':
if (!findParen) {
return {
value: functionName,
type: 'literal',
alias: null
};
}
break;
case 'LEFT_PAREN':
findParen = true;
break;
case 'RIGHT_PAREN':
if (!findParen) {
this.index--;
return {
type: 'literal',
value: functionName
};
}
return {
type: 'function',
alias: null,
value: functionName,
arguments: stack
};
case 'STRING':
stack.push({
value: `'${token[1]}'`,
type: 'string'
});
break;
case 'DBLSTRING':
stack.push({
value: `"${token[1]}"`,
type: 'string'
});
break;
case 'NUMBER':
stack.push({
value: parseFloat(token[1]),
type: 'number'
});
break;
case 'MATH_MULTI':
case 'MATH':
if (stack.length > 0) {
stack.push(this.parseMath(token[1], stack.pop()));
} else {
stack.push({
value: '*',
alias: null,
type: 'wildcard'
});
}
break;
default:
if (!findParen) {
this.index--;
return {
value: functionName,
type: 'literal',
alias: null
};
}
stack.push({
value: token[1],
type: 'literal'
});
}
}
};
sql2json.prototype.parseSelectExperimental = function () {
this.parsed.select = [];
let lastParen = false;
while(this.hasNext()) {
const token = this.next();
switch (obtainType(token)) {
case 'FROM':
this.index--;
return;
default:
let el = null;
if (this.parsed.select.length > 0) {
el = this.parsed.select.pop();
if (token[0] === 'STRING') {
token[1] = `'${token[1]}'`;
}
if (token[0] === 'DBLSTRING') {
token[1] = `"${token[1]}"`;
}
if (!lastParen && token[1] !== '(' && token[1] !== ')' && token[1] !== ',' && token[1] !== '.' && token[1] !== '*') {
el.value += ' ' + token[1];
} else {
if (token[1] === '('){
lastParen = true;
} else {
lastParen = false;
}
el.value += token[1];
}
} else {
el = {
value: token[1],
alias: null,
type: 'literal'
}
}
this.parsed.select.push(el);
break;
}
}
};
sql2json.prototype.parseSelect = function () {
this.parsed.select = [];
let containAs = false;
let isDistinct = false;
while (this.hasNext()) {
const token = this.next();
switch (obtainType(token)) {
case 'DBLSTRING':
this.parsed.select.push({
value: `"${token[1]}"`,
type: 'string'
});
break;
case 'NUMBER':
this.parsed.select.push({
value: parseFloat(token[1]),
type: 'number',
alias: null
});
break;
case 'STAR':
this.parsed.select.push({
value: '*',
alias: null,
type: 'wildcard'
});
break;
case 'LEFT_PAREN':
case 'RIGHT_PAREN':
this.parsed.select[this.parsed.select.length - 1].value = this.parsed.select[this.parsed.select.length - 1].value + token[1];
break;
case 'LITERAL':