-
Notifications
You must be signed in to change notification settings - Fork 217
/
formatting.js
682 lines (638 loc) · 23.7 KB
/
formatting.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
'use strict';
var $arr = require('../lib/array');
// Format Modification Flags;
var fmFlags = {
raw: 1, // Raw-Text variable
name: 2, // SQL Name/Identifier
json: 4, // JSON modifier
csv: 8, // CSV modifier
value: 16 // escaped, but without ''
};
// Format Modification Map;
var fmMap = {
'^': fmFlags.raw,
':raw': fmFlags.raw,
'~': fmFlags.name,
':name': fmFlags.name,
':json': fmFlags.json,
':csv': fmFlags.csv,
':value': fmFlags.value,
'#': fmFlags.value
};
////////////////////////////////////////////////////
// Converts a single value into its Postgres format.
function formatValue(value, fm, obj) {
if (value instanceof Function) {
return formatValue(resolveFunc(value, obj), fm, obj);
}
if (value && typeof value === 'object') {
var ctf = value['formatDBType']; // custom type formatting;
if (ctf instanceof Function) {
fm |= value._rawDBType ? fmFlags.raw : 0;
return formatValue(resolveFunc(ctf, value), fm, obj);
}
}
var isRaw = !!(fm & fmFlags.raw);
fm &= ~fmFlags.raw;
switch (fm) {
case fmFlags.name:
return $as.name(value);
case fmFlags.json:
return $as.json(value, isRaw);
case fmFlags.csv:
return $as.csv(value);
case fmFlags.value:
return $as.value(value);
default:
break;
}
if (isNull(value)) {
throwIfRaw(isRaw);
return 'null';
}
switch (typeof value) {
case 'string':
return $as.text(value, isRaw);
case 'boolean':
return $as.bool(value);
case 'number':
return $as.number(value);
default:
if (value instanceof Date) {
return $as.date(value, isRaw);
}
if (value instanceof Array) {
return $as.array(value);
}
if (value instanceof Buffer) {
return $as.buffer(value, isRaw);
}
return $as.json(value, isRaw);
}
}
//////////////////////////////////////////////////////////////////////////
// Converts array of values into PostgreSQL Array Constructor: array[...],
// as per PostgreSQL documentation: http://www.postgresql.org/docs/9.4/static/arrays.html
// Arrays of any depth/dimension are supported.
function formatArray(array) {
function loop(a) {
return '[' + $arr.map(a, function (v) {
return v instanceof Array ? loop(v) : formatValue(v);
}).join() + ']';
}
return 'array' + loop(array);
}
///////////////////////////////////////////////////////////////
// Formats array of javascript-type parameters as a csv string,
// so it can be passed into a PostgreSQL function.
// Both single value and array or values are supported.
function formatCSV(values) {
if (values instanceof Array) {
return $arr.map(values, function (v) {
return formatValue(v);
}).join();
}
return values === undefined ? '' : formatValue(values);
}
///////////////////////////////
// Query formatting helpers;
var formatAs = {
object: function (query, obj, raw, options) {
options = options && typeof options === 'object' ? options : {};
var pattern = /\$(?:({)|(\()|(<)|(\[)|(\/))\s*[a-zA-Z0-9\$_]+(\^|~|#|:raw|:name|:json|:csv|:value)?\s*(?:(?=\2)(?=\3)(?=\4)(?=\5)}|(?=\1)(?=\3)(?=\4)(?=\5)\)|(?=\1)(?=\2)(?=\4)(?=\5)>|(?=\1)(?=\2)(?=\3)(?=\5)]|(?=\1)(?=\2)(?=\3)(?=\4)\/)/g;
return query.replace(pattern, function (name) {
var v = formatAs.stripName(name.replace(/^\$[{(<[/]|[\s})>\]/]/g, ''), raw);
if (v.name in obj) {
return formatValue(obj[v.name], v.fm, obj);
}
if (v.name === 'this') {
return formatValue(obj, v.fm);
}
if ('default' in options) {
var d = options.default, value = d instanceof Function ? d.call(obj, v.name, obj) : d;
return formatValue(value, v.fm, obj);
}
if (options.partial) {
return name;
}
// property must exist as the object's own or inherited;
throw new Error("Property '" + v.name + "' doesn't exist.");
});
},
array: function (query, array, raw, options) {
options = options && typeof options === 'object' ? options : {};
return query.replace(/\$([1-9][0-9]{0,3}(?![0-9])(\^|~|#|:raw|:name|:json|:csv|:value)?)/g, function (name) {
var v = formatAs.stripName(name.substr(1), raw);
var idx = v.name - 1;
if (idx < array.length) {
return formatValue(array[idx], v.fm);
}
if ('default' in options) {
var d = options.default, value = d instanceof Function ? d.call(array, idx, array) : d;
return formatValue(value, v.fm);
}
if (options.partial) {
return name;
}
throw new RangeError("Variable $" + v.name + " out of range. Parameters array length: " + array.length);
});
},
value: function (query, value, raw) {
return query.replace(/\$1(?![0-9])(\^|~|#|:raw|:name|:json|:csv|:value)?/g, function (name) {
var v = formatAs.stripName(name, raw);
return formatValue(value, v.fm);
});
},
stripName: function (name, raw) {
var mod = name.match(/\^|~|#|:raw|:name|:json|:csv|:value/);
if (mod) {
return {
name: name.substr(0, mod.index),
fm: fmMap[mod[0]] | (raw ? fmFlags.raw : 0)
};
} else {
return {
name: name,
fm: raw ? fmFlags.raw : null
};
}
}
};
////////////////////////////////////////////
// Simpler check for null/undefined;
function isNull(value) {
return value === undefined || value === null;
}
/////////////////////////////////////////
// Wraps a text string in single quotes;
function TEXT(text) {
return "'" + text + "'";
}
////////////////////////////////////////////////
// Replaces each single-quote symbol ' with two,
// for compliance with PostgreSQL strings.
function safeText(text) {
return text.replace(/'/g, "''");
}
/////////////////////////////////////////////
// Throws an exception, if flag 'raw' is set.
function throwIfRaw(raw) {
if (raw) {
throw new TypeError("Values null/undefined cannot be used as raw text.");
}
}
////////////////////////////////////////////
// Recursively resolves parameter-function,
// with the optional calling context.
function resolveFunc(value, obj) {
while (value instanceof Function) {
value = obj ? value.call(obj) : value();
}
return value;
}
///////////////////////////////////////////////////////////////////////////////////
// 'pg-promise' query formatting solution;
//
// It implements two types of formatting, depending on the 'values' passed:
//
// 1. format "$1, $2, etc", when 'values' is of type string, boolean, number, date,
// function or null (or an array of the same types, plus undefined values);
// 2. format $*propName*, when 'values' is an object (not null and not Date),
// and where * is any of the supported open-close pairs: {}, (), [], <>, //
//
// NOTES:
// 1. Raw-text values can be injected using syntax: $1^,$2^,... or $*propName^*
// 2. If 'values' is an object that supports function formatDBType, either its
// own or inherited, the actual value and the formatting syntax are determined
// by the result returned from that function.
//
// When formatting fails, the function throws an error.
function $formatQuery(query, values, raw, options) {
if (typeof query !== 'string') {
throw new TypeError("Parameter 'query' must be a text string.");
}
if (values && typeof values === 'object') {
var ctf = values['formatDBType']; // custom type formatting;
if (ctf instanceof Function) {
return $formatQuery(query, resolveFunc(ctf, values), raw || values._rawDBType, options);
}
if (values instanceof Array) {
// $1, $2,... formatting to be applied;
return formatAs.array(query, values, raw, options);
}
if (!(values instanceof Date || values instanceof Buffer)) {
// $*propName* formatting to be applied;
return formatAs.object(query, values, raw, options);
}
}
// $1 formatting to be applied, if values != undefined;
return values === undefined ? query : formatAs.value(query, values, raw);
}
//////////////////////////////////////////////////////
// Formats a standard PostgreSQL function call query;
function $formatFunction(funcName, values, capSQL) {
var sql = capSQL ? 'SELECT * FROM ' : 'select * from ';
return sql + funcName + '(' + formatCSV(values) + ')';
}
/**
* @namespace formatting
* @description
* Namespace for all query-formatting functions, available from `pgp.as`, before and after initializing the library.
*
* @property {function} name
* {@link formatting.name name} - formats an SQL name.
*
* @property {function} text
* {@link formatting.text text} - formats a text string.
*
* @property {function} number
* {@link formatting.number number} - formats a number.
*
* @property {function} buffer
* {@link formatting.buffer buffer} - formats a `Buffer` object.
*
* @property {function} value
* {@link formatting.value value} - formats text as an open value.
*
* @property {function} json
* {@link formatting.json json} - formats any value as JSON.
*
* @property {function} func
* {@link formatting.func func} - formats the value returned from a function.
*
* @property {function} format
* {@link formatting.format format} - formats a query according to parameters.
*
*/
var $as = {
/**
* @method formatting.text
* @description
* Converts a value into PostgreSQL text presentation, escaped as required.
*
* Escaping the result means:
* 1. Every single-quote (apostrophe) is replaced with two
* 2. The resulting text is wrapped in apostrophes
*
* @param {value|function} value
* Value to be converted, or a function that returns the value.
*
* If the `value` resolves as `null` or `undefined`, while `raw`=`true`,
* it will throw {@link external:TypeError TypeError} = `Values null/undefined cannot be used as raw text.`
*
* @param {boolean} [raw=false]
* Indicates when not to escape the resulting text.
*
* @returns {string}
*
* - `null` string, if the `value` resolves as `null` or `undefined`
* - escaped result of `value.toString()`, if the `value` isn't a string
* - escaped string version, if `value` is a string.
*
* The result is not escaped, if `raw` was passed in as `true`.
*/
text: function (value, raw) {
value = resolveFunc(value);
if (isNull(value)) {
throwIfRaw(raw);
return 'null';
}
if (typeof value !== 'string') {
value = value.toString();
}
return raw ? value : TEXT(safeText(value));
},
/**
* @method formatting.name
* @description
* Properly escapes an sql name or identifier, fixing double-quote symbols and wrapping the result in double quotes.
*
* Implements a safe way to format SQL Names that neutralizes SQL Injection.
*
* **Added in v.4.7.7:**
*
* If the `name` contains only a single `*` (trailing spaces are ignored), then `name` is returned exactly as is.
*
* @param {String|function} name
* SQL name or identifier, or a function that returns it.
*
* The name must be at least 1 character long.
*
* If `name` doesn't resolve into a non-empty string, it throws {@link external:TypeError TypeError} = `An sql name/identifier must be a non-empty text string.`
*
* @returns {string}
* The SQL Name/Identifier properly escaped for compliance with the PostgreSQL standard for SQL names and identifiers.
*/
name: function (name) {
name = resolveFunc(name);
if (typeof name !== 'string' || !name.length) {
throw new TypeError("An sql name/identifier must be a non-empty text string.");
}
return /^\s*\*(\s*)$/.test(name) ? name : ('"' + name.replace(/"/g, '""') + '"');
},
/**
* @method formatting.value
* @description
* Represents an open value, one to be formatted according to its type, properly escaped,
* but without surrounding quotes for text types.
*
* @param {value|function} value
* Value to be converted, or a function that returns the value.
*
* If `value` resolves as `null` or `undefined`, it will throw {@link external:TypeError TypeError} = `Open values cannot be null or undefined.`
*
* @returns {string}
* Formatted and properly escaped string, but without surrounding quotes for text types.
*/
value: function (value) {
value = resolveFunc(value);
if (isNull(value)) {
throw new TypeError("Open values cannot be null or undefined.");
}
return safeText(formatValue(value, fmFlags.raw));
},
/**
* @method formatting.buffer
* @description
* Converts an object of type `Buffer` into a hex string compatible with PostgreSQL type `bytea`.
*
* @param {Buffer|function} obj
* Object to be converted, or a function that returns one.
*
* @param {boolean} [raw=false]
* Indicates when not to wrap the resulting string in quotes.
*
* The generated hex string doesn't need to be escaped.
*
* @returns {string}
*/
buffer: function (obj, raw) {
obj = resolveFunc(obj);
if (isNull(obj)) {
throwIfRaw(raw);
return 'null';
}
if (obj instanceof Buffer) {
var s = "\\x" + obj.toString("hex");
return raw ? s : TEXT(s);
}
throw new TypeError(TEXT(obj) + " is not a Buffer object.");
},
/**
* @method formatting.bool
* @description
* Converts a truthy value into PostgreSQL boolean presentation.
*
* @param {boolean|function} value
* Value to be converted, or a function that returns the value.
*
* @returns {string}
*/
bool: function (value) {
value = resolveFunc(value);
if (isNull(value)) {
return 'null';
}
return value ? 'true' : 'false';
},
/**
* @method formatting.date
* @description
* Converts a `Date`-type value into PostgreSQL date/time presentation,
* as a UTC string, wrapped in quotes (unless flag `raw` is set).
*
* @param {date|function} d
* Date object to be converted, or a function that returns one.
*
* @param {boolean} [raw=false]
* Indicates when not to escape the value.
*
* @returns {string}
*/
date: function (d, raw) {
d = resolveFunc(d);
if (isNull(d)) {
throwIfRaw(raw);
return 'null';
}
if (d instanceof Date) {
// UTC date string is what PostgreSQL understands automatically;
var s = d.toUTCString();
// NOTE: Many languages use apostrophes in month names;
return raw ? s : TEXT(safeText(s));
}
throw new TypeError(TEXT(d) + " is not a Date object.");
},
/**
* @method formatting.number
* @description
* Converts a numeric value into its PostgreSQL number presentation,
* with support for `NaN`, `+Infinity` and `-Infinity`.
*
* @param {number|function} num
* Number to be converted, or a function that returns one.
*
* @returns {string}
*/
number: function (num) {
num = resolveFunc(num);
if (isNull(num)) {
return 'null';
}
if (typeof num !== 'number') {
throw new TypeError(TEXT(num) + " is not a number.");
}
if (isFinite(num)) {
return num.toString();
}
// Converting NaN/+Infinity/-Infinity according to Postgres documentation:
// http://www.postgresql.org/docs/9.4/static/datatype-numeric.html#DATATYPE-FLOAT
//
// NOTE: strings for 'NaN'/'+Infinity'/'-Infinity' are not case-sensitive.
if (num === Number.POSITIVE_INFINITY) {
return TEXT("+Infinity");
}
if (num === Number.NEGATIVE_INFINITY) {
return TEXT("-Infinity");
}
return TEXT("NaN");
},
/**
* @method formatting.array
* @description
* Converts an array of values into its PostgreSQL presentation as an Array-Type
* constructor string: `array[]`.
*
* @param {array|function} arr
* Array to be converted, or a function that returns one.
*
* @returns {string}
*/
array: function (arr) {
arr = resolveFunc(arr);
if (isNull(arr)) {
return 'null';
}
if (arr instanceof Array) {
return formatArray(arr);
}
throw new TypeError(TEXT(arr) + " is not an Array object.");
},
/**
* @method formatting.csv
* @description
* Converts a single value or an array of values into a CSV string, with all values formatted
* according to their type.
*
* @param {array|value|function} values
* Value(s) to be converted, or a function that returns it.
*
* @returns {string}
*/
csv: function (values) {
return formatCSV(resolveFunc(values));
},
/**
* @method formatting.json
* @description
* Converts any value into JSON (using `JSON.stringify`), and returns it as
* a valid string, with single-quote symbols fixed, unless flag `raw` is set.
*
* @param {object|function} obj
* Object/Value to be converted, or a function that returns it.
*
* @param {boolean} [raw=false]
* Indicates when not to escape the result.
*
* @returns {string}
*/
json: function (obj, raw) {
obj = resolveFunc(obj);
if (isNull(obj)) {
throwIfRaw(raw);
return 'null';
}
var s = JSON.stringify(obj);
return raw ? s : TEXT(safeText(s));
},
/**
* @method formatting.func
* @description
* Calls the function to get the actual value, and then formats the result
* according to its type + `raw` flag.
*
* @param {function} func
* Function to be called, with support for nesting.
*
* @param {boolean} [raw=false]
* Indicates when not to escape the result.
*
* @param {object} [obj]
* `this` context to be passed into the function on all nested levels.
*
* @returns {string}
*/
func: function (func, raw, obj) {
if (isNull(func)) {
throwIfRaw(raw);
return 'null';
}
if (typeof func !== 'function') {
throw new TypeError(TEXT(func) + " is not a function.");
}
var fm = raw ? fmFlags.raw : null;
if (isNull(obj)) {
return formatValue(resolveFunc(func), fm);
}
if (typeof obj === 'object') {
return formatValue(resolveFunc(func, obj), fm, obj);
}
throw new TypeError(TEXT(obj) + " is not an object.");
},
/**
* @method formatting.format
* @description
* Replaces variables in a string according to the type of `values`:
*
* - Replaces `$1` occurrences when `values` is of type `string`, `boolean`, `number`, `Date`, `Buffer` or when it is `null`.
* - Replaces variables `$1`, `$2`, ...`$9999` when `values` is an array of parameters. When a variable is out of range,
* it throws {@link external:RangeError RangeError} = `Variable $n out of range. Parameters array length: x`, unless
* option `partial` is used.
* - Replaces `$*propName*`, where `*` is any of `{}`, `()`, `[]`, `<>`, `//`, when `values` is an object
* that's not a `Date`, `Buffer` or `null`. Special property name `this` refers to the formatting object itself,
* to be injected as a JSON string. When referencing a property that doesn't exist in the formatting object, it throws
* {@link external:Error Error} = `Property 'PropName' doesn't exist`, unless option `partial` is used.
*
* By default, each variable is automatically formatted according to its type, unless it is a special variable:
* - Raw-text variables end with `:raw` or symbol `^`, and prevent escaping the text. Such variables are not
* allowed to be `null` or `undefined`, or the method will throw {@link external:TypeError TypeError} = `Values null/undefined cannot be used as raw text.`
* - `$1:raw`, `$2:raw`,..., and `$*propName:raw*` (see `*` above)
* - `$1^`, `$2^`,..., and `$*propName^*` (see `*` above)
* - Open-value variables end with `:value` or symbol `#`, to be escaped, but not wrapped in quotes. Such variables are
* not allowed to be `null` or `undefined`, or the method will throw {@link external:TypeError TypeError} = `Open values cannot be null or undefined.`
* - `$1:value`, `$2:value`,..., and `$*propName:value*` (see `*` above)
* - `$1#`, `$2#`,..., and `$*propName#*` (see `*` above)
* - SQL name variables end with `:name` or symbol `~` (tilde), and provide proper escaping for SQL names/identifiers:
* - `$1:name`, `$2:name`,..., and `$*propName:name*` (see `*` above)
* - `$1~`, `$2~`,..., and `$*propName~*` (see `*` above)
* - JSON override ends with `:json` to format the value of any type as a JSON string
* - CSV override ends with `:csv` to format an array as a properly escaped comma-separated list of values.
*
* @param {string} query
* Query string with formatting variables in it.
*
* @param {array|object|value} [values]
* Formatting parameter(s) / variable value(s).
*
* @param {object} [options]
* Formatting Options.
*
* @param {boolean} [options.partial=false]
* Indicates that we intend to do only a partial replacement, i.e. throw no error when encountering a variable or
* property name that's missing within the formatting parameters.
*
* This option has no meaning when option `default` is present.
*
* @param {} [options.default]
* **Added in v.5.0.5**
*
* Sets a default value for every variable that's missing, consequently preventing errors when encountering a variable
* or property name that's missing within the formatting parameters.
*
* It can also be set to a function, to be called with two parameters that depend on the type of formatting being used,
* and to return the actual default value:
*
* - Named Parameters formatting:
* - `name` - name of the property missing in the formatting object
* - `obj` - the formatting object, and is the same as `this` context
*
* - Regular variable formatting:
* - `index` - element's index that's outside of the formatting array's range
* - `arr` - the formatting array, and is the same as `this` context
*
* @returns {string}
* Formatted query string.
*
*/
format: function (query, values, options) {
return $formatQuery(query, values, false, options);
}
};
Object.freeze($as);
module.exports = {
formatQuery: $formatQuery,
formatFunction: $formatFunction,
as: $as
};
/**
* @external Error
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
*/
/**
* @external TypeError
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
*/
/**
* @external RangeError
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError
*/