forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlQueryParser.cs
More file actions
437 lines (397 loc) · 15.3 KB
/
SqlQueryParser.cs
File metadata and controls
437 lines (397 loc) · 15.3 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Npgsql
{
class SqlQueryParser
{
readonly Dictionary<string, int> _paramIndexMap = new Dictionary<string, int>();
readonly StringBuilder _rewrittenSql = new StringBuilder();
List<NpgsqlStatement> _statements;
NpgsqlStatement _statement;
int _statementIndex;
/// <summary>
/// Receives a raw SQL query as passed in by the user, and performs some processing necessary
/// before sending to the backend.
/// This includes doing parameter placeholder processing (@p => $1), and splitting the query
/// up by semicolons if needed (SELECT 1; SELECT 2)
/// </summary>
/// <param name="sql">Raw user-provided query.</param>
/// <param name="standardConformantStrings">Whether the PostgreSQL session is configured to use standard conformant strings.</param>
/// <param name="parameters">The parameters configured on the <see cref="NpgsqlCommand"/> of this query
/// or an empty <see cref="NpgsqlParameterCollection"/> if deriveParameters is set to true.</param>
/// <param name="statements">An empty list to be populated with the statements parsed by this method</param>
/// <param name="deriveParameters">A bool indicating whether parameters contains a list of preconfigured parameters or an empty list to be filled with derived parameters.</param>
internal void ParseRawQuery(string sql, bool standardConformantStrings, NpgsqlParameterCollection parameters, List<NpgsqlStatement> statements, bool deriveParameters = false)
{
Debug.Assert(sql != null);
Debug.Assert(statements != null);
Debug.Assert(parameters != null);
Debug.Assert(deriveParameters == false || parameters.Count == 0);
_statements = statements;
_statementIndex = -1;
MoveToNextStatement();
var currCharOfs = 0;
var end = sql.Length;
var ch = '\0';
int dollarTagStart;
int dollarTagEnd;
var currTokenBeg = 0;
var blockCommentLevel = 0;
var parenthesisLevel = 0;
None:
if (currCharOfs >= end) {
goto Finish;
}
var lastChar = ch;
ch = sql[currCharOfs++];
NoneContinue:
for (; ; lastChar = ch, ch = sql[currCharOfs++]) {
switch (ch) {
case '/':
goto BlockCommentBegin;
case '-':
goto LineCommentBegin;
case '\'':
if (standardConformantStrings)
goto Quoted;
else
goto Escaped;
case '$':
if (!IsIdentifier(lastChar))
goto DollarQuotedStart;
else
break;
case '"':
goto DoubleQuoted;
case ':':
if (lastChar != ':')
goto ParamStart;
else
break;
case '@':
if (lastChar != '@')
goto ParamStart;
else
break;
case ';':
if (parenthesisLevel == 0)
goto SemiColon;
break;
case '(':
parenthesisLevel++;
break;
case ')':
parenthesisLevel--;
break;
case 'e':
case 'E':
if (!IsLetter(lastChar))
goto EscapedStart;
else
break;
}
if (currCharOfs >= end) {
goto Finish;
}
}
ParamStart:
if (currCharOfs < end) {
lastChar = ch;
ch = sql[currCharOfs];
if (IsParamNameChar(ch)) {
if (currCharOfs - 1 > currTokenBeg) {
_rewrittenSql.Append(sql.Substring(currTokenBeg, currCharOfs - 1 - currTokenBeg));
}
currTokenBeg = currCharOfs++ - 1;
goto Param;
} else {
currCharOfs++;
goto NoneContinue;
}
}
goto Finish;
Param:
// We have already at least one character of the param name
for (;;) {
lastChar = ch;
if (currCharOfs >= end || !IsParamNameChar(ch = sql[currCharOfs]))
{
var paramName = sql.Substring(currTokenBeg + 1, currCharOfs - (currTokenBeg + 1));
if (!_paramIndexMap.TryGetValue(paramName, out var index))
{
// Parameter hasn't been seen before in this query
if (!parameters.TryGetValue(paramName, out var parameter))
{
if (deriveParameters)
{
parameter = new NpgsqlParameter { ParameterName = paramName };
parameters.Add(parameter);
}
else
{
// Parameter placeholder does not match a parameter on this command.
// Leave the text as it was in the SQL, it may not be a an actual placeholder
_rewrittenSql.Append(sql.Substring(currTokenBeg, currCharOfs - currTokenBeg));
currTokenBeg = currCharOfs;
if (currCharOfs >= end)
goto Finish;
currCharOfs++;
goto NoneContinue;
}
}
if (!parameter.IsInputDirection)
throw new Exception($"Parameter '{paramName}' referenced in SQL but is an out-only parameter");
_statement.InputParameters.Add(parameter);
index = _paramIndexMap[paramName] = _statement.InputParameters.Count;
}
_rewrittenSql.Append('$');
_rewrittenSql.Append(index);
currTokenBeg = currCharOfs;
if (currCharOfs >= end) {
goto Finish;
}
currCharOfs++;
goto NoneContinue;
} else {
currCharOfs++;
}
}
Quoted:
while (currCharOfs < end) {
if (sql[currCharOfs++] == '\'') {
ch = '\0';
goto None;
}
}
goto Finish;
DoubleQuoted:
while (currCharOfs < end) {
if (sql[currCharOfs++] == '"') {
ch = '\0';
goto None;
}
}
goto Finish;
EscapedStart:
if (currCharOfs < end) {
lastChar = ch;
ch = sql[currCharOfs++];
if (ch == '\'') {
goto Escaped;
}
goto NoneContinue;
}
goto Finish;
Escaped:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '\'') {
goto MaybeConcatenatedEscaped;
}
if (ch == '\\') {
if (currCharOfs >= end) {
goto Finish;
}
currCharOfs++;
}
}
goto Finish;
MaybeConcatenatedEscaped:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '\r' || ch == '\n') {
goto MaybeConcatenatedEscaped2;
}
if (ch != ' ' && ch != '\t' && ch != '\f') {
lastChar = '\0';
goto NoneContinue;
}
}
goto Finish;
MaybeConcatenatedEscaped2:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '\'') {
goto Escaped;
}
if (ch == '-') {
if (currCharOfs >= end) {
goto Finish;
}
ch = sql[currCharOfs++];
if (ch == '-') {
goto MaybeConcatenatedEscapeAfterComment;
}
lastChar = '\0';
goto NoneContinue;
}
if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r' && ch != '\f') {
lastChar = '\0';
goto NoneContinue;
}
}
goto Finish;
MaybeConcatenatedEscapeAfterComment:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '\r' || ch == '\n') {
goto MaybeConcatenatedEscaped2;
}
}
goto Finish;
DollarQuotedStart:
if (currCharOfs < end) {
ch = sql[currCharOfs];
if (ch == '$') {
// Empty tag
dollarTagStart = dollarTagEnd = currCharOfs;
currCharOfs++;
goto DollarQuoted;
}
if (IsIdentifierStart(ch)) {
dollarTagStart = currCharOfs;
currCharOfs++;
goto DollarQuotedInFirstDelim;
}
lastChar = '$';
currCharOfs++;
goto NoneContinue;
}
goto Finish;
DollarQuotedInFirstDelim:
while (currCharOfs < end) {
lastChar = ch;
ch = sql[currCharOfs++];
if (ch == '$') {
dollarTagEnd = currCharOfs - 1;
goto DollarQuoted;
}
if (!IsDollarTagIdentifier(ch)) {
goto NoneContinue;
}
}
goto Finish;
DollarQuoted: {
var tag = sql.Substring(dollarTagStart - 1, dollarTagEnd - dollarTagStart + 2);
var pos = sql.IndexOf(tag, dollarTagEnd + 1); // Not linear time complexity, but that's probably not a problem, since PostgreSQL backend's isn't either
if (pos == -1) {
currCharOfs = end;
goto Finish;
}
currCharOfs = pos + dollarTagEnd - dollarTagStart + 2;
ch = '\0';
goto None;
}
LineCommentBegin:
if (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '-') {
goto LineComment;
}
lastChar = '\0';
goto NoneContinue;
}
goto Finish;
LineComment:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '\r' || ch == '\n') {
goto None;
}
}
goto Finish;
BlockCommentBegin:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '*') {
blockCommentLevel++;
goto BlockComment;
}
if (ch != '/') {
if (blockCommentLevel > 0) {
goto BlockComment;
}
lastChar = '\0';
goto NoneContinue;
}
}
goto Finish;
BlockComment:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '*') {
goto BlockCommentEnd;
}
if (ch == '/') {
goto BlockCommentBegin;
}
}
goto Finish;
BlockCommentEnd:
while (currCharOfs < end) {
ch = sql[currCharOfs++];
if (ch == '/') {
if (--blockCommentLevel > 0) {
goto BlockComment;
}
goto None;
}
if (ch != '*') {
goto BlockComment;
}
}
goto Finish;
SemiColon:
_rewrittenSql.Append(sql.Substring(currTokenBeg, currCharOfs - currTokenBeg - 1));
_statement.SQL = _rewrittenSql.ToString();
while (currCharOfs < end) {
ch = sql[currCharOfs];
if (char.IsWhiteSpace(ch)) {
currCharOfs++;
continue;
}
// TODO: Handle end of line comment? Although psql doesn't seem to handle them...
currTokenBeg = currCharOfs;
if (_rewrittenSql.Length > 0)
MoveToNextStatement();
goto None;
}
if (statements.Count > _statementIndex + 1)
statements.RemoveRange(_statementIndex + 1, statements.Count - (_statementIndex + 1));
return;
Finish:
_rewrittenSql.Append(sql.Substring(currTokenBeg, end - currTokenBeg));
_statement.SQL = _rewrittenSql.ToString();
if (statements.Count > _statementIndex + 1)
statements.RemoveRange(_statementIndex + 1, statements.Count - (_statementIndex + 1));
}
void MoveToNextStatement()
{
_statementIndex++;
if (_statements.Count > _statementIndex)
{
_statement = _statements[_statementIndex];
_statement.Reset();
}
else
{
_statement = new NpgsqlStatement();
_statements.Add(_statement);
}
_paramIndexMap.Clear();
_rewrittenSql.Clear();
}
static bool IsLetter(char ch)
=> 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z';
static bool IsIdentifierStart(char ch)
=> 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || 128 <= ch && ch <= 255;
static bool IsDollarTagIdentifier(char ch)
=> 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '0' <= ch && ch <= '9' || ch == '_' || 128 <= ch && ch <= 255;
static bool IsIdentifier(char ch)
=> 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '0' <= ch && ch <= '9' || ch == '_' || ch == '$' || 128 <= ch && ch <= 255;
static bool IsParamNameChar(char ch)
=> char.IsLetterOrDigit(ch) || ch == '_' || ch == '.'; // why dot??
}
}