forked from apatel-gpsw/scriptdb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileScripter.cs
More file actions
3170 lines (2806 loc) · 110 KB
/
FileScripter.cs
File metadata and controls
3170 lines (2806 loc) · 110 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
// Copyright 2013 Mercent Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.Broker;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Mercent.SqlServer.Management.IO;
namespace Mercent.SqlServer.Management
{
public class FileScripter
{
private List<ScriptFile> scriptFiles = new List<ScriptFile>();
private HashSet<string> fileSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Set of unique extended property statements (EXEC sys.sp_addextendedproperty).
/// </summary>
/// <remarks>
/// Due to the way we script out tables in multiple files, the extended properties on tables and columns
/// would be included in all 3 table files (the primary .sql, .kci.sql and .fky.sql).
/// To avoid these duplicates, we skip writing out EXEC sys.sp_addextendedproperty statement
/// if it already exists in this set.
/// </remarks>
private HashSet<string> extendedPropertySet = new HashSet<string>();
private bool ignoreFileSetModified = false;
private SortedSet<string> ignoreFileSet = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
private Server server;
private Database database;
private Char allExtraFilesResponseChar = '\0';
private Char allEmptyDirectoriesResponseChar = '\0';
private ScriptUtility utility;
private static readonly string DBName = "$(DBNAME)";
private static readonly HashSet<string> knownExtensions = new HashSet<string>(new [] { ".sql", ".cab", ".dat", ".fmt", ".utxt", ".txt" }, StringComparer.OrdinalIgnoreCase);
private string serverName;
public string ServerName
{
get { return serverName; }
set { serverName = value; }
}
private string databaseName;
public string DatabaseName
{
get { return databaseName; }
set { databaseName = value; }
}
private string outputDirectory = "";
public string OutputDirectory
{
get { return outputDirectory; }
set { outputDirectory = value; }
}
private Encoding encoding = Encoding.Default;
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
private int maxUncompressedFileSize = 100 * 1024 * 1024; // 100 MB;
/// <summary>
/// Gets or sets the max uncompressed file size (in bytes).
/// </summary>
/// <remarks>
/// The default is 100 MB.
/// </remarks>
public int MaxUncompressedFileSize
{
get { return maxUncompressedFileSize; }
set { maxUncompressedFileSize = value; }
}
/// <summary>
/// Force the scripter to continue even when errors or data loss may occur.
/// </summary>
/// <remarks>
/// Set this to <c>true</c> or <c>false</c> when running using automation tools
/// that don't have an user interaction. This avoids prompting the user.
/// This setting affects any errors where the user would normally be given the option
/// to continue or abort (a "prompted" error). It also suppresses prompting the user for what to do with
/// extra files. When set to <c>true</c> the scripter will continue on prompted
/// errors and will delete extra files. When set to <c>false</c> the scripter
/// will abort on prompted errors and keep extra files.
/// </remarks>
public bool? ForceContinue { get; set; }
public bool TargetDataTools { get; set; }
private SqlServerVersion targetServerVersion = SqlServerVersion.Version110;
public SqlServerVersion TargetServerVersion
{
get { return targetServerVersion; }
set { targetServerVersion = value; }
}
public event EventHandler<MessageReceivedEventArgs> ErrorMessageReceived;
public event EventHandler<MessageReceivedEventArgs> ProgressMessageReceived;
public event EventHandler<MessageReceivedEventArgs> OutputMessageReceived;
private void AddIgnoreFiles()
{
string ignoreFileName = Path.Combine(OutputDirectory, "IgnoreFiles.txt");
AddScriptFile("IgnoreFiles.txt", null);
if(File.Exists(ignoreFileName))
{
foreach(string line in File.ReadAllLines(ignoreFileName))
{
string ignoreLine = line.Trim();
ignoreFileSet.Add(ignoreLine);
if(ignoreLine.Contains("*"))
{
string directory = OutputDirectory;
string filePattern = ignoreLine;
string[] parts = ignoreLine.Split('\\', '/');
if(parts.Length > 0)
{
string[] dirs = parts.Take(parts.Length - 1).ToArray();
directory = Path.Combine(OutputDirectory, Path.Combine(dirs));
filePattern = parts.Last();
}
if(Directory.Exists(directory))
{
foreach(string fileName in Directory.EnumerateFiles(directory, filePattern))
{
// Get the path to the fileName relative to the OutputDirectory.
string relativePath = fileName.Substring(OutputDirectory.Length).TrimStart('/', '\\');
AddScriptFile(relativePath, null);
}
}
}
else
AddScriptFile(ignoreLine, null);
}
}
// Ignore the bin and obj directories of an SSDT project.
// It doesn't hurt to always ignore these, so no need
// to wrap this in a check for if(TargetDataTools)...
AddScriptFile("bin", null);
AddScriptFile("obj", null);
}
private void SaveIgnoreFiles()
{
if(ignoreFileSetModified)
{
string ignoreFileName = Path.Combine(OutputDirectory, "IgnoreFiles.txt");
File.WriteAllLines(ignoreFileName, this.ignoreFileSet);
}
}
private void AddScriptFile(ScriptFile scriptFile)
{
if(scriptFile == null)
throw new ArgumentNullException("scriptFile");
this.scriptFiles.Add(scriptFile);
if(scriptFile.FileName != null)
this.fileSet.Add(scriptFile.FileName);
}
private void AddScriptFile(string fileName)
{
AddScriptFile(new ScriptFile(fileName));
}
private void AddScriptFile(string fileName, string command)
{
AddScriptFile(new ScriptFile(fileName, command));
}
private void AddDataFileLoadCheck(string dataFile, string schema, string table, long rowCount)
{
string command =
$@"DECLARE @actualCount int = (SELECT SUM(rows) FROM sys.partitions WHERE object_id = Object_ID('[{schema}].[{table}]') AND index_id IN (0, 1));
IF @actualCount <> {rowCount}
RAISERROR('Error loading data file {dataFile} into [{schema}].[{table}].
The actual number of rows (%i) in the table does not equal the expected row count ({rowCount}).', 11, 1, @actualCount);
GO";
AddScriptFile(null, command);
}
private void AddUnicodeNativeDataFile(string dataFile, string schema, string table, long rowCount)
{
dataFile = CheckCompressFile(dataFile);
string command = String.Format("!!bcp \"[{0}].[{1}].[{2}]\" in \"{3}\" -S $(SQLCMDSERVER) -T -N -k -E", FileScripter.DBName, schema, table, dataFile);
AddScriptFile(dataFile, command);
AddDataFileLoadCheck(dataFile, schema, table, rowCount);
}
private void AddUtf16DataFile(string dataFile, string schema, string table, long rowCount)
{
string formatFile = Path.ChangeExtension(dataFile, ".fmt");
dataFile = CheckCompressFile(dataFile);
string command = String.Format("!!bcp \"[{0}].[{1}].[{2}]\" in \"{3}\" -S $(SQLCMDSERVER) -T -k -E -f \"{4}\"", FileScripter.DBName, schema, table, dataFile, formatFile);
AddScriptFile(dataFile, command);
AddScriptFile(formatFile, null);
AddDataFileLoadCheck(dataFile, schema, table, rowCount);
}
private void AddCodePageDataFile(string dataFile, string schema, string table, long rowCount, string codePage)
{
string formatFile = Path.ChangeExtension(dataFile, ".fmt");
dataFile = CheckCompressFile(dataFile);
string command = String.Format("!!bcp \"[{0}].[{1}].[{2}]\" in \"{3}\" -S $(SQLCMDSERVER) -T -C {4} -k -E -f \"{5}\"", FileScripter.DBName, schema, table, dataFile, codePage, formatFile);
AddScriptFile(dataFile, command);
AddScriptFile(formatFile, null);
AddDataFileLoadCheck(dataFile, schema, table, rowCount);
}
private void AddScriptFileRange(IEnumerable<string> fileNames)
{
foreach(string fileName in fileNames)
AddScriptFile(fileName);
}
private void AddScriptPermission(Database db, StringCollection script, ScriptingOptions options)
{
object preferences = GetScriptingPreferences(options);
typeof(Database).InvokeMember("AddScriptPermission", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, db, new object[] { script, preferences });
}
private void AppendHeaderColumnExpression(TextWriter writer, Column column)
{
string dataTypeAsString = GetDataTypeAsString(column.DataType);
string nonNullValue = GetNonNullLiteral(column.DataType);
if(column.Nullable || nonNullValue == null)
writer.Write("CAST(NULL AS {0})", dataTypeAsString);
else
writer.Write("ISNULL(CAST({0} AS {1}), {0})", nonNullValue, dataTypeAsString);
if(!String.IsNullOrEmpty(column.Collation))
writer.Write(" COLLATE {0}", column.Collation);
writer.Write(" AS {0}", MakeSqlBracket(column.Name));
}
private void AppendHeaderColumnExpressions(TextWriter writer, ColumnCollection columns, string delimiter = ",\r\n\t")
{
string innerDelimiter = null;
foreach(Column column in columns)
{
if(innerDelimiter == null)
innerDelimiter = delimiter;
else
writer.Write(innerDelimiter);
AppendHeaderColumnExpression(writer, column);
}
}
private string CheckCompressFile(string dataFile)
{
string fullDataFile = Path.Combine(this.outputDirectory, dataFile);
FileInfo fileInfo = new FileInfo(fullDataFile);
// If the file doesn't exist or the size is less than the max uncompressed size
// then just return the original file.
if(!fileInfo.Exists || fileInfo.Length < MaxUncompressedFileSize)
return dataFile;
// Compress the file.
string compressedFile = Path.ChangeExtension(dataFile, ".cab");
string fullCompressedFile = Path.Combine(this.outputDirectory, compressedFile);
CompressFile(fullDataFile, fullCompressedFile);
// Delete the original file (we don't want it to be included as part of the source control).
fileInfo.Delete();
// Similarly, when uncompressing the data file we want to use a different extension
// that souce control can be configured to ignore.
string tempDataFile = Path.ChangeExtension(dataFile, ".tmp");
// Add a command to the SQL script to uncompress the file.
string uncompressCommand = String.Format("!!expand \"{0}\" \"{1}\"", compressedFile, tempDataFile);
AddScriptFile(compressedFile, uncompressCommand);
return tempDataFile;
}
private void CompressFile(string source, string destination)
{
// Before compressing the file we set a bogus LastModified date.
// This is an attempt to consistently generate the same .cab file (byte for byte)
// as long as the uncompressed data file is the same.
// It also appears that MakeCab.exe uses the current offset in some date/time calculations
// rather than using the offset appropriate for the file creation date
// (i.e. is daylight savings in effect now vs then).
TimeSpan currentOffset = DateTimeOffset.Now.Offset;
DateTime defaultTime = new DateTimeOffset(2000, 01, 01, 01, 00, 00, currentOffset).UtcDateTime;
File.SetCreationTime(source, defaultTime);
File.SetLastWriteTime(source, defaultTime);
string arguments = String.Format("\"{0}\" \"{1}\"", source, destination);
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "makecab.exe",
Arguments = arguments,
UseShellExecute = false,
}
};
process.Start();
process.WaitForExit();
}
private string ScriptAddToRole(DatabaseRole role, string memberOfRole, ScriptingOptions options)
{
object preferences = GetScriptingPreferences(options);
return (string)typeof(DatabaseRole).InvokeMember("ScriptAddToRole", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, role, new object[] { memberOfRole, preferences });
}
private void ScriptCreate(FileGroup fileGroup, StringCollection script, ScriptingOptions options)
{
object preferences = GetScriptingPreferences(options);
typeof(FileGroup).InvokeMember("ScriptCreate", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, fileGroup, new object[] { script, preferences });
}
private object GetScriptingPreferences(ScriptingOptions options)
{
return typeof(ScriptingOptions).InvokeMember("GetScriptingPreferences", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, options, null);
}
public void Script()
{
VerifyProperties();
if(this.OutputDirectory.Length > 0 && !Directory.Exists(this.OutputDirectory))
Directory.CreateDirectory(this.OutputDirectory);
scriptFiles.Clear();
ignoreFileSet.Clear();
extendedPropertySet.Clear();
ignoreFileSetModified = false;
if(!ForceContinue.HasValue)
{
allEmptyDirectoriesResponseChar = '\0';
allExtraFilesResponseChar = '\0';
}
else if(ForceContinue.Value)
{
allEmptyDirectoriesResponseChar = 'd';
allExtraFilesResponseChar = 'd';
}
else
{
allEmptyDirectoriesResponseChar = 'k';
allExtraFilesResponseChar = 'k';
}
// When using the Server(string serverName) constructor some things
// don't work correct. In particular, some things (such as DatabaseRole.EnumRoles())
// incorrectly query the master database (or whatever the default database is for the login)
// rather than querying the correct database.
// Explicitly setting the database that we want to use avoids this problem.
SqlConnectionInfo connectionInfo = new SqlConnectionInfo();
connectionInfo.ServerName = ServerName;
connectionInfo.DatabaseName = DatabaseName;
ServerConnection connection = new ServerConnection(connectionInfo);
server = new Server(connection);
// We get the database object by name then create a new server object and
// get the database object by id. This is so that the database object can
// be initialized with the Name property having correct character case.
// Even when database names are not case sensitive, the Urn object is.
// In particular, when we compare Urns in the ScriptAssemblies method
// we need the database name to have the correct case.
database = server.Databases[databaseName];
if(database == null)
throw new KeyNotFoundException("The database '" + databaseName + "' was not found.");
// Get the database ID.
int databaseID = database.ID;
// Create a new server connection because the old server connection has
// cached the database object with the name we used to access it.
server = new Server(connection);
// Get the database object by ID.
database = server.Databases.ItemById(databaseID);
// The ScriptUtility instance methods need the context of the database.
// Create a new ScriptUtility instance for this database.
utility = new ScriptUtility(database);
// Set the target server version based on the compatibility level.
targetServerVersion = ScriptUtility.GetSqlServerVersion(database.CompatibilityLevel);
PrefetchObjects();
if(!TargetDataTools)
{
ScriptDatabase();
}
ScriptFileGroups();
ScriptFullTextCatalogs();
ScriptRoles();
ScriptSchemas();
ScriptXmlSchemaCollections();
ScriptServiceBrokerMessageTypes();
ScriptServiceBrokerContracts();
ScriptSynonyms();
ScriptPartitionFunctions();
ScriptPartitionSchemes();
ScriptAssemblies();
ScriptUserDefinedDataTypes();
ScriptUserDefinedTableTypes();
ScriptSequences();
if(!TargetDataTools)
{
ScriptUserDefinedFunctionHeaders();
ScriptViewHeaders();
ScriptStoredProcedureHeaders();
}
ScriptTables();
ScriptServiceBrokerQueues();
ScriptServiceBrokerServices();
ScriptUserDefinedFunctionsAndViews();
ScriptStoredProcedures();
// Here is a list of database objects that currently are not being scripted:
//database.AsymmetricKeys;
//database.Certificates;
//database.ExtendedStoredProcedures;
//database.Rules;
//database.SymmetricKeys;
//database.Triggers;
//database.Users;
if(!TargetDataTools)
{
using(StreamWriter writer = new StreamWriter(Path.Combine(OutputDirectory, "CreateDatabaseObjects.sql"), false, Encoding))
{
writer.WriteLine(":on error exit");
foreach(ScriptFile file in this.scriptFiles.Where(f => f.Command != null))
{
if(file.FileName != null)
writer.WriteLine("PRINT '{0}'", file.FileName);
writer.WriteLine("GO");
writer.WriteLine(file.Command);
}
// If the database is readonly then set it readonly at the very end.
if(database.ReadOnly)
{
writer.WriteLine("PRINT 'Setting database to read-only mode.'");
writer.WriteLine("GO");
writer.WriteLine("ALTER DATABASE [{0}] SET READ_ONLY;", FileScripter.DBName);
}
}
AddScriptFile("CreateDatabaseObjects.sql", null);
}
DirectoryInfo outputDirectoryInfo;
if(OutputDirectory != "")
outputDirectoryInfo = new DirectoryInfo(OutputDirectory);
else
outputDirectoryInfo = new DirectoryInfo(".");
// Prompt the user for what to do with extra files.
// When objects are deleted from the database ensure that the user
// wants to delete the corresponding files. There may also be other
// files in the directory that are not scripted files.
AddIgnoreFiles();
PromptExtraFiles(outputDirectoryInfo, "");
SaveIgnoreFiles();
}
private void VerifyProperties()
{
if(String.IsNullOrWhiteSpace(this.ServerName))
throw new InvalidOperationException("Set the ServerName property before calling the Script() method.");
if(String.IsNullOrWhiteSpace(this.DatabaseName))
throw new InvalidOperationException("Set the DatabaseName property before calling the Script() method.");
}
private void PrefetchObjects()
{
OnProgressMessageReceived("Prefetching objects.");
ScriptingOptions prefetchOptions = new ScriptingOptions();
prefetchOptions.AllowSystemObjects = false;
prefetchOptions.ClusteredIndexes = true;
prefetchOptions.DriChecks = true;
prefetchOptions.DriClustered = true;
prefetchOptions.DriDefaults = true;
prefetchOptions.DriIndexes = true;
prefetchOptions.DriNonClustered = true;
prefetchOptions.DriPrimaryKey = true;
prefetchOptions.DriUniqueKeys = true;
prefetchOptions.FullTextIndexes = true;
prefetchOptions.Indexes = true;
prefetchOptions.NonClusteredIndexes = true;
prefetchOptions.Permissions = true;
prefetchOptions.Statistics = true;
prefetchOptions.Triggers = true;
prefetchOptions.XmlIndexes = true;
prefetchOptions.DriForeignKeys = true;
prefetchOptions.TargetServerVersion = this.TargetServerVersion;
database.PrefetchObjects(typeof(UserDefinedType), prefetchOptions);
OnProgressMessageReceived(null);
PrefetchRoles();
OnProgressMessageReceived(null);
PrefetchFullTextCatalogs();
OnProgressMessageReceived(null);
PrefetchStoredProcedures(prefetchOptions);
OnProgressMessageReceived(null);
// Set the column fields to initialize.
// Used to prefetch view and udf columns.
// We manually prefetch the columns because the Database.PrefetchObjects()
// method does not prefetch all of the column information that we need.
// If we did not prefetch the columns here then it would query
// each column individually when we script out headers.
server.SetDefaultInitFields(typeof(Column),
"DataType",
"DataTypeSchema",
"Length",
"NumericPrecision",
"NumericScale",
"SystemType",
"Collation",
"XmlDocumentConstraint",
"XmlSchemaNamespace",
"XmlSchemaNamespaceSchema");
PrefetchViews(prefetchOptions);
OnProgressMessageReceived(null);
PrefetchUserDefinedFunctions(prefetchOptions);
OnProgressMessageReceived(null);
// Prefetching PartitionFunctions didn't help with SMO 2008.
// Actually it wouldn't script out whether the range was LEFT or RIGHT (PartitionFunction.RangeType).
database.PrefetchObjects(typeof(PartitionScheme), prefetchOptions);
OnProgressMessageReceived(null);
database.PrefetchObjects(typeof(UserDefinedAggregate), prefetchOptions);
OnProgressMessageReceived(null);
PrefetchTables(prefetchOptions);
OnProgressMessageReceived(null);
PrefetchSynonyms();
OnProgressMessageReceived(null);
PrefetchServiceBrokerMessageTypes();
OnProgressMessageReceived(null);
PrefetchServiceBrokerContracts();
OnProgressMessageReceived(null);
PrefetchServiceBrokerQueues();
OnProgressMessageReceived(null);
PrefetchServiceBrokerServices();
OnProgressMessageReceived(null);
PrefetchAssemblies(prefetchOptions);
OnProgressMessageReceived(null);
database.PrefetchObjects(typeof(XmlSchemaCollection), prefetchOptions);
OnProgressMessageReceived(null);
OnProgressMessageReceived(String.Empty);
}
private void PrefetchAssemblies(ScriptingOptions prefetchOptions)
{
// This fetches all non-collection properties of all assemblies at once
// so that when we script out the assemblies it doesn't have to query
// these properties for each assembly.
server.SetDefaultInitFields(typeof(SqlAssembly), true);
database.Assemblies.Refresh();
// In addition, this fetches the permissions for all assemblies at once.
database.PrefetchObjects(typeof(SqlAssembly), prefetchOptions);
// When scripting assemblies it still queries for assembly files and dependencies
// for each assembly.
}
private void PrefetchFullTextCatalogs()
{
server.SetDefaultInitFields
(
typeof(FullTextCatalog),
new string[]
{
"IsAccentSensitive",
"IsDefault"
}
);
database.FullTextCatalogs.Refresh();
}
private void PrefetchRoles()
{
server.SetDefaultInitFields(typeof(DatabaseRole), true);
database.Roles.Refresh();
}
private void PrefetchServiceBrokerContracts()
{
server.SetDefaultInitFields(typeof(ServiceContract), true);
database.ServiceBroker.ServiceContracts.Refresh();
}
private void PrefetchServiceBrokerMessageTypes()
{
server.SetDefaultInitFields(typeof(MessageType), true);
database.ServiceBroker.MessageTypes.Refresh();
}
private void PrefetchServiceBrokerQueues()
{
server.SetDefaultInitFields(typeof(ServiceQueue), true);
database.ServiceBroker.Queues.Refresh();
}
private void PrefetchServiceBrokerServices()
{
server.SetDefaultInitFields(typeof(BrokerService), true);
database.ServiceBroker.Services.Refresh();
}
private void PrefetchStoredProcedures(ScriptingOptions prefetchOptions)
{
server.SetDefaultInitFields(typeof(StoredProcedureParameter), true);
server.SetDefaultInitFields(typeof(StoredProcedure), true);
foreach(StoredProcedure procedure in database.StoredProcedures)
{
if(!procedure.IsSystemObject && procedure.ImplementationType == ImplementationType.SqlClr)
{
procedure.Parameters.Refresh();
}
}
database.PrefetchObjects(typeof(StoredProcedure), prefetchOptions);
string sqlCommand = "SELECT o.[object_id], parameter_id, default_value\r\n"
+ "FROM " + MakeSqlBracket(database.Name) + ".sys.objects AS o\r\n"
+ "\tJOIN " + MakeSqlBracket(database.Name) + ".sys.parameters AS p ON p.[object_id] = o.[object_id]\r\n"
+ "WHERE o.is_ms_shipped = 0 AND o.type = 'PC' AND p.has_default_value = 1\r\n"
+ "ORDER BY o.[object_id]";
StoredProcedureCollection procedures = database.StoredProcedures;
using(SqlDataReader reader = ExecuteReader(sqlCommand))
{
StoredProcedure procedure = null;
while(reader.Read())
{
int objectId = reader.GetInt32(0);
int parameterId = reader.GetInt32(1);
object sqlValue = reader.GetSqlValue(2);
if(procedure == null || procedure.ID != objectId)
procedure = procedures.ItemById(objectId);
StoredProcedureParameter parameter = procedure.Parameters.ItemById(parameterId);
DataType dataType = parameter.DataType;
SqlDataType sqlDataType;
if(dataType.SqlDataType == SqlDataType.UserDefinedDataType)
sqlDataType = GetBaseSqlDataType(dataType);
else
sqlDataType = dataType.SqlDataType;
parameter.DefaultValue = GetSqlLiteral(sqlValue, sqlDataType);
}
}
}
private void PrefetchSynonyms()
{
server.SetDefaultInitFields(typeof(Synonym), true);
database.Synonyms.Refresh();
}
private void PrefetchTables(ScriptingOptions prefetchOptions)
{
server.SetDefaultInitFields(typeof(Table), "RowCount");
database.Tables.Refresh();
database.PrefetchObjects(typeof(Table), prefetchOptions);
}
private void PrefetchUserDefinedFunctions(ScriptingOptions prefetchOptions)
{
server.SetDefaultInitFields(typeof(UserDefinedFunctionParameter), true);
server.SetDefaultInitFields(typeof(UserDefinedFunction), true);
// Prefetch the columns for each non-system, non-scalar function.
// Prefetch the parameters for clr functions.
foreach(UserDefinedFunction function in database.UserDefinedFunctions)
{
if(!function.IsSystemObject)
{
// Prefetch the columns for scripting out udf headers
if(function.FunctionType != UserDefinedFunctionType.Scalar)
function.Columns.Refresh();
// Prefetch the parameters for scripting out clr functions
if(function.ImplementationType == ImplementationType.SqlClr)
function.Parameters.Refresh();
}
}
database.PrefetchObjects(typeof(UserDefinedFunction), prefetchOptions);
string sqlCommand = "SELECT o.[object_id], parameter_id, default_value\r\n"
+ "FROM " + MakeSqlBracket(database.Name) + ".sys.objects AS o\r\n"
+ "\tJOIN " + MakeSqlBracket(database.Name) + ".sys.parameters AS p ON p.[object_id] = o.[object_id]\r\n"
+ "WHERE o.is_ms_shipped = 0 AND o.type IN ('FN', 'FS', 'FT') AND p.has_default_value = 1\r\n"
+ "ORDER BY o.[object_id]";
UserDefinedFunctionCollection functions = database.UserDefinedFunctions;
using(SqlDataReader reader = ExecuteReader(sqlCommand))
{
UserDefinedFunction function = null;
while(reader.Read())
{
int objectId = reader.GetInt32(0);
int parameterId = reader.GetInt32(1);
object sqlValue = reader.GetSqlValue(2);
if(function == null || function.ID != objectId)
function = functions.ItemById(objectId);
UserDefinedFunctionParameter parameter = function.Parameters.ItemById(parameterId);
DataType dataType = parameter.DataType;
SqlDataType sqlDataType;
if(dataType.SqlDataType == SqlDataType.UserDefinedDataType)
sqlDataType = GetBaseSqlDataType(dataType);
else
sqlDataType = dataType.SqlDataType;
parameter.DefaultValue = GetSqlLiteral(sqlValue, sqlDataType);
}
}
}
private void PrefetchViews(ScriptingOptions prefetchOptions)
{
server.SetDefaultInitFields(typeof(View),
"IsSchemaBound",
"IsSystemObject");
// Prefetch the columns for each non-system view
foreach(View view in database.Views)
{
if(!view.IsSystemObject)
{
view.Columns.Refresh();
}
}
database.PrefetchObjects(typeof(View), prefetchOptions);
}
private void PromptExtraFiles(DirectoryInfo dirInfo, string relativeDir)
{
string relativeName;
foreach(FileInfo fileInfo in dirInfo.GetFiles())
{
// Skip over the file if it isn't a known extension (.sql, .dat, .utxt, .fmt).
if(!knownExtensions.Contains(fileInfo.Extension))
continue;
relativeName = Path.Combine(relativeDir, fileInfo.Name);
if(!fileSet.Contains(relativeName))
{
Console.WriteLine("Extra file: {0}", relativeName);
char responseChar = this.allExtraFilesResponseChar;
if(allExtraFilesResponseChar == '\0')
{
Console.WriteLine("Keep, delete, or ignore this file? For all extra files? (press k, d, i, or a)");
ConsoleKeyInfo key = Console.ReadKey(true);
responseChar = key.KeyChar;
if(responseChar == 'a')
{
Console.WriteLine("Keep, delete, or ignore all remaining extra files? (press k, d, i)");
key = Console.ReadKey(true);
responseChar = key.KeyChar;
// Only accept the response char if it is k, d, or i.
// Other characters are ignored, which is the same as keeping this file.
if(responseChar == 'k' || responseChar == 'd' || responseChar == 'i')
allExtraFilesResponseChar = responseChar;
}
}
if(responseChar == 'd')
{
try
{
fileInfo.Delete();
Console.WriteLine("Deleted file.");
}
catch(Exception ex)
{
Console.WriteLine("Delete failed. {0}: {1}", ex.GetType().Name, ex.Message);
}
}
else if(responseChar == 'i')
{
ignoreFileSetModified = true;
ignoreFileSet.Add(relativeName);
}
}
}
foreach(DirectoryInfo subDirInfo in dirInfo.GetDirectories())
{
string relativeSubDir = Path.Combine(relativeDir, subDirInfo.Name);
// Skip the directory if it is hidden or in the file set (because it was in the ignore list).
if(subDirInfo.Attributes.HasFlag(FileAttributes.Hidden) || fileSet.Contains(relativeSubDir))
continue;
// If the directory is not empty then recursively call PromptExtraFiles...
if(subDirInfo.EnumerateFileSystemInfos().Any())
PromptExtraFiles(subDirInfo, relativeSubDir);
else
{
// If the directory is empty, prompt about deleting it.
Console.WriteLine("Empty directory: {0}", relativeSubDir);
char responseChar = this.allEmptyDirectoriesResponseChar;
if(allEmptyDirectoriesResponseChar == '\0')
{
Console.WriteLine("Keep, delete, or ignore this directory? For all empty directories? (press k, d, i, or a)");
ConsoleKeyInfo key = Console.ReadKey(true);
responseChar = key.KeyChar;
if(responseChar == 'a')
{
Console.WriteLine("Keep, delete, or ignore all remaining empty directories? (press k, d, i)");
key = Console.ReadKey(true);
responseChar = key.KeyChar;
// Only accept the response char if it is k, d, or i.
// Other characters are ignored, which is the same as keeping this directory.
if(responseChar == 'k' || responseChar == 'd' || responseChar == 'i')
allEmptyDirectoriesResponseChar = responseChar;
}
}
if(responseChar == 'd')
{
try
{
subDirInfo.Delete();
Console.WriteLine("Deleted directory.");
}
catch(Exception ex)
{
Console.WriteLine("Delete failed. {0}: {1}", ex.GetType().Name, ex.Message);
}
}
else if(responseChar == 'i')
{
ignoreFileSetModified = true;
ignoreFileSet.Add(relativeSubDir);
}
}
}
}
private void ScriptAssemblies()
{
// Check to make sure that the database contains at least one assembly
// that is not a system object.
bool hasNonSystemAssembly = false;
foreach(SqlAssembly assembly in database.Assemblies)
{
if(!assembly.IsSystemObject)
{
hasNonSystemAssembly = true;
break;
}
}
if(!hasNonSystemAssembly)
return;
ScriptingOptions options = new ScriptingOptions();
options.ExtendedProperties = true;
options.Permissions = true;
options.TargetServerVersion = this.TargetServerVersion;
Scripter scripter = new Scripter(server);
scripter.Options = options;
scripter.PrefetchObjects = false;
SqlExecutionModes previousModes = server.ConnectionContext.SqlExecutionModes;
try
{
server.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql;
string relativeDir = "Assemblies";
string dir = Path.Combine(OutputDirectory, relativeDir);
if(!Directory.Exists(dir))
Directory.CreateDirectory(dir);
UrnCollection assemblies = new UrnCollection();
SqlSmoObject[] objects = new SqlSmoObject[1];
DependencyTree tree;
foreach(SqlAssembly assembly in database.Assemblies)
{
// Skip system objects.
if(assembly.IsSystemObject)
continue;
string fileName = Path.Combine(relativeDir, assembly.Name + ".sql");
string outputPath = Path.Combine(OutputDirectory, fileName);
objects[0] = assembly;
OnProgressMessageReceived(fileName);
StringCollection script = script = scripter.ScriptWithList(objects);
// SSDT projects should reference assemblies by using an assembly or project reference,
// so we don't want to include the CREATE ASSEMBLY statement.
// I tried setting ScriptingOptions.PrimaryObject = false, but that didn't prevent
// the Scripter from scripting the CREATE ASSEMBLY statement.
// So we remove the first batch in the script.
// This may be the only batch in the script, but the script may also include permissions
// on the assembly.
if(TargetDataTools)
script.RemoveAt(0);
WriteBatches(outputPath, script);
// Check if the assembly is visible.
// If the assembly is visible then it can have CLR objects.
// If the assembly is not visible then it is intended to be called from
// other assemblies.
if(assembly.IsVisible)
{
tree = scripter.DiscoverDependencies(objects, DependencyType.Children);
// tree.FirstChild is the assembly and tree.FirstChild.FirstChild is the first dependent object
if(tree.HasChildNodes && tree.FirstChild.HasChildNodes)
{
IDictionary<string, Urn> sortedChildren = new SortedDictionary<string, Urn>(StringComparer.InvariantCultureIgnoreCase);
// loop through the children, which should be the SQL CLR objects such
// as user defined functions, user defined types, etc.
for(DependencyTreeNode child = tree.FirstChild.FirstChild; child != null; child = child.NextSibling)
{
// Make sure the object isn't another SqlAssembly that depends on this assembly
// because we don't want to include the script for the other assembly in the
// script for this assembly
if(child.Urn.Type != "SqlAssembly")
{
sortedChildren.Add(child.Urn.Value, child.Urn);
}
}
// script out the dependent objects, appending to the file
Urn[] children = new Urn[sortedChildren.Count];
sortedChildren.Values.CopyTo(children, 0);
script = scripter.ScriptWithList(children);
WriteBatches(outputPath, true, script);
}
}
else if(!TargetDataTools)
{
// The create script doesn't include VISIBILITY (this appears
// to be a bug in SQL SMO) here we reset it and call Alter()
// to generate an alter statement.
// We don't include this for SSDT projects because visibility is set as
// a property of the assembly reference.
assembly.IsVisible = true;
assembly.IsVisible = false;
server.ConnectionContext.CapturedSql.Clear();
assembly.Alter();
StringCollection batches = server.ConnectionContext.CapturedSql.Text;
// Remove the first string, which is a USE statement to set the database context
batches.RemoveAt(0);
WriteBatches(outputPath, true, batches);
}
assemblies.Add(assembly.Urn);
}
// Determine proper order of assemblies based on dependencies
DependencyWalker walker = new DependencyWalker(server);
tree = walker.DiscoverDependencies(assemblies, DependencyType.Parents);
DependencyCollection dependencies = walker.WalkDependencies(tree);
foreach(DependencyCollectionNode node in dependencies)
{
// Check that the dependency is an assembly that we have scripted out
if(assemblies.Contains(node.Urn) && node.Urn.Type == "SqlAssembly")
{
string fileName = node.Urn.GetAttribute("Name") + ".sql";
AddScriptFile(Path.Combine(relativeDir, fileName));
}
}
}
finally
{
server.ConnectionContext.SqlExecutionModes = previousModes;