-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxql.js
5754 lines (4879 loc) · 159 KB
/
xql.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
// xql.js <https://github.com/jsstuff/xql>
(function($export, $as) {
"use strict";
/**
* Root namespace.
*
* @namespace
* @alias xql
*/
const xql = $export[$as] = {};
// ============================================================================
// [Public Constants]
// ============================================================================
/**
* Version string.
*
* @alias xql.misc.VERSION
*/
const VERSION = "1.4.12";
/**
* Identifier's quote style.
*
* @alias xql.QuoteStyle
*/
const QuoteStyle = Object.freeze({
Double : 0, // Double quotes, for example "identifier".
Grave : 1, // Grave quotes, for example `identifier`.
Brackets : 2 // Brackets, for example [identifier].
});
xql.QuoteStyle = QuoteStyle;
/**
* Node flags.
*
* @alias xql.NodeFlags
*/
const NodeFlags = Object.freeze({
Immutable : 0x00000001, // Node is immutable (cannot be changed).
Not : 0x00000002, // Expression is negated (NOT).
Ascending : 0x00000010, // Sort ascending (ASC).
Descending : 0x00000020, // Sort descending (DESC).
NullsFirst : 0x00000040, // Sort nulls first (NULLS FIRST).
NullsLast : 0x00000080, // Sort nulls last (NULLS LAST).
All : 0x00000100, // ALL flag.
Distinct : 0x00000200, // DISTINCT flag.
Statement : 0x10000000 // This node represents a statement (like SELECT, UPDATE, etc).
});
xql.NodeFlags = NodeFlags;
/**
* Operator and function flags.
*
* @alias xql.OpFlags
*/
const OpFlags = Object.freeze({
Unary : 0x00000001, // Unary operator (has one child node - `value`).
Binary : 0x00000002, // Binary operator (has two child nodes - `left` and `right`).
Function : 0x00000004, // Function (has arguments).
Aggregate : 0x00000008, // Function is an aggregate.
Void : 0x00000010, // Has no return value.
LeftValues : 0x00000100, // Operator expects left values as (a, b[, ...]).
RightValues : 0x00000200, // Operator expects right values as (a, b[, ...]).
SpaceSeparate : 0x00000400 // Separate the function or operator by spaces before and after.
});
xql.OpFlags = OpFlags;
// ============================================================================
// [Internal Constants]
// ============================================================================
// Empty object/array used as an replacement for null/undefined in some cases.
const NoObject = Object.freeze(Object.create(null));
const NoArray = Object.freeze([]);
// Aliases that we use in xql.js source code.
const NF = NodeFlags;
const OF = OpFlags;
// Map of identifiers that are not escaped.
const IdentifierMap = { "*": true };
const StatementToOutputKeywordMap = Object.freeze({
"INSERT": "INSERTED",
"UPDATE": "UPDATED",
"DELETE": "DELETED"
});
// Map of strings which can be implicitly casted to `TRUE` or `FALSE`.
const BoolMap = (function() {
const map = {
"0" : false,
"f" : false,
"false" : false,
"n" : false,
"no" : false,
"off" : false,
"1" : true,
"t" : true,
"true" : true,
"y" : true,
"yes" : true,
"on" : true
};
Object.keys(map).forEach(function(key) { map[key.toUpperCase()] = map[key]; });
return Object.freeze(map);
})();
const DateFieldMap = {
"CENTURY" : true,
"DAY" : true,
"DECADE" : true,
"DOW" : true,
"DOY" : true,
"EPOCH" : true,
"HOUR" : true,
"ISODOW" : true,
"ISOYEAR" : true,
"MICROSECONDS" : true,
"MILLENIUM" : true,
"MILLISECONDS" : true,
"MINUTE" : true,
"MONTH" : true,
"QUARTER" : true,
"SECOND" : true,
"TIMEZONE" : true,
"TIMEZONE_HOUR" : true,
"TIMEZONE_MINUTE": true,
"WEEK" : true,
"YEAR" : true
};
const TypeMap = {
"bool" : "boolean",
"boolean" : "boolean",
"bigint" : "integer",
"int" : "integer",
"integer" : "integer",
"smallint" : "integer",
"real" : "number",
"float" : "number",
"number" : "number",
"numeric" : "number",
"char" : "string",
"varchar" : "string",
"string" : "string",
"text" : "string",
"array" : "array",
"json" : "json",
"jsonb" : "json",
"object" : "json",
"raw" : "raw",
"values" : "values",
"date" : "date",
"time" : "time",
"timestamp" : "timestamp",
"timestamptz" : "timestamptz",
"interval" : "interval"
};
Object.keys(TypeMap).forEach(function(key) {
TypeMap[key.toUpperCase()] = TypeMap[key];
});
// Sort direction enum value from string.
const SortDirection = Object.freeze({
"" : 0,
"0" : 0,
"1" : NF.Ascending,
"-1" : NF.Descending,
"ASC" : NF.Ascending,
"DESC" : NF.Descending
});
// Sort nulls enum value from string.
const SortNulls = Object.freeze({
"NULLS FIRST" : NF.NullsFirst,
"NULLS LAST" : NF.NullsLast
});
// ============================================================================
// [Regular Expressions]
// ============================================================================
// Check for new line characters.
const reNewLine = /\n/g;
// Check for grave (`) quotes.
const reGraveQuotes = /`/g;
// Check for double (") quotes.
const reDoubleQuotes = /\"/g;
// Check for [] brackets.
const reBrackets = /\[\]/g;
// Check for '.' or '\0' characters.
const reDotOrNull = /[\.\x00]/g;
// Check for a well-formatted int with optional '-' sign.
const reInteger = /^-?\d+$/;
// Checks if a string is a well formatted integer or floating point number, also
// accepts scientific notation "E[+-]?xxx" and NaN/Infinity.
const reNumber = /^(NaN|-?Infinity|^-?((\d+\.?|\d*\.\d+)([eE][-+]?\d+)?))$/;
// Check for an UPPERCASE function name (no spaces).
const reUpperFunctionName = /^[A-Z_][A-Z_0-9]*$/;
// Check for an UPPERCASE operator name (can contain spaces between words).
const reUpperOperatorName = /^[A-Z_][A-Z_0-9 ]*(?: [A-Z_][A-Z_0-9 ]*)*$/;
// ============================================================================
// [Internal Functions]
// ============================================================================
// Always returns false, used internally for browser support.
function returnFalse() { return false; }
// Global shorthands.
const hasOwn = Object.prototype.hasOwnProperty;
const slice = Array.prototype.slice;
const isArray = Array.isArray;
const isBuffer = typeof Buffer === "function" ? Buffer.isBuffer : returnFalse;
const deprecated = (function() {
const map = Object.create(null);;
return function(message) {
if (message in map)
return;
map[message] = true;
console.log(message);
}
})();
function blobToHex(blob) {
return blob.toString("hex");
}
function alias(classobj, spec) {
const p = classobj.prototype;
for (var member in spec)
p[member] = p[spec[member]];
return classobj;
}
// ============================================================================
// [xql.OpInfo]
// ============================================================================
/**
* Operator and function information.
*
* @alias xml.OpInfo
*/
const OpInfo = new class OpInfo {
constructor() {
this._map = Object.create(null);
}
get(name) {
const map = this._map;
return name && hasOwn.call(map, name) ? map[name] : null;
}
add(info) {
this._addInternal(info.name, info);
if (info.nameNot) {
const infoNot = Object.assign({}, info);
infoNot.nodeFlags = NF.Not;
this._addInternal(info.nameNot, infoNot);
}
return this;
}
_addInternal(key, info) {
this._map[key] = info;
const alias = key.replace(/ /g, "_");
if (alias !== key)
this._map[alias] = info;
}
addAlias(a, b) {
this._map[a] = this._map[b];
return this;
}
addNegation(a, b) {
const aInfo = this._map[a];
const bInfo = this._map[b];
aInfo.not = bInfo;
bInfo.not = aInfo;
return this;
}
all() {
return this._map;
}
forEach(cb, thisArg) {
const map = this._map;
for (var k in map)
cb.call(thisArg, k, map[k]);
return this;
}
};
xql.OpInfo = OpInfo;
// ============================================================================
// [xql.error]
// ============================================================================
/**
* Namespace which provides classes that represent errors thrown as exceptions.
*
* @namespace
* @alias xql.error
*/
const xql$error = xql.error = {};
/**
* Error thrown if data is wrong.
*
* @param message Error message.
*
* @alias xql.error.ValueError
*/
class ValueError extends Error {
constructor(message) {
super(message);
this.name = "ValueError";
this.message = message;
}
}
xql$error.ValueError = ValueError;
/**
* Error thrown if SQL construct is wrong and cannot be compiled.
*
* @param message Error message.
*
* @alias xql.error.CompileError
*/
class CompileError extends Error {
constructor(message) {
super(message);
this.name = "CompileError";
this.message = message;
}
}
xql$error.CompileError = CompileError;
function throwTypeError(message) { throw new TypeError(message); }
function throwValueError(message) { throw new ValueError(message); }
function throwCompileError(message) { throw new CompileError(message); }
// ============================================================================
// [xql.misc]
// ============================================================================
/**
* Miscellaneous namespace.
*
* @namespace
* @alias xql.misc
*/
const xql$misc = xql.misc = {};
/**
* Version information in a "major.minor.patch" form.
*
* Note: Version information has been put into the `xql.misc` namespace to
* prevent a possible clashing with SQL builder's interface exported in the
* root namespace.
*
* @alias xql.misc.VERSION
*/
xql$misc.VERSION = VERSION;
/**
* Get a type of the `value` as a string. This function extends a javascript
* `typeof` operator with "array", "buffer", "null" and "undefined". It's used
* for debugging and error handling purposes to enhance error messages.
*
* @param {*} value
* @return {string}
*
* @function xql.misc.typeOf
*/
function typeOf(value) {
if (value == null)
return value === null ? "null" : "undefined";
if (typeof value !== "object")
return typeof value;
if (isArray(value))
return "array";
if (isBuffer(value))
return "buffer";
if (value instanceof Node)
return value._type || "Node";
return "object";
}
xql$misc.typeOf = typeOf;
function parseVersion(s) {
const parts = s.split(".");
const re = /^[0-9]+$/g;
var major = 0;
var minor = 0;
var patch = 0;
for (var i = 0, len = Math.min(parts.length, 3); i < len; i++) {
var part = parts[i];
if (!re.test(part))
break;
var n = parseInt(part);
switch (i) {
case 0: major = n; break;
case 1: minor = n; break;
case 2: patch = n; break;
}
}
return {
major: major,
minor: minor,
patch: patch
}
}
function indent(s, indentation) {
return (s && indentation) ? indentation + s.replace(reNewLine, "\n" + indentation) : s;
}
xql$misc.indent = indent;
// ============================================================================
// [xql.dialect]
// ============================================================================
/**
* Database dialects namespace.
*
* @namespace
* @alias xql.dialect
*/
const xql$dialect = xql.dialect = Object.create(null);
/**
* Mapping from a dialect string into a dialect `Context` class.
*
* @var xql.dialect.registry
*/
const xql$dialect$registry = Object.create(null);
xql$dialect.registry = xql$dialect$registry;
/**
* Checks whether the `dialect` exists in the global registry.
*
* @param {string} dialect A name of the dialect (always lowercase).
* @return {boolean}
*
* @function xql.dialect.has
*/
function xql$dialect$has(dialect) {
return hasOwn.call(xql$dialect$registry, dialect);
}
xql$dialect.has = xql$dialect$has;
/**
* Checks whether the `dialect` exists in the global registry.
*
* @param {string} dialect A name of the dialect (always lowercase).
* @return {Context} A dialect Context (if found) or null.
*
* @function xql.dialect.get
*/
function xql$dialect$get(dialect) {
return hasOwn.call(xql$dialect$registry, dialect) ? xql$dialect$registry[dialect] : null;
}
xql$dialect.get = xql$dialect$get;
/**
* Adds a new dialect to the global registry.
*
* @param {string} dialect A name of the dialect (always lowercase).
* @param {function} classobj A `Context` class object (not instantiated).
*
* @function xql.dialect.add
*/
function xql$dialect$add(dialect, classobj) {
xql$dialect$registry[dialect] = classobj;
}
xql$dialect.add = xql$dialect$add;
/**
* Constructs a new `Context` for a given options.
*
* @param {object} options Context options.
* @param {string} options.dialect Database dialect (must be registered).
* @return {Context} Instantiated `Context`.
*
* @function xql.dialect.newContext
*/
function $xql$dialect$newContext(options) {
if (typeof options !== "object" || options === null)
throwTypeError("xql.dialect.newContext() - Options must be Object");
const dialect = options.dialect;
if (typeof dialect !== "string")
throwTypeError("xql.dialect.newContext() - Options must have a dialect key");
if (!hasOwn.call(xql$dialect$registry, dialect))
throwTypeError("xql.dialect.newContext() - Unknown dialect '" + dialect + "'");
const classobj = xql$dialect$registry[dialect];
return new classobj(options);
}
xql$dialect.newContext = $xql$dialect$newContext;
// ============================================================================
// [xql.dialect.Context]
// ============================================================================
function fnEscapeBrackets(s) {
return s.charCodeAt(0) === 91 ? "[[" : "]]";
}
/**
* Database dialect context that provides an interface that query builders can
* use to build a dialect-specific queries. The context itself provides some
* dialect-agnostic functionality that is shared between multiple dialect
* implementations.
*
* It's essential to call `_updateInternalData()` in your own constructor when
* extending `Context` to implement your own database dialect.
*
* @param {string} dialect Database dialect the context is using.
* @param {object} options Context options.
*
* @alias xql.dialect.Context
*/
class Context {
constructor(dialect, options) {
this.dialect = dialect;
// Context configuration.
this.pretty = options.pretty ? true : false;
this.indentation = options.indentation || 2;
// Dialect version (no version specified is the default).
this.version = options.version ? parseVersion(options.version) : {
major: 0,
minor: 0,
patch: 0
};
// Dialect features (these are modified by a dialect-specific `Context`).
this.features = {
quoteStyle : QuoteStyle.Double, // The default SQL quotes are "".
nativeBoolean : false, // Supports BOOLEAN.
nativeRange : false, // Supports RANGE.
nativeArray : false, // Supports ARRAY.
nativeJSON : false, // Supports JSON.
nativeJSONB : false, // Supports JSONB.
nativeHSTORE : false, // Supports HSTORE.
nullsOrdering : false, // Supports NULLS FIRST and NULLS LAST.
nullsSortBottom : false, // NULLs are sorted last by default.
defaultValues : false, // Supports DEFAULT keyword in VALUES(...).
selectTopN : false, // Supports Top-N queries.
leastGreatest : "LEAST|GREATEST", // Supports GREATEST/LEAST functions.
returning : "", // If RETURNING or OUTPUT is supported.
specialNumbers : false // No special numbers by default.
};
// Computed properties based on configuration and dialect features. These
// require `_updateInternalData()` to be called after one or more property
// is changed.
this._DB_TRUE = ""; // Dialect-specific TRUE value.
this._DB_FALSE = ""; // Dialect-specific FALSE value.
this._DB_NAN = ""; // Dialect-specific NaN value.
this._DB_POS_INF = ""; // Dialect-specific Positive infinity value.
this._DB_NEG_INF = ""; // Dialect-specific Negative infinity value.
this._DB_IDENT_OPEN = ""; // Escape character inserted before SQL identifier.
this._DB_IDENT_CLOSE = ""; // Escape character inserted after SQL identifier.
this._STR_OPT_NL = ""; // Optional newline (will either be "\n" or "").
this._STR_BLANK = ""; // Space or newline (will either be "\n" or " ").
this._STR_COMMA = ""; // Comma separator, either ", " or ",\n" (pretty).
this._STR_INDENT = ""; // Indentation string.
this._STR_CONCAT = ""; // Concatenation string, equals to `space + _STR_INDENT`.
// Regular expression that checks if the identifier needs escaping.
this._RE_IDENT_CHECK = null;
// Functions that can be updated based on the settings and database dialect.
this.indent = null;
this.concat = null;
this.concatNoSpace = null;
this._wrap = null;
this._compileInsert = null;
this._compileReturning = null;
this._compileOffsetLimit = null;
}
/**
* Set the version of the dialect to the given `version`.
*
* @param {string} version Version string as "major.minor.patch". The string
* can omit any version part if not used, gratefully accepting "major.minor"
* and/or "major" only. If any version part that is omitted will be set to 0.
*
* @return {this}
*/
setVersion(version) {
this.version = parseVersion(version);
this._updateInternalData();
return this;
}
/**
* Compiles the given expression or statement `q`.
*
* @param {string|Node} q Expression or statement to compile, can be either
* string or `xql.Node`.
*
* @return {string} Compiled SQL expression or statement as a string.
*
* @throws {TypeError} If `q` is an object that is not compatible with `xql.Node`.
*/
compile(q) {
if (typeof q === "string")
return q;
if (q && typeof q.compileStatement === "function")
return q.compileStatement(this);
throwTypeError("xql.Context.compile() - Invalid argument");
}
_compile(something, valueType) {
if (something instanceof Node)
return something.compileNode(this);
else
return this.escapeValue(something, valueType);
}
/**
* Escapes a single or multiple SQL identifier(s).
*
* @param {string|string[]} ident Idenfifier or array of identifiers to escape.
* @return {string} Escaped identifier(s).
*/
escapeIdentifier(ident) {
var input = "";
var output = "";
var i = 0;
var len = 1;
if (isArray(ident)) {
len = ident.length;
if (len > 0)
input = ident[0];
}
else {
input = ident;
}
const re = this._RE_IDENT_CHECK;
for (;;) {
// Apply escaping to all parts of the identifier (if any).
for (;;) {
// Ignore undefined/null parts of the input.
if (input == null)
break;
var m = input.search(re);
var p = input;
// Multiple arguments are joined by using ".".
if (output) output += ".";
if (m !== -1) {
var c = input.charCodeAt(m);
// `.` === 46.
if (c === 46) {
// Dot separator, that's fine
p = input.substr(0, m);
}
else {
// NULL character in identifier is not allowed.
if (c === 0)
throwCompileError("Identifier can't contain NULL character");
// Character that needs escaping. In this case we repeat the
// search by using simpler regular expression and then pass
// the whole string to a function that will properly escape
// it (as this function is very generic and can handle all
// dialects easily).
m = input.search(reDotOrNull);
if (m !== -1) {
c = input.charCodeAt(m);
if (c === 46)
p = input.substr(0, m);
else
throwCompileError("Identifier can't contain NULL character");
}
p = this.escapeIdentifierImpl(p);
}
}
if (hasOwn.call(IdentifierMap, p))
output += p;
else
output += this._DB_IDENT_OPEN + p + this._DB_IDENT_CLOSE;
if (m === -1)
break;
input = input.substr(m + 1);
}
if (++i >= len)
break;
input = ident[i];
}
// Return an empty identifier (allowed) in case the output is empty.
return output ? output : this._DB_IDENT_OPEN + this._DB_IDENT_CLOSE;
}
/**
* Escapes a single identifier.
*
* Please do not use this function directly. It's called by `escapeIdentifier`
* to escape an identifier (or some part of it) in a dialect-specific way.
*
* @param {string} ident Identifier to escape, which should be already
* checked (for example it shouldn't contain NULL characters).
* @return {string} Escaped identifier.
*/
escapeIdentifierImpl(ident) {
// NOTE: This function is only called when `ident` contains one or more
// characters to escape. It doesn't have to be super fast as it involes
// regexp search & replace anyway. This is the main reason it's generally
// not reimplemented by a dialect-specific implementation as it won't
// bring any performance gain.
const qs = this.features.quoteStyle;
if (qs == QuoteStyle.Double ) return ident.replace(reDoubleQuotes, "\"\"");
if (qs == QuoteStyle.Grave ) return ident.replace(reGraveQuotes, "``");
if (qs == QuoteStyle.Brackets) return ident.replace(reBrackets, fnEscapeBrackets);
throwCompileError("Cannot escape identifier: Invalid 'features.quoteStyle' set");
}
/**
* Escapes `value` so it can be inserted into a SQL query.
*
* The `value` can be any JS type that can be implicitly or explicitly
* converted to SQL. The `explicitType` parameter can be used to force
* the type explicitly in case of ambiguity.
*
* @param {*} value A value to escape.
* @param {string} [explicitType] SQL type override
* @return {string} Escaped `value` as string.
*/
escapeValue(value, explicitType) {
if (value instanceof Node)
throwTypeError("Context.escapeValue() - Value cannot be node here, use '_compile()' instead");
// Explicitly Defined Type (`explicitType` is set)
// -----------------------------------------------
if (explicitType) {
var type = TypeMap[explicitType];
if (!type)
throwValueError("Unknown explicit type '" + explicitType + "'");
switch (type) {
case "boolean":
if (value == null) return "NULL";
if (typeof value === "boolean")
return value === true ? this._DB_TRUE : this._DB_FALSE;
if (typeof value === "string" && hasOwn.call(BoolMap, value))
return BoolMap[value] === true ? this._DB_TRUE : this._DB_FALSE;
if (typeof value === "number") {
if (value === 0) return this._DB_FALSE;
if (value === 1) return this._DB_TRUE;
throwValueError("Couldn't convert 'number(" + value + ")' to 'boolean'");
}
// Will throw.
break;
case "integer":
if (value == null) return "NULL";
if (typeof value === "number") {
if (!isFinite(value) || Math.floor(value) !== value)
throwValueError("Couldn't convert 'number(" + value + ")' to 'integer'");
return value.toString();
}
if (typeof value === "string") {
if (!reInteger.test(value))
throwValueError("Couldn't convert ill formatted 'string' to 'integer'");
return value;
}
// Will throw.
break;
case "number":
if (value == null) return "NULL";
if (typeof value === "number")
return this.escapeNumber(value);
if (typeof value === "string") {
if (!reNumber.test(value))
throwValueError("Couldn't convert ill formatted 'string' to 'number'");
return value;
}
// Will throw
break;
case "string":
if (value == null) return "NULL";
if (typeof value === "string")
return this.escapeString(value);
if (typeof value === "number" || typeof value === "boolean")
return this.escapeString(value.toString());
if (typeof value === "object")
return this.escapeString(JSON.stringify(value));
// Will throw.
break;
case "values":
if (value == null) return "NULL";
if (Array.isArray(value))
return this.escapeValues(value, false);
// Will throw.
break;
case "date":
case "time":
case "timestamp":
case "timestamptz":
case "interval":
if (typeof value === "string") {
return explicitType + " " + this.escapeString(value);
}
// Will throw.
break;
case "array":
if (value == null) return "NULL";
if (Array.isArray(value))
return this.escapeArray(value, false);
// Will throw.
break;
case "json":
case "jsonb":
// `undefined` maps to native DB `NULL` type while `null` maps to
// JSON `null` type. This is the only way to distinguish between
// these. `undefined` is disallowed by JSON anyway.
if (value === undefined) return "NULL";
return this.escapeJSON(value, type);
case "raw":
return value;
}
throwValueError("Couldn't convert '" + typeOf(value) + "' to '" + explicitType + "'");
}
// Implicitly Defined Type (deduced from `value`)
// ----------------------------------------------
// Check - `string`, `number` and `boolean`.
//
// These types are expected in most cases so they are checked first. All
// other types require more processing to escape them properly anyway.
if (typeof value === "string") return this.escapeString(value);
if (typeof value === "number") return this.escapeNumber(value);
if (typeof value === "boolean") return value === true ? this._DB_TRUE : this._DB_FALSE;
// Check - `undefined` and `null`.
//
// Undefined implicitly converts to `NULL`.
if (value == null) return "NULL";
// Sanity.
//
// At this point the only expected type of value is `object`.
if (typeof value !== "object")
throwValueError("Unexpected implicit value type '" + (typeof value) + "'");
// Node.
//
// All xql objects extend `Node`.
if (value instanceof Node)
return value.compileNode(this);
// Check - Buffer (BLOB / BINARY).
if (isBuffer(value))
return this.escapeBuffer(value);
// Check - Array (ARRAY).
if (isArray(value))
return this.escapeArray(value, false);
return this.escapeJSON(value, "json");
}
/**
* Escapes a number `value` into a SQL number.
*
* @param {number} value Number to escape.
* @return {string} Escaped `value` as string.
*/
escapeNumber(value) {
if (!isFinite(value)) {
var out = (value === Infinity) ? this._DB_POS_INF :
(value === -Infinity) ? this._DB_NEG_INF : this._DB_NAN;
if (out === "")
throwValueError("Couldn't process a special number (Infinity/NaN)");
return out;
}
return value.toString();
}
/**
* Escapes a number `value` into a SQL string.
*
* @param {string} value A string to escape.
* @return {string} Escaped `value` as string.
*
* @abstract
*/
escapeString(value) {
throwTypeError("Abstract method called");
}
/**
* Escapes a buffer/blob `value` into a SQL buffer representation.
*
* @param {Buffer} value Buffer to escape.
* @return {string} Escaped `value` as buffer.
*/
escapeBuffer(value) {
return "x'" + blobToHex(value) + "'";
}
/**
* Escapes an array into SQL `VALUES` representation.
*
* @param {array} value Array to escape.
* @return {string} Escaped `value` as SQL `VALUES`.
*/
escapeValues(value) {
var out = "";
for (var i = 0, len = value.length; i < len; i++) {