-
Notifications
You must be signed in to change notification settings - Fork 15
/
util.ts
97 lines (94 loc) · 2.99 KB
/
util.ts
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
type SupportTypeElement =
| string
| Date
| number
| boolean
| null
| undefined
// deno-lint-ignore ban-types
| {};
// Array
type SupportType = SupportTypeElement | SupportTypeElement[];
export function replaceParams(
sql: string,
params?: null | SupportType[]
): string {
if (!params) return sql;
let paramIndex = 0;
sql = sql.replace(
/('[^'\\]*(?:\\.[^'\\]*)*')|("[^"\\]*(?:\\.[^"\\]*)*")|(\?\?)|(\?)/g,
(str) => {
if (paramIndex >= params.length) return str;
// ignore
if (/".*"/g.test(str) || /'.*'/g.test(str)) {
return str;
}
// identifier
if (str === '??') {
const val = params[paramIndex++];
if (val instanceof Array) {
return `(${val
.map((item) => replaceParams('??', [item]))
.join(',')})`;
} else if (val === '*') {
return val;
} else if (typeof val === 'string' && val.includes('.')) {
// a.b => `a`.`b`
const _arr = val.split('.');
return replaceParams(_arr.map(() => '??').join('.'), _arr);
} else if (
typeof val === 'string' &&
(val.includes(' as ') || val.includes(' AS '))
) {
// a as b => `a` AS `b`
const newVal = val.replace(' as ', ' AS ');
const _arr = newVal.split(' AS ');
return replaceParams(_arr.map(() => '??').join(' AS '), _arr);
} else {
return ['`', val, '`'].join('');
}
}
// value
const val = params[paramIndex++];
if (val === null) return 'NULL';
switch (typeof val) {
case 'object':
if (val instanceof Date) return `"${formatDate(val)}"`;
if (val instanceof Array) {
return `(${val
.map((item) => replaceParams('?', [item]))
.join(',')})`;
}
throw new Error(
`Unsupported argument type in your sql query: ${
// deno-lint-ignore ban-types
(val as object).constructor.name
}`
);
case 'string':
return `"${escapeString(val)}"`;
case 'undefined':
return 'NULL';
case 'number':
case 'boolean':
default:
return `${val}`;
}
}
);
return sql;
}
function formatDate(date: Date) {
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const days = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
// Date does not support microseconds precision, so we only keep the milliseconds part.
const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
return `${year}-${month}-${days} ${hours}:${minutes}:${seconds}.${milliseconds}`;
}
function escapeString(str: string) {
return str.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
}