-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathProgram.cs
More file actions
241 lines (222 loc) · 10.1 KB
/
Program.cs
File metadata and controls
241 lines (222 loc) · 10.1 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
/*
* Copyright 2006 Jesse Hersch
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of Jesse Hersch or
* Elsasoft LLC not be used in advertising or publicity
* pertaining to distribution of the software without specific, written
* prior permission. Jesse Hersch and Elsasoft LLC make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* Jesse Hersch and Elsasoft LLC disclaim all warranties with
* regard to this software, including all implied warranties of
* merchantability and fitness, in no event shall Jesse Hersch or
* Elsasoft LLC be liable for any special, indirect or
* consequential damages or any damages whatsoever resulting from loss of
* use, data or profits, whether in an action of contract, negligence or
* other tortious action, arising out of or in connection with the use or
* performance of this software.
*
* Author:
* Jesse Hersch
* Elsasoft LLC
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using ScriptDb;
namespace Elsasoft.ScriptDb
{
class Program
{
static void Main(string[] args)
{
try
{
Parameters parameters;
if (!Parameters.TryParse(args, out parameters))
{
return;
}
var outputDirectory = parameters.OutputDirectory;
var connectionString = BuildConnectionString(parameters);
using (var sc = new SqlConnection(connectionString))
{
if (outputDirectory != null && (outputDirectory.Contains("{server}") || outputDirectory.Contains("{serverclean}")))
{
var serverConnection = new ServerConnection(sc);
var s = new Server(serverConnection);
// Get the proper case for the database name
//var database = s.Databases[sc.Database.ToLowerInvariant()].Name; // If I index into the collection, the .Name property gives me back the same case I put in!
var database = s.Databases.Cast<Database>().Single(d => String.Equals(d.Name, sc.Database, StringComparison.InvariantCultureIgnoreCase)).Name;
outputDirectory = outputDirectory.Replace("{server}", s.Name);
outputDirectory = outputDirectory.Replace("{serverclean}", DatabaseScripter.FixUpFileName(s.Name));
outputDirectory = outputDirectory.Replace("{database}", database);
outputDirectory = outputDirectory.Replace("{databaseclean}", DatabaseScripter.FixUpFileName(database));
}
}
if (outputDirectory != null && !Directory.Exists(outputDirectory))
{
Directory.CreateDirectory(outputDirectory);
}
var ds = new DatabaseScripter();
ds.ConnectionString = connectionString;
ds.Filters = parameters.Filters;
var tableDataFile = parameters.TableDataFilterFile;
if(tableDataFile != null)
{
ds.DatabaseTableDataFilter = ReadTableDataFile(tableDataFile);
}
ds.TableOneFile = parameters.TableOneFile;
ds.ScriptAsCreate = parameters.ScriptAsCreate;
ds.Permissions = parameters.ScriptPermissions;
ds.NoCollation = parameters.NoCollation;
ds.Statistics = parameters.ScriptStatistics;
ds.IncludeDatabase = parameters.ScriptDatabase;
ds.IncludeSystemObjects = parameters.IncludeSystemObjects;
ds.CreateOnly = parameters.ScriptCreateOnly;
ds.OutputFileName = parameters.OutputFileName;
ds.StartCommand = parameters.StartCommand;
ds.PreScriptingCommand = parameters.PreScriptingCommand;
ds.PostScriptingCommand = parameters.PostScriptingCommand;
ds.FinishCommand = parameters.FinishCommand;
var watch = new Stopwatch();
watch.Start();
ds.GenerateScripts(outputDirectory, parameters.ScriptAllDatabases, parameters.Purge, parameters.DataScriptingFormat, parameters.Verbose, parameters.ScriptProperties);
Console.Error.WriteLine("Took {0} ms", watch.ElapsedMilliseconds);
}
catch (Exception e)
{
Console.Error.WriteLine("Exception caught in Main()");
Console.Error.WriteLine("---------------------------------------");
while (e != null)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine(e.GetType().FullName);
Console.Error.WriteLine();
Console.Error.WriteLine(e.StackTrace);
Console.Error.WriteLine("---------------------------------------");
e = e.InnerException;
}
}
}
private static string BuildConnectionString(Parameters parameters)
{
var builder = new SqlConnectionStringBuilder
{
ApplicationName = "ScriptDb",
DataSource = parameters.Server.ToLowerInvariant(),
};
if (!string.IsNullOrWhiteSpace(parameters.Database))
{
builder.InitialCatalog = parameters.Database;
}
if (string.IsNullOrWhiteSpace(parameters.UserName))
{
builder.IntegratedSecurity = true;
}
else
{
builder.UserID = parameters.UserName;
builder.Password = parameters.Password;
}
var connectionString = builder.ToString();
return connectionString;
}
private static Dictionary<string, List<string>> ReadTableDataFile(string tableDataFile)
{
var tablesByDatabase = new Dictionary<string, List<string>>(StringComparer.InvariantCultureIgnoreCase);
var lines = File.ReadAllLines(tableDataFile);
foreach(var line in lines)
{
if(string.IsNullOrEmpty(line) || line.IndexOf(':') == -1)
{
continue;
}
var parts = line.Split(new[] {':'}, 2);
var databaseName = parts[0];
var tableNames = parts[1].Split(',');
tablesByDatabase.Add(databaseName, new List<string>(tableNames));
}
return tablesByDatabase;
}
private static void PrintHelp()
{
Console.Error.WriteLine(
@"ScriptDb.exe usage:
ScriptDb.exe
-con:<ConnectionString>
-outdir:<OutputDirectory>
[-d[:<sql,csv,bcp>]]
[-v]
[-p]
[-table:table1,table2] [-TableOneFile]
[-tableDataFile:<TableDataFileName>]
[-view:view1,view2]
[-sp:sp1,sp2]
[-ScriptAsCreate]
[-ScriptAllDatabases]
[-IncludeDatabase]
[-Permissions]
[-Statistics]
[-NoCollation]
[-CreateOnly]
[-Purge]
[-filename:<FileName> | -]
[-StartCommand:<command>]
[-FinishCommand:<command>]
[-PreScriptingCommand:<command>]
[-PostScriptingCommand:<command>]
-con:<ConnectionString> is a connection string to the db.
-outDir:<OutputDirectory> is where the output scripts are placed.
-d script data to files in formats sql (default), csv, and/or bcp
-v for verbose output.
-p to script extended properties for each object.
-table - comma separated list of tables to script
-TableOneFile - script table definition into one file instad of multiple
-tableDataFile - text file of tables to script
with lines of format databasename:{table1,table2|*}
-view - comma separated list of views to script
-sp - comma separated list of stored procedures to script
-ScriptAsCreate - script stored procedures as CREATE instead ALTER
-ScriptAllDatabases - script all databases on the current server
-IncludeDatabase - Include Database Context in scripted objects
-Permissions - script permissions
-Statistics - script statistics
-NoCollation - skip the collation clause in the script
-CreateOnly - Do not generate DROP statements
-Purge - delete files from output folder before generating scripts
-filename - specify output filename. If file exists,
script will be appended to the end of the file
specify '-' to output to console
Commands to run:
-StartCommand - at startup
-FinishCommand - before shutdown
-PreScriptingCommand - before scripting one database
-PostScriptingCommand - after scripting one database
Commands can include these tokens:
{path} - the output directory
{server} - the SQL server name
{serverclean} - same as above, but safe for use as a filename
{database} - the database name
{databaseclean} - same as above, but safe for use as a filename
The -outDir parameter can also use all these tokens except {path}.
{database} is meaningful in StartCommand, FinishCommand and outDir only when
just a single database is specified in the connection string to be scripted.
Example:
ScriptDb.exe -con:server=(local);database=pubs;trusted_connection=yes -outDir:scripts [-d] [-v] [-p] [-table:table1,table2] [-TableOneFile] [-view:view1,view2] [-sp:sp1,sp2] [-ScriptAsCreate] [-Permissions] [-NoCollation] [-IncludeDatabase] -filename:-
");
}
}
}