-
Notifications
You must be signed in to change notification settings - Fork 934
/
Copy pathSqlString.cs
1107 lines (961 loc) · 33.1 KB
/
SqlString.cs
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using NHibernate.SqlCommand.Parser;
using System.Text.RegularExpressions;
namespace NHibernate.SqlCommand
{
/// <summary>
/// This is a non-modifiable SQL statement that is ready to be prepared
/// and sent to the Database for execution.
/// </summary>
/// <remarks>
/// <para>A <see cref="SqlString"/> represents a (potentially partial) SQL query string
/// that may or may not contain query parameter references. A <see cref="SqlString"/>
/// decomposes the underlying SQL query string into a list of parts. Each part is either
/// 1) a string part, which represents a fragment of the underlying SQL query string that
/// does not contain any parameter references, or 2) a parameter part, which represents
/// a single query parameter reference in the underlying SQL query string.
/// </para>
/// <para>The <see cref="SqlString"/> constructors ensure that the number of string parts
/// in a <see cref="SqlString"/> are kept to an absolute minimum (as compact as possible)
/// by concatenating any adjoining string parts into a single string part.
/// </para>
/// <para>
/// Substring operations on a <see cref="SqlString"/> (such as <see cref="Substring(int,int)"/>,
/// <see cref="Split"/>, <see cref="Trim"/>) return a <see cref="SqlString"/> that reuses the parts
/// list of the <see cref="SqlString"/> instance on which the operation was performed.
/// Besides a reference to this parts list, the resulting <see cref="SqlString"/> instance
/// also stores the character offset into the original underlying SQL string at which the
/// substring starts and the length of the substring. By avoiding the unnecessary rebuilding
/// of part lists these operations have O(1) behaviour rather than O(n) behaviour.
/// </para>
/// <para>
/// If you need to modify this object pass it to a <see cref="SqlStringBuilder"/> and
/// get a new object back from it.
/// </para>
/// </remarks>
[Serializable]
public class SqlString : ICollection, IEnumerable<object>
{
/// <summary>
/// Empty <see cref="SqlString"/> instance.
/// </summary>
public static readonly SqlString Empty = new SqlString(Enumerable.Empty<object>());
#region Instance fields
/// <summary>
/// Immutable list of string and parameter parts that make up this <see cref="SqlString"/>.
/// This list may be shared by multiple <see cref="SqlString"/> instances that present
/// different fragments of a common underlying SQL query string.
/// </summary>
private readonly List<Part> _parts;
/// <summary>
/// List of SQL query parameter references that occur in this <see cref="SqlString"/>.
/// </summary>
private readonly SortedList<int, Parameter> _parameters;
/// <summary>
/// Cached index of first part in <see cref="_parts"/> that contains (part of)
/// a SQL fragment that falls within the scope of this <see cref="SqlString"/> instance.
/// </summary>
private readonly int _firstPartIndex;
/// <summary>
/// Cached index of last part in <see cref="_parts"/> that contains (part of)
/// a SQL fragment that falls within the scope of this <see cref="SqlString"/> instance.
/// </summary>
private readonly int _lastPartIndex;
/// <summary>
/// Index of first character of the underlying SQL query string that is within scope of
/// this <see cref="SqlString"/> instance.
/// </summary>
private readonly int _sqlStartIndex;
/// <summary>
/// Number of characters of the underlying SQL query string that are within scope of
/// this <see cref="SqlString"/> instance from <see cref="_sqlStartIndex"/> onwards.
/// </summary>
private readonly int _length;
#endregion
#region Constructor(s)
/// <summary>
/// Creates copy of other <see cref="SqlString"/>.
/// </summary>
/// <param name="other"></param>
private SqlString(SqlString other)
{
_parts = other._parts;
_sqlStartIndex = other._sqlStartIndex;
_length = other._length;
_firstPartIndex = other._firstPartIndex;
_lastPartIndex = other._lastPartIndex;
var parameterCount = other._parameters.Count;
if (parameterCount > 0)
{
_parameters = new SortedList<int, Parameter>(other._parameters.Count);
foreach (var parameterByIndex in other._parameters)
{
var otherParameter = parameterByIndex.Value;
var parameter = otherParameter.Clone();
if (otherParameter.ParameterPosition < 0)
{
// placeholder for sub-query parameter
parameter.ParameterPosition = otherParameter.ParameterPosition;
}
_parameters.Add(parameterByIndex.Key, parameter);
}
}
else
{
_parameters = Empty._parameters;
}
}
/// <summary>
/// Creates substring of other <see cref="SqlString"/>.
/// </summary>
/// <param name="other"></param>
/// <param name="sqlStartIndex"></param>
/// <param name="length"></param>
private SqlString(SqlString other, int sqlStartIndex, int length)
{
_parts = other._parts;
_sqlStartIndex = sqlStartIndex;
_length = length;
_firstPartIndex = other.GetPartIndexForSqlIndex(sqlStartIndex);
_lastPartIndex = other.GetPartIndexForSqlIndex(_sqlStartIndex + _length - 1);
if (_firstPartIndex != _lastPartIndex || _parts[_firstPartIndex].IsParameter)
{
_parameters = new SortedList<int, Parameter>(other._parameters.Count);
using (var otherParameterEnum = other._parameters.GetEnumerator())
{
while (otherParameterEnum.MoveNext())
{
if (otherParameterEnum.Current.Key >= _sqlStartIndex) break;
}
var sqlEndIndex = _sqlStartIndex + _length;
do
{
if (otherParameterEnum.Current.Key > sqlEndIndex) break;
_parameters.Add(otherParameterEnum.Current.Key, otherParameterEnum.Current.Value);
} while (otherParameterEnum.MoveNext());
}
}
else
{
_parameters = Empty._parameters;
}
}
/// <summary>
/// Creates <see cref="SqlString"/> consisting of single string part.
/// </summary>
/// <param name="sql">A SQL fragment</param>
public SqlString(string sql)
{
if (sql == null) throw new ArgumentNullException("sql");
_parts = new List<Part>(1) { new Part(0, sql) };
_parameters = Empty._parameters;
_length = sql.Length;
}
/// <summary>
/// Creates <see cref="SqlString"/> consisting of single parameter part.
/// </summary>
/// <param name="parameter">A query parameter</param>
public SqlString(Parameter parameter)
{
if (parameter == null) throw new ArgumentNullException("parameter");
_parts = new List<Part>(1) { new Part(0) };
_parameters = new SortedList<int, Parameter>(1) { { 0, parameter } };
_length = _parts[0].Length;
}
/// <summary>
/// Creates <see cref="SqlString"/> consisting of multiple parts.
/// </summary>
/// <param name="parts">Arbitrary number of parts, which must be
/// either <see cref="string"/>, <see cref="Parameter"/> or <see cref="SqlString"/>
/// values.</param>
/// <remarks>The <see cref="SqlString"/> instance is automatically compacted.</remarks>
public SqlString(params object[] parts)
: this((IEnumerable<object>)parts)
{ }
internal SqlString(IEnumerable<object> parts)
{
_parts = new List<Part>();
_parameters = new SortedList<int, Parameter>();
var sqlIndex = 0;
var pendingContent = new StringBuilder(); // Collect adjoining string parts (the compaction).
foreach (var part in parts)
{
Add(part, pendingContent, ref sqlIndex);
}
AppendAndResetPendingContent(pendingContent, ref sqlIndex);
_firstPartIndex = _parts.Count > 0 ? 0 : -1;
_lastPartIndex = _parts.Count - 1;
_length = sqlIndex;
}
#endregion
#region Factory methods
/// <summary>
/// Parse SQL in <paramref name="sql" /> and create a SqlString representing it.
/// </summary>
/// <remarks>
/// Parameter marks in single quotes will be correctly skipped, but otherwise the
/// lexer is very simple and will not parse double quotes or escape sequences
/// correctly, for example.
/// </remarks>
public static SqlString Parse(string sql)
{
return new SqlString(ParseParts(sql));
}
private static IEnumerable<object> ParseParts(string text)
{
if (string.IsNullOrEmpty(text)) yield break;
int offset = 0;
int maxOffset = text.Length;
int partOffset = 0;
while (offset < maxOffset)
{
var ch = text[offset];
switch (ch)
{
case '?': // Parameter marker
if (offset > partOffset)
{
yield return text.Substring(partOffset, offset - partOffset);
}
yield return Parameter.Placeholder;
partOffset = offset += 1;
break;
case '\'': // String literals
case '\"': // ANSI quoted identifiers
case '[': // Sql Server quoted indentifiers
offset += SqlParserUtils.ReadDelimitedText(text, maxOffset, offset);
continue;
case '/':
if (offset + 1 < maxOffset && text[offset + 1] == '*')
{
offset += SqlParserUtils.ReadMultilineComment(text, maxOffset, offset);
continue;
}
break;
case '-':
if (offset + 1 < maxOffset && text[offset + 1] == '-')
{
offset += SqlParserUtils.ReadLineComment(text, maxOffset, offset);
continue;
}
break;
}
offset++;
}
if (maxOffset > partOffset)
{
yield return text.Substring(partOffset, offset - partOffset);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the number of SqlParts contained in this SqlString.
/// </summary>
/// <value>The number of SqlParts contained in this SqlString.</value>
public int Count
{
get { return _length > 0 ? _lastPartIndex - _firstPartIndex + 1 : 0; }
}
public int Length
{
get { return _length; }
}
#endregion
#region Operators
public static SqlString operator +(SqlString lhs, SqlString rhs)
{
return lhs.Append(rhs);
}
#endregion
#region Public methods
/// <summary>
/// Appends the SqlString parameter to the end of the current SqlString to create a
/// new SqlString object.
/// </summary>
/// <param name="sql">The SqlString to append.</param>
/// <returns>A new SqlString object.</returns>
/// <remarks>
/// A SqlString object is immutable so this returns a new SqlString. If multiple Appends
/// are called it is better to use the SqlStringBuilder.
/// </remarks>
public SqlString Append(SqlString sql)
{
if (sql == null || sql._length == 0) return this;
if (_length == 0) return sql;
return new SqlString(new object[] { this, sql });
}
/// <summary>
/// Appends the string parameter to the end of the current SqlString to create a
/// new SqlString object.
/// </summary>
/// <param name="text">The string to append.</param>
/// <returns>A new SqlString object.</returns>
/// <remarks>
/// A SqlString object is immutable so this returns a new SqlString. If multiple Appends
/// are called it is better to use the SqlStringBuilder.
/// </remarks>
public SqlString Append(string text)
{
if (string.IsNullOrEmpty(text)) return this;
if (_length == 0) return new SqlString(text);
return new SqlString(this, text);
}
public SqlString Append(params object[] parts)
{
return _length == 0
? new SqlString(parts)
: new SqlString(GetAppendParts(parts));
}
private IEnumerable<object> GetAppendParts(object[] parts)
{
yield return this;
foreach (var part in parts)
{
yield return part;
}
}
/// <summary>
/// Makes a copy of the SqlString, with new parameter references (Placeholders)
/// </summary>
public SqlString Copy()
{
return new SqlString(this);
}
/// <summary>
/// Determines whether the end of this instance matches the specified String.
/// </summary>
/// <param name="value">A string to seek at the end.</param>
/// <returns><see langword="true" /> if the end of this instance matches value; otherwise, <see langword="false" /></returns>
public bool EndsWith(string value)
{
return value != null
&& value.Length <= _length
&& IndexOf(value, _length - value.Length, value.Length, StringComparison.InvariantCulture) >= 0;
}
public bool EndsWithCaseInsensitive(string value)
{
return value != null
&& value.Length <= _length
&& IndexOf(value, _length - value.Length, value.Length, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
public IEnumerable<Parameter> GetParameters()
{
return _parameters.Values;
}
public int GetParameterCount()
{
return _parameters.Count;
}
/// <summary>
/// Returns the index of the first occurrence of <paramref name="text" />, case-insensitive.
/// </summary>
/// <param name="text">Text to look for in the <see cref="SqlString" />. Must be in lower
/// case.</param>
/// <remarks>
/// The text must be located entirely in a string part of the <see cref="SqlString" />.
/// Searching for <c>"a ? b"</c> in an <see cref="SqlString" /> consisting of
/// <c>"a ", Parameter, " b"</c> will result in no matches.
/// </remarks>
/// <returns>The index of the first occurrence of <paramref name="text" />, or -1
/// if not found.</returns>
public int IndexOfCaseInsensitive(string text)
{
return IndexOf(text, 0, _length, StringComparison.InvariantCultureIgnoreCase);
}
internal int IndexOfOrdinal(string text)
{
return IndexOf(text, 0, _length, StringComparison.Ordinal);
}
internal bool Contains(string text)
{
return IndexOfOrdinal(text) >= 0;
}
/// <summary>
/// Returns the index of the first occurrence of <paramref name="text" />, case-insensitive.
/// </summary>
/// <param name="text">Text to look for in the <see cref="SqlString" />. Must be in lower</param>
/// <param name="startIndex">The zero-based index of the search starting position.</param>
/// <param name="length">The number of character positions to examine.</param>
/// <param name="stringComparison">One of the enumeration values that specifies the rules for the search.</param>
/// <remarks>
/// The text must be located entirely in a string part of the <see cref="SqlString" />.
/// Searching for <c>"a ? b"</c> in an <see cref="SqlString" /> consisting of
/// <c>"a ", Parameter, " b"</c> will result in no matches.
/// </remarks>
/// <returns>The index of the first occurrence of <paramref name="text" />, or -1
/// if not found.</returns>
public int IndexOf(string text, int startIndex, int length, StringComparison stringComparison)
{
if (text == null) throw new ArgumentNullException("text");
var sqlSearchStartIndex = _sqlStartIndex + startIndex;
var maxSearchLength = Math.Min(length, _sqlStartIndex + _length - sqlSearchStartIndex);
if (maxSearchLength >= text.Length)
{
var partIndex = GetPartIndexForSqlIndex(sqlSearchStartIndex);
if (partIndex >= 0)
{
while (maxSearchLength > 0 && partIndex <= _lastPartIndex)
{
var part = _parts[partIndex];
var partStartOffset = sqlSearchStartIndex - part.SqlIndex;
var partLength = Math.Min(maxSearchLength, part.Length - partStartOffset);
var partOffset = part.Content.IndexOf(text, partStartOffset, partLength, stringComparison);
if (partOffset >= 0) return part.SqlIndex + partOffset - _sqlStartIndex;
sqlSearchStartIndex += partLength;
maxSearchLength -= partLength;
partIndex++;
}
}
}
return -1;
}
public SqlString Insert(int index, string text)
{
if (string.IsNullOrEmpty(text)) return this;
return new SqlString(new object[] { Substring(0, index), text, Substring(index, _length - index) });
}
public SqlString Insert(int index, SqlString sql)
{
if (sql == null || sql._length == 0) return this;
return new SqlString(new object[] { Substring(0, index), sql, Substring(index, _length - index) });
}
/// <summary>
/// Returns the index of the first occurrence of <paramref name="text" />, case-insensitive.
/// </summary>
/// <param name="text">Text to look for in the <see cref="SqlString" />. Must be in lower
/// case.</param>
/// <remarks>
/// The text must be located entirely in a string part of the <see cref="SqlString" />.
/// Searching for <c>"a ? b"</c> in an <see cref="SqlString" /> consisting of
/// <c>"a ", Parameter, " b"</c> will result in no matches.
/// </remarks>
/// <returns>The index of the first occurrence of <paramref name="text" />, or -1
/// if not found.</returns>
public int LastIndexOfCaseInsensitive(string text)
{
return LastIndexOf(text, 0, _length, StringComparison.InvariantCultureIgnoreCase);
}
internal int LastIndexOf(string text, StringComparison comparison)
{
return LastIndexOf(text, 0, _length, comparison);
}
/// <summary>
/// Returns the index of the first occurrence of <paramref name="text" />, case-insensitive.
/// </summary>
/// <param name="text">Text to look for in the <see cref="SqlString" />. Must be in lower case.</param>
/// <param name="startIndex">The zero-based index of the search starting position.</param>
/// <param name="length">The number of character positions to examine.</param>
/// <param name="stringComparison">One of the enumeration values that specifies the rules for the search.</param>
/// <remarks>
/// The text must be located entirely in a string part of the <see cref="SqlString" />.
/// Searching for <c>"a ? b"</c> in an <see cref="SqlString" /> consisting of
/// <c>"a ", Parameter, " b"</c> will result in no matches.
/// </remarks>
/// <returns>The index of the first occurrence of <paramref name="text" />, or -1
/// if not found.</returns>
private int LastIndexOf(string text, int startIndex, int length, StringComparison stringComparison)
{
if (text == null) throw new ArgumentNullException("text");
var sqlSearchEndIndex = _sqlStartIndex + Math.Min(_length, startIndex + length);
var maxSearchLength = sqlSearchEndIndex - _sqlStartIndex - startIndex;
if (maxSearchLength > text.Length)
{
var partIndex = GetPartIndexForSqlIndex(sqlSearchEndIndex - 1);
if (partIndex >= 0)
{
while (maxSearchLength > 0 && partIndex >= _firstPartIndex)
{
var part = _parts[partIndex];
var partEndOffset = sqlSearchEndIndex - part.SqlIndex;
var partLength = Math.Min(maxSearchLength, partEndOffset);
var partOffset = part.Content.LastIndexOf(text, partEndOffset - 1, partLength, stringComparison);
if (partOffset >= 0) return part.SqlIndex + partOffset - _sqlStartIndex;
sqlSearchEndIndex -= partLength;
maxSearchLength -= partLength;
partIndex--;
}
}
}
return -1;
}
/// <summary>
/// Replaces all occurrences of a specified <see cref="String"/> in this instance,
/// with another specified <see cref="String"/> .
/// </summary>
/// <param name="oldValue">A String to be replaced.</param>
/// <param name="newValue">A String to replace all occurrences of oldValue. </param>
/// <returns>
/// A new SqlString with oldValue replaced by the newValue. The new SqlString is
/// in the compacted form.
/// </returns>
public SqlString Replace(string oldValue, string newValue)
{
return new SqlString(ReplaceParts(oldValue, newValue));
}
private IEnumerable<object> ReplaceParts(string oldValue, string newValue)
{
foreach (var part in this)
{
var content = part as string;
yield return content != null
? content.Replace(oldValue, newValue)
: part;
}
}
public SqlString[] Split(string splitter)
{
return SplitParts(splitter).ToArray();
}
internal SqlString[] SplitWithRegex(string pattern)
{
var sql = Regex.Split(ToString(), pattern).Select(s => SqlString.Parse(s)).ToArray();
var parameters = _parameters.Values;
int i = 0;
foreach (var p in sql.SelectMany(s => s.GetParameters()))
{
p.BackTrack = parameters[i].BackTrack;
i++;
}
return sql;
}
private IEnumerable<SqlString> SplitParts(string splitter)
{
var startIndex = 0;
while (startIndex < _length)
{
var splitterIndex = IndexOf(splitter, startIndex, _length - startIndex, StringComparison.InvariantCultureIgnoreCase);
if (splitterIndex < 0) break;
yield return new SqlString(this, _sqlStartIndex + startIndex, splitterIndex - startIndex);
startIndex = splitterIndex + splitter.Length;
}
if (startIndex < _length)
{
yield return new SqlString(this, _sqlStartIndex + startIndex, _length - startIndex);
}
}
/// <summary>
/// Determines whether the beginning of this SqlString matches the specified System.String,
/// using case-insensitive comparison.
/// </summary>
/// <param name="value">The System.String to seek</param>
/// <returns>true if the SqlString starts with the value.</returns>
public bool StartsWithCaseInsensitive(string value)
{
return value != null
&& value.Length <= _length
&& IndexOf(value, 0, value.Length, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
/// <summary>
/// Determines whether the sqlString matches the specified System.String,
/// using case-insensitive comparison
/// </summary>
/// <param name="value">The System.String to match</param>
/// <returns>true if the SqlString matches the value.</returns>
public bool EqualsCaseInsensitive(string value)
{
return value != null
&& value.Length == _length
&& IndexOf(value, 0, value.Length, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
/// <summary>
/// Retrieves a substring from this instance. The substring starts at a specified character position.
/// </summary>
/// <param name="startIndex">The starting character position of a substring in this instance.</param>
/// <returns>
/// A new SqlString to the substring that begins at startIndex in this instance.
/// </returns>
/// <remarks>
/// If the startIndex is greater than the length of the SqlString then <see cref="SqlString.Empty" /> is returned.
/// </remarks>
public SqlString Substring(int startIndex)
{
return Substring(startIndex, _length - startIndex);
}
public SqlString Substring(int startIndex, int length)
{
if (startIndex == 0 && length == _length) return this;
length = Math.Min(_length - startIndex, length);
return length > 0
? new SqlString(this, _sqlStartIndex + startIndex, length)
: Empty;
}
/// <summary>
/// Returns substring of this SqlString starting with the specified
/// <paramref name="text" />. If the text is not found, returns an
/// empty, not-null SqlString.
/// </summary>
/// <remarks>
/// The method performs case-insensitive comparison, so the <paramref name="text" />
/// passed should be in lower case.
/// </remarks>
public SqlString SubstringStartingWithLast(string text)
{
int lastIndex = LastIndexOfCaseInsensitive(text);
return lastIndex >= 0 ? Substring(lastIndex) : Empty;
}
/// <summary>
/// Returns true if content is empty or white space characters only
/// </summary>
public bool IsEmptyOrWhitespace()
{
if (Length <= 0)
return true;
GetTrimmedIndexes(out _, out var newLength);
return newLength <= 0;
}
/// <summary>
/// Removes all occurrences of white space characters from the beginning and end of this instance.
/// </summary>
/// <returns>
/// A new SqlString equivalent to this instance after white space characters
/// are removed from the beginning and end.
/// </returns>
public SqlString Trim()
{
if (_firstPartIndex < 0) return this;
GetTrimmedIndexes(out var sqlStartIndex, out var length);
return length > 0
? new SqlString(this, sqlStartIndex, length)
: Empty;
}
private void GetTrimmedIndexes(out int sqlStartIndex, out int length)
{
var firstPart = _parts[_firstPartIndex];
var firstPartOffset = _sqlStartIndex - firstPart.SqlIndex;
var firstPartLength = Math.Min(firstPart.Length - firstPartOffset, _length);
while (firstPartLength > 0 && char.IsWhiteSpace(firstPart.Content[firstPartOffset]))
{
firstPartOffset++;
firstPartLength--;
}
var lastPart = _parts[_lastPartIndex];
var lastPartOffset = _sqlStartIndex + _length - 1 - lastPart.SqlIndex;
var lastPartLength = Math.Min(lastPartOffset + 1, _length);
while (lastPartLength > 0 && char.IsWhiteSpace(lastPart.Content[lastPartOffset]))
{
lastPartOffset--;
lastPartLength--;
}
sqlStartIndex = firstPart.SqlIndex + firstPartOffset;
length = lastPart.SqlIndex + lastPartOffset + 1 - sqlStartIndex;
}
public void Visit(ISqlStringVisitor visitor)
{
foreach (object part in this)
{
var partString = part as string;
if (partString != null)
{
visitor.String(partString);
continue;
}
var partSqlString = part as SqlString;
if (partSqlString != null)
{
visitor.String(partSqlString);
continue;
}
var partParameter = part as Parameter;
if (partParameter != null)
{
visitor.Parameter(partParameter);
}
}
}
#endregion
#region Private methods
/// <summary>
/// Locate the part that contains the requested character index, and return the
/// part's index. Return -1 if the character position isn't found.
/// </summary>
private int GetPartIndexForSqlIndex(int sqlIndex)
{
if (sqlIndex < _sqlStartIndex || sqlIndex >= _sqlStartIndex + _length) return -1;
var min = _firstPartIndex;
var max = _lastPartIndex;
while (min < max)
{
var i = (min + max + 1) / 2;
if (sqlIndex < _parts[i].SqlIndex)
{
max = i - 1;
}
else
{
min = i;
}
}
var part = _parts[min];
return sqlIndex >= part.SqlIndex && sqlIndex < part.SqlIndex + part.Length ? min : -1;
}
private void Add(object part, StringBuilder pendingContent, ref int sqlIndex)
{
var stringPart = part as string;
if (stringPart != null)
{
pendingContent.Append(stringPart);
return;
}
var parameter = part as Parameter;
if (parameter != null)
{
AppendAndResetPendingContent(pendingContent, ref sqlIndex);
_parts.Add(new Part(sqlIndex));
_parameters.Add(sqlIndex, parameter);
sqlIndex += 1;
return;
}
var sql = part as SqlString;
if (sql != null)
{
foreach (var otherPart in sql)
{
Add(otherPart, pendingContent, ref sqlIndex);
}
return;
}
throw new ArgumentException("Only string, Parameter or SqlString values are supported as SqlString parts.");
}
/// <summary>
/// It the pendingContent is non-empty, append it as a new part and reset the pendingContent
/// to empty. The new part will be given the sqlIndex. After return, the sqlIndex will have
/// been updated to the next available index.
/// </summary>
/// <param name="pendingContent"></param>
/// <param name="sqlIndex"></param>
private void AppendAndResetPendingContent(StringBuilder pendingContent, ref int sqlIndex)
{
if (pendingContent.Length > 0)
{
_parts.Add(new Part(sqlIndex, pendingContent.ToString()));
sqlIndex += pendingContent.Length;
pendingContent.Length = 0;
}
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
foreach (var part in this)
{
array.SetValue(part, index++);
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return null; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IEnumerable<object> Members
public IEnumerator<object> GetEnumerator()
{
if (_firstPartIndex < 0) yield break;
// Yield (substring of) first part
var partIndex = _firstPartIndex;
var part = _parts[partIndex++];
if (part.IsParameter)
{
yield return _parameters[part.SqlIndex];
}
else
{
var firstPartOffset = _sqlStartIndex - part.SqlIndex;
var firstPartLength = Math.Min(part.Length - firstPartOffset, _length);
yield return part.Content.Substring(firstPartOffset, firstPartLength);
}
if (_firstPartIndex == _lastPartIndex) yield break;
// Yield middle parts
while (partIndex < _lastPartIndex)
{
part = _parts[partIndex++];
yield return part.IsParameter
? (object)_parameters[part.SqlIndex]
: part.Content;
}
// Yield (substring of) last part
part = _parts[partIndex];
if (part.IsParameter)
{
yield return _parameters[part.SqlIndex];
}
else
{
var lastPartLength = _sqlStartIndex + _length - part.SqlIndex;
yield return part.Content.Substring(0, lastPartLength);
}
}
#endregion
#region System.Object Members
public override bool Equals(object obj)
{
var other = obj as SqlString;
if (other == null) return false;
if (other == this) return true;
// Exit early if the length or number of parts differ - cannot be equal then.
if (_length != other._length) return false;
if (_lastPartIndex - _firstPartIndex != other._lastPartIndex - other._firstPartIndex) return false;
if (_parameters.Count != other._parameters.Count) return false;
using (var partEnum = this.GetEnumerator())
using (var otherPartEnum = other.GetEnumerator())
{
while (partEnum.MoveNext())
{
if (!otherPartEnum.MoveNext()) return false;
if (!Equals(partEnum.Current, otherPartEnum.Current)) return false;
}
if (otherPartEnum.MoveNext()) return false;
}
return true;
}
public override int GetHashCode()
{
const uint FNV_OFFSET_BASIS = 2166136261;
const uint FNV_PRIME = 16777619;
uint hashCode = FNV_OFFSET_BASIS;
unchecked
{
// Iterate the calculated parts - cannot use the underlying _parts
// directly, as that may contain elements no longer part of this string.
foreach (var part in this)
{
hashCode ^= (uint)part.GetHashCode();
hashCode *= FNV_PRIME;
}
return (int)hashCode;
}
}
/// <summary>
/// Returns the SqlString in a string where it looks like
/// SELECT col1, col2 FROM table WHERE col1 = ?
/// </summary>
/// <remarks>
/// The question mark is used as the indicator of a parameter because at
/// this point we are not using the specific provider so we don't know
/// how that provider wants our parameters formatted.
/// </remarks>
/// <returns>A provider-neutral version of the CommandText</returns>
public override string ToString()
{
return ToString(0, _length);
}
public string ToString(int startIndex)
{
return ToString(startIndex, _length - startIndex);
}
public string ToString(int startIndex, int length)
{
var sqlStartIndex = _sqlStartIndex + startIndex;
var nextPartIndex = GetPartIndexForSqlIndex(sqlStartIndex);
if (nextPartIndex < 0) return string.Empty;
var maxSearchLength = Math.Min(_sqlStartIndex + _length - sqlStartIndex, length);
var part = _parts[nextPartIndex++];
var firstPartOffset = sqlStartIndex - part.SqlIndex;
var firstPartLength = Math.Min(part.Length - firstPartOffset, maxSearchLength);
// Shortcut when result can be taken from single part
if (firstPartLength == maxSearchLength)