Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
279 lines (250 loc) · 9.16 KB
/
Copy pathProgram.cs
File metadata and controls
279 lines (250 loc) · 9.16 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
using System.CommandLine;
using Microsoft.Data.SqlClient;
using Microsoft.Data.Sqlite;
using Siphon.Extensions;
using Siphon.Models;
using Siphon.Services;
var serverOption = new Option<string>("--server", "-s")
{
Description = "SQL Server hostname or instance name"
};
var databaseOption = new Option<string>("--database", "-d")
{
Description = "Source database name"
};
var tableOption = new Option<List<string>>("--table", "-t")
{
Description = "Table names to extract (supports wildcards: * and ?)",
AllowMultipleArgumentsPerToken = true
};
var outputOption = new Option<string>("--output", "-o")
{
Description = "Output SQLite file path"
};
var usernameOption = new Option<string?>("--username", "-u")
{
Description = "SQL authentication username"
};
var passwordOption = new Option<string?>("--password", "-p")
{
Description = "SQL authentication password"
};
var windowsAuthOption = new Option<bool>("--windows-auth", "-w")
{
Description = "Use Windows integrated authentication",
DefaultValueFactory = _ => false
};
var overwriteOption = new Option<bool>("--overwrite")
{
Description = "Overwrite existing SQLite file",
DefaultValueFactory = _ => false
};
var rootCommand = new RootCommand("Siphon - Extract SQL Server tables to SQLite")
{
serverOption,
databaseOption,
tableOption,
outputOption,
usernameOption,
passwordOption,
windowsAuthOption,
overwriteOption
};
rootCommand.SetAction(async parseResult =>
{
var server = parseResult.GetValue(serverOption);
var database = parseResult.GetValue(databaseOption);
var tables = parseResult.GetValue(tableOption);
var output = parseResult.GetValue(outputOption);
var username = parseResult.GetValue(usernameOption);
var password = parseResult.GetValue(passwordOption);
var windowsAuth = parseResult.GetValue(windowsAuthOption);
var overwrite = parseResult.GetValue(overwriteOption);
if (string.IsNullOrEmpty(server))
{
server = ConsoleExtensions.PromptString("SQL Server hostname or instance");
}
if (string.IsNullOrEmpty(database))
{
database = ConsoleExtensions.PromptString("Source database name");
}
if (tables == null || tables.Count == 0)
{
var tablesInput = ConsoleExtensions.PromptString("Table names (comma-separated, schema.table format optional)");
tables = tablesInput
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToList();
}
if (string.IsNullOrEmpty(output))
{
output = ConsoleExtensions.PromptString("Output SQLite file path");
}
if (!windowsAuth && string.IsNullOrEmpty(username))
{
var useWindows = ConsoleExtensions.PromptYesNo("Use Windows authentication?", true);
if (useWindows)
{
windowsAuth = true;
}
else
{
username = ConsoleExtensions.PromptString("SQL authentication username");
password = ConsoleExtensions.PromptPassword("SQL authentication password");
}
}
else if (!windowsAuth && !string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password))
{
password = ConsoleExtensions.PromptPassword("SQL authentication password");
}
var options = new ConnectionOptions
{
Server = server!,
Database = database!,
Tables = tables!,
OutputPath = output!,
Username = username,
Password = password,
UseWindowsAuth = windowsAuth,
Overwrite = overwrite
};
return await RunAsync(options);
});
return await rootCommand.Parse(args).InvokeAsync();
static async Task<int> RunAsync(ConnectionOptions options)
{
ConsoleExtensions.WriteInfo("Siphon - SQL Server to SQLite Extractor");
Console.WriteLine();
ConsoleExtensions.WriteInfo("Connection Settings:");
Console.WriteLine($" Server: {options.Server}");
Console.WriteLine($" Database: {options.Database}");
Console.WriteLine($" Auth: {(options.UseWindowsAuth ? "Windows" : "SQL")}");
Console.WriteLine($" Tables: {string.Join(", ", options.Tables)}");
Console.WriteLine($" Output: {options.OutputPath}");
Console.WriteLine();
try
{
await using var reader = new SqlServerReader(options);
ConsoleExtensions.WriteInfo("Testing SQL Server connection...");
var connected = await reader.TestConnectionAsync();
if (!connected)
{
ConsoleExtensions.WriteError("Failed to connect to SQL Server. Check your connection settings.");
return 1;
}
ConsoleExtensions.WriteSuccess("Connected successfully.");
Console.WriteLine();
var hasWildcards = options.Tables.Any(ExportPreflight.ContainsWildcard);
if (hasWildcards)
ConsoleExtensions.WriteInfo("Discovering tables for wildcard patterns...");
var mappings = await ExportPreflight.BuildAsync(reader, options.Tables, (pattern, count) =>
{
if (count == 0)
{
ConsoleExtensions.WriteWarning($" Pattern '{pattern}' matched no tables");
}
else
{
ConsoleExtensions.WriteSuccess($" Pattern '{pattern}' matched {count} table(s)");
}
});
Console.WriteLine();
using var writer = new SqliteWriter(options.OutputPath);
await writer.InitializeAsync(options.Overwrite);
ConsoleExtensions.WriteSuccess($"Created SQLite database: {options.OutputPath}");
Console.WriteLine();
var result = await TableExportRunner.RunAsync(mappings,
mapping => ExportTableAsync(mapping, reader, writer),
(_, ex) =>
{
ConsoleExtensions.WriteError($" Error: {ex.Message}");
ExportFailureContext.WriteTo(Console.Out, ex);
Console.WriteLine();
});
ConsoleExtensions.WriteInfo("Summary:");
if (hasWildcards)
{
Console.WriteLine($" Patterns specified: {options.Tables.Count}");
Console.WriteLine($" Tables processed: {result.TablesProcessed}");
}
else
{
Console.WriteLine($" Tables processed: {result.TablesProcessed}");
}
if (result.TablesFailed > 0)
Console.WriteLine($" Tables failed: {result.TablesFailed}");
Console.WriteLine($" Total rows: {result.TotalRows:N0}");
Console.WriteLine($" Output file: {Path.GetFullPath(options.OutputPath)}");
Console.WriteLine();
if (result.ExitCode == 0)
ConsoleExtensions.WriteSuccess(result.CompletionMessage);
else
ConsoleExtensions.WriteError(result.CompletionMessage);
return result.ExitCode;
}
catch (InvalidOperationException ex)
{
ConsoleExtensions.WriteError($"Error: {ex.Message}");
ExportFailureContext.WriteTo(Console.Out, ex);
return 1;
}
catch (SqlException ex)
{
ConsoleExtensions.WriteError($"SQL Server error: {ex.Message}");
ExportFailureContext.WriteTo(Console.Out, ex);
return 1;
}
catch (SqliteException ex)
{
ConsoleExtensions.WriteError($"SQLite error: {ex.Message}");
ExportFailureContext.WriteTo(Console.Out, ex);
return 1;
}
catch (Exception ex)
{
ConsoleExtensions.WriteError($"Error: {ex.Message}");
ExportFailureContext.WriteTo(Console.Out, ex);
Console.WriteLine();
Console.WriteLine("Stack trace:");
Console.WriteLine(ex.StackTrace);
return 1;
}
}
static async Task<long> ExportTableAsync(TableMapping mapping, SqlServerReader reader, SqliteWriter writer)
{
var identity = mapping.SourceIdentity!;
ConsoleExtensions.WriteInfo($"Processing table: {mapping.SourceTable}");
Console.WriteLine($" Columns: {mapping.Columns.Count}");
var operation = "Create SQLite table";
try
{
await writer.CreateTableAsync(mapping);
ConsoleExtensions.WriteSuccess($" Created table: {mapping.DestinationTable}");
operation = "Read source row count";
var rowCount = await reader.GetRowCountAsync(identity.SchemaName, identity.TableName);
Console.WriteLine($" Source rows: {rowCount:N0}");
long inserted = 0;
if (rowCount > 0)
{
operation = "Transfer table";
var lastProgress = 0;
inserted = await writer.InsertDataAsync(mapping, reader.ReadTableDataAsync(mapping),
batchSize: 1000, progressCallback: rows =>
{
var progress = (int)Math.Min(rows, rowCount);
if (progress > lastProgress)
{
ConsoleExtensions.WriteProgress(progress, (int)rowCount, identity.TableName);
lastProgress = progress;
}
});
ConsoleExtensions.WriteSuccess($" Transferred {inserted:N0} rows");
}
Console.WriteLine();
return inserted;
}
catch (Exception exception)
{
new ExportFailureContext(mapping.SourceTable, mapping.DestinationTable, operation).Attach(exception);
throw;
}
}