-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStoredProcedureConverter.cs
1881 lines (1532 loc) · 84.8 KB
/
StoredProcedureConverter.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.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using PRISM;
using TableColumnNameMapContainer;
namespace SQLServer_Stored_Procedure_Converter
{
internal class StoredProcedureConverter : EventNotifier
{
// ReSharper disable once CommentTypo
// Ignore Spelling: auth, bs, dbo, desc, lookbehind, mem, myemsl, regex, tmp
// Ignore Spelling: smallint, tinyint, varchar
private enum ControlBlockTypes
{
If = 0,
While = 1
}
/// <summary>
/// This is used when backtracking and forward tracking to find lines of code that should be processed as a block
/// </summary>
private static readonly Regex mBlockBoundaryMatcher = new(
@"^\s*(Begin|End|If|Else)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to match Desc, Auth, or Date keywords in a comment block
/// It captures both the keyword and any text after the keyword
/// For example, given: Auth: mem
/// The Label group will have "Auth" and the Value group will have "mem"
/// </summary>
private readonly Regex mCommentBlockLabelMatcher = new(
@"^\*\*\s+(?<Label>Desc|Auth|Date):\s*(?<Value>.*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Regex mExecStoreReturnMatcher = new(
@"exec\s+(?<TargetVariable>@[a-z]+) *=(?<TargetProcedureAndParams>.*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to match varchar(10) or longer
/// </summary>
private readonly Regex mVarcharMatcher = new(
@"n*varchar\((\d{2,}|max)\)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly Regex mLeadingTabMatcher = new(@"^\t+", RegexOptions.Compiled);
/// <summary>
/// This finds leading whitespace (spaces and tabs)
/// </summary>
private readonly Regex mLeadingWhitespaceMatcher = new(@"^\s+", RegexOptions.Compiled);
/// <summary>
/// This finds lines like:
/// Set NoCount On
/// Set NoCount Off
/// Set XACT_ABORT, NoCount on
/// </summary>
private readonly Regex mSetNoCountMatcher = new(
@"^\s*Set +(XACT_ABORT|NoCount) +(On|Off) *$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This finds variable assignment statements, looking for Set followed by a variable name and an equals sign
/// Although there is typically a value after the equals sign, this is not a requirement (the value could be on the next line)
/// </summary>
private readonly Regex mSetStatementMatcher = new(
@"^(?<LeadingWhitespace>\s*)Set\s+[@_](?<VariableName>[^\s]+)\s*=\s*(?<AssignedValue>.*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to switch from + to || for string concatenation
/// It matches single quoted text followed by a plus sign (including '' +)
/// </summary>
/// <remarks>This Regex uses positive lookbehind to find the quoted text before the plus sign</remarks>
private readonly Regex mConcatenationReplacerA = new(
@"(?<='[^']*'\s*)\+",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to switch from + to || for string concatenation
/// It matches single quoted text preceded by a plus sign (including + '')
/// </summary>
/// <remarks>This Regex uses positive lookahead to find the quoted text after the plus sign</remarks>
private readonly Regex mConcatenationReplacerB = new(
@"\+(?=\s*'[^']*')",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to switch from + to || for string concatenation
/// It matches single quoted text preceded by a plus sign (including + '')
/// </summary>
private readonly Regex mLenFunctionUpdater = new(
@"\bLen\s*\(",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to switch from CharIndex('text', 'TextToSearch') to
/// position('Text' in 'TextToSearch')
/// </summary>
private readonly Regex mCharIndexUpdater = new(
@"CharIndex\s*\(\s*(?<TextToFind>[^)]+)\s*,\s*(?<TextToSearch>[^)]+)\s*\)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to switch from Convert(DataType, @Variable) to _Variable::DataType
/// </summary>
private readonly Regex mConvertDataTypeUpdater = new(
@"Convert\s*\(\s*(?<DataType>[^,]+)+\s*,\s*[@_](?<VariableName>[^\s]+)\s*\)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to find SQL Server variable names (which start with @)
/// It uses negative look behind to avoid matching @@error
/// </summary>
private readonly Regex mVariableNameMatcher = new(
@"(?<!@)@(?<FirstCharacter>[a-z0-9_])(?<RemainingCharacters>[^\s]+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to find text that starts with @ plus the next letter, number, or underscore
/// It uses negative look behind to avoid matching @@error
/// </summary>
private readonly Regex mVariableStartMatcher = new(
"(?<!@)@(?<FirstCharacter>[a-z0-9_])",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to find fields declared as Identity(1,1)
/// </summary>
private readonly Regex mIdentityFieldMatcher = new(
@"(Identity\s*\(1,1\)\s*NOT NULL|Not Null Identity\s*\(1,1\)|Identity\s*\(1,1\))",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to find cases where the LIKE keyword is followed by text in quotes where a square bracket is used to denote a character class
/// </summary>
private readonly Regex mLikeCharacterClassMatcher = new(
@"\bLIKE(?<ComparisonSpec>\s*'.*\[[^]]+\].*')",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// This is used to find UPDATE or DELETE queries
/// </summary>
private readonly Regex mUpdateOrDeleteQueryMatcher = new(
@"^\s*(?<QueryType>UPDATE|DELETE)\s+(?<TargetTable>[^ ]+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// Options
/// </summary>
private readonly StoredProcedureConverterOptions mOptions;
/// <summary>
/// Constructor
/// </summary>
/// <param name="options"></param>
public StoredProcedureConverter(StoredProcedureConverterOptions options)
{
mOptions = options;
}
/// <summary>
/// Add a line to the procedure body, replacing tabs with spaces
/// </summary>
/// <param name="procedureBody"></param>
/// <param name="dataLine"></param>
private void AppendLine(ICollection<string> procedureBody, string dataLine)
{
var updatedLine = ReplaceTabs(dataLine);
if (string.IsNullOrWhiteSpace(updatedLine) &&
string.IsNullOrWhiteSpace(procedureBody.LastOrDefault()))
{
// Prevent two blank lines in a row
return;
}
while (updatedLine != null && updatedLine.EndsWith(";;"))
{
updatedLine = updatedLine.Substring(0, updatedLine.Length - 1);
}
procedureBody.Add(updatedLine);
}
/// <summary>
/// If the line contains a comment, add it to the body
/// </summary>
/// <param name="procedureBody"></param>
/// <param name="dataLine"></param>
private void AppendLineComment(ICollection<string> procedureBody, string dataLine)
{
if (string.IsNullOrWhiteSpace(dataLine))
return;
var commentIndex = dataLine.IndexOf("--", StringComparison.Ordinal);
if (commentIndex < 0)
return;
var leadingWhitespace = GetLeadingWhitespace(dataLine);
AppendLine(procedureBody, leadingWhitespace + dataLine.Substring(commentIndex));
}
private void AppendProcedureToWriter(
StreamWriter writer,
StoredProcedureDDL storedProcedureInfo,
Dictionary<string, WordReplacer> tableNameMap,
Dictionary<string, Dictionary<string, WordReplacer>> columnNameMap,
bool updateSchemaOnTables)
{
var procedureNameWithoutSchema = StoredProcedureDDL.GetNameWithoutSchema(storedProcedureInfo.ProcedureName);
if (mOptions.StoredProcedureNamesToSkip.Contains(procedureNameWithoutSchema))
{
OnStatusEvent("Skipping " + storedProcedureInfo.ProcedureName);
return;
}
// Write out the previous procedure (or function)
if (storedProcedureInfo.IsFunction)
OnStatusEvent("Writing function " + storedProcedureInfo.ProcedureName);
else
OnStatusEvent("Writing stored procedure " + storedProcedureInfo.ProcedureName);
UpdateTableAndColumnNames(storedProcedureInfo.ProcedureBody, tableNameMap, columnNameMap, updateSchemaOnTables);
storedProcedureInfo.ToWriterForPostgres(writer);
}
/// <summary>
/// Convert the object name to snake_case
/// </summary>
/// <param name="objectName"></param>
public static string ConvertNameToSnakeCase(string objectName)
{
return NameUpdater.ConvertNameToSnakeCase(objectName);
}
/// <summary>
/// Examine the cached lines to find lines of code related to the line at the given index
/// </summary>
/// <param name="cachedLines">Cached SQL code</param>
/// <param name="index">Index in cachedLines to start at when finding the lines to add to the block</param>
/// <param name="updatedLineIndices">
/// Tracks the indexes of lines that have been updated;
/// this is used to assure we don't backtrack into a region that has already been processed
/// </param>
/// <param name="blockStartIndex">The index in cachedLines of the first line in the returned block of text</param>
/// <returns>Lines of related SQL code, adjacent to the line at cachedLines[index]</returns>
private List<string> FindCurrentBlock(
IReadOnlyList<string> cachedLines,
int index,
IEnumerable<int> updatedLineIndices,
out int blockStartIndex)
{
// Backtrack to find the start of this block
blockStartIndex = index;
var blockEndIndex = index;
var minimumIndex = Math.Max(0, updatedLineIndices.LastOrDefault());
var onlyIncludeCommentLines = cachedLines[index].Trim().StartsWith("--");
while (blockStartIndex > minimumIndex)
{
var previousLine = cachedLines[blockStartIndex - 1].Trim();
if (onlyIncludeCommentLines)
{
if (!previousLine.Trim().StartsWith("--"))
break;
}
else
{
if (IsBlockBoundary(previousLine))
break;
}
blockStartIndex--;
}
// Forward track to find the end of this block
var stopEndIndex = cachedLines.Count - 1;
while (blockEndIndex < stopEndIndex)
{
var nextLine = cachedLines[blockEndIndex + 1].Trim();
if (onlyIncludeCommentLines)
{
if (!nextLine.Trim().StartsWith("--"))
break;
}
else
{
if (IsBlockBoundary(nextLine))
break;
}
blockEndIndex++;
}
var currentBlock = new List<string>();
for (var i = blockStartIndex; i <= blockEndIndex; i++)
{
currentBlock.Add(cachedLines[i]);
}
return currentBlock;
}
private string GetLeadingWhitespace(string dataLine)
{
var match = mLeadingWhitespaceMatcher.Match(dataLine);
return !match.Success ? string.Empty : match.Value;
}
private static bool IsBlankOrComment(string dataLine)
{
return string.IsNullOrWhiteSpace(dataLine) || dataLine.Trim().StartsWith("--");
}
/// <summary>
/// Return true if the line is whitespace, or starts with --, Begin, If, or Else
/// </summary>
/// <param name="dataLine"></param>
private static bool IsBlockBoundary(string dataLine)
{
return
string.IsNullOrWhiteSpace(dataLine) ||
dataLine.Trim().StartsWith("--") ||
mBlockBoundaryMatcher.IsMatch(dataLine);
}
/// <summary>
/// Load the column name map file, if defined
/// It is a tab-delimited file with five columns, created by sqlserver2pgsql.pl or by the PgSqlViewCreatorHelper
/// Columns:
/// SourceTable SourceName Schema NewTable NewName
/// </summary>
/// <param name="tableNameMap">
/// Dictionary where keys are the original (source) table names
/// and values are WordReplacer classes that track the new table names and new column names in PostgreSQL
/// </param>
/// <param name="columnNameMap">
/// Dictionary where keys are new table names
/// and values are a Dictionary of mappings of original column names to new column names in PostgreSQL;
/// names should not have double quotes around them
/// </param>
private bool LoadColumnNameMapFile(
out Dictionary<string, WordReplacer> tableNameMap,
out Dictionary<string, Dictionary<string, WordReplacer>> columnNameMap)
{
if (string.IsNullOrWhiteSpace(mOptions.ColumnNameMapFile))
{
tableNameMap = new Dictionary<string, WordReplacer>();
columnNameMap = new Dictionary<string, Dictionary<string, WordReplacer>>();
return true;
}
var mapFile = new FileInfo(mOptions.ColumnNameMapFile);
if (!mapFile.Exists)
{
OnErrorEvent("Column name map file not found: " + mapFile.FullName);
tableNameMap = new Dictionary<string, WordReplacer>();
columnNameMap = new Dictionary<string, Dictionary<string, WordReplacer>>();
return false;
}
var mapReader = new NameMapReader();
RegisterEvents(mapReader);
const string defaultSchema = "public";
return mapReader.LoadSqlServerToPgSqlColumnMapFile(
mapFile,
defaultSchema,
false,
out tableNameMap,
out columnNameMap);
}
public bool ProcessFile(string inputFilePath)
{
try
{
var inputFile = new FileInfo(inputFilePath);
if (!inputFile.Exists)
{
OnWarningEvent("File not found: " + inputFilePath);
if (!inputFilePath.Equals(inputFile.FullName))
{
OnStatusEvent(" ... " + inputFile.FullName);
}
return false;
}
if (string.IsNullOrWhiteSpace(mOptions.OutputFilePath))
{
mOptions.OutputFilePath = mOptions.GetDefaultOutputFilePath();
}
var outputFile = new FileInfo(mOptions.OutputFilePath);
if (outputFile.Directory == null)
{
OnWarningEvent("Unable to determine the parent directory of the output file: " + mOptions.OutputFilePath);
return false;
}
if (!outputFile.Directory.Exists)
{
outputFile.Directory.Create();
}
return ProcessFile(inputFile, outputFile);
}
catch (Exception ex)
{
OnErrorEvent("Error in ProcessFile", ex);
return false;
}
}
private bool ProcessFile(FileSystemInfo inputFile, FileSystemInfo outputFile)
{
try
{
// This extracts a procedure name between the second pair of square brackets
// For example, given: [dbo].[PostLogEntry]
// ProcedureName will be PostLogEntry
var procedureNameMatcher = new Regex(
@"\[[^\]]+\]\.\[(?<ProcedureName>[^\]]+)\]",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for lines that start with whitespace then (
var argumentListStartMatcher = new Regex(@"^\s*\(", RegexOptions.Compiled);
// This looks for lines that start with whitespace then )
var argumentListEndMatcher = new Regex(@"^\s*\)", RegexOptions.Compiled);
// This looks for lines of the form
// ** Copyright 2005, Battelle Memorial Institute
var copyrightMatcher = new Regex(@"\*\* Copyright 20\d\d, Battelle Memorial Institute", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for lines that start with ()
var emptyArgumentListMatcher = new Regex(@"^\s*\(\s*\)", RegexOptions.Compiled);
// This looks for the Return type of functions
var returnTypeMatcher = new Regex(
@"^\s*RETURNS\s+(?<ReturnType>.+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for functions where the return type is specified on the next line
var returnTypeMatcherNoType = new Regex(
@"^\s*RETURNS\s*$",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for variable declaration statements, where a value is assigned to the variable
var declareAndAssignMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)Declare\s+@(?<VariableName>[^\s]+)(?<DataType>[^=]+)\s*=\s*(?<AssignedValue>.+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for variable declaration statements where no value is assigned
var declareMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)Declare\s+@(?<VariableName>[^\s]+)(?<DataType>[^=]+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for lines that start with End
var endStatementMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)End\b(?<ExtraInfo>.*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This looks for lines of the form
// Print @variable
var printVariableMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)Print\b\s+@(?<VariableName>[^\s]+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This is used to change
// SELECT @myRowCount = @@rowcount statements to
// GET DIAGNOSTICS _rowcount = ROW_COUNT;
var selectRowCountMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)SELECT.+@(?<VariableName>[^\s]+)\s*=\s*@@rowcount",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This is used to update SELECT statements that assign a value to a variable
var selectAssignVariableMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)SELECT.+@(?<VariableName>[^\s]+)\s*=\s*(?<SourceColumn>.+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// This is used to find SELECT statements that use TOP N to limit the number of rows retrieved
var selectTopMatcher = new Regex(
@"^(?<LeadingWhitespace>\s*)SELECT\s+TOP\s+(?<RowCount>\d+)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
var createTempTableMatcher = new Regex(
@"^(?<LeadingWhitespace>\s+)CREATE TABLE #(?<TempTableName>[^\s]+)(?<ExtraInfo>.*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
var mapFileSuccess = LoadColumnNameMapFile(out var tableNameMap, out var columnNameMap);
if (!mapFileSuccess)
return false;
// Define the schema name
var schemaName = string.IsNullOrWhiteSpace(mOptions.SchemaName) ? "public" : mOptions.SchemaName;
var foundStartOfProcedureCommentBlock = false;
var foundEndOfProcedureCommentBlock = false;
var foundArgumentListStart = false;
var foundArgumentListEnd = false;
// This queue tracks lines read from the input file; it is first in, first out (FIFO)
var cachedLines = new Queue<string>();
var tempTableDropStatements = new List<string>();
var updateSchemaOnTables =
!string.IsNullOrWhiteSpace(mOptions.SchemaName) &&
!mOptions.SchemaName.Equals("public", StringComparison.OrdinalIgnoreCase);
var skipNextLineIfGo = false;
var insideDateBlock = false;
var trimmedLine = string.Empty;
var mostRecentUpdateOrDeleteType = string.Empty;
var mostRecentUpdateOrDeleteTable = string.Empty;
var limitRowCountDDL = string.Empty;
// This stack tracks nested if and while blocks; it is last in, first out (LIFO)
var controlBlockStack = new Stack<ControlBlockTypes>();
var storedProcedureInfo = new StoredProcedureDDL(mOptions, this, string.Empty);
using var reader = new StreamReader(new FileStream(inputFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
using var writer = new StreamWriter(new FileStream(outputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read));
while (!reader.EndOfStream)
{
var dataLine = cachedLines.Count > 0 ? cachedLines.Dequeue() : reader.ReadLine();
// Skip lines that are null, but don't skip blank lines
if (dataLine == null)
continue;
// Skip Copyright lines
if (dataLine.Trim().Equals("** Pacific Northwest National Laboratory, Richland, WA"))
continue;
if (copyrightMatcher.IsMatch(dataLine))
continue;
// Replace smart quotes with straight quotes
dataLine = PunctuationUpdater.ProcessLine(dataLine);
var previousTrimmedLine = string.Copy(trimmedLine);
// Note that .Trim() removes leading and trailing spaces and tabs
trimmedLine = dataLine.Trim();
if (trimmedLine.Contains("Custom SQL to find"))
Console.WriteLine("Check this code");
if (!string.IsNullOrWhiteSpace(limitRowCountDDL) && (trimmedLine.Length == 0 || trimmedLine.StartsWith("--")))
{
AppendLine(storedProcedureInfo.ProcedureBody, limitRowCountDDL);
limitRowCountDDL = string.Empty;
}
// Skip lines that assign 0 to @myError
if (trimmedLine.Equals("Set @myError = 0", StringComparison.OrdinalIgnoreCase))
continue;
// If the previous line was "Declare @myRowCount" or "Declare @myError", skip lines that assign 0 to @myRowCount
if (trimmedLine.Equals("Set @myRowCount = 0", StringComparison.OrdinalIgnoreCase) &&
(previousTrimmedLine.StartsWith("Declare @myRowCount", StringComparison.OrdinalIgnoreCase) ||
previousTrimmedLine.StartsWith("Declare @myError", StringComparison.OrdinalIgnoreCase) ||
previousTrimmedLine.StartsWith("Set @myError = 0", StringComparison.OrdinalIgnoreCase)))
{
continue;
}
if (skipNextLineIfGo && trimmedLine.Equals("GO", StringComparison.OrdinalIgnoreCase))
{
SkipNextLineIfBlank(reader, cachedLines);
skipNextLineIfGo = false;
continue;
}
if (trimmedLine.Equals("GO", StringComparison.OrdinalIgnoreCase) && tempTableDropStatements.Count > 0)
{
storedProcedureInfo.ProcedureBody.AddRange(tempTableDropStatements);
tempTableDropStatements.Clear();
}
if (!string.IsNullOrWhiteSpace(mostRecentUpdateOrDeleteTable) && string.IsNullOrWhiteSpace(trimmedLine))
{
mostRecentUpdateOrDeleteTable = string.Empty;
}
if (SkipLine(trimmedLine, out skipNextLineIfGo))
continue;
if (trimmedLine.StartsWith("CREATE PROCEDURE", StringComparison.OrdinalIgnoreCase) ||
trimmedLine.StartsWith("CREATE FUNCTION", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrWhiteSpace(storedProcedureInfo.ProcedureName))
{
AppendProcedureToWriter(writer, storedProcedureInfo, tableNameMap, columnNameMap, updateSchemaOnTables);
}
// Reset the tracking variables
foundStartOfProcedureCommentBlock = false;
foundEndOfProcedureCommentBlock = false;
foundArgumentListStart = false;
foundArgumentListEnd = false;
skipNextLineIfGo = false;
controlBlockStack.Clear();
var isFunction = trimmedLine.StartsWith("CREATE FUNCTION", StringComparison.OrdinalIgnoreCase);
var createKeywords = isFunction ? "CREATE FUNCTION" : "CREATE PROCEDURE";
var matchedName = procedureNameMatcher.Match(trimmedLine);
string procedureNameWithSchema;
if (matchedName.Success)
{
procedureNameWithSchema = schemaName + "." + matchedName.Groups["ProcedureName"].Value;
}
else
{
procedureNameWithSchema = schemaName + "." + trimmedLine.Substring(createKeywords.Length + 1);
}
storedProcedureInfo.Reset(procedureNameWithSchema, isFunction);
continue;
}
if (!foundStartOfProcedureCommentBlock && trimmedLine.StartsWith("/*****************"))
{
foundStartOfProcedureCommentBlock = true;
insideDateBlock = false;
storedProcedureInfo.ProcedureCommentBlock.Add(ReplaceTabs(dataLine));
continue;
}
if (foundStartOfProcedureCommentBlock && !foundEndOfProcedureCommentBlock && trimmedLine.EndsWith("*****************/"))
{
foundEndOfProcedureCommentBlock = true;
if (insideDateBlock)
{
storedProcedureInfo.ProcedureCommentBlock.Add(string.Format(
"** {0:MM/dd/yyyy} mem - Ported to PostgreSQL",
DateTime.Now));
insideDateBlock = false;
}
storedProcedureInfo.ProcedureCommentBlock.Add(ReplaceTabs(dataLine));
continue;
}
if (foundStartOfProcedureCommentBlock && !foundEndOfProcedureCommentBlock)
{
if (dataLine.IndexOf("Return values: 0: success, otherwise, error code", StringComparison.OrdinalIgnoreCase) > 0 ||
dataLine.IndexOf("Return values: 0 if no error; otherwise error code", StringComparison.OrdinalIgnoreCase) > 0)
{
// Skip this line that we traditionally have included as boilerplate
ReadAndCacheLines(reader, cachedLines, 1);
if (cachedLines.Count > 0 && cachedLines.Peek().Trim().Equals("**"))
{
// The next line is just "**"
// Skip it too
cachedLines.Dequeue();
}
continue;
}
if (dataLine.IndexOf("Parameters:", StringComparison.OrdinalIgnoreCase) > 1)
{
// Skip lines of the form "** Parameters:" if the next line is blank
var lineAfterAsterisks = dataLine.Substring(2).Trim();
if (lineAfterAsterisks.Equals("Parameters:", StringComparison.OrdinalIgnoreCase))
{
ReadAndCacheLines(reader, cachedLines, 1);
if (cachedLines.Count > 0 && cachedLines.Peek().Trim().Equals("**"))
{
// The next line is just "**"
// Skip this line and the next one
cachedLines.Dequeue();
continue;
}
}
}
if (insideDateBlock && trimmedLine.Equals("**"))
{
storedProcedureInfo.ProcedureCommentBlock.Add(string.Format(
"** {0:MM/dd/yyyy} mem - Ported to PostgreSQL",
DateTime.Now));
insideDateBlock = false;
}
StoreProcedureCommentLine(storedProcedureInfo, dataLine, out var startOfDateBlock);
if (startOfDateBlock)
{
insideDateBlock = true;
}
continue;
}
if (!foundArgumentListStart && argumentListStartMatcher.IsMatch(dataLine))
{
foundArgumentListStart = true;
if (emptyArgumentListMatcher.IsMatch(dataLine))
foundArgumentListEnd = true;
continue;
}
if (foundArgumentListStart && !foundArgumentListEnd && argumentListEndMatcher.IsMatch(dataLine))
{
foundArgumentListEnd = true;
continue;
}
if (foundArgumentListStart && !foundArgumentListEnd)
{
// Inside the argument list
StoreProcedureArgument(storedProcedureInfo, dataLine);
continue;
}
if (returnTypeMatcher.IsMatch(dataLine))
{
var match = returnTypeMatcher.Match(dataLine);
storedProcedureInfo.FunctionReturnType = match.Groups["ReturnType"].Value;
continue;
}
if (returnTypeMatcherNoType.IsMatch(dataLine))
{
// The return type is on the next line
storedProcedureInfo.FunctionReturnType = cachedLines.Count > 0 ? cachedLines.Dequeue() : reader.ReadLine();
continue;
}
// Perform some standard text replacements using ReplaceText
// It performs a case-insensitive search/replace and it supports Regex
dataLine = ReplaceText(dataLine, @"\bIsNull\b", "Coalesce");
dataLine = ReplaceText(dataLine, @"\bDatetime\b", "timestamp");
dataLine = ReplaceText(dataLine, @"\bGetDate\b\s*\(\)", "CURRENT_TIMESTAMP");
// Stored procedures with smallint parameters are harder to call, since you have to explicitly cast numbers to ::smallint
// Thus, replace both tinyint and smallint with int (aka integer or int4)
dataLine = ReplaceText(dataLine, @"\b(tinyint|smallint)\b", "int");
// ReSharper disable CommentTypo
// This matches user_name(), suser_name(), or suser_sname()
dataLine = ReplaceText(dataLine, @"\bs*user_s*name\b\s*\(\)", "session_user");
// ReSharper restore CommentTypo
dataLine = ReplaceText(dataLine, "(dbo.)*AlterEnteredByUserMultiID", "public.alter_entered_by_user_multi_id");
dataLine = ReplaceText(dataLine, "(dbo.)*AlterEnteredByUser", "public.alter_entered_by_user");
dataLine = ReplaceText(dataLine, "(dbo.)*AlterEventLogEntryUserMultiID", "public.alter_event_log_entry_user_multi_id");
dataLine = ReplaceText(dataLine, "(dbo.)*AlterEventLogEntryUser", "public.alter_event_log_entry_user");
dataLine = ReplaceText(dataLine, "(dbo.)*udfParseDelimitedIntegerList", "public.parse_delimited_integer_list");
dataLine = ReplaceText(dataLine, "(dbo.)*udfParseDelimitedListOrdered", "public.parse_delimited_list_ordered");
dataLine = ReplaceText(dataLine, "(dbo.)*udfParseDelimitedList", "public.parse_delimited_list");
dataLine = ReplaceText(dataLine, "(dbo.)*udfCombinePaths", "public.combine_paths");
dataLine = ReplaceText(dataLine, "(dbo.)*udfGetFilename", "public.get_filename");
dataLine = ReplaceText(dataLine, "(dbo.)*udfTimeStampText", "public.timestamp_text");
dataLine = ReplaceText(dataLine, "(dbo.)*udfWhitespaceChars", "public.has_whitespace_chars");
// ReSharper disable once StringLiteralTypo
dataLine = ReplaceText(dataLine, "(dbo.)*MakeTableFromListDelim", "public.parse_delimited_list");
dataLine = ReplaceText(dataLine, "(dbo.)*MakeTableFromList", "public.parse_delimited_list");
dataLine = ReplaceLeadingTabs(dataLine);
if (dataLine.IndexOf("LTrim(RTrim", StringComparison.OrdinalIgnoreCase) >= 0)
{
dataLine = ReplaceText(dataLine, @"LTrim\(RTrim", "Trim");
var trimIndex = dataLine.IndexOf("Trim(", StringComparison.OrdinalIgnoreCase);
// Replace the next occurrence of )) with )
var parenthesesIndex = dataLine.IndexOf("))", Math.Max(0, trimIndex), StringComparison.OrdinalIgnoreCase);
if (parenthesesIndex > 0)
{
dataLine = dataLine.Substring(0, parenthesesIndex) + dataLine.Substring(parenthesesIndex + 1);
}
}
var createTempTableMatch = createTempTableMatcher.Match(dataLine);
if (createTempTableMatch.Success)
{
dataLine = string.Format(
"{0}CREATE TEMP TABLE {1}{2}",
createTempTableMatch.Groups["LeadingWhitespace"],
createTempTableMatch.Groups["TempTableName"],
createTempTableMatch.Groups["ExtraInfo"]
);
tempTableDropStatements.Add(" DROP TABLE " + createTempTableMatch.Groups["TempTableName"]);
}
dataLine = ReplaceText(dataLine, "#Tmp", "Tmp");
dataLine = ReplaceText(dataLine, "#IX", "IX");
dataLine = ReplaceText(dataLine, "(dbo.)*AppendToText", "public.append_to_text");
if (dataLine.IndexOf("identity_insert", StringComparison.OrdinalIgnoreCase) >= 0 && dataLine.IndexOf("Off", StringComparison.OrdinalIgnoreCase) < 0)
{
var whitespace = GetLeadingWhitespace(dataLine);
AppendLine(storedProcedureInfo.ProcedureBody, string.Format("{0}-- Use OVERRIDING SYSTEM VALUE to insert an explicit value for the identity column, for example:", whitespace));
AppendLine(storedProcedureInfo.ProcedureBody, string.Format("{0}--", whitespace));
AppendLine(storedProcedureInfo.ProcedureBody, string.Format("{0}-- INSERT INTO mc.t_log_entries (entry_id, posted_by, posting_time, type, message)", whitespace));
AppendLine(storedProcedureInfo.ProcedureBody, string.Format("{0}-- OVERRIDING SYSTEM VALUE", whitespace));
AppendLine(storedProcedureInfo.ProcedureBody, string.Format("{0}-- VALUES (12345, 'Test', CURRENT_TIMESTAMP, 'Test', 'Message');", whitespace));
}
var declareAndAssignMatch = declareAndAssignMatcher.Match(dataLine);
if (declareAndAssignMatch.Success)
{
StoreVariableToDeclare(storedProcedureInfo, declareAndAssignMatch);
continue;
}
var declareMatch = declareMatcher.Match(dataLine);
if (declareMatch.Success)
{
StoreVariableToDeclare(storedProcedureInfo, declareMatch);
continue;
}
var assignVariableMatch = mSetStatementMatcher.Match(dataLine);
if (assignVariableMatch.Success)
{
StoreSetStatement(storedProcedureInfo.ProcedureBody, assignVariableMatch);
continue;
}
var printVariableMatch = printVariableMatcher.Match(dataLine);
if (printVariableMatch.Success)
{
StorePrintVariable(storedProcedureInfo.ProcedureBody, printVariableMatch);
continue;
}
var selectRowcountMatch = selectRowCountMatcher.Match(dataLine);
if (selectRowcountMatch.Success)
{
StoreSelectRowCount(storedProcedureInfo.ProcedureBody, selectRowcountMatch);
continue;
}
var selectTopMatch = selectTopMatcher.Match(dataLine);
if (selectTopMatch.Success)
{
// Cache DDL to be written to the output file when the next blank line or line that starts with a comment is found
// For example:
// LIMIT 1;
limitRowCountDDL = string.Format("{0}LIMIT {1};",
selectTopMatch.Groups["LeadingWhitespace"].Value,
selectTopMatch.Groups["RowCount"].Value);
AppendLine(storedProcedureInfo.ProcedureBody,
string.Format("{0}-- Moved to bottom of query: TOP {1}",
selectTopMatch.Groups["LeadingWhitespace"].Value,
selectTopMatch.Groups["RowCount"].Value));
}
var selectAssignVariableMatch = selectAssignVariableMatcher.Match(dataLine);
if (selectAssignVariableMatch.Success)
{
StoreSelectAssignVariable(storedProcedureInfo.ProcedureBody, selectAssignVariableMatch);
continue;
}
var identityFieldMatch = mIdentityFieldMatcher.Match(dataLine);
if (identityFieldMatch.Success)
{
dataLine = mIdentityFieldMatcher.Replace(dataLine, "PRIMARY KEY GENERATED ALWAYS AS IDENTITY");
}
var likeCharacterClassMatch = mLikeCharacterClassMatcher.Match(dataLine);
if (likeCharacterClassMatch.Success)
{
dataLine = mLikeCharacterClassMatcher.Replace(dataLine, "SIMILAR TO${ComparisonSpec}");
}
var endMatch = endStatementMatcher.Match(dataLine);
if (endMatch.Success && controlBlockStack.Count > 0)
{
var leadingWhitespace = endMatch.Groups["LeadingWhitespace"].Value;
var extraInfo = endMatch.Groups["ExtraInfo"].Value;
switch (controlBlockStack.Pop())
{
case ControlBlockTypes.If:
// If the next line is ELSE, skip this END statement
ReadAndCacheLines(reader, cachedLines, 1);
if (cachedLines.Count > 0 && cachedLines.Peek().Trim().StartsWith("Else", StringComparison.OrdinalIgnoreCase))
{
var elseLine = ReplaceText(cachedLines.Dequeue(), "else", "Else");
UpdateAndAppendLine(storedProcedureInfo.ProcedureBody, elseLine);
ReadAndCacheLines(reader, cachedLines, 1);
// Look for Begin on the next line
// If found, push ControlBlockTypes.If onto the stack
// Skip the line if no comment; otherwise, write the comment
if (NextCachedLineIsBegin(cachedLines, storedProcedureInfo.ProcedureBody, controlBlockStack))
{
continue;
}
if (cachedLines.Count > 0)
{
// The next line does not start Begin
// 1) Write the next line (rename variables and change = to := if necessary)
// 2) Write End If;
var nextLine = cachedLines.Dequeue();
UpdateAndAppendLine(storedProcedureInfo.ProcedureBody, nextLine + ";");
AppendLine(storedProcedureInfo.ProcedureBody, leadingWhitespace + "End If;");
}
continue;
}
AppendLine(storedProcedureInfo.ProcedureBody, leadingWhitespace + "End If;" + extraInfo);
continue;
case ControlBlockTypes.While:
AppendLine(storedProcedureInfo.ProcedureBody, leadingWhitespace + "End Loop;" + extraInfo);
continue;
}
}
if (trimmedLine.StartsWith("If ", StringComparison.OrdinalIgnoreCase))
{
// If statement
// Change to "If ... Then"
// This change assumes the If condition does not span multiple lines
var updatedLine = UpdateFunctionNames(UpdateVariableNames(dataLine));
AppendLine(storedProcedureInfo.ProcedureBody, updatedLine + " Then");
// Peek at the next two or three lines to determine what to do
// The following logic does not support "ELSE IF" code; that will need to be manually updated
ReadAndCacheLines(reader, cachedLines, 3);
if (cachedLines.Count == 0)
continue;
// Look for Begin on the next line
// If found, push ControlBlockTypes.If onto the stack
// Skip the line if no comment; otherwise, write the comment
if (NextCachedLineIsBegin(cachedLines, storedProcedureInfo.ProcedureBody, controlBlockStack))
{
continue;
}
var leadingWhitespace = GetLeadingWhitespace(dataLine);
if (cachedLines.Count > 1 && cachedLines.Take(2).Last().Trim().StartsWith("Else", StringComparison.OrdinalIgnoreCase))
{
// The line after the next line starts with Else:
// 1) Write out the next line (rename variables and change = to := if necessary)
// 2) Write Else