|
| 1 | +using Dapper; |
| 2 | +using Microsoft.SqlServer.Management.Common; |
| 3 | +using Microsoft.SqlServer.Management.Smo; |
| 4 | +using MongoDB.Driver; |
| 5 | +using NetCoreStack.WebSockets; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.Data; |
| 9 | +using System.Data.SqlClient; |
| 10 | +using System.Diagnostics; |
| 11 | +using System.Linq; |
| 12 | +using System.Threading; |
| 13 | +using System.Threading.Tasks; |
| 14 | + |
| 15 | +namespace DataTransform.Api.Hosting |
| 16 | +{ |
| 17 | + public class SqlTransformTask : ITransformTask |
| 18 | + { |
| 19 | + private readonly SqlDatabase _sourceSqlDatabase; |
| 20 | + private readonly SqlDatabase _targetSqlDatabase; |
| 21 | + private readonly TransformOptions _options; |
| 22 | + private readonly IConnectionManager _connectionManager; |
| 23 | + private readonly CancellationToken _cancellationToken; |
| 24 | + private readonly SqlConnectionStringBuilder _targetSqlConnectionBuilder; |
| 25 | + public List<SqlTransformContext> DbTransformContexts { get; } |
| 26 | + |
| 27 | + public SqlTransformTask(TransformOptions options, IConnectionManager connectionManager, CancellationToken cancellationToken) |
| 28 | + { |
| 29 | + _options = options ?? throw new ArgumentNullException(nameof(options)); |
| 30 | + _connectionManager = connectionManager ?? throw new ArgumentNullException(nameof(connectionManager)); |
| 31 | + _cancellationToken = cancellationToken; |
| 32 | + |
| 33 | + _sourceSqlDatabase = new SqlDatabase(options.SourceConnectionString); |
| 34 | + _targetSqlDatabase = new SqlDatabase(options.TargetConnectionString); |
| 35 | + |
| 36 | + _targetSqlConnectionBuilder = new SqlConnectionStringBuilder(options.TargetConnectionString); |
| 37 | + |
| 38 | + DbTransformContexts = options.CreateSqlTransformContexts(_cancellationToken); |
| 39 | + } |
| 40 | + |
| 41 | + private long GetCount(SqlTransformContext context) |
| 42 | + { |
| 43 | + List<dynamic> sqlItems = new List<dynamic>(); |
| 44 | + using (var connection = _sourceSqlDatabase.CreateConnection()) |
| 45 | + { |
| 46 | + return connection.ExecuteScalar<long>(context.CountSql); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private async Task<int> TokenizeLoopAsync(SqlTransformContext context) |
| 51 | + { |
| 52 | + int take = context.BundleSize; |
| 53 | + object indexId = context.LastIndexId; |
| 54 | + int totalIndices = 0; |
| 55 | + var identityColumnName = context.IdentityColumnName; |
| 56 | + List<string> fields = context.FieldPattern == "*" ? new List<string>(new[] { "*" }) : context.FieldPattern.Split(',').Select(f => f.Trim()).ToList(); |
| 57 | + bool allFields = fields.Contains("*"); |
| 58 | + |
| 59 | + DataTable dataTable = new DataTable(); |
| 60 | + using (var connection = _sourceSqlDatabase.CreateConnection()) |
| 61 | + { |
| 62 | + string targetDatabaseName = _targetSqlConnectionBuilder.InitialCatalog; |
| 63 | + Server server = new Server(new ServerConnection(connection)); |
| 64 | + var database = server.Databases[targetDatabaseName]; |
| 65 | + var tableName = context.TableName; |
| 66 | + if (tableName.Contains(".")) |
| 67 | + { |
| 68 | + tableName = tableName.Split('.').Last(); |
| 69 | + } |
| 70 | + |
| 71 | + var table = database.Tables[tableName]; |
| 72 | + for (int i = 0; i < table.Columns.Count; i++) |
| 73 | + { |
| 74 | + var column = table.Columns[i]; |
| 75 | + var name = column.Name; |
| 76 | + if (allFields) |
| 77 | + { |
| 78 | + var dataColumn = new DataColumn(column.Name, column.DataType.SqlDataType.GetClrType()); |
| 79 | + dataTable.Columns.Add(dataColumn); |
| 80 | + } |
| 81 | + else |
| 82 | + { |
| 83 | + if(fields.Contains(name)) |
| 84 | + { |
| 85 | + var dataColumn = new DataColumn(column.Name, column.DataType.SqlDataType.GetClrType()); |
| 86 | + dataTable.Columns.Add(dataColumn); |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + do |
| 93 | + { |
| 94 | + if (context.CancellationToken.IsCancellationRequested) |
| 95 | + { |
| 96 | + break; |
| 97 | + } |
| 98 | + |
| 99 | + var predicateSql = $"SELECT TOP {take} {context.FieldPattern} FROM {context.TableName} " + |
| 100 | + $"WHERE {identityColumnName} > {indexId} ORDER BY {identityColumnName} ASC"; |
| 101 | + |
| 102 | + using (var connection = _sourceSqlDatabase.CreateConnection()) |
| 103 | + { |
| 104 | + SqlCommand cmd = new SqlCommand(predicateSql, connection); |
| 105 | + SqlDataAdapter da = new SqlDataAdapter(cmd); |
| 106 | + da.Fill(dataTable); |
| 107 | + } |
| 108 | + |
| 109 | + var itemsCount = dataTable.Rows.Count; |
| 110 | + totalIndices += itemsCount; |
| 111 | + if (itemsCount > 0) |
| 112 | + { |
| 113 | + DataRow lastRow = dataTable.Rows[itemsCount - 1]; |
| 114 | + indexId = lastRow[identityColumnName]; |
| 115 | + using (var connection = _targetSqlDatabase.CreateConnection()) |
| 116 | + { |
| 117 | + var tableName = context.TableName; |
| 118 | + SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity); |
| 119 | + sqlBulkCopy.DestinationTableName = tableName; |
| 120 | + sqlBulkCopy.SqlRowsCopied += SqlBulkCopySqlRowsCopied; |
| 121 | + await sqlBulkCopy.WriteToServerAsync(dataTable); |
| 122 | + sqlBulkCopy.Close(); |
| 123 | + dataTable.Clear(); |
| 124 | + } |
| 125 | + |
| 126 | + await _connectionManager.WsLogAsync($"Table: {context.TableName} total: {totalIndices} record(s) progressed."); |
| 127 | + } |
| 128 | + |
| 129 | + if (totalIndices == 0) |
| 130 | + { |
| 131 | + break; |
| 132 | + } |
| 133 | + |
| 134 | + } while (totalIndices < context.Count); |
| 135 | + |
| 136 | + return totalIndices; |
| 137 | + } |
| 138 | + |
| 139 | + private void SqlBulkCopySqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) |
| 140 | + { |
| 141 | + return; |
| 142 | + } |
| 143 | + |
| 144 | + private void EnsureDatabase() |
| 145 | + { |
| 146 | + SqlQueryHelper.EnsureTargetStates(_options); |
| 147 | + } |
| 148 | + |
| 149 | + public async Task InvokeAsync() |
| 150 | + { |
| 151 | + EnsureDatabase(); |
| 152 | + |
| 153 | + Stopwatch sw = new Stopwatch(); |
| 154 | + sw.Start(); |
| 155 | + int totalRecords = 0; |
| 156 | + |
| 157 | + foreach (var context in DbTransformContexts) |
| 158 | + { |
| 159 | + object lastIndexId = SqlQueryHelper.GetLatestId(_targetSqlDatabase, context); |
| 160 | + long count = GetCount(context); |
| 161 | + try |
| 162 | + { |
| 163 | + context.Count = count; |
| 164 | + context.LastIndexId = lastIndexId; |
| 165 | + totalRecords += await TokenizeLoopAsync(context); |
| 166 | + } |
| 167 | + catch (Exception ex) |
| 168 | + { |
| 169 | + await _connectionManager.WsErrorLog(ex); |
| 170 | + } |
| 171 | + finally |
| 172 | + { |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + sw.Stop(); |
| 177 | + await _connectionManager.WsLogAsync(string.Format("Transformed total records: {0} time elapsed: {1}", totalRecords, sw.Elapsed)); |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments