forked from danzel/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlCommand.Rewrite.cs
More file actions
1052 lines (846 loc) · 37.3 KB
/
NpgsqlCommand.Rewrite.cs
File metadata and controls
1052 lines (846 loc) · 37.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
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
// created on 18/11/2013
// Npgsql.NpgsqlCommand.Rewrite.cs
//
// Author:
// Francisco Jr. (fxjrlists@yahoo.com.br)
//
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using NpgsqlTypes;
namespace Npgsql
{
/// <summary>
/// Represents a SQL statement or function (stored procedure) to execute
/// against a PostgreSQL database. This class cannot be inherited.
/// </summary>
public sealed partial class NpgsqlCommand : DbCommand, ICloneable
{
///<summary>
/// This method checks the connection state to see if the connection
/// is set or it is open. If one of this conditions is not met, throws
/// an InvalidOperationException
///</summary>
private void CheckConnectionState()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "CheckConnectionState");
// Check the connection state.
if (Connector == null || Connector.State == ConnectionState.Closed)
{
throw new InvalidOperationException(resman.GetString("Exception_ConnectionNotOpen"));
}
if (Connector.State != ConnectionState.Open)
{
throw new InvalidOperationException(
"There is already an open DataReader associated with this Command which must be closed first.");
}
}
/// <summary>
/// This method substitutes the <see cref="Npgsql.NpgsqlCommand.Parameters">Parameters</see>, if exist, in the command
/// to their actual values.
/// The parameter name format is <b>:ParameterName</b>.
/// </summary>
/// <returns>A version of <see cref="Npgsql.NpgsqlCommand.CommandText">CommandText</see> with the <see cref="Npgsql.NpgsqlCommand.Parameters">Parameters</see> inserted.</returns>
internal byte[] GetCommandText()
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetCommandText");
byte[] ret = string.IsNullOrEmpty(planName) ? GetCommandText(false, false) : GetExecuteCommandText();
return ret;
}
private Boolean CheckFunctionNeedsColumnDefinitionList()
{
// If and only if a function returns "record" and has no OUT ("o" in proargmodes), INOUT ("b"), or TABLE
// ("t") return arguments to characterize the result columns, we must provide a column definition list.
// See http://pgfoundry.org/forum/forum.php?thread_id=1075&forum_id=519
// We would use our Output and InputOutput parameters to construct that column definition list. If we have
// no such parameters, skip the check: we could only construct "AS ()", which yields a syntax error.
// Updated after 0.99.3 to support the optional existence of a name qualifying schema and allow for case insensitivity
// when the schema or procedure name do not contain a quote.
// The hard-coded schema name 'public' was replaced with code that uses schema as a qualifier, only if it is provided.
String returnRecordQuery;
StringBuilder parameterTypes = new StringBuilder("");
// Process parameters
Boolean seenDef = false;
foreach (NpgsqlParameter p in Parameters)
{
if ((p.Direction == ParameterDirection.Input) || (p.Direction == ParameterDirection.InputOutput))
{
parameterTypes.Append(Connection.Connector.OidToNameMapping[p.TypeInfo.Name].OID.ToString() + " ");
}
if ((p.Direction == ParameterDirection.Output) || (p.Direction == ParameterDirection.InputOutput))
{
seenDef = true;
}
}
if (!seenDef)
{
return false;
}
// Process schema name.
String schemaName = String.Empty;
String procedureName = String.Empty;
String[] fullName = CommandText.Split('.');
String predicate = "prorettype = ( select oid from pg_type where typname = 'record' ) "
+ "and proargtypes=:proargtypes and proname=:proname "
// proargmodes && array['o','b','t']::"char"[] performs just as well, but it requires PostgreSQL 8.2.
+ "and ('o' = any (proargmodes) OR 'b' = any (proargmodes) OR 't' = any (proargmodes)) is not true";
if (fullName.Length == 2)
{
returnRecordQuery =
"select count(*) > 0 from pg_proc p left join pg_namespace n on p.pronamespace = n.oid where " + predicate + " and n.nspname=:nspname";
schemaName = (fullName[0].IndexOf("\"") != -1) ? fullName[0] : fullName[0].ToLower();
procedureName = (fullName[1].IndexOf("\"") != -1) ? fullName[1] : fullName[1].ToLower();
}
else
{
// Instead of defaulting don't use the nspname, as an alternative, query pg_proc and pg_namespace to try and determine the nspname.
//schemaName = "public"; // This was removed after build 0.99.3 because the assumption that a function is in public is often incorrect.
returnRecordQuery =
"select count(*) > 0 from pg_proc p where " + predicate;
procedureName = (CommandText.IndexOf("\"") != -1) ? CommandText : CommandText.ToLower();
}
bool ret;
using (NpgsqlCommand c = new NpgsqlCommand(returnRecordQuery, Connection))
{
c.Parameters.Add(new NpgsqlParameter("proargtypes", NpgsqlDbType.Oidvector));
c.Parameters.Add(new NpgsqlParameter("proname", NpgsqlDbType.Name));
c.Parameters[0].Value = parameterTypes.ToString();
c.Parameters[1].Value = procedureName;
if (schemaName != null && schemaName.Length > 0)
{
c.Parameters.Add(new NpgsqlParameter("nspname", NpgsqlDbType.Name));
c.Parameters[2].Value = schemaName;
}
ret = (Boolean)c.ExecuteScalar();
}
return ret;
}
private void AddFunctionColumnListSupport(Stream st)
{
bool isFirstOutputOrInputOutput = true;
PGUtil.WriteString(st, " AS (");
for (int i = 0 ; i < Parameters.Count ; i++)
{
var p = Parameters[i];
switch(p.Direction)
{
case ParameterDirection.Output: case ParameterDirection.InputOutput:
if (isFirstOutputOrInputOutput)
{
isFirstOutputOrInputOutput = false;
}
else
{
st.WriteString(", ");
}
st
.WriteString(p.CleanName)
.WriteBytes((byte)ASCIIBytes.Space)
.WriteString(p.TypeInfo.Name);
break;
}
}
st.WriteByte((byte)ASCIIBytes.ParenRight);
}
private class StringChunk
{
public readonly int Begin;
public readonly int Length;
public StringChunk(int begin, int length)
{
this.Begin = begin;
this.Length = length;
}
}
/// <summary>
/// Process this.commandText, trimming each distinct command and substituting paramater
/// tokens.
/// </summary>
/// <param name="prepare"></param>
/// <param name="forExtendQuery"></param>
/// <returns>UTF8 encoded command ready to be sent to the backend.</returns>
private byte[] GetCommandText(bool prepare, bool forExtendQuery)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetCommandText");
MemoryStream commandBuilder = new MemoryStream();
StringChunk[] chunks;
chunks = GetDistinctTrimmedCommands(commandText);
if (chunks.Length > 1)
{
if (prepare || commandType == CommandType.StoredProcedure)
{
throw new NpgsqlException("Multiple queries not supported for this command type");
}
}
foreach (StringChunk chunk in chunks)
{
if (commandBuilder.Length > 0)
{
commandBuilder
.WriteBytes((byte)ASCIIBytes.SemiColon)
.WriteBytes(ASCIIByteArrays.LineTerminator);
}
if (prepare && ! forExtendQuery)
{
commandBuilder
.WriteString("PREPARE ")
.WriteString(planName)
.WriteString(" AS ");
}
if (commandType == CommandType.StoredProcedure)
{
if (! prepare && ! functionChecksDone)
{
functionNeedsColumnListDefinition = Parameters.Count != 0 && CheckFunctionNeedsColumnDefinitionList();
functionChecksDone = true;
}
commandBuilder.WriteString("SELECT * FROM ");
if (commandText[chunk.Begin + chunk.Length - 1] == ')')
{
AppendCommandReplacingParameterValues(commandBuilder, commandText, chunk.Begin, chunk.Length, prepare, forExtendQuery);
}
else
{
commandBuilder
.WriteString(commandText.Substring(chunk.Begin, chunk.Length))
.WriteBytes((byte)ASCIIBytes.ParenLeft);
if (prepare)
{
AppendParameterPlaceHolders(commandBuilder);
}
else
{
AppendParameterValues(commandBuilder);
}
commandBuilder.WriteBytes((byte)ASCIIBytes.ParenRight);
}
if (! prepare && functionNeedsColumnListDefinition)
{
AddFunctionColumnListSupport(commandBuilder);
}
}
else if (commandType == CommandType.TableDirect)
{
commandBuilder
.WriteString("SELECT * FROM ")
.WriteString(commandText.Substring(chunk.Begin, chunk.Length));
}
else
{
AppendCommandReplacingParameterValues(commandBuilder, commandText, chunk.Begin, chunk.Length, prepare, forExtendQuery);
}
}
return commandBuilder.ToArray();
}
private enum TokenType
{
None,
LineComment,
BlockComment,
Quoted,
LineCommentBegin,
BlockCommentBegin,
BlockCommentEnd,
Param,
Colon,
FullTextMatchOp
}
/// <summary>
/// Find the beginning and end of each distinct SQL command and produce
/// a list of descriptors, one for each command. Commands described are trimmed of
/// leading and trailing white space and their terminating semi-colons.
/// </summary>
/// <param name="src">Raw command text.</param>
/// <returns>List of chunk descriptors.</returns>
private static StringChunk[] GetDistinctTrimmedCommands(string src)
{
TokenType currTokenType = TokenType.None;
bool quoteEscape = false;
int currCharOfs = -1;
int currChunkBeg = 0;
int currChunkRawLen = 0;
int currChunkTrimLen = 0;
List<StringChunk> chunks = new List<StringChunk>();
foreach (char ch in src)
{
currCharOfs++;
// goto label for character re-evaluation:
ProcessCharacter:
switch (currTokenType)
{
case TokenType.None :
switch (ch)
{
case '\'' :
currTokenType = TokenType.Quoted;
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case ';' :
if (currChunkTrimLen > 0)
{
chunks.Add(new StringChunk(currChunkBeg, currChunkTrimLen));
}
currChunkBeg = currCharOfs + 1;
currChunkRawLen = 0;
currChunkTrimLen = 0;
break;
case ' ' :
case '\t' :
case '\r' :
case '\n' :
if (currChunkTrimLen == 0)
{
currChunkBeg++;
}
else
{
currChunkRawLen++;
}
break;
case '/' :
currTokenType = TokenType.BlockCommentBegin;
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case '-' :
currTokenType = TokenType.LineCommentBegin;
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
default :
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
}
break;
case TokenType.LineCommentBegin :
if (ch == '-')
{
currTokenType = TokenType.LineComment;
}
else
{
currTokenType = TokenType.None;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case TokenType.BlockCommentBegin :
if (ch == '*')
{
currTokenType = TokenType.BlockComment;
}
else
{
currTokenType = TokenType.None;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case TokenType.BlockCommentEnd :
if (ch == '/')
{
currTokenType = TokenType.None;
}
else
{
currTokenType = TokenType.BlockComment;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case TokenType.Quoted :
switch (ch)
{
case '\'' :
if (quoteEscape)
{
quoteEscape = false;
}
else
{
quoteEscape = true;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
default :
if (quoteEscape)
{
quoteEscape = false;
currTokenType = TokenType.None;
// Re-evaluate this character
goto ProcessCharacter;
}
else
{
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
}
break;
}
break;
case TokenType.LineComment :
if (ch == '\n')
{
currTokenType = TokenType.None;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
case TokenType.BlockComment :
if (ch == '*')
{
currTokenType = TokenType.BlockCommentEnd;
}
currChunkRawLen++;
currChunkTrimLen = currChunkRawLen;
break;
}
}
if (currChunkTrimLen > 0)
{
chunks.Add(new StringChunk(currChunkBeg, currChunkTrimLen));
}
return chunks.ToArray();
}
private void AppendParameterPlaceHolders(Stream dest)
{
bool first = true;
for (int i = 0; i < parameters.Count; i++)
{
NpgsqlParameter parameter = parameters[i];
if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
{
if (first)
{
first = false;
}
else
{
dest.WriteString(", ");
}
AppendParameterPlaceHolder(dest, parameter, i + 1);
}
}
}
private void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber)
{
string parameterSize = "";
dest.WriteBytes((byte)ASCIIBytes.ParenLeft);
if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
{
parameterSize = string.Format("({0})", parameter.Size);
}
if (parameter.UseCast)
{
dest.WriteString("${0}::{1}{2}", paramNumber, parameter.TypeInfo.CastName, parameterSize);
}
else
{
dest.WriteString("${0}{1}", paramNumber, parameterSize);
}
dest.WriteBytes((byte)ASCIIBytes.ParenRight);
}
private void AppendParameterValues(Stream dest)
{
bool first = true;
for (int i = 0 ; i < parameters.Count ; i++)
{
NpgsqlParameter parameter = parameters[i];
if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
{
if (first)
{
first = false;
}
else
{
dest.WriteString(", ");
}
AppendParameterValue(dest, parameter);
}
}
}
private void AppendParameterValue(Stream dest, NpgsqlParameter parameter)
{
byte[] serialised = parameter.TypeInfo.ConvertToBackend(parameter.NpgsqlValue, false, Connector.NativeToBackendTypeConverterOptions);
// Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue
// See bug #1010543
// Check if this parenthesis can be collapsed with the previous one about the array support. This way, we could use
// only one pair of parentheses for the two purposes instead of two pairs.
dest
.WriteBytes((byte)ASCIIBytes.ParenLeft)
.WriteBytes((byte)ASCIIBytes.ParenLeft)
.WriteBytes(serialised)
.WriteBytes((byte)ASCIIBytes.ParenRight);
if (parameter.UseCast)
{
dest.WriteString("::{0}", parameter.TypeInfo.CastName);
if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
{
dest.WriteString("({0})", parameter.Size);
}
}
dest.WriteBytes((byte)ASCIIBytes.ParenRight);
}
private static bool IsParamNameChar(char ch)
{
if (ch < '.' || ch > 'z')
{
return false;
}
else
{
return ((byte)ParamNameCharTable.GetValue(ch) != 0);
}
}
/// <summary>
/// Append a region of a source command text to an output command, performing parameter token
/// substitutions.
/// </summary>
/// <param name="dest">Stream to which to append output.</param>
/// <param name="src">Command text.</param>
/// <param name="begin">Starting index within src.</param>
/// <param name="length">Length of region to be processed.</param>
/// <param name="prepare"></param>
/// <param name="forExtendedQuery"></param>
private void AppendCommandReplacingParameterValues(Stream dest, string src, int begin, int length, bool prepare, bool forExtendedQuery)
{
char lastChar = '\0';
TokenType currTokenType = TokenType.None;
char paramMarker = '\0';
int currTokenBeg = begin;
int currTokenLen = 0;
Dictionary<NpgsqlParameter, int> paramOrdinalMap = null;
int end = begin + length;
if (prepare)
{
paramOrdinalMap = new Dictionary<NpgsqlParameter, int>();
for (int i = 0 ; i < parameters.Count ; i++)
{
paramOrdinalMap[parameters[i]] = i + 1;
}
}
for (int currCharOfs = begin ; currCharOfs < end ; currCharOfs++)
{
char ch = src[currCharOfs];
// goto label for character re-evaluation:
ProcessCharacter:
switch (currTokenType)
{
case TokenType.None :
switch (ch)
{
case '\'' :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
currTokenType = TokenType.Quoted;
currTokenBeg = currCharOfs;
currTokenLen = 1;
break;
case ':' :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
currTokenType = TokenType.Colon;
currTokenBeg = currCharOfs;
currTokenLen = 1;
break;
case '<' :
case '@' :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
currTokenType = TokenType.FullTextMatchOp;
currTokenBeg = currCharOfs;
currTokenLen = 1;
break;
case '-' :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
currTokenType = TokenType.LineCommentBegin;
currTokenBeg = currCharOfs;
currTokenLen = 1;
break;
case '/' :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
currTokenType = TokenType.BlockCommentBegin;
currTokenBeg = currCharOfs;
currTokenLen = 1;
break;
default :
currTokenLen++;
break;
}
break;
case TokenType.Param :
if (IsParamNameChar(ch))
{
currTokenLen++;
}
else
{
string paramName = src.Substring(currTokenBeg, currTokenLen);
NpgsqlParameter parameter;
bool wroteParam = false;
if (parameters.TryGetValue(paramName, out parameter))
{
if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
{
if (prepare)
{
AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
}
else
{
AppendParameterValue(dest, parameter);
}
}
wroteParam = true;
}
if (! wroteParam)
{
dest.WriteString("{0}{1}", paramMarker, paramName);
}
currTokenType = TokenType.None;
currTokenBeg = currCharOfs;
currTokenLen = 0;
// Re-evaluate this character
goto ProcessCharacter;
}
break;
case TokenType.Quoted :
switch (ch)
{
case '\'' :
currTokenLen++;
break;
default :
if (currTokenLen > 1 && lastChar == '\'')
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
currTokenType = TokenType.None;
currTokenBeg = currCharOfs;
currTokenLen = 0;
// Re-evaluate this character
goto ProcessCharacter;
}
else
{
currTokenLen++;
}
break;
}
break;
case TokenType.LineComment :
if (ch == '\n')
{
currTokenType = TokenType.None;
}
currTokenLen++;
break;
case TokenType.BlockComment :
if (ch == '*')
{
currTokenType = TokenType.BlockCommentEnd;
}
currTokenLen++;
break;
case TokenType.Colon :
if (IsParamNameChar(ch))
{
// Switch to parameter name token, include this character.
currTokenType = TokenType.Param;
currTokenBeg = currCharOfs;
currTokenLen = 1;
paramMarker = ':';
}
else
{
// Demote to the unknown token type and continue.
currTokenType = TokenType.None;
currTokenLen++;
}
break;
case TokenType.FullTextMatchOp :
if (lastChar == '@' && IsParamNameChar(ch))
{
// Switch to parameter name token, include this character.
currTokenType = TokenType.Param;
currTokenBeg = currCharOfs;
currTokenLen = 1;
paramMarker = '@';
}
else
{
// Demote to the unknown token type.
currTokenType = TokenType.None;
// Re-evaluate this character
goto ProcessCharacter;
}
break;
case TokenType.LineCommentBegin :
if (ch == '-')
{
currTokenType = TokenType.LineComment;
currTokenLen++;
}
else
{
// Demote to the unknown token type.
currTokenType = TokenType.None;
// Re-evaluate this character
goto ProcessCharacter;
}
break;
case TokenType.BlockCommentBegin :
if (ch == '*')
{
currTokenType = TokenType.BlockComment;
currTokenLen++;
}
else
{
// Demote to the unknown token type.
currTokenType = TokenType.None;
// Re-evaluate this character
goto ProcessCharacter;
}
break;
case TokenType.BlockCommentEnd :
if (ch == '/')
{
currTokenType = TokenType.None;
currTokenLen++;
}
else
{
currTokenType = TokenType.BlockComment;
currTokenLen++;
}
break;
}
lastChar = ch;
}
switch (currTokenType)
{
case TokenType.Param :
string paramName = src.Substring(currTokenBeg, currTokenLen);
NpgsqlParameter parameter;
bool wroteParam = false;
if (parameters.TryGetValue(paramName, out parameter))
{
if (
(parameter.Direction == ParameterDirection.Input) ||
(parameter.Direction == ParameterDirection.InputOutput)
)
{
if (prepare)
{
AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
}
else
{
AppendParameterValue(dest, parameter);
}
}
wroteParam = true;
}
if (! wroteParam)
{
dest.WriteString("{0}{1}", paramMarker, paramName);
}
break;
default :
if (currTokenLen > 0)
{
dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
}
break;
}
}