pg-format.ts77 lines · main
1// [Joshen] These are from https://github.com/datalanche/node-pg-format/blob/master/lib/index.js
2function formatDate(date: any) {
3 date = date.replace('T', ' ')
4 date = date.replace('Z', '+00')
5 return date
6}
7
8function arrayToList(useSpace: any, array: any, formatter: any) {
9 let sql = ''
10
11 sql += useSpace ? ' (' : '('
12 for (var i = 0; i < array.length; i++) {
13 sql += (i === 0 ? '' : ', ') + formatter(array[i])
14 }
15 sql += ')'
16
17 return sql
18}
19
20export function quoteLiteral(value: any): any {
21 let literal = null
22 let explicitCast = null
23
24 if (value === undefined || value === null) {
25 return 'NULL'
26 } else if (value === false) {
27 return "'f'"
28 } else if (value === true) {
29 return "'t'"
30 } else if (value instanceof Date) {
31 return "'" + formatDate(value.toISOString()) + "'"
32 } else if (value instanceof Buffer) {
33 return "E'\\\\x" + value.toString('hex') + "'"
34 } else if (Array.isArray(value) === true) {
35 let temp = []
36 for (let i = 0; i < value.length; i++) {
37 if (Array.isArray(value[i]) === true) {
38 temp.push(arrayToList(i !== 0, value[i], quoteLiteral))
39 } else {
40 temp.push(quoteLiteral(value[i]))
41 }
42 }
43 return temp.toString()
44 } else if (value === Object(value)) {
45 explicitCast = 'jsonb'
46 literal = JSON.stringify(value)
47 } else {
48 literal = value.toString().slice(0) // create copy
49 }
50
51 let hasBackslash = false
52 let quoted = "'"
53
54 for (let i = 0; i < literal.length; i++) {
55 let c = literal[i]
56 if (c === "'") {
57 quoted += c + c
58 } else if (c === '\\') {
59 quoted += c + c
60 hasBackslash = true
61 } else {
62 quoted += c
63 }
64 }
65
66 quoted += "'"
67
68 if (hasBackslash === true) {
69 quoted = 'E' + quoted
70 }
71
72 if (explicitCast) {
73 quoted += '::' + explicitCast
74 }
75
76 return quoted
77}