{{ message }}
forked from NpgsqlRest/NpgsqlRest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlFileParser.cs
More file actions
947 lines (851 loc) · 37.5 KB
/
Copy pathSqlFileParser.cs
File metadata and controls
947 lines (851 loc) · 37.5 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
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
using System.Text;
using NpgsqlRest.Common;
namespace NpgsqlRest.SqlFileSource;
/// <summary>
/// Result of parsing a SQL file.
/// </summary>
public class SqlFileParseResult
{
/// <summary>
/// Extracted comment text (all comments concatenated, markers stripped).
/// Fed to DefaultCommentParser for annotation processing.
/// </summary>
public string Comment { get; set; } = "";
/// <summary>
/// Individual SQL statements (split on ; outside strings/quotes/comments).
/// </summary>
public List<string> Statements { get; } = [];
/// <summary>
/// Whether a mutation command (INSERT, UPDATE, DELETE) was detected outside strings/quotes/comments.
/// </summary>
public bool HasInsert { get; set; }
public bool HasUpdate { get; set; }
public bool HasDelete { get; set; }
/// <summary>
/// Whether a DO block was detected.
/// </summary>
public bool IsDoBlock { get; set; }
/// <summary>
/// Virtual parameters from @define_param annotations.
/// Each entry is (name, type) where type may be null (defaults to text).
/// </summary>
public List<(string Name, string? Type)> VirtualParams { get; } = [];
/// <summary>
/// Per-command @single annotations (positional).
/// Key is 0-based statement index, value is true if @single was placed before that statement.
/// </summary>
public HashSet<int> SingleCommands { get; } = [];
/// <summary>
/// Per-command @result annotations (positional).
/// Key is 0-based statement index, value is the custom result name.
/// </summary>
public Dictionary<int, string> PositionalResultNames { get; } = [];
/// <summary>
/// Per-command @skip annotations (positional).
/// Contains 0-based statement indices of commands that should execute but not produce result keys.
/// </summary>
public HashSet<int> SkipCommands { get; } = [];
/// <summary>
/// Per-command @returns annotations (positional).
/// Key is 0-based statement index, value is the composite type name.
/// When present, the Describe step is skipped for that statement and
/// columns are resolved from the composite type metadata instead.
/// </summary>
public Dictionary<int, string> ReturnsTypeOverrides { get; } = [];
/// <summary>
/// Errors encountered during parsing.
/// </summary>
public List<string> Errors { get; } = [];
/// <summary>
/// Auto-detected HTTP method based on mutations.
/// DELETE > POST (UPDATE) > PUT (INSERT) > GET (none).
/// </summary>
public Method AutoHttpMethod
{
get
{
if (IsDoBlock) return Method.POST;
if (HasDelete) return Method.DELETE;
if (HasUpdate) return Method.POST;
if (HasInsert) return Method.PUT;
return Method.GET;
}
}
}
/// <summary>
/// Result of the named-parameter (:name) rewrite pass (<see cref="SqlFileParser.RewriteNamedParameters"/>).
/// </summary>
public sealed class NamedParamRewriteResult
{
/// <summary>
/// Placeholder names in first-appearance order; index i corresponds to $(i+1) in the rewritten SQL.
/// The same name (case-insensitive) always maps to the same ordinal, file-wide.
/// </summary>
public List<string> Names { get; } = [];
/// <summary>The file uses :name placeholders.</summary>
public bool HasNamed => Names.Count > 0;
/// <summary>A native positional ($N) placeholder was found outside strings/comments/dollar-quotes.</summary>
public bool HasPositional { get; set; }
}
/// <summary>
/// Single-pass SQL file parser. Extracts comments and splits statements simultaneously.
/// Handles: line comments (--), block comments (/* */), single-quoted strings (''),
/// dollar-quoted strings ($$...$$, $tag$...$tag$), and semicolon statement splitting.
/// Also detects mutation commands and DO blocks outside quoted/commented regions.
/// </summary>
public static class SqlFileParser
{
private enum State
{
Normal,
LineComment,
BlockComment,
SingleQuote,
DollarQuote,
}
/// <summary>
/// Parse a SQL file content into comments and statements.
/// </summary>
/// <param name="content">The SQL file content.</param>
/// <param name="commentScope">Which comments to extract as annotations.</param>
public static SqlFileParseResult Parse(ReadOnlySpan<char> content, CommentScope commentScope = CommentScope.All)
{
var result = new SqlFileParseResult();
if (content.IsEmpty) return result;
var state = State.Normal;
var commentBuilder = new ValueStringBuilder(stackalloc char[512]);
var stmtBuilder = new ValueStringBuilder(stackalloc char[Math.Min(content.Length, 4096)]);
var dollarTag = new ValueStringBuilder(stackalloc char[64]);
int blockCommentDepth = 0;
bool firstStatementSeen = false;
// Track the token before a dollar-quote for DO block detection
var lastToken = new ValueStringBuilder(stackalloc char[16]);
bool lastTokenIsWord = false;
// Track comments between statements for positional per-command annotations
var interStmtCommentBuilder = new ValueStringBuilder(stackalloc char[256]);
// Track header comment length (before first statement) for per-command annotation extraction
int headerCommentLength = -1;
// Track whether we're still on the same line as the last semicolon (for inline annotations)
bool sameLineAsSemicolon = false;
// Track whether a block comment started on the same line as a semicolon
bool blockCommentSameLine = false;
var blockCommentBuffer = new ValueStringBuilder(stackalloc char[128]);
int i = 0;
int len = content.Length;
try
{
while (i < len)
{
char c = content[i];
switch (state)
{
case State.Normal:
// Check for line comment: --
if (c == '-' && i + 1 < len && content[i + 1] == '-')
{
// Extract comment text until end of line
i += 2;
int commentStart = i;
while (i < len && content[i] != '\n' && content[i] != '\r')
i++;
if (ShouldCollectComment(commentScope, firstStatementSeen))
{
if (commentBuilder.Length > 0) commentBuilder.Append('\n');
commentBuilder.Append(content[commentStart..i]);
}
// Collect inter-statement comments for positional annotations
if (firstStatementSeen)
{
if (sameLineAsSemicolon)
{
// Comment on same line as ; → applies to the just-completed statement
var prevIndex = result.Statements.Count - 1;
if (prevIndex >= 0)
{
ExtractPerCommandAnnotations(content[commentStart..i].ToString(), prevIndex, result);
}
}
else
{
if (interStmtCommentBuilder.Length > 0) interStmtCommentBuilder.Append('\n');
interStmtCommentBuilder.Append(content[commentStart..i]);
}
}
sameLineAsSemicolon = false;
// Skip \r\n
if (i < len && content[i] == '\r') i++;
if (i < len && content[i] == '\n') i++;
continue;
}
// Check for block comment: /*
if (c == '/' && i + 1 < len && content[i + 1] == '*')
{
state = State.BlockComment;
blockCommentDepth = 1;
blockCommentSameLine = sameLineAsSemicolon;
i += 2;
if (ShouldCollectComment(commentScope, firstStatementSeen))
{
if (commentBuilder.Length > 0) commentBuilder.Append('\n');
}
if (firstStatementSeen && !blockCommentSameLine)
{
if (interStmtCommentBuilder.Length > 0) interStmtCommentBuilder.Append('\n');
}
continue;
}
// Check for single quote: '
if (c == '\'')
{
state = State.SingleQuote;
stmtBuilder.Append(c);
lastTokenIsWord = false;
lastToken.Clear();
i++;
continue;
}
// Check for dollar quote: $tag$ or $$
if (c == '$')
{
int tagStart = i;
i++;
// Collect tag name (alphanumeric + underscore)
while (i < len && (char.IsLetterOrDigit(content[i]) || content[i] == '_'))
i++;
if (i < len && content[i] == '$')
{
// Valid dollar quote opening
dollarTag.Clear();
dollarTag.Append(content[tagStart..(i + 1)]);
state = State.DollarQuote;
// Check if the last token before this dollar-quote was DO
if (lastTokenIsWord && lastToken.Length == 2 &&
char.ToUpperInvariant(lastToken[0]) == 'D' &&
char.ToUpperInvariant(lastToken[1]) == 'O')
{
result.IsDoBlock = true;
}
// Append the dollar-quote opening to statement
stmtBuilder.Append(content[tagStart..(i + 1)]);
lastTokenIsWord = false;
lastToken.Clear();
i++;
continue;
}
else
{
// Not a valid dollar quote, treat $ as normal char
stmtBuilder.Append(content[tagStart..i]);
// Don't increment i — we've already advanced past the $+tag chars
continue;
}
}
// Check for semicolon: statement separator
if (c == ';')
{
var stmt = stmtBuilder.ToString().Trim();
if (stmt.Length > 0)
{
// Before adding this statement, extract per-command annotations
// from comments collected between the previous statement and this one
if (firstStatementSeen && interStmtCommentBuilder.Length > 0)
{
var nextIndex = result.Statements.Count; // 0-based index of the statement about to be added
ExtractPerCommandAnnotations(interStmtCommentBuilder.ToString(), nextIndex, result);
interStmtCommentBuilder.Clear();
}
if (!firstStatementSeen)
{
headerCommentLength = commentBuilder.Length;
}
result.Statements.Add(stmt);
firstStatementSeen = true;
}
stmtBuilder.Clear();
lastTokenIsWord = false;
lastToken.Clear();
sameLineAsSemicolon = true;
i++;
continue;
}
// Track tokens for mutation detection and DO block detection
if (char.IsLetter(c) || c == '_')
{
int wordStart = i;
while (i < len && (char.IsLetterOrDigit(content[i]) || content[i] == '_'))
i++;
var word = content[wordStart..i];
stmtBuilder.Append(word);
// Track last token for DO detection
lastToken.Clear();
lastToken.Append(word);
lastTokenIsWord = true;
// Mutation detection (case-insensitive)
DetectMutation(word, result);
continue;
}
// Whitespace and other characters
if (char.IsWhiteSpace(c))
{
stmtBuilder.Append(c);
// Don't clear lastToken on whitespace — DO $$ has space between
if (c == '\n') sameLineAsSemicolon = false;
}
else
{
stmtBuilder.Append(c);
lastTokenIsWord = false;
lastToken.Clear();
}
i++;
break;
// ReSharper disable once UnreachableSwitchCaseDueToIntegerAnalysis
case State.LineComment:
// Shouldn't reach here — line comments handled inline above
i++;
break;
case State.BlockComment:
if (c == '/' && i + 1 < len && content[i + 1] == '*')
{
blockCommentDepth++;
if (ShouldCollectComment(commentScope, firstStatementSeen))
commentBuilder.Append("/*");
i += 2;
continue;
}
if (c == '*' && i + 1 < len && content[i + 1] == '/')
{
blockCommentDepth--;
if (blockCommentDepth == 0)
{
state = State.Normal;
if (blockCommentSameLine && firstStatementSeen && blockCommentBuffer.Length > 0)
{
var prevIndex = result.Statements.Count - 1;
if (prevIndex >= 0)
{
ExtractPerCommandAnnotations(blockCommentBuffer.ToString(), prevIndex, result);
}
blockCommentBuffer.Clear();
}
blockCommentSameLine = false;
i += 2;
continue;
}
if (ShouldCollectComment(commentScope, firstStatementSeen))
commentBuilder.Append("*/");
i += 2;
continue;
}
if (ShouldCollectComment(commentScope, firstStatementSeen))
commentBuilder.Append(c);
if (firstStatementSeen)
{
if (blockCommentSameLine)
blockCommentBuffer.Append(c);
else
interStmtCommentBuilder.Append(c);
}
i++;
break;
case State.SingleQuote:
stmtBuilder.Append(c);
if (c == '\'')
{
// Check for escaped quote ''
if (i + 1 < len && content[i + 1] == '\'')
{
stmtBuilder.Append('\'');
i += 2;
continue;
}
state = State.Normal;
}
i++;
break;
case State.DollarQuote:
stmtBuilder.Append(c);
// Check if we're at the closing dollar-quote tag
if (c == '$' && i + dollarTag.Length - 1 <= len)
{
var candidate = content[i..(i + dollarTag.Length)];
bool match = true;
for (int j = 0; j < dollarTag.Length; j++)
{
if (candidate[j] != dollarTag[j])
{
match = false;
break;
}
}
if (match)
{
// Append rest of closing tag (we already appended c which is $)
stmtBuilder.Append(content[(i + 1)..(i + dollarTag.Length)]);
i += dollarTag.Length;
state = State.Normal;
continue;
}
}
i++;
break;
}
}
// Handle remaining statement (no trailing semicolon)
var lastStmt = stmtBuilder.ToString().Trim();
if (lastStmt.Length > 0)
{
if (firstStatementSeen && interStmtCommentBuilder.Length > 0)
{
var nextIndex = result.Statements.Count;
ExtractPerCommandAnnotations(interStmtCommentBuilder.ToString(), nextIndex, result);
interStmtCommentBuilder.Clear();
}
result.Statements.Add(lastStmt);
}
result.Comment = commentBuilder.ToString();
// Extract positional per-command annotations from header comments for the first command
if (headerCommentLength > 0)
{
ExtractPerCommandAnnotations(result.Comment[..headerCommentLength], 0, result);
}
// Extract @define_param annotations
ExtractVirtualParams(result);
return result;
}
finally
{
commentBuilder.Dispose();
stmtBuilder.Dispose();
dollarTag.Dispose();
lastToken.Dispose();
interStmtCommentBuilder.Dispose();
blockCommentBuffer.Dispose();
}
}
private static bool ShouldCollectComment(CommentScope scope, bool firstStatementSeen)
{
return scope == CommentScope.All || (scope == CommentScope.Header && !firstStatementSeen);
}
/// <summary>
/// Extract positional per-command annotations from comments between statements.
/// Supports: @single, @skip, @result name, @result is name
/// </summary>
private static void ExtractPerCommandAnnotations(string comment, int statementIndex, SqlFileParseResult result)
{
var lines = comment.Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var trimmed = line.Trim();
var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed;
// @single / @single_record / @single_result
if (CommentPrimitives.StrEqualsToArray(s, "single", "single_record", "single_result"))
{
result.SingleCommands.Add(statementIndex);
continue;
}
// @skip / @skip_result / @no_result
if (CommentPrimitives.StrEqualsToArray(s, "skip", "skip_result", "no_result"))
{
result.SkipCommands.Add(statementIndex);
continue;
}
// @returns type_name (positional — skip Describe, use composite type columns)
if (s.StartsWith("returns", StringComparison.OrdinalIgnoreCase) && s.Length > 7)
{
var typeName = s[7..].TrimStart().TrimEnd(';');
if (typeName.Length > 0)
{
result.ReturnsTypeOverrides[statementIndex] = typeName;
}
continue;
}
// @result name / @result is name (positional)
if (s.StartsWith("result", StringComparison.OrdinalIgnoreCase) && s.Length > 6)
{
var afterResult = s[6..].TrimStart();
if (afterResult.Length == 0) continue;
var rest = afterResult;
var parts = rest.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
string? name = null;
if (parts.Length >= 2 && string.Equals(parts[0], "is", StringComparison.OrdinalIgnoreCase))
{
name = parts[1];
}
else if (parts.Length >= 1)
{
name = parts[0];
}
if (name is not null)
{
result.PositionalResultNames[statementIndex] = name;
}
}
}
}
/// <summary>
/// Extract @define_param annotations from comment text.
/// Supports: @define_param name, @define_param name type
/// </summary>
private static void ExtractVirtualParams(SqlFileParseResult result)
{
if (string.IsNullOrEmpty(result.Comment)) return;
var lines = result.Comment.Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var trimmed = line.Trim();
var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed;
if (!s.StartsWith("define_param", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var parts = s.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
continue; // no name provided
}
var name = parts[1];
var type = parts.Length >= 3 ? parts[2] : null;
result.VirtualParams.Add((name, type));
}
}
/// <summary>
/// Extract parameter type hints from @param annotations.
/// Positional patterns: @param $1 name type, @param $1 is name type.
/// Named patterns (when <paramref name="namedParams"/> is supplied — the file uses :name placeholders):
/// @param :name type, @param name type is type.
/// Only extracts when an explicit type is present. Returns null if no type hints found.
/// </summary>
public static Dictionary<int, string>? ExtractParamTypeHints(string? comment, IReadOnlyList<string>? namedParams = null)
{
if (string.IsNullOrEmpty(comment)) return null;
Dictionary<int, string>? hints = null;
var lines = comment.Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
var trimmed = line.Trim();
var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed;
if (!s.StartsWith("param ", StringComparison.OrdinalIgnoreCase) &&
!s.StartsWith("parameter ", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var parts = s.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
continue;
}
int paramIndex;
string? typeName = null;
if (parts[1][0] == '$')
{
if (!int.TryParse(parts[1].AsSpan(1), out paramIndex) || paramIndex < 1)
{
continue;
}
// @param $1 name type ... → parts[3] is type candidate
// @param $1 is name type ... → parts[4] is type candidate
if (parts.Length >= 4 && parts[2].Equals("is", StringComparison.OrdinalIgnoreCase))
{
if (parts.Length >= 5)
{
typeName = TypeCandidate(parts[4]);
}
}
else if (parts.Length >= 4)
{
typeName = TypeCandidate(parts[3]);
}
}
else if (namedParams is not null)
{
// @param :name type ... → parts[2] is type candidate
// @param name type is type ... → parts[4] is type candidate
string name;
int typeIdx;
if (parts[1][0] == ':' && parts[1].Length > 1)
{
name = parts[1][1..];
typeIdx = 2;
}
else if (parts.Length >= 5 &&
parts[2].Equals("type", StringComparison.OrdinalIgnoreCase) &&
parts[3].Equals("is", StringComparison.OrdinalIgnoreCase))
{
name = parts[1];
typeIdx = 4;
}
else
{
continue;
}
paramIndex = IndexOfName(namedParams, name) + 1;
if (paramIndex < 1 || parts.Length <= typeIdx)
{
continue;
}
typeName = TypeCandidate(parts[typeIdx]);
}
else
{
continue;
}
if (typeName is not null)
{
var descriptor = new NpgsqlRest.TypeDescriptor(typeName);
if (descriptor.DbType != NpgsqlTypes.NpgsqlDbType.Unknown)
{
hints ??= [];
hints[paramIndex - 1] = typeName;
}
}
}
return hints;
static string? TypeCandidate(string part)
{
var candidate = part.TrimEnd(';').ToLowerInvariant();
return candidate is "default" or "=" ? null : candidate;
}
}
/// <summary>0-based index of a named parameter (case-insensitive), or -1.</summary>
public static int IndexOfName(IReadOnlyList<string> namedParams, string name)
{
for (int i = 0; i < namedParams.Count; i++)
{
if (string.Equals(namedParams[i], name, StringComparison.OrdinalIgnoreCase))
{
return i;
}
}
return -1;
}
/// <summary>
/// Rewrite named (:name) placeholders in the parsed statements to native positional ($N) placeholders.
/// Names are assigned ordinals in first-appearance order across the whole file (case-insensitive), so
/// the same name used repeatedly — including across statements — maps to the SAME parameter. The
/// rewritten SQL is what gets described and executed; PostgreSQL never sees the :name form.
///
/// Token-aware: strings ('', ""), comments (-- and nested /* */), and dollar-quoted bodies are left
/// untouched. `::` casts, `:=` assignments, and numeric slice bounds (a[1:3]) never match because a
/// placeholder requires an identifier-start character immediately after the colon (a slice with a
/// variable bound, a[1:n], must be written with a space: a[1 : n]).
///
/// Also detects native $N placeholders so the caller can reject files mixing both styles.
/// </summary>
public static NamedParamRewriteResult RewriteNamedParameters(List<string> statements)
{
var result = new NamedParamRewriteResult();
for (int s = 0; s < statements.Count; s++)
{
var sql = statements[s];
StringBuilder? sb = null; // created lazily on the first replacement
var state = State.Normal;
int blockDepth = 0;
string dollarTag = "";
char quote = '\0';
for (int i = 0; i < sql.Length; i++)
{
char c = sql[i];
char next = i + 1 < sql.Length ? sql[i + 1] : '\0';
switch (state)
{
case State.Normal:
if (c == '-' && next == '-')
{
state = State.LineComment;
}
else if (c == '/' && next == '*')
{
state = State.BlockComment;
blockDepth = 1;
sb?.Append(c); sb?.Append(next); i++;
continue;
}
else if (c == '\'' || c == '"')
{
state = State.SingleQuote;
quote = c;
}
else if (c == '$')
{
// Dollar-quote open ($$ / $tag$) vs positional param ($1). A dollar-quote tag
// must start with a letter/underscore, so $ followed by a digit is always $N.
if (next == '$' || char.IsAsciiLetter(next) || next == '_')
{
int t = i + 1;
while (t < sql.Length && (char.IsAsciiLetterOrDigit(sql[t]) || sql[t] == '_')) t++;
if (t < sql.Length && sql[t] == '$')
{
dollarTag = sql[i..(t + 1)];
state = State.DollarQuote;
sb?.Append(dollarTag);
i = t;
continue;
}
}
else if (char.IsAsciiDigit(next))
{
result.HasPositional = true;
}
}
else if (c == ':')
{
if (next == ':')
{
// `::` cast — copy both, never a placeholder
sb?.Append("::");
i++;
continue;
}
if (char.IsAsciiLetter(next) || next == '_')
{
int e = i + 1;
while (e < sql.Length && (char.IsAsciiLetterOrDigit(sql[e]) || sql[e] == '_')) e++;
var name = sql[(i + 1)..e];
int idx = IndexOfName(result.Names, name);
if (idx < 0)
{
result.Names.Add(name);
idx = result.Names.Count - 1;
}
sb ??= new StringBuilder(sql[..i], sql.Length);
sb.Append('$').Append(idx + 1);
i = e - 1;
continue;
}
}
break;
case State.LineComment:
if (c == '\n') state = State.Normal;
break;
case State.BlockComment:
if (c == '*' && next == '/')
{
if (--blockDepth == 0) state = State.Normal;
sb?.Append(c); sb?.Append(next); i++;
continue;
}
if (c == '/' && next == '*')
{
blockDepth++;
sb?.Append(c); sb?.Append(next); i++;
continue;
}
break;
case State.SingleQuote:
if (c == quote)
{
if (next == quote)
{
// '' / "" escape — stay in the string
sb?.Append(c); sb?.Append(next); i++;
continue;
}
state = State.Normal;
}
break;
case State.DollarQuote:
if (c == '$' && i + dollarTag.Length <= sql.Length
&& sql.AsSpan(i, dollarTag.Length).SequenceEqual(dollarTag))
{
sb?.Append(dollarTag);
i += dollarTag.Length - 1;
state = State.Normal;
continue;
}
break;
}
sb?.Append(c);
}
if (sb is not null)
{
statements[s] = sb.ToString();
}
}
return result;
}
private static void DetectMutation(ReadOnlySpan<char> word, SqlFileParseResult result)
{
if (word.Length == 6 &&
(word[0] == 'I' || word[0] == 'i') &&
(word[1] == 'N' || word[1] == 'n') &&
(word[2] == 'S' || word[2] == 's') &&
(word[3] == 'E' || word[3] == 'e') &&
(word[4] == 'R' || word[4] == 'r') &&
(word[5] == 'T' || word[5] == 't'))
{
result.HasInsert = true;
}
else if (word.Length == 6 &&
(word[0] == 'U' || word[0] == 'u') &&
(word[1] == 'P' || word[1] == 'p') &&
(word[2] == 'D' || word[2] == 'd') &&
(word[3] == 'A' || word[3] == 'a') &&
(word[4] == 'T' || word[4] == 't') &&
(word[5] == 'E' || word[5] == 'e'))
{
result.HasUpdate = true;
}
else if (word.Length == 6 &&
(word[0] == 'D' || word[0] == 'd') &&
(word[1] == 'E' || word[1] == 'e') &&
(word[2] == 'L' || word[2] == 'l') &&
(word[3] == 'E' || word[3] == 'e') &&
(word[4] == 'T' || word[4] == 't') &&
(word[5] == 'E' || word[5] == 'e'))
{
result.HasDelete = true;
}
}
}
/// <summary>
/// Stack-allocated string builder for efficient parsing without heap allocations during scanning.
/// </summary>
internal ref struct ValueStringBuilder
{
private Span<char> _buffer;
private char[]? _arrayFromPool;
private int _pos;
public ValueStringBuilder(Span<char> initialBuffer)
{
_buffer = initialBuffer;
_arrayFromPool = null;
_pos = 0;
}
public int Length => _pos;
public char this[int index] => _buffer[index];
public void Append(char c)
{
if (_pos >= _buffer.Length)
Grow(1);
_buffer[_pos++] = c;
}
public void Append(ReadOnlySpan<char> value)
{
if (_pos + value.Length > _buffer.Length)
Grow(value.Length);
value.CopyTo(_buffer[_pos..]);
_pos += value.Length;
}
public void Append(string value) => Append(value.AsSpan());
public void Clear() => _pos = 0;
public override string ToString() => _buffer[.._pos].ToString();
private void Grow(int additionalCapacity)
{
int newCapacity = Math.Max(_buffer.Length * 2, _buffer.Length + additionalCapacity);
var newArray = System.Buffers.ArrayPool<char>.Shared.Rent(newCapacity);
_buffer[.._pos].CopyTo(newArray);
if (_arrayFromPool is not null)
System.Buffers.ArrayPool<char>.Shared.Return(_arrayFromPool);
_arrayFromPool = newArray;
_buffer = newArray;
}
public void Dispose()
{
if (_arrayFromPool is not null)
{
System.Buffers.ArrayPool<char>.Shared.Return(_arrayFromPool);
_arrayFromPool = null;
}
}
}
You can’t perform that action at this time.
