-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
sql.ts
256 lines (201 loc) · 8.14 KB
/
sql.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
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
import isPlainObject from 'lodash/isPlainObject';
import type { AbstractDialect } from '../dialects/abstract/index.js';
import { escape as escapeSqlValue } from '../sql-string';
type BindOrReplacements = { [key: string]: unknown } | unknown[];
/**
* Inlines replacements in places where they would be valid SQL values.
*
* @param sqlString The SQL that contains the replacements
* @param dialect The dialect of the SQL
* @param replacements if provided, this method will replace ':named' replacements & positional replacements (?)
*
* @returns The SQL with replacements rewritten in their dialect-specific syntax.
*/
export function injectReplacements(
sqlString: string,
dialect: AbstractDialect,
replacements: BindOrReplacements
): string {
if (replacements == null) {
return sqlString;
}
if (!Array.isArray(replacements) && !isPlainObject(replacements)) {
throw new TypeError(`"replacements" must be an array or a plain object, but received ${JSON.stringify(replacements)} instead.`);
}
const isNamedReplacements = isPlainObject(replacements);
const isPositionalReplacements = Array.isArray(replacements);
let lastConsumedPositionalReplacementIndex = -1;
let output = '';
let currentDollarStringTagName = null;
let isString = false;
let isColumn = false;
let previousSliceEnd = 0;
let isSingleLineComment = false;
let isCommentBlock = false;
let stringIsBackslashEscapable = false;
for (let i = 0; i < sqlString.length; i++) {
const char = sqlString[i];
if (isColumn) {
if (char === dialect.TICK_CHAR_RIGHT) {
isColumn = false;
}
continue;
}
if (isString) {
if (
char === '\'' &&
(!stringIsBackslashEscapable || !isBackslashEscaped(sqlString, i - 1))
) {
isString = false;
stringIsBackslashEscapable = false;
}
continue;
}
if (currentDollarStringTagName !== null) {
if (char !== '$') {
continue;
}
const remainingString = sqlString.slice(i, sqlString.length);
const dollarStringStartMatch = remainingString.match(/^\$(?<name>[a-z_][0-9a-z_]*)?(\$)/i);
const tagName = dollarStringStartMatch?.groups?.name || '';
if (currentDollarStringTagName === tagName) {
currentDollarStringTagName = null;
}
continue;
}
if (isSingleLineComment) {
if (char === '\n') {
isSingleLineComment = false;
}
continue;
}
if (isCommentBlock) {
if (char === '*' && sqlString[i + 1] === '/') {
isCommentBlock = false;
}
continue;
}
if (char === dialect.TICK_CHAR_LEFT) {
isColumn = true;
continue;
}
if (char === '\'') {
isString = true;
// The following query is supported in almost all dialects,
// SELECT E'test';
// but postgres interprets it as an E-prefixed string, while other dialects interpret it as
// SELECT E 'test';
// which selects the type E and aliases it to 'test'.
stringIsBackslashEscapable =
// all ''-style strings in this dialect can be backslash escaped
dialect.canBackslashEscape() ||
// checking if this is a postgres-style E-prefixed string, which also supports backslash escaping
dialect.supports.escapeStringConstants &&
// is this a E-prefixed string, such as `E'abc'`, `e'abc'` ?
(sqlString[i - 1] === 'E' || sqlString[i - 1] === 'e') &&
// reject things such as `AE'abc'` (the prefix must be exactly E)
canPrecedeNewToken(sqlString[i - 2]);
continue;
}
if (char === '-' && sqlString.slice(i, i + 3) === '-- ') {
isSingleLineComment = true;
continue;
}
if (char === '/' && sqlString.slice(i, i + 2) === '/*') {
isCommentBlock = true;
continue;
}
// either the start of a $bind parameter, or the start of a $tag$string$tag$
if (char === '$') {
const previousChar = sqlString[i - 1];
// we are part of an identifier
if (/[0-9a-z_]/i.test(previousChar)) {
continue;
}
const remainingString = sqlString.slice(i, sqlString.length);
const dollarStringStartMatch = remainingString.match(/^\$(?<name>[a-z_][0-9a-z_]*)?(\$)/i);
if (dollarStringStartMatch) {
currentDollarStringTagName = dollarStringStartMatch.groups?.name ?? '';
i += dollarStringStartMatch[0].length - 1;
continue;
}
continue;
}
if (isNamedReplacements && char === ':') {
const previousChar = sqlString[i - 1];
// we want to be conservative with what we consider to be a replacement to avoid risk of conflict with potential operators
// users need to add a space before the bind parameter (except after '(', ',', and '=', '[' (for arrays))
if (!canPrecedeNewToken(previousChar) && previousChar !== '[') {
continue;
}
const remainingString = sqlString.slice(i, sqlString.length);
const match = remainingString.match(/^:(?<name>[a-z_][0-9a-z_]*)(?:\)|,|$|\s|::|;|])/i);
const replacementName = match?.groups?.name;
if (!replacementName) {
continue;
}
// @ts-expect-error -- isPlainObject does not tell typescript that replacements is a plain object, not an array
const replacementValue = replacements[replacementName];
if (!Object.prototype.hasOwnProperty.call(replacements, replacementName) || replacementValue === undefined) {
throw new Error(`Named replacement ":${replacementName}" has no entry in the replacement map.`);
}
const escapedReplacement = escapeSqlValue(replacementValue, undefined, dialect.name, true);
// add everything before the bind parameter name
output += sqlString.slice(previousSliceEnd, i);
// continue after the bind parameter name
previousSliceEnd = i + replacementName.length + 1;
output += escapedReplacement;
continue;
}
if (isPositionalReplacements && char === '?') {
const previousChar = sqlString[i - 1];
// we want to be conservative with what we consider to be a replacement to avoid risk of conflict with potential operators
// users need to add a space before the bind parameter (except after '(', ',', and '=', '[' (for arrays))
// -> [ is temporarily added to allow 'ARRAY[:name]' to be replaced
// https://github.com/sequelize/sequelize/issues/14410 will make this obsolete.
if (!canPrecedeNewToken(previousChar) && previousChar !== '[') {
continue;
}
// don't parse ?| and ?& operators as replacements
const nextChar = sqlString[i + 1];
if (nextChar === '|' || nextChar === '&') {
continue;
}
const replacementIndex = ++lastConsumedPositionalReplacementIndex;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore -- ts < 4.4 loses the information that 'replacements' is an array when using 'isPositionalReplacements' instead of 'Array.isArray'
// but performance matters here.
const replacementValue = replacements[lastConsumedPositionalReplacementIndex];
if (replacementValue === undefined) {
throw new Error(`Positional replacement (?) ${replacementIndex} has no entry in the replacement map (replacements[${replacementIndex}] is undefined).`);
}
const escapedReplacement = escapeSqlValue(replacementValue as any, undefined, dialect.name, true);
// add everything before the bind parameter name
output += sqlString.slice(previousSliceEnd, i);
// continue after the bind parameter name
previousSliceEnd = i + 1;
output += escapedReplacement;
}
}
if (isString) {
throw new Error(
`The following SQL query includes an unterminated string literal:\n${sqlString}`
);
}
output += sqlString.slice(previousSliceEnd, sqlString.length);
return output;
}
function canPrecedeNewToken(char: string | undefined): boolean {
return char === undefined || /[\s(>,=]/.test(char);
}
function isBackslashEscaped(string: string, pos: number): boolean {
let escaped = false;
for (let i = pos; i >= 0; i--) {
const char = string[i];
if (char !== '\\') {
break;
}
escaped = !escaped;
}
return escaped;
}