-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDBSchemaExportTool.cs
1971 lines (1621 loc) · 79.9 KB
/
DBSchemaExportTool.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.RegularExpressions;
using PRISM;
using PRISM.Logging;
// ReSharper disable UnusedMember.Global
namespace DB_Schema_Export_Tool
{
/// <summary>
/// Database schema export tool
/// </summary>
public class DBSchemaExportTool : LoggerBase
{
// ReSharper disable CommentTypo
// Ignore Spelling: dba, lcms, myemsl, PostgreSQL, psm, Quantitation, Repo, Svn, tmp, unimod, unpause, unpaused, uri
// ReSharper restore CommentTypo
private enum DifferenceReasonType
{
Unchanged = 0,
NewFile = 1,
Changed = 2
}
private enum RepoManagerType
{
Svn = 0,
Hg = 1,
Git = 2
}
private readonly Regex mDateMatcher;
private DBSchemaExporterBase mDBSchemaExporter;
private readonly SchemaExportOptions mOptions;
private readonly Regex mVersionExtractor;
/// <summary>
/// Error code
/// </summary>
public DBSchemaExporterBase.DBSchemaExportErrorCodes ErrorCode => mDBSchemaExporter?.ErrorCode ?? DBSchemaExporterBase.DBSchemaExportErrorCodes.NoError;
/// <summary>
/// Pause status
/// </summary>
public DBSchemaExporterBase.PauseStatusConstants PauseStatus => mDBSchemaExporter?.PauseStatus ?? DBSchemaExporterBase.PauseStatusConstants.Unpaused;
/// <summary>
/// Most recent Status, Warning, or Error message
/// </summary>
public string StatusMessage { get; private set; }
/// <summary>
/// Database export starting event
/// </summary>
public event DBSchemaExporterBase.DBExportStartingHandler DBExportStarting;
/// <summary>
/// Pause status changed event
/// </summary>
public event DBSchemaExporterBase.PauseStatusChangeHandler PauseStatusChange;
/// <summary>
/// Processing complete event
/// </summary>
public event DBSchemaExporterBase.ProgressCompleteHandler ProgressComplete;
/// <summary>
/// Constructor
/// </summary>
/// <param name="options">Options</param>
public DBSchemaExportTool(SchemaExportOptions options) : base(options)
{
mOptions = options;
mDateMatcher = new Regex(@"'\d+/\d+/\d+ \d+:\d+:\d+ [AP]M'", RegexOptions.Compiled | RegexOptions.IgnoreCase);
mVersionExtractor = new Regex(@"version (?<Major>\d+)\.(?<Minor>\d+)");
if (mOptions.PostgreSQL)
{
mDBSchemaExporter = new DBSchemaExporterPostgreSQL(mOptions);
}
else
{
mDBSchemaExporter = new DBSchemaExporterSQLServer(mOptions);
}
RegisterEvents(mDBSchemaExporter);
InitializeLogFile(options);
}
/// <summary>
/// Request that processing be aborted
/// </summary>
/// <remarks>Useful when the scripting is running in another thread</remarks>
public void AbortProcessingNow()
{
mDBSchemaExporter?.AbortProcessingNow();
}
private static void AddToSortedSetIfNew(ISet<string> filteredNames, string value)
{
// filteredNames is a set, and thus we can call .Add() even if it already has the value
if (!string.IsNullOrWhiteSpace(value))
filteredNames.Add(value);
}
private string CheckPlural(int value, string textIfOne, string textIfSeveral)
{
return value == 1 ? textIfOne : textIfSeveral;
}
/// <summary>
/// Connect to the server specified in mOptions
/// </summary>
/// <returns>True if successfully connected, false if a problem</returns>
public bool ConnectToServer()
{
var isValid = ValidateSchemaExporter();
if (!isValid)
return false;
return mDBSchemaExporter.ConnectToServer();
}
/// <summary>
/// Export database schema to the specified directory
/// </summary>
/// <remarks>
/// If CreatedDirectoryForEachDB is true, or if databaseNamesAndOutputPaths contains more than one entry,
/// then each database will be scripted to a subdirectory below the output directory
/// </remarks>
/// <param name="outputDirectoryPath">Output directory path</param>
/// <param name="databaseNamesAndOutputPaths">
/// Dictionary where keys are database names and values will be updated to have the output directory path used
/// </param>
/// <returns>True if success, false if a problem</returns>
/// <exception cref="ArgumentException"></exception>
public bool ExportSchema(string outputDirectoryPath, ref Dictionary<string, string> databaseNamesAndOutputPaths)
{
try
{
if (string.IsNullOrWhiteSpace(outputDirectoryPath))
{
throw new ArgumentException("Output directory cannot be empty", nameof(outputDirectoryPath));
}
if (!Directory.Exists(outputDirectoryPath))
{
// Try to create the missing directory
OnStatusEvent("Creating output directory: " + outputDirectoryPath);
Directory.CreateDirectory(outputDirectoryPath);
}
mOptions.OutputDirectoryPath = outputDirectoryPath;
if (databaseNamesAndOutputPaths.Count > 1)
{
mOptions.CreateDirectoryForEachDB = true;
}
}
catch (Exception ex)
{
OnErrorEvent("Error in ExportSchema configuring the options", ex);
return false;
}
try
{
var startTime = DateTime.UtcNow;
var isValid = ValidateSchemaExporter();
if (!isValid)
return false;
if (mOptions.DisableAutoDataExport)
{
ShowTrace("Auto selection of tables for data export is disabled");
mDBSchemaExporter.TableNamesToAutoExportData.Clear();
mDBSchemaExporter.TableNameRegexToAutoExportData.Clear();
}
else
{
mDBSchemaExporter.StoreTableNamesToAutoExportData(GetTableNamesToAutoExportData(mOptions.PostgreSQL));
mDBSchemaExporter.StoreTableNameRegexToAutoExportData(GetTableRegExToAutoExportData());
}
var databaseList = databaseNamesAndOutputPaths.Keys.ToList();
List<TableDataExportInfo> tablesForDataExport;
if (string.IsNullOrWhiteSpace(mOptions.TableDataToExportFile))
{
tablesForDataExport = new List<TableDataExportInfo>();
}
else
{
tablesForDataExport = LoadTablesForDataExport(mOptions.TableDataToExportFile, out var abortProcessing);
if (abortProcessing)
return false;
}
// Append any tables defined in TableNameFilterSet
foreach (var item in mOptions.TableNameFilterSet)
{
// Skip this table if LoadTablesForDataExport already added it to tablesForDataExport
var skipTable = tablesForDataExport.Any(existingItem => existingItem.SourceTableName.Equals(item, StringComparison.OrdinalIgnoreCase));
if (skipTable)
continue;
var sourceTable = new TableDataExportInfo(item)
{
UsePgInsert = mOptions.PgInsertTableData
};
tablesForDataExport.Add(sourceTable);
}
List<string> tableDataExportOrder;
if (string.IsNullOrWhiteSpace(mOptions.TableDataExportOrderFile))
{
tableDataExportOrder = new List<string>();
}
else
{
tableDataExportOrder = LoadTableDataExportOrderFile(mOptions.TableDataExportOrderFile, out var abortProcessing);
if (abortProcessing)
return false;
}
if (!string.IsNullOrWhiteSpace(mOptions.TableDataColumnMapFile))
{
// This method updates mOptions.ColumnMapForDataExport
LoadColumnMapInfo(mOptions.TableDataColumnMapFile);
}
if (!string.IsNullOrWhiteSpace(mOptions.ExistingSchemaFileToParse))
{
var schemaUpdater = new DBSchemaUpdater(mOptions);
RegisterEvents(schemaUpdater);
var successUpdatingColumnNames = schemaUpdater.UpdateColumnNamesInExistingSchemaFile(
mOptions.ExistingSchemaFileToParse, mOptions, tablesForDataExport, out var updatedSchemaFilePath);
if (!successUpdatingColumnNames)
return false;
var renamedTablesAndViews = new Dictionary<string, string>();
// ReSharper disable once ForeachCanBeConvertedToQueryUsingAnotherGetEnumerator
foreach (var item in tablesForDataExport)
{
if (!string.IsNullOrWhiteSpace(item.TargetTableName) &&
!item.SourceTableName.Equals(item.TargetTableName, StringComparison.Ordinal))
{
renamedTablesAndViews.Add(item.SourceTableName, item.TargetTableName);
}
}
if (renamedTablesAndViews.Count > 0)
{
// Need to rename one or more tables and views
var successUpdatingTableNames = schemaUpdater.UpdateTableAndViewNamesInExistingSchemaFile(updatedSchemaFilePath, renamedTablesAndViews);
if (!successUpdatingTableNames)
return false;
}
}
if (!string.IsNullOrWhiteSpace(mOptions.TableDataColumnFilterFile))
{
var columnFilterSuccess = LoadColumnFiltersForTableData(mOptions.TableDataColumnFilterFile);
if (!columnFilterSuccess)
return false;
}
if (!string.IsNullOrWhiteSpace(mOptions.TableDataDateFilterFile))
{
// This method updates mOptions.ColumnMapForDataExport
var dateFilterSuccess = LoadDateFiltersForTableData(mOptions.TableDataDateFilterFile, tablesForDataExport);
if (!dateFilterSuccess)
return false;
}
var success = ScriptServerAndDBObjectsWork(databaseList, tablesForDataExport, tableDataExportOrder);
// Populate a dictionary with the database names (properly capitalized) and the output directory path used for each
var databaseNameToDirectoryMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var exportedDatabase in mDBSchemaExporter.SchemaOutputDirectories)
{
databaseNameToDirectoryMap.Add(exportedDatabase.Key, exportedDatabase.Value);
}
// Add any other databases in databaseList that are missing (as would be the case if it doesn't exist on the server)
foreach (var databaseName in databaseList)
{
if (!databaseNameToDirectoryMap.ContainsKey(databaseName))
{
databaseNameToDirectoryMap.Add(databaseName, string.Empty);
}
}
// Now update databaseNamesAndOutputPaths to match databaseNameToDirectoryMap (which has properly capitalized database names)
databaseNamesAndOutputPaths = databaseNameToDirectoryMap;
if (mOptions.ShowStats)
{
OnStatusEvent("Exported database schema in {0:0.0} seconds", DateTime.UtcNow.Subtract(startTime).TotalSeconds);
}
return success;
}
catch (Exception ex)
{
OnErrorEvent("Error in ExportSchema configuring dbSchemaExporter", ex);
return false;
}
}
/// <summary>
/// Compare the contents of the two files using a line-by-line comparison
/// </summary>
/// <remarks>
/// Several files are treated specially to ignore changing dates or numbers, in particular:
/// In DBDefinition files, the database size values are ignored
/// In T_Process_Step_Control_Data files, in the Insert Into lines, any date values or text after a date value is ignored
/// In T_Signatures_Data files, in the Insert Into lines, any date values are ignored
/// In PostgreSQL database dump files, the database version and pg_dump versions are ignored if they are a minor version difference
/// </remarks>
/// <param name="baseFile">Base file</param>
/// <param name="comparisonFile">Comparison file</param>
/// <param name="differenceReason">Output parameter: reason for the difference, or DifferenceReasonType.Unchanged if identical</param>
/// <returns>True if the files differ (i.e. if they do not match)</returns>
private bool FilesDiffer(FileInfo baseFile, FileInfo comparisonFile, out DifferenceReasonType differenceReason)
{
try
{
differenceReason = DifferenceReasonType.Unchanged;
if (!baseFile.Exists)
{
return false;
}
if (!comparisonFile.Exists)
{
differenceReason = DifferenceReasonType.NewFile;
return true;
}
var dbDefinitionFile = false;
var dateIgnoreFiles = new SortedSet<string>(StringComparer.OrdinalIgnoreCase)
{
"T_Process_Step_Control_Data.sql",
"T_Signatures_Data.sql",
"T_MTS_Peptide_DBs_Data.sql",
"T_MTS_MT_DBs_Data.sql",
"T_Processor_Tool_Data.sql",
"T_Processor_Tool_Group_Details_Data.sql",
};
var ignoreInsertIntoDates = false;
if (baseFile.Name.StartsWith(DBSchemaExporterSQLServer.DB_DEFINITION_FILE_PREFIX))
{
// DB Definition file; don't worry if file lengths differ
dbDefinitionFile = true;
}
else if (dateIgnoreFiles.Contains(baseFile.Name))
{
// Files where date values are being ignored; don't worry if file lengths differ
OnStatusEvent("Ignoring date values in file " + baseFile.Name);
ignoreInsertIntoDates = true;
}
else if (baseFile.Length != comparisonFile.Length)
{
differenceReason = DifferenceReasonType.Changed;
return true;
}
// Perform a line-by-line comparison
using var baseFileReader = new StreamReader(new FileStream(baseFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
using var comparisonFileReader = new StreamReader(new FileStream(comparisonFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
while (!baseFileReader.EndOfStream)
{
var dataLine = baseFileReader.ReadLine();
if (comparisonFileReader.EndOfStream) continue;
var comparisonLine = comparisonFileReader.ReadLine();
var linesMatch = StringMatch(dataLine, comparisonLine);
if (linesMatch)
{
continue;
}
if (dataLine == null && comparisonLine != null)
{
differenceReason = DifferenceReasonType.Changed;
return true;
}
if (dataLine != null && comparisonLine == null)
{
differenceReason = DifferenceReasonType.Changed;
return true;
}
if (dataLine == null)
{
continue;
}
if (dbDefinitionFile && dataLine.StartsWith("( NAME =") && comparisonLine.StartsWith("( NAME ="))
{
// DBDefinition file, example line:
// NAME = N'Protein_Sequences_Data', FILENAME = N'J:\SQLServerData\Protein_Sequences.mdf' , SIZE = 174425088KB , MAXSIZE = UNLIMITED
// Split on commas
var sourceCols = dataLine.Split(',').ToList();
var comparisonCols = comparisonLine.Split(',').ToList();
if (sourceCols.Count == comparisonCols.Count)
{
linesMatch = true;
for (var dataColumnIndex = 0; dataColumnIndex < sourceCols.Count; dataColumnIndex++)
{
var sourceValue = sourceCols[dataColumnIndex].Trim();
var comparisonValue = comparisonCols[dataColumnIndex].Trim();
if (sourceValue.StartsWith("SIZE") && comparisonValue.StartsWith("SIZE"))
{
// Example: SIZE = 186294784KB vs. SIZE = 174425088KB
// Don't worry if these values differ
}
else if (!StringMatch(sourceValue, comparisonValue))
{
linesMatch = false;
break;
}
}
}
}
if (ignoreInsertIntoDates && dataLine.StartsWith("INSERT INTO ") && comparisonLine.StartsWith("INSERT INTO "))
{
// Data file where we're ignoring dates
// Truncate each of the data lines at the first occurrence of a date
var matchBaseFile = mDateMatcher.Match(dataLine);
var matchComparisonFile = mDateMatcher.Match(comparisonLine);
if (matchBaseFile.Success && matchComparisonFile.Success)
{
dataLine = dataLine.Substring(0, matchBaseFile.Index);
comparisonLine = comparisonLine.Substring(0, matchComparisonFile.Index);
linesMatch = StringMatch(dataLine, comparisonLine);
}
}
if (dataLine.StartsWith("-- Dumped from database version") && comparisonLine.StartsWith("-- Dumped from") ||
dataLine.StartsWith("-- Dumped by pg_dump version") && comparisonLine.StartsWith("-- Dumped by"))
{
if (MajorVersionsMatch(dataLine, comparisonLine))
continue;
}
if (!linesMatch)
{
// Difference found
differenceReason = DifferenceReasonType.Changed;
return true;
}
}
return false;
}
catch (Exception ex)
{
OnErrorEvent("Error in FilesDiffer", ex);
differenceReason = DifferenceReasonType.Changed;
return true;
}
}
/// <summary>
/// Retrieve a list of tables in the given database
/// </summary>
/// <param name="databaseName">Database to query</param>
/// <param name="includeTableRowCounts">When true, determines the row count in each table</param>
/// <param name="includeSystemObjects">When true, also returns system tables</param>
/// <returns>Dictionary where keys are table names and values are row counts (if includeTableRowCounts = true)</returns>
public Dictionary<TableDataExportInfo, long> GetDatabaseTables(string databaseName, bool includeTableRowCounts, bool includeSystemObjects)
{
return mDBSchemaExporter.GetDatabaseTables(databaseName, includeTableRowCounts, includeSystemObjects);
}
/// <summary>
/// Retrieve a list of database names for the current server
/// </summary>
public IEnumerable<string> GetServerDatabases()
{
return mDBSchemaExporter.GetServerDatabases();
}
/// <summary>
/// Look for the table named sourceTableName in tablesForDataExport
/// </summary>
/// <param name="tablesForDataExport">Tables to export data from</param>
/// <param name="sourceTableName">Source table name</param>
/// <param name="tableInfo">Output: tableInfo for the named table, or null if not found</param>
/// <returns>True if found, otherwise false</returns>
public static bool GetTableByName(IEnumerable<TableDataExportInfo> tablesForDataExport, string sourceTableName, out TableDataExportInfo tableInfo)
{
foreach (var candidateTable in tablesForDataExport)
{
if (!candidateTable.SourceTableName.Equals(sourceTableName, StringComparison.OrdinalIgnoreCase))
continue;
tableInfo = candidateTable;
return true;
}
tableInfo = null;
return false;
}
#pragma warning disable VSSpell001 // Spell Check
/// <summary>
/// Get a list of table names to auto-export data
/// </summary>
/// <param name="isPostgreSQL">When true, return PostgreSQL table names</param>
public static SortedSet<string> GetTableNamesToAutoExportData(bool isPostgreSQL)
#pragma warning restore VSSpell001 // Spell Check
{
// Keys are table names
// Values are the equivalent PostgreSQL name (empty strings for table names that will not get ported in the near future, or ever)
var tableNames = new Dictionary<string, string>
{
// ReSharper disable StringLiteralTypo
// MT_Main
{"T_Folder_Paths", string.Empty},
// MT DBs
{"T_Peak_Matching_Defaults", string.Empty},
{"T_Process_Config", string.Empty},
{"T_Process_Config_Parameters", string.Empty},
// MTS_Master
{"T_Quantitation_Defaults", string.Empty},
{"T_MTS_DB_Types", string.Empty},
{"T_MTS_MT_DBs", string.Empty},
{"T_MTS_Peptide_DBs", string.Empty},
{"T_MTS_Servers", string.Empty},
{"T_MyEMSL_Cache_Paths", string.Empty},
// Peptide DB
{"T_Dataset_Scan_Type_Name", string.Empty},
// Prism_IFC
{"T_Match_Methods", string.Empty},
{"T_SP_Categories", string.Empty},
{"T_SP_Column_Direction_Types", string.Empty},
{"T_SP_Glossary", string.Empty},
{"T_SP_List", string.Empty},
// Prism_RPT
{"T_Analysis_Job_Processor_Tools", string.Empty},
{"T_Analysis_Job_Processors", string.Empty},
{"T_Status", string.Empty},
// DMS5
{"T_Dataset_Rating_Name", "public.t_dataset_rating_name"},
{"T_Default_PSM_Job_Types", "public.t_default_psm_job_types"},
{"T_Enzymes", "public.t_enzymes"},
{"T_Instrument_Ops_Role", "public.t_instrument_ops_role"},
{"T_MiscPaths", "public.t_misc_paths"},
{"T_Modification_Types", "public.t_modification_types"},
{"T_MyEMSLState", "public.t_myemsl_state"},
{"T_Predefined_Analysis_Scheduling_Rules", "public.t_predefined_analysis_scheduling_rules"},
{"T_Research_Team_Roles", "public.t_research_team_roles"},
{"T_Residues", "public.t_residues"},
{"T_User_Operations", "public.t_user_operations"},
// Data_Package
{"T_Properties", "dpkg.t_properties"},
{"T_URI_Paths", "public.t_uri_paths"},
// Ontology_Lookup
{"T_Unimod_AminoAcids", "ont.t_unimod_amino_acids"},
{"T_Unimod_Bricks", "ont.t_unimod_bricks"},
{"T_Unimod_Specificity_NL", "ont.t_unimod_specificity_nl"},
// DMS_Pipeline and DMS_Capture
{"T_Automatic_Jobs", "cap.t_automatic_jobs"},
{"T_Default_SP_Params", "cap.t_default_sp_params"},
{"T_Processor_Instrument", "cap.t_processor_instrument"},
{"T_Processor_Tool", "cap.t_processor_tool"},
{"T_Processor_Tool_Group_Details", "cap.t_processor_tool_group_details"},
{"T_Processor_Tool_Groups", "cap.t_processor_tool_groups"},
{"T_Scripts", "cap.t_scripts"},
{"T_Scripts_History", "cap.t_scripts_history"},
{"T_Signatures", "cap.t_signatures"},
{"T_Step_Tools", "cap.t_step_tools"},
// Protein Sequences
{"T_Annotation_Types", "pc.t_annotation_types"},
{"T_Archived_File_Types", "pc.t_archived_file_types"},
{"T_Creation_Option_Keywords", "pc.t_creation_option_keywords"},
{"T_Creation_Option_Values", "pc.t_creation_option_values"},
{"T_Naming_Authorities", "pc.t_naming_authorities"},
{"T_Output_Sequence_Types", "pc.t_output_sequence_types"},
{"T_Protein_Collection_Types", "pc.t_protein_collection_types"},
// dba
{"AlertContacts", string.Empty},
{"AlertSettings", string.Empty},
// pg_timetable
{"timetable.chain", "timetable.chain"},
{"timetable.task", "timetable.task"}
// ReSharper restore StringLiteralTypo
};
var filteredNames = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in tableNames)
{
AddToSortedSetIfNew(filteredNames, isPostgreSQL ? item.Value : item.Key);
}
return filteredNames;
}
/// <summary>
/// Get a list of RegEx expressions for auto-exporting data
/// </summary>
public static SortedSet<string> GetTableRegExToAutoExportData()
{
return new SortedSet<string>
{
".*_?Type_?Name",
".*_?State_?Name",
".*_State",
".*_States"
};
}
private void InitializeLogFile(SchemaExportOptions options)
{
if (!options.LogMessagesToFile)
return;
var baseLogFilePath = SchemaExportOptions.GetLogFilePath(options, "DB_Schema_Export_Tool_log");
LogTools.CreateFileLogger(baseLogFilePath, BaseLogger.LogLevels.DEBUG);
// Move log files over 32 days old into a year-based subdirectory
FileLogger.ArchiveOldLogFilesNow();
ConsoleMsgUtils.ShowDebug("Log file path: " + LogTools.CurrentLogFilePath);
}
/// <summary>
/// Return true if the text in headerName matches one of the supported names for the Table Name column
/// </summary>
/// <param name="headerName">Header name</param>
private bool IsHeaderRowTableColumn(string headerName)
{
headerName = headerName.Trim();
return headerName.Equals("Table", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("TableName", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Table Name", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("Table_Name", StringComparison.OrdinalIgnoreCase) ||
headerName.Equals("SourceTableName", StringComparison.OrdinalIgnoreCase);
}
private void LoadColumnMapInfo(string columnMapFilePath)
{
mOptions.ColumnMapForDataExport.Clear();
var currentTable = string.Empty;
var currentTableColumns = new ColumnMapInfo(string.Empty);
try
{
if (string.IsNullOrWhiteSpace(columnMapFilePath))
{
return;
}
var dataFile = new FileInfo(columnMapFilePath);
if (!dataFile.Exists)
{
Console.WriteLine();
OnStatusEvent("Column Map File not found");
OnWarningEvent("File not found: " + dataFile.FullName);
return;
}
ShowTrace(string.Format("Reading column information from {0}", dataFile.FullName));
var headerLineChecked = false;
using var dataReader = new StreamReader(new FileStream(dataFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
while (!dataReader.EndOfStream)
{
var dataLine = dataReader.ReadLine();
if (string.IsNullOrWhiteSpace(dataLine))
continue;
var lineParts = dataLine.Split('\t');
if (!headerLineChecked)
{
headerLineChecked = true;
if (IsHeaderRowTableColumn(lineParts[0]))
continue;
}
if (lineParts.Length < 3)
{
OnDebugEvent("Skipping line with fewer than three columns: " + dataLine);
continue;
}
var sourceTableName = lineParts[0].Trim();
var sourceColumnName = lineParts[1].Trim();
var targetColumnName = lineParts[2].Trim();
if (!currentTable.Equals(sourceTableName, StringComparison.OrdinalIgnoreCase))
{
if (!mOptions.ColumnMapForDataExport.TryGetValue(sourceTableName, out currentTableColumns))
{
currentTableColumns = new ColumnMapInfo(sourceTableName);
mOptions.ColumnMapForDataExport.Add(sourceTableName, currentTableColumns);
}
currentTable = sourceTableName;
}
currentTableColumns.AddColumn(sourceColumnName, targetColumnName);
}
var tableText = mOptions.ColumnMapForDataExport.Count == 1 ? "table" : "tables";
ShowTrace(string.Format(
"Loaded column information for {0} {1} from {2}",
mOptions.ColumnMapForDataExport.Count, tableText, dataFile.Name));
}
catch (Exception ex)
{
OnErrorEvent("Error in LoadColumnMapInfo", ex);
}
}
private bool LoadColumnFiltersForTableData(string columnFilterFilePath)
{
try
{
if (string.IsNullOrWhiteSpace(columnFilterFilePath))
{
return true;
}
var filterFile = new FileInfo(columnFilterFilePath);
if (!filterFile.Exists)
{
Console.WriteLine();
OnStatusEvent("Table Data Column Filter File not found");
OnWarningEvent("File not found: " + filterFile.FullName);
return false;
}
ShowTrace(string.Format("Reading date filter information from {0}", filterFile.FullName));
var headerLineChecked = false;
var tableCountWithFilters = 0;
using var dataReader = new StreamReader(new FileStream(filterFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
while (!dataReader.EndOfStream)
{
var dataLine = dataReader.ReadLine();
if (string.IsNullOrWhiteSpace(dataLine))
continue;
var lineParts = dataLine.Split('\t');
if (!headerLineChecked)
{
headerLineChecked = true;
if (IsHeaderRowTableColumn(lineParts[0]))
continue;
}
if (lineParts.Length < 2)
{
OnDebugEvent("Skipping line with fewer than two columns: " + dataLine);
continue;
}
var tableName = lineParts[0].Trim();
var columnName = lineParts[1].Trim();
if (mOptions.ColumnMapForDataExport.TryGetValue(tableName, out var currentTableColumns))
{
currentTableColumns.SkipColumn(columnName);
}
else
{
var tableColumns = new ColumnMapInfo(columnName);
tableColumns.SkipColumn(columnName);
mOptions.ColumnMapForDataExport.Add(tableName, tableColumns);
}
tableCountWithFilters++;
}
var tableText = tableCountWithFilters == 1 ? "table" : "tables";
ShowTrace(string.Format(
"Loaded column filters for {0} {1} from {2}",
tableCountWithFilters, tableText, filterFile.Name));
return true;
}
catch (Exception ex)
{
OnErrorEvent("Error in LoadColumnFiltersForTableData", ex);
return false;
}
}
/// <summary>
/// Parse a file that defines date filters to use when exporting table data
/// </summary>
/// <param name="dateFilterFilePath">Date filter file path</param>
/// <param name="tablesForDataExport">Tables to export data from</param>
/// <returns>True if success (or if dateFilterFilePath is an empty string); false if an error</returns>
private bool LoadDateFiltersForTableData(string dateFilterFilePath, ICollection<TableDataExportInfo> tablesForDataExport)
{
try
{
if (string.IsNullOrWhiteSpace(dateFilterFilePath))
{
return true;
}
var filterFile = new FileInfo(dateFilterFilePath);
if (!filterFile.Exists)
{
Console.WriteLine();
OnStatusEvent("Table Data Date Filter File not found");
OnWarningEvent("File not found: " + filterFile.FullName);
return false;
}
ShowTrace(string.Format("Reading date filter information from {0}", filterFile.FullName));
var headerLineChecked = false;
var tableCountWithFilters = 0;
using var dataReader = new StreamReader(new FileStream(filterFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
while (!dataReader.EndOfStream)
{
var dataLine = dataReader.ReadLine();
if (string.IsNullOrWhiteSpace(dataLine))
continue;
var lineParts = dataLine.Split('\t');
if (!headerLineChecked)
{
headerLineChecked = true;
if (IsHeaderRowTableColumn(lineParts[0]))
continue;
}
if (lineParts.Length < 3)
{
OnDebugEvent("Skipping line with fewer than three columns: " + dataLine);
continue;
}
var sourceTableName = lineParts[0].Trim();
var dateColumnName = lineParts[1].Trim();
var minimumDateText = lineParts[2].Trim();
if (!DateTime.TryParse(minimumDateText, out var minimumDate))
{
OnDebugEvent("Date filter for column {0} in table {1} is not a valid date: {2}", dateColumnName, sourceTableName, minimumDateText);
continue;
}
TableDataExportInfo tableInfo;
if (GetTableByName(tablesForDataExport, sourceTableName, out var matchingTableInfo))
{
tableInfo = matchingTableInfo;
}
else
{
tableInfo = new TableDataExportInfo(sourceTableName);
tablesForDataExport.Add(tableInfo);
}
tableInfo.DefineDateFilter(dateColumnName, minimumDate);
tableCountWithFilters++;
}
var tableText = tableCountWithFilters == 1 ? "table" : "tables";
ShowTrace(string.Format(
"Loaded date filters for {0} {1} from {2}",
tableCountWithFilters, tableText, filterFile.Name));
return true;
}
catch (Exception ex)
{
OnErrorEvent("Error in LoadDateFiltersForTableData", ex);
return false;
}
}
private List<string> LoadTableDataExportOrderFile(string dataExportOrderFilePath, out bool abortProcessing)
{
var tableDataExportOrder = new List<string>();
// This SortedSet is used to check for duplicate table names
var tableNames = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
abortProcessing = false;
try
{
if (string.IsNullOrWhiteSpace(dataExportOrderFilePath))
{
return tableDataExportOrder;
}
var dataFile = new FileInfo(dataExportOrderFilePath);
if (!dataFile.Exists)
{
LogWarning("Table Data Export Order File not found: " + dataFile.FullName);
abortProcessing = true;
return tableDataExportOrder;
}
ShowTrace(string.Format("Reading table data export order from file {0}", dataFile.FullName));
// This is not incremented for blank lines or comment lines
var linesRead = 0;
using var dataReader = new StreamReader(new FileStream(dataFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
while (!dataReader.EndOfStream)
{
var dataLine = dataReader.ReadLine();
// Lines that start with # are treated as comment lines
if (string.IsNullOrWhiteSpace(dataLine) || dataLine.Trim().StartsWith("#"))