commit 1e3504707a207b2fba1c893e17cc5cbe3bea1dac Author: chenshoulin Date: Wed Nov 18 21:21:06 2026 +0800 初始提交:数据库数据对比工具 Co-authored-by: Cursor diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..731ea72 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +bin/ +obj/ +.vs/ +publish/ +publish.zip +TestResults/ +*.user +*.suo diff --git a/DataCompare.sln b/DataCompare.sln new file mode 100644 index 0000000..7036210 --- /dev/null +++ b/DataCompare.sln @@ -0,0 +1,84 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataCompare.Core", "src\DataCompare.Core\DataCompare.Core.csproj", "{1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataCompare.Data", "src\DataCompare.Data\DataCompare.Data.csproj", "{1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataCompare.App", "src\DataCompare.App\DataCompare.App.csproj", "{B1B9C135-E50F-4935-91CC-B3B278028653}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataCompare.Tests", "src\DataCompare.Tests\DataCompare.Tests.csproj", "{0CAFFF6D-6862-43E6-B392-B2108DD43E6D}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|x64.ActiveCfg = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|x64.Build.0 = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|x86.ActiveCfg = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Debug|x86.Build.0 = Debug|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|Any CPU.Build.0 = Release|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|x64.ActiveCfg = Release|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|x64.Build.0 = Release|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|x86.ActiveCfg = Release|Any CPU + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556}.Release|x86.Build.0 = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|x64.ActiveCfg = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|x64.Build.0 = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Debug|x86.Build.0 = Debug|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|Any CPU.Build.0 = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|x64.ActiveCfg = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|x64.Build.0 = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|x86.ActiveCfg = Release|Any CPU + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9}.Release|x86.Build.0 = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|x64.ActiveCfg = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|x64.Build.0 = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|x86.ActiveCfg = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Debug|x86.Build.0 = Debug|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|Any CPU.Build.0 = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|x64.ActiveCfg = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|x64.Build.0 = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|x86.ActiveCfg = Release|Any CPU + {B1B9C135-E50F-4935-91CC-B3B278028653}.Release|x86.Build.0 = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|x64.ActiveCfg = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|x64.Build.0 = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|x86.ActiveCfg = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Debug|x86.Build.0 = Debug|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|Any CPU.Build.0 = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|x64.ActiveCfg = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|x64.Build.0 = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|x86.ActiveCfg = Release|Any CPU + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {1B0B1B8F-7F3A-4D37-8032-9D00FDA37556} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {1C9E847F-CCBC-45F1-84ED-5CF66AD981D9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {B1B9C135-E50F-4935-91CC-B3B278028653} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {0CAFFF6D-6862-43E6-B392-B2108DD43E6D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + EndGlobalSection +EndGlobal diff --git a/src/DataCompare.App/AppIcon.cs b/src/DataCompare.App/AppIcon.cs new file mode 100644 index 0000000..7e6aaa6 --- /dev/null +++ b/src/DataCompare.App/AppIcon.cs @@ -0,0 +1,47 @@ +using System; +using System.Drawing; +using System.IO; +using System.Reflection; +using System.Windows.Forms; + +namespace DataCompare.App +{ + static class AppIcon + { + static readonly Icon Shared = Load(); + + public static void Apply(Form form) + { + if (Shared != null) + form.Icon = Shared; + } + + static Icon Load() + { + var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DataCompare.App.app.ico"); + if (stream != null) + { + try + { + using (stream) + return new Icon(stream); + } + catch (ArgumentException) + { + } + } + + try + { + var path = Application.ExecutablePath; + if (!string.IsNullOrEmpty(path) && File.Exists(path)) + return Icon.ExtractAssociatedIcon(path); + } + catch (Exception) + { + } + + return null; + } + } +} diff --git a/src/DataCompare.App/ConnectionEditForm.cs b/src/DataCompare.App/ConnectionEditForm.cs new file mode 100644 index 0000000..0ab62b1 --- /dev/null +++ b/src/DataCompare.App/ConnectionEditForm.cs @@ -0,0 +1,244 @@ +using System; +using System.Drawing; +using System.Globalization; +using System.Windows.Forms; +using DataCompare.Core; +using DataCompare.Data; + +namespace DataCompare.App +{ + sealed class ConnectionEditForm : Form + { + readonly ConnectionProfile _existing; + readonly TextBox _name = new TextBox(); + readonly ComboBox _kind = new ComboBox(); + readonly TextBox _host = new TextBox(); + readonly TextBox _port = new TextBox(); + readonly TextBox _database = new TextBox(); + readonly TextBox _user = new TextBox(); + readonly TextBox _password = new TextBox(); + readonly TextBox _schema = new TextBox(); + readonly TextBox _extra = new TextBox(); + int _defaultPort; + + public ConnectionProfile Profile { get; private set; } + + public ConnectionEditForm(ConnectionProfile existing) + { + AppIcon.Apply(this); + _existing = existing; + Text = existing == null ? "新建连接" : "编辑连接"; + FormBorderStyle = FormBorderStyle.FixedDialog; + StartPosition = FormStartPosition.CenterParent; + MinimizeBox = false; + MaximizeBox = false; + ShowInTaskbar = false; + Font = MainForm.UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + + _kind.DropDownStyle = ComboBoxStyle.DropDownList; + _kind.Items.AddRange(new object[] { "SQL Server", "MySQL", "GaussDB" }); + _password.UseSystemPasswordChar = true; + _kind.SelectedIndexChanged += delegate { OnKindChanged(); }; + + int rowHeight = Math.Max(UiMetrics.Px(32), _name.PreferredHeight + UiMetrics.Px(10)); + int labelWidth = UiMetrics.Fit("附加参数", Font, 12); + int clientWidth = labelWidth + UiMetrics.Px(340); + var hintText = "Schema 可留空。MySQL 留空时使用当前数据库。\r\n附加参数会拼到连接串末尾,例如 Ssl Mode=Require。编辑时密码留空表示不修改。"; + int hintWidth = clientWidth - UiMetrics.Px(28); + var hintSize = TextRenderer.MeasureText(hintText, Font, new Size(hintWidth, int.MaxValue), TextFormatFlags.WordBreak); + int buttonHeight = TextRenderer.MeasureText("保存", Font).Height + UiMetrics.Px(14); + int hintRow = hintSize.Height + UiMetrics.Px(12); + int buttonRow = buttonHeight + UiMetrics.Px(12); + int clientHeight = UiMetrics.Px(12) + UiMetrics.Px(10) + (rowHeight * 9) + hintRow + buttonRow; + ClientSize = new Size(clientWidth, clientHeight); + + var layout = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = 2, + Padding = new Padding(UiMetrics.Px(14), UiMetrics.Px(12), UiMetrics.Px(14), UiMetrics.Px(10)), + AutoScroll = false + }; + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, labelWidth)); + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + string[] labels = + { + "名称", "类型", "主机", "端口", "数据库", "用户名", "密码", "Schema", "附加参数" + }; + Control[] editors = + { + _name, _kind, _host, _port, _database, _user, _password, _schema, _extra + }; + for (int i = 0; i < labels.Length; i++) + { + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, rowHeight)); + layout.Controls.Add(new Label + { + Text = labels[i], + TextAlign = ContentAlignment.MiddleLeft, + Dock = DockStyle.Fill, + AutoEllipsis = false, + UseMnemonic = false + }, 0, i); + editors[i].Dock = DockStyle.Fill; + editors[i].Margin = new Padding(0, UiMetrics.Px(4), 0, UiMetrics.Px(4)); + layout.Controls.Add(editors[i], 1, i); + } + + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, hintRow)); + var hint = new Label + { + Text = hintText, + Dock = DockStyle.Fill, + AutoSize = false, + ForeColor = Color.FromArgb(90, 90, 90), + UseMnemonic = false + }; + layout.SetColumnSpan(hint, 2); + layout.Controls.Add(hint, 0, labels.Length); + + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, buttonRow)); + var buttons = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.RightToLeft, + WrapContents = false, + Padding = new Padding(0, UiMetrics.Px(4), 0, 0) + }; + var ok = DialogButton("保存"); + var cancel = DialogButton("取消"); + var test = DialogButton("测试连接"); + ok.DialogResult = DialogResult.None; + cancel.DialogResult = DialogResult.Cancel; + ok.Click += OnSave; + test.Click += OnTest; + buttons.Controls.Add(ok); + buttons.Controls.Add(cancel); + buttons.Controls.Add(test); + layout.SetColumnSpan(buttons, 2); + layout.Controls.Add(buttons, 0, labels.Length + 1); + + Controls.Add(layout); + AcceptButton = ok; + CancelButton = cancel; + + if (existing == null) + { + _kind.SelectedIndex = 0; + _port.Text = "1433"; + _defaultPort = 1433; + } + else + { + _name.Text = existing.Name; + _kind.SelectedIndex = (int)existing.Kind; + _host.Text = existing.Host; + _port.Text = existing.Port.ToString(CultureInfo.InvariantCulture); + _database.Text = existing.Database; + _user.Text = existing.Username; + _schema.Text = existing.Schema; + _extra.Text = existing.Extra; + _defaultPort = DbKindInfo.DefaultPort(existing.Kind); + } + } + + Button DialogButton(string text) + { + var size = TextRenderer.MeasureText(text, Font); + return new Button + { + Text = text, + AutoSize = false, + Width = size.Width + UiMetrics.Px(28), + Height = size.Height + UiMetrics.Px(12), + Margin = new Padding(UiMetrics.Px(8), 0, 0, 0), + UseVisualStyleBackColor = true + }; + } + + void OnKindChanged() + { + int port; + int.TryParse(_port.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out port); + int next = DbKindInfo.DefaultPort(SelectedKind()); + if (port == 0 || port == _defaultPort) + _port.Text = next.ToString(CultureInfo.InvariantCulture); + _defaultPort = next; + } + + DbKind SelectedKind() + { + if (_kind.SelectedIndex < 0) + return DbKind.SqlServer; + return (DbKind)_kind.SelectedIndex; + } + + ConnectionProfile ReadProfile() + { + var name = _name.Text.Trim(); + if (name.Length == 0) + throw new InvalidOperationException("请填写连接名称。"); + var host = _host.Text.Trim(); + if (host.Length == 0) + throw new InvalidOperationException("请填写主机。"); + int port; + if (!int.TryParse(_port.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out port) || port < 1 || port > 65535) + throw new InvalidOperationException("端口必须是 1 到 65535。"); + var database = _database.Text.Trim(); + if (database.Length == 0) + throw new InvalidOperationException("请填写数据库名。"); + var password = _password.Text; + if (password.Length == 0 && _existing != null) + password = _existing.Password ?? ""; + return new ConnectionProfile + { + Id = _existing == null ? Guid.NewGuid() : _existing.Id, + Name = name, + Kind = SelectedKind(), + Host = host, + Port = port, + Database = database, + Username = _user.Text.Trim(), + Password = password, + Schema = _schema.Text.Trim(), + Extra = _extra.Text.Trim() + }; + } + + void OnSave(object sender, EventArgs e) + { + try + { + Profile = ReadProfile(); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "无法保存", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + + void OnTest(object sender, EventArgs e) + { + try + { + UseWaitCursor = true; + var profile = ReadProfile(); + using (var source = DataSourceFactory.Create(profile)) + source.Test(); + MessageBox.Show(this, "连接成功。", "测试连接", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + finally + { + UseWaitCursor = false; + } + } + } +} diff --git a/src/DataCompare.App/ConnectionStore.cs b/src/DataCompare.App/ConnectionStore.cs new file mode 100644 index 0000000..cd3b923 --- /dev/null +++ b/src/DataCompare.App/ConnectionStore.cs @@ -0,0 +1,176 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using DataCompare.Core; + +namespace DataCompare.App +{ + public sealed class ConnectionDto + { + public string Id { get; set; } + public string Name { get; set; } + public int Kind { get; set; } + public string Host { get; set; } + public int Port { get; set; } + public string Database { get; set; } + public string Username { get; set; } + public string PasswordProtected { get; set; } + public string Schema { get; set; } + public string Extra { get; set; } + } + + public sealed class StoreFile + { + public int Version { get; set; } + public List Connections { get; set; } + } + + static class ConnectionStore + { + static readonly byte[] Entropy = Encoding.UTF8.GetBytes("DataCompare.v1"); + static readonly JsonSerializerOptions StoreJson = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }; + + public static string FilePath + { + get + { + return Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "DataCompare", + "connections.json"); + } + } + + public static List Load(out int unreadablePasswords) + { + unreadablePasswords = 0; + var list = new List(); + if (!File.Exists(FilePath)) + return list; + + StoreFile file; + try + { + var json = File.ReadAllText(FilePath, Encoding.UTF8); + file = JsonSerializer.Deserialize(json, StoreJson); + } + catch (Exception) + { + var bad = FilePath + ".bad"; + File.Copy(FilePath, bad, true); + throw new InvalidOperationException("连接配置无法读取,已保留为 " + bad); + } + + if (file == null || file.Connections == null) + return list; + + for (int i = 0; i < file.Connections.Count; i++) + { + var dto = file.Connections[i]; + if (dto == null) + continue; + Guid id; + if (!Guid.TryParse(dto.Id, out id)) + id = Guid.NewGuid(); + var password = ""; + if (!string.IsNullOrEmpty(dto.PasswordProtected)) + { + try + { + password = Unprotect(dto.PasswordProtected); + } + catch (CryptographicException) + { + unreadablePasswords++; + } + } + list.Add(new ConnectionProfile + { + Id = id, + Name = dto.Name ?? "", + Kind = Enum.IsDefined(typeof(DbKind), dto.Kind) ? (DbKind)dto.Kind : DbKind.SqlServer, + Host = dto.Host ?? "", + Port = dto.Port, + Database = dto.Database ?? "", + Username = dto.Username ?? "", + Password = password, + Schema = dto.Schema ?? "", + Extra = dto.Extra ?? "" + }); + } + return list; + } + + public static void Save(IList profiles) + { + var dtos = new List(); + for (int i = 0; i < profiles.Count; i++) + { + var profile = profiles[i]; + dtos.Add(new ConnectionDto + { + Id = profile.Id.ToString("D"), + Name = profile.Name ?? "", + Kind = (int)profile.Kind, + Host = profile.Host ?? "", + Port = profile.Port, + Database = profile.Database ?? "", + Username = profile.Username ?? "", + PasswordProtected = string.IsNullOrEmpty(profile.Password) ? "" : Protect(profile.Password), + Schema = profile.Schema ?? "", + Extra = profile.Extra ?? "" + }); + } + var json = JsonSerializer.Serialize(new StoreFile + { + Version = 1, + Connections = dtos + }, StoreJson); + var directory = Path.GetDirectoryName(FilePath); + Directory.CreateDirectory(directory); + var temp = FilePath + ".tmp"; + File.WriteAllText(temp, json, new UTF8Encoding(false)); + if (File.Exists(FilePath)) + File.Replace(temp, FilePath, null); + else + File.Move(temp, FilePath); + } + + public static ConnectionProfile Clone(ConnectionProfile profile) + { + return new ConnectionProfile + { + Id = profile.Id, + Name = profile.Name, + Kind = profile.Kind, + Host = profile.Host, + Port = profile.Port, + Database = profile.Database, + Username = profile.Username, + Password = profile.Password, + Schema = profile.Schema, + Extra = profile.Extra + }; + } + + static string Protect(string plain) + { + var data = Encoding.UTF8.GetBytes(plain); + var protectedBytes = ProtectedData.Protect(data, Entropy, DataProtectionScope.CurrentUser); + return Convert.ToBase64String(protectedBytes); + } + + static string Unprotect(string stored) + { + var data = Convert.FromBase64String(stored); + var plain = ProtectedData.Unprotect(data, Entropy, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(plain); + } + } +} diff --git a/src/DataCompare.App/DataCompare.App.csproj b/src/DataCompare.App/DataCompare.App.csproj new file mode 100644 index 0000000..4645486 --- /dev/null +++ b/src/DataCompare.App/DataCompare.App.csproj @@ -0,0 +1,70 @@ + + + WinExe + net9.0-windows + 6.2 + true + disable + DataCompare.App + DataCompare + 10.0 + disable + $(NoWarn);WFO0003 + app.manifest + app.ico + DataCompare.App.Program + 1.0.0 + 数据对比 + 数据对比 + 对比两个数据库表的数据差异 + + + + + + + + + + + <_OutDir>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\..\publish')) + + + <_OldPublish Include="$(_OutDir)\*.*" /> + + + + + + + + <_UcrtDir Condition="Exists('$(MSBuildProgramFiles32)\Windows Kits\10\Redist\ucrt\DLLs\x64\ucrtbase.dll')">$(MSBuildProgramFiles32)\Windows Kits\10\Redist\ucrt\DLLs\x64\ + <_UcrtDir Condition="'$(_UcrtDir)' == '' AND Exists('$(ProgramW6432)\Microsoft Visual Studio\2022\Community\Common7\IDE\Remote Debugger\x64\ucrtbase.dll')">$(ProgramW6432)\Microsoft Visual Studio\2022\Community\Common7\IDE\Remote Debugger\x64\ + <_UcrtDir Condition="'$(_UcrtDir)' == '' AND Exists('$(ProgramW6432)\Microsoft Visual Studio\2022\Professional\Common7\IDE\Remote Debugger\x64\ucrtbase.dll')">$(ProgramW6432)\Microsoft Visual Studio\2022\Professional\Common7\IDE\Remote Debugger\x64\ + <_UcrtDir Condition="'$(_UcrtDir)' == '' AND Exists('$(ProgramW6432)\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Remote Debugger\x64\ucrtbase.dll')">$(ProgramW6432)\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\Remote Debugger\x64\ + <_UcrtDir Condition="'$(_UcrtDir)' == '' AND Exists('$(ProgramW6432)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\Remote Debugger\x64\ucrtbase.dll')">$(ProgramW6432)\Microsoft Visual Studio\2022\BuildTools\Common7\IDE\Remote Debugger\x64\ + + + + <_DownlevelDll Include="$(_UcrtDir)ucrtbase.dll" /> + <_DownlevelDll Include="$(_UcrtDir)api-ms-win-crt-*.dll" /> + <_DownlevelDll Include="$(_UcrtDir)api-ms-win-core-*.dll" /> + <_DownlevelDll Include="$(_UcrtDir)vcruntime140.dll" /> + <_DownlevelDll Include="$(_UcrtDir)vcruntime140_1.dll" /> + <_DownlevelDll Include="$(_UcrtDir)msvcp140.dll" /> + <_DownlevelDll Include="$(_UcrtDir)msvcp140_atomic_wait.dll" /> + + + + <_PublishClean>$([System.IO.Path]::GetFullPath('$(PublishDir)')) + + + <_PublishPdb Include="$(_PublishClean)\*.pdb" /> + + + + diff --git a/src/DataCompare.App/FodyWeavers.xsd b/src/DataCompare.App/FodyWeavers.xsd new file mode 100644 index 0000000..dbeb102 --- /dev/null +++ b/src/DataCompare.App/FodyWeavers.xsd @@ -0,0 +1,186 @@ + + + + + + + + + + + + A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks + + + + + A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. + + + + + A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks + + + + + A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks. + + + + + A list of runtimes to exclude from the default action of "embed all Copy Local references", delimited with line breaks + + + + + A list of runtimes names to include from the default action of "embed all Copy Local references", delimited with line breaks. + + + + + Obsolete, use UnmanagedWinX86Assemblies instead + + + + + A list of unmanaged X86 (32 bit) assembly names to include, delimited with line breaks. + + + + + Obsolete, use UnmanagedWinX64Assemblies instead. + + + + + A list of unmanaged X64 (64 bit) assembly names to include, delimited with line breaks. + + + + + A list of unmanaged Arm64 (64 bit) assembly names to include, delimited with line breaks. + + + + + The order of preloaded assemblies, delimited with line breaks. + + + + + + This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file. + + + + + Controls if .pdbs for reference assemblies are also embedded. + + + + + Controls if runtime assemblies are also embedded. + + + + + Controls whether the runtime assemblies are embedded with their full path or only with their assembly name. + + + + + Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option. + + + + + As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off. + + + + + The attach method no longer subscribes to the `AppDomain.AssemblyResolve` (.NET 4.x) and `AssemblyLoadContext.Resolving` (.NET 6.0+) events. + + + + + Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code. + + + + + Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior. + + + + + A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with | + + + + + A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |. + + + + + A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with | + + + + + A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with |. + + + + + Obsolete, use UnmanagedWinX86Assemblies instead + + + + + A list of unmanaged X86 (32 bit) assembly names to include, delimited with |. + + + + + Obsolete, use UnmanagedWinX64Assemblies instead + + + + + A list of unmanaged X64 (64 bit) assembly names to include, delimited with |. + + + + + A list of unmanaged Arm64 (64 bit) assembly names to include, delimited with |. + + + + + The order of preloaded assemblies, delimited with |. + + + + + + + + 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed. + + + + + A comma-separated list of error codes that can be safely ignored in assembly verification. + + + + + 'false' to turn off automatic generation of the XML Schema file. + + + + + \ No newline at end of file diff --git a/src/DataCompare.App/MainForm.cs b/src/DataCompare.App/MainForm.cs new file mode 100644 index 0000000..78405de --- /dev/null +++ b/src/DataCompare.App/MainForm.cs @@ -0,0 +1,1552 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using DataCompare.Core; +using DataCompare.Data; + +namespace DataCompare.App +{ + sealed class MainForm : Form + { + static Font _uiFont; + + readonly List _profiles = new List(); + readonly List _view = new List(); + + TabControl _tabs; + DataGridView _connGrid; + ComboBox _leftConn; + ComboBox _rightConn; + TableCombo _leftTable; + TableCombo _rightTable; + TextBox _leftFilter; + TextBox _rightFilter; + DataGridView _mapGrid; + CheckBox _trim; + CheckBox _ignoreCase; + CheckBox _nullEmpty; + CheckBox _coerceNumber; + CheckBox _coerceBool; + CheckBox _coerceDate; + ComboBox _datePrecision; + ComboBox _decimalScale; + TextBox _tolerance; + Button _btnRead; + Button _btnMatch; + Button _btnPreview; + Button _btnCompare; + Button _btnCancel; + ToolStripStatusLabel _status; + readonly ToolTip _tips = new ToolTip(); + DataGridView _diffGrid; + DataGridView _detailGrid; + ComboBox _statusFilter; + CheckBox _onlyDiffCells; + Label _stats; + TextBox _cellText; + + IList _leftColumns; + IList _rightColumns; + CompareResult _result; + CancellationTokenSource _cts; + bool _suppress; + int _leftGen; + int _rightGen; + int _badPasswords; + string _loadError; + + public static Font UiFont() + { + if (_uiFont != null) + return _uiFont; + try + { + var font = new Font("Microsoft YaHei UI", 9F); + if (font.Name == "Microsoft YaHei UI") + { + _uiFont = font; + return _uiFont; + } + font.Dispose(); + } + catch (ArgumentException) + { + } + _uiFont = SystemFonts.MessageBoxFont; + return _uiFont; + } + + public MainForm() + { + AppIcon.Apply(this); + Text = "数据对比"; + Font = UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + StartPosition = FormStartPosition.CenterScreen; + ClientSize = new Size(UiMetrics.Px(1180), UiMetrics.Px(760)); + MinimumSize = new Size(UiMetrics.Px(1020), UiMetrics.Px(680)); + + _tabs = new TabControl { Dock = DockStyle.Fill }; + _tabs.TabPages.Add(BuildConnectionPage()); + _tabs.TabPages.Add(BuildComparePage()); + _tabs.TabPages.Add(BuildResultPage()); + + var strip = new StatusStrip(); + _status = new ToolStripStatusLabel + { + Spring = true, + TextAlign = ContentAlignment.MiddleLeft, + Text = "就绪" + }; + strip.Items.Add(_status); + + Controls.Add(_tabs); + Controls.Add(strip); + + try + { + _profiles.AddRange(ConnectionStore.Load(out _badPasswords)); + } + catch (Exception ex) + { + _loadError = ex.Message; + } + FillConnectionGrid(); + FillConnectionCombos(); + } + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + if (!string.IsNullOrEmpty(_loadError)) + MessageBox.Show(this, _loadError, "连接配置", MessageBoxButtons.OK, MessageBoxIcon.Warning); + else if (_badPasswords > 0) + MessageBox.Show(this, "有 " + _badPasswords + " 个连接的密码无法解密,请重新编辑并保存。", "连接配置", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + if (_cts != null) + _cts.Cancel(); + base.OnFormClosing(e); + } + + TabPage BuildConnectionPage() + { + var page = new TabPage("连接") { Padding = new Padding(8) }; + _connGrid = CreateGrid(true); + _connGrid.Columns.Add(TextColumn("名称", 180)); + _connGrid.Columns.Add(TextColumn("类型", 110)); + _connGrid.Columns.Add(TextColumn("主机", 180)); + _connGrid.Columns.Add(TextColumn("端口", 70)); + _connGrid.Columns.Add(TextColumn("数据库", 160)); + _connGrid.Columns.Add(TextColumn("用户", 120)); + _connGrid.CellDoubleClick += (sender, args) => + { + if (args.RowIndex >= 0) + EditConnection(); + }; + + var bar = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Padding = new Padding(0, UiMetrics.Px(8), 0, UiMetrics.Px(4)) + }; + bar.Controls.Add(MakeButton("新建", delegate { EditConnection(null); })); + bar.Controls.Add(MakeButton("编辑", delegate { EditConnection(); })); + bar.Controls.Add(MakeButton("删除", delegate { DeleteConnection(); })); + bar.Controls.Add(MakeButton("测试连接", delegate { TestStoredConnection(); })); + page.Controls.Add(_connGrid); + page.Controls.Add(bar); + return page; + } + + TabPage BuildComparePage() + { + var page = new TabPage("对比") { Padding = new Padding(8) }; + _leftConn = Combo(); + _rightConn = Combo(); + _leftTable = new TableCombo(); + _rightTable = new TableCombo(); + const string tableTip = "输入关键字筛选表,多个词用空格分开。例如 task queue"; + _tips.SetToolTip(_leftTable, tableTip); + _tips.SetToolTip(_rightTable, tableTip); + _leftFilter = new TextBox { Dock = DockStyle.Fill }; + _rightFilter = new TextBox { Dock = DockStyle.Fill }; + const string filterTip = "不要写 WHERE,不要写分号。例如 status = 1 AND city = '上海'"; + _tips.SetToolTip(_leftFilter, filterTip); + _tips.SetToolTip(_rightFilter, filterTip); + _leftConn.SelectedIndexChanged += async delegate + { + if (!_suppress) + await LoadTablesAsync(_leftTable, SelectedProfile(_leftConn), true); + }; + _rightConn.SelectedIndexChanged += async delegate + { + if (!_suppress) + await LoadTablesAsync(_rightTable, SelectedProfile(_rightConn), false); + }; + _leftTable.TableChanged += delegate { if (!_suppress) ClearMapping(); }; + _rightTable.TableChanged += delegate { if (!_suppress) ClearMapping(); }; + _leftTable.FilterChanged += delegate { ShowTableFilter("左侧", _leftTable); }; + _rightTable.FilterChanged += delegate { ShowTableFilter("右侧", _rightTable); }; + + _mapGrid = CreateGrid(false); + _mapGrid.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2; + _mapGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + _mapGrid.Columns.Add(new DataGridViewCheckBoxColumn + { + Name = "Key", + HeaderText = "键", + Width = UiMetrics.Fit("键", Font, 20), + FillWeight = 40, + FalseValue = false, + TrueValue = true + }); + _mapGrid.Columns.Add(new DataGridViewCheckBoxColumn + { + Name = "Compare", + HeaderText = "对比", + Width = UiMetrics.Fit("对比", Font, 20), + FillWeight = 46, + FalseValue = false, + TrueValue = true + }); + _mapGrid.Columns.Add(TextColumn("左侧列", 160, "LeftName")); + _mapGrid.Columns.Add(TextColumn("左类型", 90, "LeftType")); + var rightName = new DataGridViewComboBoxColumn + { + Name = "RightName", + HeaderText = "右侧列", + FlatStyle = FlatStyle.Flat, + DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton, + FillWeight = 140, + ValueType = typeof(string) + }; + rightName.Items.Add(""); + _mapGrid.Columns.Add(rightName); + _mapGrid.Columns.Add(TextColumn("右类型", 90, "RightType")); + _mapGrid.Columns["LeftName"].ReadOnly = true; + _mapGrid.Columns["LeftType"].ReadOnly = true; + _mapGrid.Columns["RightType"].ReadOnly = true; + _mapGrid.CurrentCellDirtyStateChanged += delegate + { + if (_mapGrid.IsCurrentCellDirty) + _mapGrid.CommitEdit(DataGridViewDataErrorContexts.Commit); + }; + _mapGrid.CellValueChanged += MapCellChanged; + _mapGrid.DataError += delegate { }; + + _trim = Check("去掉首尾空格", true); + _ignoreCase = Check("忽略大小写", false); + _nullEmpty = Check("空串等于 NULL", false); + _coerceNumber = Check("数字与数字文本相同", true); + _coerceBool = Check("0/1 与布尔相同", true); + _coerceDate = Check("文本日期与日期相同", true); + _datePrecision = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = UiMetrics.Fit("不截断", Font, 32) }; + _datePrecision.Items.AddRange(new object[] { "秒", "毫秒", "不截断" }); + _datePrecision.SelectedIndex = 0; + _decimalScale = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = UiMetrics.Fit("不处理", Font, 32) }; + _decimalScale.Items.AddRange(new object[] { "不处理", "0 位", "2 位", "4 位", "6 位" }); + _decimalScale.SelectedIndex = 0; + _tolerance = new TextBox { Text = "0.0001", Width = UiMetrics.Fit("0.0001", Font, 16) }; + + var options = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + WrapContents = true, + FlowDirection = FlowDirection.LeftToRight, + Padding = new Padding(0), + Margin = new Padding(0) + }; + options.Controls.Add(_trim); + options.Controls.Add(_ignoreCase); + options.Controls.Add(_nullEmpty); + options.Controls.Add(_coerceNumber); + options.Controls.Add(_coerceBool); + options.Controls.Add(_coerceDate); + options.Controls.Add(InlineLabel("时间精度")); + options.Controls.Add(_datePrecision); + options.Controls.Add(InlineLabel("小数位")); + options.Controls.Add(_decimalScale); + options.Controls.Add(InlineLabel("浮点容差")); + options.Controls.Add(_tolerance); + + _btnRead = MakeButton("读取字段", async delegate { await ReadColumnsAsync(); }); + _btnMatch = MakeButton("按列名匹配", delegate { ApplyNameMatch(true); }); + _btnPreview = MakeButton("预览前 100 行", async delegate { await PreviewAsync(); }); + _btnCompare = MakeButton("开始对比", async delegate { await CompareAsync(); }); + _btnCompare.BackColor = Color.FromArgb(37, 99, 168); + _btnCompare.ForeColor = Color.White; + _btnCompare.FlatStyle = FlatStyle.Flat; + _btnCompare.FlatAppearance.BorderSize = 0; + _btnCancel = MakeButton("取消", delegate { if (_cts != null) _cts.Cancel(); }); + _btnCancel.Enabled = false; + var buttons = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + WrapContents = false, + FlowDirection = FlowDirection.LeftToRight + }; + buttons.Controls.Add(_btnRead); + buttons.Controls.Add(_btnMatch); + buttons.Controls.Add(_btnPreview); + buttons.Controls.Add(_btnCompare); + buttons.Controls.Add(_btnCancel); + + int line = Math.Max(_leftConn.PreferredHeight, _leftTable.PreferredHeight) + UiMetrics.Px(8); + int groupRow = line * 2 + UiMetrics.Px(40); + int filterRow = line * 2; + int optionRow = UiMetrics.Px(112); + int buttonRow = UiMetrics.Px(46); + var layout = new TableLayoutPanel + { + Dock = DockStyle.Top, + Height = groupRow + filterRow + optionRow + buttonRow, + ColumnCount = 2, + RowCount = 4, + Padding = new Padding(0, 0, 0, UiMetrics.Px(4)) + }; + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, groupRow)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, filterRow)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, optionRow)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, buttonRow)); + layout.Controls.Add(SideBox("左侧", _leftConn, _leftTable, line), 0, 0); + layout.Controls.Add(SideBox("右侧", _rightConn, _rightTable, line), 1, 0); + + var filters = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; + filters.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("左侧筛选", Font, 16))); + filters.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + filters.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); + filters.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); + filters.Controls.Add(FieldLabel("左侧筛选"), 0, 0); + filters.Controls.Add(_leftFilter, 1, 0); + filters.Controls.Add(FieldLabel("右侧筛选"), 0, 1); + filters.Controls.Add(_rightFilter, 1, 1); + PlaceField(_leftFilter); + PlaceField(_rightFilter); + layout.Controls.Add(filters, 0, 1); + layout.SetColumnSpan(filters, 2); + layout.Controls.Add(options, 0, 2); + layout.SetColumnSpan(options, 2); + layout.Controls.Add(buttons, 0, 3); + layout.SetColumnSpan(buttons, 2); + + page.Controls.Add(_mapGrid); + page.Controls.Add(layout); + return page; + } + + TabPage BuildResultPage() + { + var page = new TabPage("结果") { Padding = new Padding(8) }; + _stats = new Label + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(28), + TextAlign = ContentAlignment.MiddleLeft, + Text = "尚未对比" + }; + _statusFilter = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = UiMetrics.Fit("内容不同", Font, 32) }; + _statusFilter.Items.AddRange(new object[] { "全部差异", "仅左侧", "仅右侧", "内容不同", "键问题" }); + _statusFilter.SelectedIndex = 0; + _statusFilter.SelectedIndexChanged += delegate { if (!_suppress) BindView(); }; + _onlyDiffCells = Check("明细只显示不同列", true); + _onlyDiffCells.CheckedChanged += delegate { ShowCurrentDetail(); }; + var export = MakeButton("导出 CSV", delegate { ExportCsv(); }); + var showLabel = InlineLabel("显示"); + var header = new Panel { Dock = DockStyle.Top, Height = UiMetrics.Px(72) }; + var bar = new CenterRow(header); + bar.Add(showLabel, 0); + bar.Add(_statusFilter, UiMetrics.Px(6)); + bar.Add(_onlyDiffCells, UiMetrics.Px(16)); + bar.Add(export, UiMetrics.Px(12)); + header.Controls.Add(bar); + header.Controls.Add(_stats); + + _diffGrid = CreateGrid(true); + _diffGrid.VirtualMode = true; + _diffGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + _diffGrid.Columns.Add(TextColumn("状态", 90)); + _diffGrid.Columns.Add(TextColumn("键", 280)); + _diffGrid.Columns.Add(TextColumn("摘要", 360)); + _diffGrid.CellValueNeeded += DiffCellValueNeeded; + _diffGrid.CellFormatting += DiffCellFormatting; + _diffGrid.SelectionChanged += delegate { if (!_suppress) ShowCurrentDetail(); }; + + _detailGrid = CreateGrid(true); + _detailGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + _detailGrid.Columns.Add(TextColumn("列", 180)); + _detailGrid.Columns.Add(TextColumn("左侧", 280)); + _detailGrid.Columns.Add(TextColumn("右侧", 280)); + _detailGrid.CellFormatting += DetailCellFormatting; + _detailGrid.CellEnter += delegate + { + if (_detailGrid.CurrentCell != null) + _cellText.Text = Convert.ToString(_detailGrid.CurrentCell.Value); + }; + + _cellText = new TextBox + { + Dock = DockStyle.Bottom, + Height = UiMetrics.Px(72), + Multiline = true, + ReadOnly = true, + ScrollBars = ScrollBars.Vertical + }; + + var detail = new Panel { Dock = DockStyle.Fill }; + detail.Controls.Add(_detailGrid); + detail.Controls.Add(_cellText); + + var split = new SplitContainer + { + Dock = DockStyle.Fill, + Orientation = Orientation.Horizontal, + SplitterWidth = 6 + }; + split.Panel1.Controls.Add(_diffGrid); + split.Panel2.Controls.Add(detail); + + page.Controls.Add(split); + page.Controls.Add(header); + page.Enter += delegate + { + if (split.Height > 200 && split.SplitterDistance < 80) + split.SplitterDistance = 240; + }; + Load += delegate + { + try + { + if (split.Height > 220) + split.SplitterDistance = Math.Min(280, split.Height / 2); + } + catch (InvalidOperationException) + { + } + }; + return page; + } + + void FillConnectionGrid() + { + _connGrid.Rows.Clear(); + for (int i = 0; i < _profiles.Count; i++) + { + var profile = _profiles[i]; + int index = _connGrid.Rows.Add( + profile.Name, + DbKindInfo.DisplayName(profile.Kind), + profile.Host, + profile.Port.ToString(CultureInfo.InvariantCulture), + profile.Database, + profile.Username); + _connGrid.Rows[index].Tag = profile.Id; + } + } + + void FillConnectionCombos() + { + var leftId = ProfileId(_leftConn); + var rightId = ProfileId(_rightConn); + _suppress = true; + try + { + FillCombo(_leftConn); + FillCombo(_rightConn); + Reselect(_leftConn, leftId); + Reselect(_rightConn, rightId); + } + finally + { + _suppress = false; + } + } + + void FillCombo(ComboBox box) + { + box.Items.Clear(); + for (int i = 0; i < _profiles.Count; i++) + box.Items.Add(_profiles[i]); + } + + void Reselect(ComboBox box, Guid? id) + { + if (!id.HasValue) + return; + for (int i = 0; i < box.Items.Count; i++) + { + var profile = box.Items[i] as ConnectionProfile; + if (profile != null && profile.Id == id.Value) + { + box.SelectedIndex = i; + return; + } + } + } + + void EditConnection(ConnectionProfile existing) + { + using (var dialog = new ConnectionEditForm(existing == null ? null : ConnectionStore.Clone(existing))) + { + if (dialog.ShowDialog(this) != DialogResult.OK) + return; + var saved = dialog.Profile; + bool replaced = false; + for (int i = 0; i < _profiles.Count; i++) + { + if (_profiles[i].Id == saved.Id) + { + _profiles[i] = saved; + replaced = true; + break; + } + } + if (!replaced) + _profiles.Add(saved); + ConnectionStore.Save(_profiles); + FillConnectionGrid(); + FillConnectionCombos(); + } + } + + void EditConnection() + { + var profile = SelectedStoredProfile(); + if (profile == null) + { + MessageBox.Show(this, "请先选择一个连接。", "编辑连接", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + EditConnection(profile); + } + + void DeleteConnection() + { + var profile = SelectedStoredProfile(); + if (profile == null) + return; + if (MessageBox.Show(this, "删除连接「" + profile.Name + "」?", "删除连接", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + return; + _profiles.Remove(profile); + ConnectionStore.Save(_profiles); + FillConnectionGrid(); + FillConnectionCombos(); + ClearMapping(); + } + + void TestStoredConnection() + { + var profile = SelectedStoredProfile(); + if (profile == null) + { + MessageBox.Show(this, "请先选择一个连接。", "测试连接", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + try + { + UseWaitCursor = true; + using (var source = DataSourceFactory.Create(profile)) + source.Test(); + MessageBox.Show(this, "连接成功。", "测试连接", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + finally + { + UseWaitCursor = false; + } + } + + ConnectionProfile SelectedStoredProfile() + { + if (_connGrid.CurrentRow == null || !(_connGrid.CurrentRow.Tag is Guid)) + return null; + var id = (Guid)_connGrid.CurrentRow.Tag; + for (int i = 0; i < _profiles.Count; i++) + { + if (_profiles[i].Id == id) + return _profiles[i]; + } + return null; + } + + async Task LoadTablesAsync(TableCombo box, ConnectionProfile profile, bool left) + { + int generation = left ? ++_leftGen : ++_rightGen; + _suppress = true; + box.SetTables(null); + _suppress = false; + ClearMapping(); + if (profile == null) + return; + var snapshot = ConnectionStore.Clone(profile); + try + { + _status.Text = "正在读取表…"; + var tables = await Task.Run(() => + { + using (var source = DataSourceFactory.Create(snapshot)) + return source.GetTables(); + }); + if (IsDisposed || (left ? generation != _leftGen : generation != _rightGen)) + return; + _suppress = true; + var catalogs = new HashSet(StringComparer.OrdinalIgnoreCase); + for (int i = 0; i < tables.Count; i++) + { + if (!string.IsNullOrEmpty(tables[i].Catalog)) + catalogs.Add(tables[i].Catalog); + } + box.SetTables(tables); + _suppress = false; + var summary = (left ? "左侧" : "右侧") + "已读取 " + tables.Count + " 张表"; + if (catalogs.Count > 1) + summary += ",来自 " + catalogs.Count + " 个库"; + _status.Text = summary; + } + catch (Exception ex) + { + _suppress = false; + if (!IsDisposed) + { + _status.Text = "读取表失败"; + MessageBox.Show(this, ex.Message, "读取表失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + } + + async Task ReadColumnsAsync() + { + var leftProfile = SelectedProfile(_leftConn); + var rightProfile = SelectedProfile(_rightConn); + var leftTable = _leftTable.SelectedTable; + var rightTable = _rightTable.SelectedTable; + if (leftProfile == null || rightProfile == null || leftTable == null || rightTable == null) + { + MessageBox.Show(this, "请先选择两侧的连接和表。", "读取字段", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + var leftSnap = ConnectionStore.Clone(leftProfile); + var rightSnap = ConnectionStore.Clone(rightProfile); + var leftRef = CopyTable(leftTable); + var rightRef = CopyTable(rightTable); + try + { + SetBusy(true); + _status.Text = "正在读取字段…"; + var loaded = await Task.Run(() => + { + IList leftCols; + IList rightCols; + using (var source = DataSourceFactory.Create(leftSnap)) + leftCols = source.GetColumns(leftRef); + using (var source = DataSourceFactory.Create(rightSnap)) + rightCols = source.GetColumns(rightRef); + return new ColumnPair { Left = leftCols, Right = rightCols }; + }); + if (IsDisposed) + return; + _leftColumns = loaded.Left; + _rightColumns = loaded.Right; + FillMapping(); + _status.Text = "左侧 " + _leftColumns.Count + " 列,右侧 " + _rightColumns.Count + " 列"; + } + catch (Exception ex) + { + if (!IsDisposed) + { + _status.Text = "读取字段失败"; + MessageBox.Show(this, ex.Message, "读取字段失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + finally + { + if (!IsDisposed) + SetBusy(false); + } + } + + void FillMapping() + { + _suppress = true; + try + { + _mapGrid.Rows.Clear(); + var combo = (DataGridViewComboBoxColumn)_mapGrid.Columns["RightName"]; + combo.Items.Clear(); + combo.Items.Add(""); + for (int i = 0; i < _rightColumns.Count; i++) + combo.Items.Add(_rightColumns[i].Name); + for (int i = 0; i < _leftColumns.Count; i++) + { + var left = _leftColumns[i]; + int index = _mapGrid.Rows.Add(); + var row = _mapGrid.Rows[index]; + var match = FindColumn(_rightColumns, left.Name); + row.Cells["Key"].Value = false; + row.Cells["Compare"].Value = match != null; + row.Cells["LeftName"].Value = left.Name; + row.Cells["LeftType"].Value = left.DataType; + row.Cells["RightName"].Value = match == null ? "" : match.Name; + row.Cells["RightType"].Value = match == null ? "" : match.DataType; + } + } + finally + { + _suppress = false; + } + } + + void ApplyNameMatch(bool overwriteCompare) + { + if (_rightColumns == null) + return; + _suppress = true; + try + { + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + var leftName = Convert.ToString(row.Cells["LeftName"].Value); + var match = FindColumn(_rightColumns, leftName); + row.Cells["RightName"].Value = match == null ? "" : match.Name; + row.Cells["RightType"].Value = match == null ? "" : match.DataType; + if (overwriteCompare) + row.Cells["Compare"].Value = match != null; + } + } + finally + { + _suppress = false; + } + } + + void MapCellChanged(object sender, DataGridViewCellEventArgs e) + { + if (_suppress || e.RowIndex < 0) + return; + if (_mapGrid.Columns[e.ColumnIndex].Name != "RightName") + return; + var row = _mapGrid.Rows[e.RowIndex]; + var name = Convert.ToString(row.Cells["RightName"].Value); + var match = FindColumn(_rightColumns, name); + row.Cells["RightType"].Value = match == null ? "" : match.DataType; + } + + void ClearMapping() + { + _leftColumns = null; + _rightColumns = null; + if (_mapGrid != null) + _mapGrid.Rows.Clear(); + } + + async Task PreviewAsync() + { + try + { + var request = CaptureRequest(false); + SetBusy(true); + _status.Text = "正在预览…"; + var data = await Task.Run(() => + { + List leftRows; + List rightRows; + using (var source = DataSourceFactory.Create(request.LeftProfile)) + leftRows = source.ReadRows(request.LeftTable, request.LeftColumns, request.LeftFilter, 100, CancellationToken.None, null); + using (var source = DataSourceFactory.Create(request.RightProfile)) + rightRows = source.ReadRows(request.RightTable, request.RightColumns, request.RightFilter, 100, CancellationToken.None, null); + return new PreviewPair { Left = leftRows, Right = rightRows }; + }); + if (IsDisposed) + return; + _status.Text = "预览完成"; + using (var form = new PreviewForm( + request.LeftTable.Display, + request.LeftColumns, + data.Left, + request.RightTable.Display, + request.RightColumns, + data.Right)) + { + form.ShowDialog(this); + } + } + catch (Exception ex) + { + if (!IsDisposed) + { + _status.Text = "预览失败"; + MessageBox.Show(this, ex.Message, "预览失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + finally + { + if (!IsDisposed) + SetBusy(false); + } + } + + async Task CompareAsync() + { + CompareRequest request; + try + { + request = CaptureRequest(true); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "无法开始对比", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + _cts = new CancellationTokenSource(); + var token = _cts.Token; + var progress = new Progress(text => + { + if (!IsDisposed) + _status.Text = text; + }); + var watch = Stopwatch.StartNew(); + try + { + SetBusy(true); + var result = await Task.Run(() => CompareSession.Execute( + request.LeftProfile, + request.LeftTable, + request.LeftFilter, + request.RightProfile, + request.RightTable, + request.RightFilter, + request.Mappings, + request.Options, + progress, + token)); + if (IsDisposed) + return; + _result = result; + _tabs.SelectedIndex = 2; + BindView(); + _status.Text = "对比完成,耗时 " + watch.Elapsed.TotalSeconds.ToString("0.0") + " 秒"; + } + catch (OperationCanceledException) + { + if (!IsDisposed) + _status.Text = "已取消"; + } + catch (Exception ex) + { + if (!IsDisposed) + { + if (token.IsCancellationRequested) + _status.Text = "已取消"; + else + { + _status.Text = "对比失败"; + MessageBox.Show(this, ex.Message, "对比失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + } + finally + { + if (_cts != null) + { + _cts.Dispose(); + _cts = null; + } + if (!IsDisposed) + SetBusy(false); + } + } + + CompareRequest CaptureRequest(bool requireKey) + { + var leftProfile = SelectedProfile(_leftConn); + var rightProfile = SelectedProfile(_rightConn); + var leftTable = _leftTable.SelectedTable; + var rightTable = _rightTable.SelectedTable; + if (leftProfile == null || rightProfile == null) + throw new InvalidOperationException("请选择左右两侧的连接。"); + if (leftTable == null || rightTable == null) + throw new InvalidOperationException("请选择左右两侧的表。"); + if (_leftColumns == null || _rightColumns == null) + throw new InvalidOperationException("请先读取字段。"); + + List leftColumns; + List rightColumns; + List mappings = null; + if (requireKey) + { + mappings = ReadMappings(); + leftColumns = new List(); + rightColumns = new List(); + for (int i = 0; i < mappings.Count; i++) + { + AddUnique(leftColumns, mappings[i].LeftColumn); + AddUnique(rightColumns, mappings[i].RightColumn); + } + } + else + { + leftColumns = PreviewColumns(true); + rightColumns = PreviewColumns(false); + } + + return new CompareRequest + { + LeftProfile = ConnectionStore.Clone(leftProfile), + RightProfile = ConnectionStore.Clone(rightProfile), + LeftTable = CopyTable(leftTable), + RightTable = CopyTable(rightTable), + LeftFilter = _leftFilter.Text, + RightFilter = _rightFilter.Text, + LeftColumns = leftColumns, + RightColumns = rightColumns, + Mappings = mappings, + Options = ReadOptions() + }; + } + + List ReadMappings() + { + var list = new List(); + var leftSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + var rightSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + bool key = Checked(row, "Key"); + bool compare = Checked(row, "Compare"); + if (!key && !compare) + continue; + var left = (Convert.ToString(row.Cells["LeftName"].Value) ?? "").Trim(); + var right = (Convert.ToString(row.Cells["RightName"].Value) ?? "").Trim(); + if (left.Length == 0 || right.Length == 0) + throw new InvalidOperationException("键列和对比列都需要同时选择左右字段。"); + if (!leftSeen.Add(left)) + throw new InvalidOperationException("左侧列重复选择:" + left); + if (!rightSeen.Add(right)) + throw new InvalidOperationException("右侧列重复选择:" + right); + list.Add(new ColumnMapping + { + LeftColumn = left, + RightColumn = right, + IsKey = key, + Compare = compare + }); + } + bool anyKey = false; + for (int i = 0; i < list.Count; i++) + { + if (list[i].IsKey) + anyKey = true; + } + if (!anyKey) + throw new InvalidOperationException("请至少勾选一个键列。键用来把两侧的行对齐。"); + return list; + } + + List PreviewColumns(bool left) + { + var picked = new List(); + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + if (!Checked(row, "Key") && !Checked(row, "Compare")) + continue; + var name = Convert.ToString(row.Cells[left ? "LeftName" : "RightName"].Value); + if (!string.IsNullOrWhiteSpace(name)) + AddUnique(picked, name.Trim()); + } + if (picked.Count > 0) + return picked; + var source = left ? _leftColumns : _rightColumns; + int count = Math.Min(30, source.Count); + for (int i = 0; i < count; i++) + picked.Add(source[i].Name); + if (picked.Count == 0) + throw new InvalidOperationException("没有可预览的列。"); + return picked; + } + + DataCompare.Core.CompareOptions ReadOptions() + { + var options = DataCompare.Core.CompareOptions.CreateDefault(); + options.TrimStrings = _trim.Checked; + options.IgnoreCase = _ignoreCase.Checked; + options.NullEqualsEmpty = _nullEmpty.Checked; + options.CoerceNumericStrings = _coerceNumber.Checked; + options.CoerceBoolNumbers = _coerceBool.Checked; + options.CoerceDateStrings = _coerceDate.Checked; + if (_datePrecision.SelectedIndex <= 0) + options.DatePrecision = DatePrecision.Second; + else if (_datePrecision.SelectedIndex == 1) + options.DatePrecision = DatePrecision.Millisecond; + else + options.DatePrecision = DatePrecision.Full; + switch (_decimalScale.SelectedIndex) + { + case 1: options.DecimalScale = 0; break; + case 2: options.DecimalScale = 2; break; + case 3: options.DecimalScale = 4; break; + case 4: options.DecimalScale = 6; break; + default: options.DecimalScale = -1; break; + } + decimal tolerance; + var text = (_tolerance.Text ?? "").Trim(); + if (!decimal.TryParse(text, NumberStyles.Number, CultureInfo.CurrentCulture, out tolerance) + && !decimal.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out tolerance)) + throw new InvalidOperationException("浮点容差不是有效数字。"); + if (tolerance < 0) + throw new InvalidOperationException("浮点容差不能为负数。"); + options.FloatTolerance = tolerance; + return options; + } + + void BindView() + { + _view.Clear(); + if (_result != null && _result.Diffs != null) + { + for (int i = 0; i < _result.Diffs.Length; i++) + { + if (PassFilter(_result.Diffs[i])) + _view.Add(_result.Diffs[i]); + } + } + _stats.Text = _result == null + ? "尚未对比" + : "左侧 " + _result.LeftRowCount + " 行 右侧 " + _result.RightRowCount + + " 行 值相同 " + _result.MatchedCount + + " 仅左侧 " + _result.LeftOnlyCount + + " 仅右侧 " + _result.RightOnlyCount + + " 内容不同 " + _result.DifferentCount + + " 键重复 " + _result.DuplicateCount + + " 键无效 " + _result.InvalidCount; + + _suppress = true; + _diffGrid.RowCount = 0; + _diffGrid.RowCount = _view.Count; + _suppress = false; + _detailGrid.Rows.Clear(); + _cellText.Text = ""; + if (_view.Count > 0) + { + try + { + _diffGrid.CurrentCell = _diffGrid.Rows[0].Cells[0]; + } + catch (InvalidOperationException) + { + ShowDetail(_view[0]); + } + } + } + + bool PassFilter(RowDiff diff) + { + switch (_statusFilter.SelectedIndex) + { + case 1: return diff.Status == DiffStatus.LeftOnly; + case 2: return diff.Status == DiffStatus.RightOnly; + case 3: return diff.Status == DiffStatus.Different; + case 4: return diff.Status == DiffStatus.DuplicateKey || diff.Status == DiffStatus.InvalidKey; + default: return true; + } + } + + void DiffCellValueNeeded(object sender, DataGridViewCellValueEventArgs e) + { + if (e.RowIndex < 0 || e.RowIndex >= _view.Count) + return; + var diff = _view[e.RowIndex]; + if (e.ColumnIndex == 0) + e.Value = diff.StatusText; + else if (e.ColumnIndex == 1) + e.Value = diff.KeyText; + else + e.Value = diff.Summary; + } + + void DiffCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) + { + if (e.RowIndex < 0 || e.RowIndex >= _view.Count) + return; + Color color; + switch (_view[e.RowIndex].Status) + { + case DiffStatus.LeftOnly: color = Color.FromArgb(255, 228, 228); break; + case DiffStatus.RightOnly: color = Color.FromArgb(226, 244, 226); break; + case DiffStatus.Different: color = Color.FromArgb(255, 246, 220); break; + default: color = Color.FromArgb(255, 232, 210); break; + } + PaintCell(e, color); + } + + void ShowCurrentDetail() + { + if (_diffGrid.CurrentRow == null) + { + ShowDetail(null); + return; + } + int index = _diffGrid.CurrentRow.Index; + if (index < 0 || index >= _view.Count) + { + ShowDetail(null); + return; + } + ShowDetail(_view[index]); + } + + void ShowDetail(RowDiff diff) + { + _detailGrid.Rows.Clear(); + _cellText.Text = ""; + if (diff == null) + return; + if (!string.IsNullOrEmpty(diff.Message) && (diff.Cells == null || diff.Cells.Length == 0 || diff.Status == DiffStatus.InvalidKey || diff.Status == DiffStatus.DuplicateKey)) + { + int note = _detailGrid.Rows.Add("说明", diff.Message, diff.Message); + _detailGrid.Rows[note].Tag = null; + } + if (diff.Cells == null) + return; + for (int i = 0; i < diff.Cells.Length; i++) + { + var cell = diff.Cells[i]; + if (_onlyDiffCells.Checked && !cell.IsDifferent && diff.Status == DiffStatus.Different) + continue; + int index = _detailGrid.Rows.Add(cell.ColumnName, cell.LeftText, cell.RightText); + _detailGrid.Rows[index].Tag = cell; + } + } + + void DetailCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) + { + if (e.RowIndex < 0) + return; + var cell = _detailGrid.Rows[e.RowIndex].Tag as CellDiff; + if (cell == null || !cell.IsDifferent) + return; + if (e.ColumnIndex == 1) + { + if (cell.LeftMissing) + e.CellStyle.ForeColor = Color.FromArgb(120, 120, 120); + else + PaintCell(e, Color.FromArgb(255, 214, 214)); + if (cell.LeftIsNull) + e.CellStyle.ForeColor = Color.FromArgb(120, 120, 120); + } + else if (e.ColumnIndex == 2) + { + if (cell.RightMissing) + e.CellStyle.ForeColor = Color.FromArgb(120, 120, 120); + else + PaintCell(e, Color.FromArgb(210, 236, 210)); + if (cell.RightIsNull) + e.CellStyle.ForeColor = Color.FromArgb(120, 120, 120); + } + } + + void ExportCsv() + { + if (_view.Count == 0) + { + MessageBox.Show(this, "没有可导出的差异。", "导出", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + using (var dialog = new SaveFileDialog()) + { + dialog.Filter = "CSV 文件|*.csv"; + dialog.FileName = "差异.csv"; + if (dialog.ShowDialog(this) != DialogResult.OK) + return; + var builder = new StringBuilder(); + builder.AppendLine("状态,键,摘要,列,左侧,右侧,是否不同"); + for (int i = 0; i < _view.Count; i++) + { + var diff = _view[i]; + if (diff.Cells == null || diff.Cells.Length == 0) + { + builder.AppendLine(string.Join(",", new[] + { + Csv(diff.StatusText), Csv(diff.KeyText), Csv(diff.Summary), "", "", "", "" + })); + continue; + } + for (int c = 0; c < diff.Cells.Length; c++) + { + var cell = diff.Cells[c]; + builder.AppendLine(string.Join(",", new[] + { + Csv(diff.StatusText), + Csv(diff.KeyText), + Csv(diff.Summary), + Csv(cell.ColumnName), + Csv(cell.LeftText), + Csv(cell.RightText), + cell.IsDifferent ? "是" : "否" + })); + } + } + File.WriteAllText(dialog.FileName, builder.ToString(), new UTF8Encoding(true)); + _status.Text = "已导出 " + dialog.FileName; + } + } + + void SetBusy(bool busy) + { + _btnCompare.Enabled = !busy; + _btnPreview.Enabled = !busy; + _btnRead.Enabled = !busy; + _btnMatch.Enabled = !busy; + _btnCancel.Enabled = busy; + UseWaitCursor = busy; + } + + static void PaintCell(DataGridViewCellFormattingEventArgs e, Color color) + { + e.CellStyle.BackColor = color; + e.CellStyle.SelectionForeColor = Color.Black; + e.CellStyle.SelectionBackColor = Color.FromArgb( + Math.Max(0, color.R - 20), + Math.Max(0, color.G - 20), + Math.Max(0, color.B - 16)); + } + + static string Csv(string value) + { + if (string.IsNullOrEmpty(value)) + return ""; + if (value[0] == '=' || value[0] == '@') + value = "'" + value; + if (value.IndexOf('"') >= 0 || value.IndexOf(',') >= 0 || value.IndexOf('\n') >= 0 || value.IndexOf('\r') >= 0) + return "\"" + value.Replace("\"", "\"\"") + "\""; + return value; + } + + static void AddUnique(List list, string name) + { + for (int i = 0; i < list.Count; i++) + { + if (string.Equals(list[i], name, StringComparison.OrdinalIgnoreCase)) + return; + } + list.Add(name); + } + + static bool Checked(DataGridViewRow row, string column) + { + return row.Cells[column].Value is bool && (bool)row.Cells[column].Value; + } + + static ColumnInfo FindColumn(IList columns, string name) + { + if (columns == null || string.IsNullOrEmpty(name)) + return null; + for (int i = 0; i < columns.Count; i++) + { + if (string.Equals(columns[i].Name, name, StringComparison.OrdinalIgnoreCase)) + return columns[i]; + } + return null; + } + + static ConnectionProfile SelectedProfile(ComboBox box) + { + return box.SelectedItem as ConnectionProfile; + } + + void ShowTableFilter(string side, TableCombo box) + { + if (_suppress || string.IsNullOrEmpty(box.FilterMessage)) + return; + _status.Text = side + box.FilterMessage; + } + + static TableRef CopyTable(TableRef table) + { + return new TableRef + { + Catalog = table.Catalog, + Schema = table.Schema, + Name = table.Name + }; + } + + static Guid? ProfileId(ComboBox box) + { + var profile = box.SelectedItem as ConnectionProfile; + if (profile == null) + return null; + return profile.Id; + } + + static DataGridView CreateGrid(bool readOnly) + { + var grid = new DataGridView + { + Dock = DockStyle.Fill, + ReadOnly = readOnly, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, + RowHeadersVisible = false, + MultiSelect = false, + SelectionMode = DataGridViewSelectionMode.FullRowSelect, + BackgroundColor = Color.White, + BorderStyle = BorderStyle.None, + Font = UiFont(), + AutoGenerateColumns = false + }; + grid.ColumnHeadersHeight = UiMetrics.Px(30); + grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + grid.EnableHeadersVisualStyles = false; + grid.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(245, 246, 248); + grid.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black; + grid.DefaultCellStyle.SelectionForeColor = Color.Black; + grid.DefaultCellStyle.SelectionBackColor = Color.FromArgb(210, 227, 246); + grid.RowTemplate.Height = UiMetrics.Px(26); + typeof(DataGridView).InvokeMember( + "DoubleBuffered", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetProperty, + null, + grid, + new object[] { true }); + return grid; + } + + static DataGridViewTextBoxColumn TextColumn(string header, int width) + { + return TextColumn(header, width, null); + } + + static DataGridViewTextBoxColumn TextColumn(string header, int width, string name) + { + return new DataGridViewTextBoxColumn + { + Name = name ?? header, + HeaderText = header, + Width = width, + MinimumWidth = 50, + SortMode = DataGridViewColumnSortMode.NotSortable + }; + } + + static ComboBox Combo() + { + return new ComboBox + { + DropDownStyle = ComboBoxStyle.DropDownList, + Anchor = AnchorStyles.Left | AnchorStyles.Right, + Margin = new Padding(0) + }; + } + + static Label FieldLabel(string text) + { + return new Label + { + Text = text, + AutoSize = true, + Anchor = AnchorStyles.Left, + Margin = new Padding(0, 0, UiMetrics.Px(8), 0) + }; + } + + static void PlaceField(Control input) + { + input.Dock = DockStyle.None; + input.Anchor = AnchorStyles.Left | AnchorStyles.Right; + input.Margin = new Padding(0); + } + + static CheckBox Check(string text, bool value) + { + return new CheckBox + { + Text = text, + Checked = value, + AutoSize = true, + Margin = new Padding(0, 6, 12, 0) + }; + } + + static Label InlineLabel(string text) + { + return new Label + { + Text = text, + AutoSize = true, + Margin = new Padding(0, 8, 4, 0) + }; + } + + static Button MakeButton(string text, EventHandler click) + { + var button = new Button + { + Text = text, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + Padding = new Padding(UiMetrics.Px(12), UiMetrics.Px(3), UiMetrics.Px(12), UiMetrics.Px(3)), + Margin = new Padding(0, UiMetrics.Px(4), UiMetrics.Px(8), 0), + UseVisualStyleBackColor = true + }; + button.Click += click; + return button; + } + + static Control SideBox(string title, ComboBox connection, ComboBox table, int line) + { + PlaceField(connection); + PlaceField(table); + var box = new GroupBox + { + Text = title, + Dock = DockStyle.Fill, + Padding = new Padding(UiMetrics.Px(8), UiMetrics.Px(4), UiMetrics.Px(8), UiMetrics.Px(4)) + }; + var inner = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("连接", UiFont(), 16))); + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + inner.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); + inner.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); + inner.Controls.Add(FieldLabel("连接"), 0, 0); + inner.Controls.Add(connection, 1, 0); + inner.Controls.Add(FieldLabel("表"), 0, 1); + inner.Controls.Add(table, 1, 1); + box.Controls.Add(inner); + return box; + } + + sealed class CenterRow : Panel + { + readonly List _order = new List(); + readonly Panel _host; + bool _busy; + + public CenterRow(Panel host) + { + _host = host; + Dock = DockStyle.Top; + } + + public void Add(Control control, int gap) + { + control.Margin = Padding.Empty; + control.Anchor = AnchorStyles.Top | AnchorStyles.Left; + control.Tag = gap; + _order.Add(control); + Controls.Add(control); + } + + protected override void OnLayout(LayoutEventArgs e) + { + base.OnLayout(e); + if (_busy || _order.Count == 0) + return; + _busy = true; + try + { + int maxH = 0; + var sizes = new Size[_order.Count]; + for (int i = 0; i < _order.Count; i++) + { + sizes[i] = Measure(_order[i]); + if (sizes[i].Height > maxH) + maxH = sizes[i].Height; + } + int pad = UiMetrics.Px(4); + int row = maxH + pad * 2; + if (Height != row) + Height = row; + int x = 0; + for (int i = 0; i < _order.Count; i++) + { + int gap = _order[i].Tag is int g ? g : 0; + x += gap; + int y = pad + Math.Max(0, (maxH - sizes[i].Height) / 2); + _order[i].SetBounds(x, y, sizes[i].Width, sizes[i].Height); + x += sizes[i].Width; + } + int stats = 0; + foreach (Control sibling in _host.Controls) + { + if (sibling != this && sibling.Dock == DockStyle.Top) + stats += sibling.Height; + } + int hostH = row + stats; + if (_host.Height != hostH) + _host.Height = hostH; + } + finally + { + _busy = false; + } + } + + static Size Measure(Control control) + { + if (control is ComboBox combo) + return new Size(Math.Max(combo.Width, 8), Math.Max(combo.PreferredHeight, 8)); + control.AutoSize = false; + Size size = control.GetPreferredSize(Size.Empty); + if (size.Width < 8) + size.Width = Math.Max(control.Width, 8); + if (size.Height < 8) + size.Height = Math.Max(control.Height, 8); + return size; + } + } + + sealed class ColumnPair + { + public IList Left; + public IList Right; + } + + sealed class PreviewPair + { + public List Left; + public List Right; + } + + sealed class CompareRequest + { + public ConnectionProfile LeftProfile; + public ConnectionProfile RightProfile; + public TableRef LeftTable; + public TableRef RightTable; + public string LeftFilter; + public string RightFilter; + public List LeftColumns; + public List RightColumns; + public List Mappings; + public DataCompare.Core.CompareOptions Options; + } + } +} diff --git a/src/DataCompare.App/PreviewForm.cs b/src/DataCompare.App/PreviewForm.cs new file mode 100644 index 0000000..28bf625 --- /dev/null +++ b/src/DataCompare.App/PreviewForm.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace DataCompare.App +{ + sealed class PreviewForm : Form + { + public PreviewForm( + string leftTitle, + IList leftColumns, + IList leftRows, + string rightTitle, + IList rightColumns, + IList rightRows) + { + AppIcon.Apply(this); + Text = "预览前 100 行"; + StartPosition = FormStartPosition.CenterParent; + Font = MainForm.UiFont(); + ClientSize = new Size(1100, 640); + MinimumSize = new Size(800, 480); + + var split = new SplitContainer + { + Dock = DockStyle.Fill, + Orientation = Orientation.Vertical, + SplitterWidth = 6 + }; + split.Panel1.Controls.Add(Build(leftTitle, leftColumns, leftRows)); + split.Panel2.Controls.Add(Build(rightTitle, rightColumns, rightRows)); + Controls.Add(split); + Load += delegate + { + split.SplitterDistance = Math.Max(200, split.Width / 2); + }; + } + + static Control Build(string title, IList columns, IList rows) + { + var root = new Panel { Dock = DockStyle.Fill }; + var header = new Label + { + Dock = DockStyle.Top, + Height = 28, + TextAlign = ContentAlignment.MiddleLeft, + Padding = new Padding(8, 0, 0, 0), + Text = title + " " + (rows == null ? 0 : rows.Count) + " 行" + }; + var grid = new DataGridView + { + Dock = DockStyle.Fill, + ReadOnly = true, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, + RowHeadersVisible = false, + SelectionMode = DataGridViewSelectionMode.CellSelect, + BackgroundColor = Color.White, + BorderStyle = BorderStyle.None, + Font = MainForm.UiFont(), + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None + }; + grid.ColumnHeadersHeight = 28; + grid.RowTemplate.Height = 24; + if (columns != null) + { + for (int i = 0; i < columns.Count; i++) + { + grid.Columns.Add(new DataGridViewTextBoxColumn + { + HeaderText = columns[i], + Width = 140, + SortMode = DataGridViewColumnSortMode.NotSortable + }); + } + } + if (rows != null) + { + for (int r = 0; r < rows.Count; r++) + { + var values = new object[columns.Count]; + for (int c = 0; c < columns.Count; c++) + { + var value = c < rows[r].Length ? rows[r][c] : null; + values[c] = value == null || value == DBNull.Value ? "NULL" : Convert.ToString(value); + } + int index = grid.Rows.Add(values); + for (int c = 0; c < columns.Count; c++) + { + if ((string)values[c] == "NULL" && (c >= rows[r].Length || rows[r][c] == null || rows[r][c] == DBNull.Value)) + grid.Rows[index].Cells[c].Style.ForeColor = Color.FromArgb(120, 120, 120); + } + } + } + root.Controls.Add(grid); + root.Controls.Add(header); + return root; + } + } +} diff --git a/src/DataCompare.App/Program.cs b/src/DataCompare.App/Program.cs new file mode 100644 index 0000000..6034bdb --- /dev/null +++ b/src/DataCompare.App/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Windows.Forms; + +namespace DataCompare.App +{ + static class Program + { + [STAThread] + static void Main() + { + Application.SetHighDpiMode(HighDpiMode.SystemAware); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); + Application.ThreadException += (sender, args) => + { + MessageBox.Show(args.Exception.Message, "数据对比", MessageBoxButtons.OK, MessageBoxIcon.Error); + }; + Application.Run(new MainForm()); + } + } +} diff --git a/src/DataCompare.App/TableCombo.cs b/src/DataCompare.App/TableCombo.cs new file mode 100644 index 0000000..7b8b326 --- /dev/null +++ b/src/DataCompare.App/TableCombo.cs @@ -0,0 +1,283 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using DataCompare.Core; + +namespace DataCompare.App +{ + sealed class TableCombo : ComboBox + { + const int MatchLimit = 200; + + readonly List _all = new List(); + bool _busy; + + public TableCombo() + { + DropDownStyle = ComboBoxStyle.DropDown; + AutoCompleteMode = AutoCompleteMode.None; + AutoCompleteSource = AutoCompleteSource.None; + IntegralHeight = false; + MaxDropDownItems = 18; + Anchor = AnchorStyles.Left | AnchorStyles.Right; + Margin = new Padding(0); + } + + public event EventHandler TableChanged; + + public event EventHandler FilterChanged; + + public string FilterMessage { get; private set; } + + public TableRef SelectedTable + { + get { return SelectedItem as TableRef; } + } + + public void SetTables(IList tables) + { + _all.Clear(); + if (tables != null) + { + for (int i = 0; i < tables.Count; i++) + _all.Add(tables[i]); + } + FilterMessage = ""; + Fill(_all, null, false); + _busy = true; + Text = ""; + _busy = false; + } + + protected override void OnTextUpdate(EventArgs e) + { + if (_busy) + return; + string text = Text ?? ""; + int caret = SelectionStart; + bool truncated; + var matches = Filter(_all, text, out truncated); + _busy = true; + BeginUpdate(); + Items.Clear(); + for (int i = 0; i < matches.Count; i++) + Items.Add(matches[i]); + EndUpdate(); + UpdateWidth(matches); + DroppedDown = true; + Text = text; + SelectionStart = Math.Max(0, Math.Min(caret, text.Length)); + SelectionLength = 0; + Cursor.Current = Cursors.Default; + _busy = false; + PublishFilter(text, matches.Count, truncated); + } + + protected override void OnDropDown(EventArgs e) + { + if (!_busy && SelectedItem is TableRef && _all.Count > 0 && Items.Count != _all.Count) + Fill(_all, (TableRef)SelectedItem, false); + base.OnDropDown(e); + } + + protected override void OnDropDownClosed(EventArgs e) + { + base.OnDropDownClosed(e); + if (_busy || SelectedItem is TableRef) + return; + var found = FindExact(Text); + if (found != null) + Fill(_all, found, true); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter && Items.Count == 1 && !(SelectedItem is TableRef)) + { + Fill(new TableRef[] { (TableRef)Items[0] }, (TableRef)Items[0], true); + DroppedDown = false; + e.Handled = true; + e.SuppressKeyPress = true; + return; + } + base.OnKeyDown(e); + } + + protected override void OnSelectedIndexChanged(EventArgs e) + { + base.OnSelectedIndexChanged(e); + if (_busy || !(SelectedItem is TableRef)) + return; + if (TableChanged != null) + TableChanged(this, EventArgs.Empty); + } + + void Fill(IList items, TableRef reselect, bool notify) + { + _busy = true; + BeginUpdate(); + Items.Clear(); + int index = -1; + for (int i = 0; i < items.Count; i++) + { + Items.Add(items[i]); + if (reselect != null && Same(items[i], reselect)) + index = i; + } + EndUpdate(); + UpdateWidth(items); + if (index >= 0) + SelectedIndex = index; + else + SelectedIndex = -1; + _busy = false; + if (notify && index >= 0 && TableChanged != null) + TableChanged(this, EventArgs.Empty); + } + + void PublishFilter(string text, int shown, bool truncated) + { + if (string.IsNullOrWhiteSpace(text)) + FilterMessage = ""; + else if (shown == 0) + FilterMessage = "没有匹配的表"; + else if (truncated) + FilterMessage = "匹配超过 " + shown + " 张,请继续输入"; + else + FilterMessage = "匹配 " + shown + " 张表"; + if (FilterChanged != null) + FilterChanged(this, EventArgs.Empty); + } + + TableRef FindExact(string text) + { + text = (text ?? "").Trim(); + if (text.Length == 0) + return null; + for (int i = 0; i < _all.Count; i++) + { + if (string.Equals(_all[i].Display, text, StringComparison.OrdinalIgnoreCase)) + return _all[i]; + } + return null; + } + + void UpdateWidth(IList items) + { + int width = Width; + int scan = Math.Min(items.Count, 80); + for (int i = 0; i < scan; i++) + { + int textWidth = TextRenderer.MeasureText(items[i].Display, Font).Width + UiMetrics.Px(28); + if (textWidth > width) + width = textWidth; + } + DropDownWidth = Math.Min(width, UiMetrics.Px(760)); + } + + static List Filter(List all, string keyword, out bool truncated) + { + truncated = false; + var tokens = Tokenize(keyword); + if (tokens.Count == 0) + return new List(all); + + var direct = new List(); + var fuzzy = new List(); + for (int i = 0; i < all.Count; i++) + { + var display = all[i].Display ?? ""; + if (ContainsAll(display, tokens)) + direct.Add(all[i]); + else if (SubsequenceAll(display, tokens)) + fuzzy.Add(all[i]); + } + + var result = new List(); + for (int i = 0; i < direct.Count && result.Count < MatchLimit; i++) + result.Add(direct[i]); + for (int i = 0; i < fuzzy.Count && result.Count < MatchLimit; i++) + result.Add(fuzzy[i]); + truncated = direct.Count + fuzzy.Count > result.Count; + return result; + } + + static List Tokenize(string keyword) + { + var tokens = new List(); + if (string.IsNullOrWhiteSpace(keyword)) + return tokens; + var parts = keyword.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < parts.Length; i++) + tokens.Add(parts[i]); + return tokens; + } + + static bool ContainsAll(string display, List tokens) + { + for (int i = 0; i < tokens.Count; i++) + { + if (display.IndexOf(tokens[i], StringComparison.OrdinalIgnoreCase) < 0) + return false; + } + return true; + } + + static bool SubsequenceAll(string display, List tokens) + { + for (int i = 0; i < tokens.Count; i++) + { + if (!Subsequence(display, tokens[i])) + return false; + } + return true; + } + + static bool Subsequence(string text, string pattern) + { + int matched = 0; + int need = 0; + for (int i = 0; i < pattern.Length; i++) + { + char c = pattern[i]; + if (c == '.' || c == '_' || c == ' ') + continue; + need++; + } + if (need < 2) + return false; + for (int i = 0; i < text.Length && matched < need; i++) + { + char c = text[i]; + if (c == '.' || c == '_' || c == ' ') + continue; + char expect = NextPatternChar(pattern, matched); + if (char.ToUpperInvariant(c) == char.ToUpperInvariant(expect)) + matched++; + } + return matched == need; + } + + static char NextPatternChar(string pattern, int ordinal) + { + int seen = 0; + for (int i = 0; i < pattern.Length; i++) + { + char c = pattern[i]; + if (c == '.' || c == '_' || c == ' ') + continue; + if (seen == ordinal) + return c; + seen++; + } + return '\0'; + } + + static bool Same(TableRef left, TableRef right) + { + return string.Equals(left.Catalog ?? "", right.Catalog ?? "", StringComparison.OrdinalIgnoreCase) + && string.Equals(left.Schema ?? "", right.Schema ?? "", StringComparison.OrdinalIgnoreCase) + && string.Equals(left.Name ?? "", right.Name ?? "", StringComparison.OrdinalIgnoreCase); + } + } +} diff --git a/src/DataCompare.App/UiMetrics.cs b/src/DataCompare.App/UiMetrics.cs new file mode 100644 index 0000000..eef9277 --- /dev/null +++ b/src/DataCompare.App/UiMetrics.cs @@ -0,0 +1,27 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace DataCompare.App +{ + static class UiMetrics + { + public static float Scale { get; private set; } + + public static void Bind(Control control) + { + using (var graphics = control.CreateGraphics()) + Scale = Math.Max(1f, graphics.DpiY / 96f); + } + + public static int Px(int designPixels) + { + return (int)Math.Round(designPixels * (Scale <= 0f ? 1f : Scale)); + } + + public static int Fit(string text, Font font, int extra) + { + return TextRenderer.MeasureText(text, font).Width + Px(extra); + } + } +} diff --git a/src/DataCompare.App/app.ico b/src/DataCompare.App/app.ico new file mode 100644 index 0000000..0892984 Binary files /dev/null and b/src/DataCompare.App/app.ico differ diff --git a/src/DataCompare.App/app.manifest b/src/DataCompare.App/app.manifest new file mode 100644 index 0000000..4a98112 --- /dev/null +++ b/src/DataCompare.App/app.manifest @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + true + System + + + diff --git a/src/DataCompare.Core/CompareEngine.cs b/src/DataCompare.Core/CompareEngine.cs new file mode 100644 index 0000000..b6b8b40 --- /dev/null +++ b/src/DataCompare.Core/CompareEngine.cs @@ -0,0 +1,480 @@ +using System; +using System.Collections.Generic; + +namespace DataCompare.Core +{ + public static class CompareEngine + { + public static CompareResult Execute( + IList leftColumns, + IList leftRows, + IList rightColumns, + IList rightRows, + IList mappings, + CompareOptions options) + { + if (options == null) + options = CompareOptions.CreateDefault(); + if (leftRows == null) + leftRows = new object[0][]; + if (rightRows == null) + rightRows = new object[0][]; + + var plan = BuildPlan(leftColumns, rightColumns, mappings); + var leftPrep = Prepare(leftRows, leftColumns, plan.LeftKeyIndex, plan.LeftValueIndex, options); + var rightPrep = Prepare(rightRows, rightColumns, plan.RightKeyIndex, plan.RightValueIndex, options); + + var diffs = new List(); + int invalid = EmitInvalid(leftPrep, plan, options, true, diffs); + invalid += EmitInvalid(rightPrep, plan, options, false, diffs); + + var leftValid = ValidOnly(leftPrep); + var rightValid = ValidOnly(rightPrep); + leftValid.Sort((a, b) => CompareRows(a, b, options)); + rightValid.Sort((a, b) => CompareRows(a, b, options)); + + var leftGroups = Group(leftValid, options); + var rightGroups = Group(rightValid, options); + + int matched = 0; + int leftOnly = 0; + int rightOnly = 0; + int different = 0; + int duplicate = 0; + int leftUsed = CountInvalid(leftPrep); + int rightUsed = CountInvalid(rightPrep); + int li = 0; + int ri = 0; + while (li < leftGroups.Count || ri < rightGroups.Count) + { + int order; + if (li >= leftGroups.Count) + order = 1; + else if (ri >= rightGroups.Count) + order = -1; + else + order = CompareRows(leftGroups[li][0], rightGroups[ri][0], options); + + if (order < 0) + { + Consume(leftGroups[li], null, plan, options, diffs, ref leftOnly, ref duplicate, ref leftUsed, ref rightUsed); + li++; + } + else if (order > 0) + { + Consume(null, rightGroups[ri], plan, options, diffs, ref rightOnly, ref duplicate, ref leftUsed, ref rightUsed); + ri++; + } + else + { + var leftGroup = leftGroups[li]; + var rightGroup = rightGroups[ri]; + if (leftGroup.Count == 1 && rightGroup.Count == 1) + { + if (EmitPair(leftGroup[0], rightGroup[0], plan, options, diffs)) + different++; + else + matched++; + leftUsed++; + rightUsed++; + } + else + { + diffs.Add(MakeDuplicate(leftGroup, rightGroup, plan)); + duplicate++; + leftUsed += leftGroup.Count; + rightUsed += rightGroup.Count; + } + li++; + ri++; + } + } + + if (li != leftGroups.Count || ri != rightGroups.Count + || leftUsed != leftRows.Count || rightUsed != rightRows.Count) + { + throw new InvalidOperationException( + "对比结果与行数不一致。左侧 " + leftRows.Count + " 行,计入 " + leftUsed + + ";右侧 " + rightRows.Count + " 行,计入 " + rightUsed + "。"); + } + + diffs.Sort(CompareDiffs); + return new CompareResult + { + LeftRowCount = leftRows.Count, + RightRowCount = rightRows.Count, + MatchedCount = matched, + LeftOnlyCount = leftOnly, + RightOnlyCount = rightOnly, + DifferentCount = different, + DuplicateCount = duplicate, + InvalidCount = invalid, + Diffs = diffs.ToArray() + }; + } + + static void Consume( + List leftGroup, + List rightGroup, + Plan plan, + CompareOptions options, + List diffs, + ref int onlyCount, + ref int duplicateCount, + ref int leftUsed, + ref int rightUsed) + { + var group = leftGroup ?? rightGroup; + bool isLeft = leftGroup != null; + if (group.Count > 1) + { + diffs.Add(MakeDuplicate(isLeft ? group : null, isLeft ? null : group, plan)); + duplicateCount++; + } + else + { + diffs.Add(MakeMissing(group[0], plan, options, isLeft)); + onlyCount++; + } + if (isLeft) + leftUsed += group.Count; + else + rightUsed += group.Count; + } + + static bool EmitPair(PreparedRow left, PreparedRow right, Plan plan, CompareOptions options, List diffs) + { + var cells = new CellDiff[plan.ValueNames.Length]; + bool any = false; + for (int i = 0; i < cells.Length; i++) + { + var lv = left.Values[i]; + var rv = right.Values[i]; + bool different = !ScalarValue.AreEqual(lv, rv, options, true); + if (different) + any = true; + cells[i] = new CellDiff + { + ColumnName = plan.ValueNames[i], + LeftText = lv.ToDisplay(), + RightText = rv.ToDisplay(), + LeftIsNull = lv.IsNull, + RightIsNull = rv.IsNull, + IsDifferent = different + }; + } + if (!any) + return false; + diffs.Add(new RowDiff + { + Status = DiffStatus.Different, + KeyText = FormatKey(left.Keys), + Cells = cells + }); + return true; + } + + static RowDiff MakeMissing(PreparedRow row, Plan plan, CompareOptions options, bool isLeft) + { + var cells = new CellDiff[plan.ValueNames.Length]; + for (int i = 0; i < cells.Length; i++) + { + var value = row.Values[i]; + cells[i] = new CellDiff + { + ColumnName = plan.ValueNames[i], + LeftText = isLeft ? value.ToDisplay() : "(无此行)", + RightText = isLeft ? "(无此行)" : value.ToDisplay(), + LeftIsNull = isLeft && value.IsNull, + RightIsNull = !isLeft && value.IsNull, + LeftMissing = !isLeft, + RightMissing = isLeft, + IsDifferent = true + }; + } + return new RowDiff + { + Status = isLeft ? DiffStatus.LeftOnly : DiffStatus.RightOnly, + KeyText = FormatKey(row.Keys), + Cells = cells + }; + } + + static RowDiff MakeDuplicate(List leftGroup, List rightGroup, Plan plan) + { + int lc = leftGroup == null ? 0 : leftGroup.Count; + int rc = rightGroup == null ? 0 : rightGroup.Count; + var sample = leftGroup != null ? leftGroup[0] : rightGroup[0]; + string message; + if (rc == 0) + message = "左侧有 " + lc + " 行使用此键,右侧没有,已跳过值比较。"; + else if (lc == 0) + message = "右侧有 " + rc + " 行使用此键,左侧没有,已跳过值比较。"; + else + message = "左侧 " + lc + " 行、右侧 " + rc + " 行使用此键,已跳过值比较。"; + return new RowDiff + { + Status = DiffStatus.DuplicateKey, + KeyText = FormatKey(sample.Keys), + Message = message, + Cells = new CellDiff[0] + }; + } + + static int EmitInvalid(List rows, Plan plan, CompareOptions options, bool isLeft, List diffs) + { + int count = 0; + for (int i = 0; i < rows.Count; i++) + { + var row = rows[i]; + if (!row.Invalid) + continue; + count++; + var names = new List(); + for (int k = 0; k < row.Keys.Length; k++) + { + if (row.Keys[k].IsNull) + names.Add(plan.KeyNames[k]); + } + var cells = new CellDiff[plan.ValueNames.Length]; + for (int c = 0; c < cells.Length; c++) + { + var value = row.Values[c]; + cells[c] = new CellDiff + { + ColumnName = plan.ValueNames[c], + LeftText = isLeft ? value.ToDisplay() : "(无此行)", + RightText = isLeft ? "(无此行)" : value.ToDisplay(), + LeftIsNull = isLeft && value.IsNull, + RightIsNull = !isLeft && value.IsNull, + LeftMissing = !isLeft, + RightMissing = isLeft, + IsDifferent = true + }; + } + diffs.Add(new RowDiff + { + Status = DiffStatus.InvalidKey, + KeyText = FormatKey(row.Keys), + Message = (isLeft ? "左侧" : "右侧") + "键含 NULL(" + string.Join(",", names.ToArray()) + "),无法对齐。", + Cells = cells + }); + } + return count; + } + + static int CompareDiffs(RowDiff a, RowDiff b) + { + int s = ((int)a.Status).CompareTo((int)b.Status); + if (s != 0) + return s; + return string.Compare(a.KeyText, b.KeyText, StringComparison.Ordinal); + } + + static string FormatKey(ScalarValue[] keys) + { + var parts = new string[keys.Length]; + for (int i = 0; i < keys.Length; i++) + parts[i] = keys[i].ToDisplay(); + return string.Join(" | ", parts); + } + + static int CountInvalid(List rows) + { + int n = 0; + for (int i = 0; i < rows.Count; i++) + { + if (rows[i].Invalid) + n++; + } + return n; + } + + static List ValidOnly(List rows) + { + var list = new List(); + for (int i = 0; i < rows.Count; i++) + { + if (!rows[i].Invalid) + list.Add(rows[i]); + } + return list; + } + + static int CompareRows(PreparedRow left, PreparedRow right, CompareOptions options) + { + int n = left.Keys.Length; + for (int i = 0; i < n; i++) + { + int c = ScalarValue.CompareKey(left.Keys[i], right.Keys[i], options); + if (c != 0) + return c; + } + return 0; + } + + static List> Group(List rows, CompareOptions options) + { + var groups = new List>(); + int i = 0; + while (i < rows.Count) + { + int j = i + 1; + while (j < rows.Count && CompareRows(rows[i], rows[j], options) == 0) + j++; + var group = new List(j - i); + for (int k = i; k < j; k++) + group.Add(rows[k]); + groups.Add(group); + i = j; + } + return groups; + } + + static List Prepare( + IList rows, + IList columns, + int[] keyIndex, + int[] valueIndex, + CompareOptions options) + { + int width = columns == null ? 0 : columns.Count; + var list = new List(rows.Count); + for (int r = 0; r < rows.Count; r++) + { + var row = rows[r]; + if (row == null || row.Length != width) + throw new InvalidOperationException("读取到的列数与字段列表不一致。"); + var keys = new ScalarValue[keyIndex.Length]; + bool invalid = false; + for (int i = 0; i < keyIndex.Length; i++) + { + keys[i] = ScalarValue.From(row[keyIndex[i]], options); + if (keys[i].IsNull) + invalid = true; + } + var values = new ScalarValue[valueIndex.Length]; + for (int i = 0; i < valueIndex.Length; i++) + values[i] = ScalarValue.From(row[valueIndex[i]], options); + list.Add(new PreparedRow { Keys = keys, Values = values, Invalid = invalid }); + } + return list; + } + + static Plan BuildPlan(IList leftColumns, IList rightColumns, IList mappings) + { + var active = new List(); + var leftSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + var rightSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + if (mappings != null) + { + for (int i = 0; i < mappings.Count; i++) + { + var mapping = mappings[i]; + if (mapping == null || (!mapping.IsKey && !mapping.Compare)) + continue; + var left = (mapping.LeftColumn ?? "").Trim(); + var right = (mapping.RightColumn ?? "").Trim(); + if (left.Length == 0 || right.Length == 0) + throw new InvalidOperationException("键列和对比列都需要同时选择左右字段。"); + if (!leftSeen.Add(left)) + throw new InvalidOperationException("左侧列重复选择:" + left); + if (!rightSeen.Add(right)) + throw new InvalidOperationException("右侧列重复选择:" + right); + active.Add(new ColumnMapping + { + LeftColumn = left, + RightColumn = right, + IsKey = mapping.IsKey, + Compare = mapping.Compare + }); + } + } + if (!active.Exists(m => m.IsKey)) + throw new InvalidOperationException("请至少勾选一个键列。"); + + var keyMaps = new List(); + var valueMaps = new List(); + for (int i = 0; i < active.Count; i++) + { + if (active[i].IsKey) + keyMaps.Add(active[i]); + if (active[i].Compare) + valueMaps.Add(active[i]); + } + + return new Plan + { + KeyNames = Names(keyMaps), + ValueNames = ValueNames(valueMaps), + LeftKeyIndex = Indexes(leftColumns, keyMaps, true), + RightKeyIndex = Indexes(rightColumns, keyMaps, false), + LeftValueIndex = Indexes(leftColumns, valueMaps, true), + RightValueIndex = Indexes(rightColumns, valueMaps, false) + }; + } + + static string[] Names(List maps) + { + var names = new string[maps.Count]; + for (int i = 0; i < maps.Count; i++) + names[i] = maps[i].LeftColumn; + return names; + } + + static string[] ValueNames(List maps) + { + var names = new string[maps.Count]; + for (int i = 0; i < maps.Count; i++) + { + var left = maps[i].LeftColumn; + var right = maps[i].RightColumn; + names[i] = string.Equals(left, right, StringComparison.OrdinalIgnoreCase) + ? left + : left + " → " + right; + } + return names; + } + + static int[] Indexes(IList columns, List maps, bool left) + { + var indexes = new int[maps.Count]; + for (int i = 0; i < maps.Count; i++) + { + var name = left ? maps[i].LeftColumn : maps[i].RightColumn; + indexes[i] = IndexOf(columns, name); + } + return indexes; + } + + static int IndexOf(IList columns, string name) + { + if (columns != null) + { + for (int i = 0; i < columns.Count; i++) + { + if (string.Equals(columns[i], name, StringComparison.OrdinalIgnoreCase)) + return i; + } + } + throw new InvalidOperationException("找不到列:" + name); + } + + sealed class PreparedRow + { + public ScalarValue[] Keys; + public ScalarValue[] Values; + public bool Invalid; + } + + sealed class Plan + { + public string[] KeyNames; + public string[] ValueNames; + public int[] LeftKeyIndex; + public int[] RightKeyIndex; + public int[] LeftValueIndex; + public int[] RightValueIndex; + } + } +} diff --git a/src/DataCompare.Core/DataCompare.Core.csproj b/src/DataCompare.Core/DataCompare.Core.csproj new file mode 100644 index 0000000..204177d --- /dev/null +++ b/src/DataCompare.Core/DataCompare.Core.csproj @@ -0,0 +1,10 @@ + + + net9.0 + DataCompare.Core + DataCompare.Core + disable + 10.0 + disable + + diff --git a/src/DataCompare.Core/DbKind.cs b/src/DataCompare.Core/DbKind.cs new file mode 100644 index 0000000..3d8d8bf --- /dev/null +++ b/src/DataCompare.Core/DbKind.cs @@ -0,0 +1,34 @@ +namespace DataCompare.Core +{ + public enum DbKind + { + SqlServer = 0, + MySql = 1, + GaussDb = 2 + } + + public static class DbKindInfo + { + public static string DisplayName(DbKind kind) + { + switch (kind) + { + case DbKind.SqlServer: return "SQL Server"; + case DbKind.MySql: return "MySQL"; + case DbKind.GaussDb: return "GaussDB"; + default: return kind.ToString(); + } + } + + public static int DefaultPort(DbKind kind) + { + switch (kind) + { + case DbKind.SqlServer: return 1433; + case DbKind.MySql: return 3306; + case DbKind.GaussDb: return 5432; + default: return 0; + } + } + } +} diff --git a/src/DataCompare.Core/Models.cs b/src/DataCompare.Core/Models.cs new file mode 100644 index 0000000..729937f --- /dev/null +++ b/src/DataCompare.Core/Models.cs @@ -0,0 +1,194 @@ +using System; + +namespace DataCompare.Core +{ + public sealed class ConnectionProfile + { + public Guid Id { get; set; } + public string Name { get; set; } + public DbKind Kind { get; set; } + public string Host { get; set; } + public int Port { get; set; } + public string Database { get; set; } + public string Username { get; set; } + public string Password { get; set; } + public string Schema { get; set; } + public string Extra { get; set; } + + public override string ToString() + { + if (!string.IsNullOrWhiteSpace(Name)) + return Name; + return (Host ?? "") + ":" + Port; + } + } + + public sealed class TableRef + { + public string Catalog { get; set; } + public string Schema { get; set; } + public string Name { get; set; } + + public string Display + { + get + { + var text = Name ?? ""; + if (!string.IsNullOrEmpty(Schema)) + text = Schema + "." + text; + if (!string.IsNullOrEmpty(Catalog)) + text = Catalog + "." + text; + return text; + } + } + + public override string ToString() + { + return Display; + } + } + + public sealed class ColumnInfo + { + public string Name { get; set; } + public string DataType { get; set; } + public bool Nullable { get; set; } + } + + public sealed class ColumnMapping + { + public string LeftColumn { get; set; } + public string RightColumn { get; set; } + public bool IsKey { get; set; } + public bool Compare { get; set; } + } + + public enum DatePrecision + { + Second = 0, + Millisecond = 1, + Full = 2 + } + + public sealed class CompareOptions + { + public bool TrimStrings { get; set; } + public bool IgnoreCase { get; set; } + public bool NullEqualsEmpty { get; set; } + public bool CoerceNumericStrings { get; set; } + public bool CoerceBoolNumbers { get; set; } + public bool CoerceDateStrings { get; set; } + public DatePrecision DatePrecision { get; set; } + public int DecimalScale { get; set; } + public decimal FloatTolerance { get; set; } + + public static CompareOptions CreateDefault() + { + return new CompareOptions + { + TrimStrings = true, + IgnoreCase = false, + NullEqualsEmpty = false, + CoerceNumericStrings = true, + CoerceBoolNumbers = true, + CoerceDateStrings = true, + DatePrecision = DatePrecision.Second, + DecimalScale = -1, + FloatTolerance = 0.0001m + }; + } + } + + public enum DiffStatus + { + LeftOnly = 0, + RightOnly = 1, + Different = 2, + DuplicateKey = 3, + InvalidKey = 4 + } + + public sealed class CellDiff + { + public string ColumnName { get; set; } + public string LeftText { get; set; } + public string RightText { get; set; } + public bool LeftIsNull { get; set; } + public bool RightIsNull { get; set; } + public bool LeftMissing { get; set; } + public bool RightMissing { get; set; } + public bool IsDifferent { get; set; } + } + + public sealed class RowDiff + { + public DiffStatus Status { get; set; } + public string KeyText { get; set; } + public string Message { get; set; } + public CellDiff[] Cells { get; set; } + + public string StatusText + { + get + { + switch (Status) + { + case DiffStatus.LeftOnly: return "仅左侧"; + case DiffStatus.RightOnly: return "仅右侧"; + case DiffStatus.Different: return "内容不同"; + case DiffStatus.DuplicateKey: return "键重复"; + case DiffStatus.InvalidKey: return "键无效"; + default: return ""; + } + } + } + + public string Summary + { + get + { + if (Status == DiffStatus.Different) + { + int count = 0; + var names = ""; + if (Cells != null) + { + for (int i = 0; i < Cells.Length; i++) + { + if (!Cells[i].IsDifferent) + continue; + if (count < 8) + { + if (count > 0) + names += ","; + names += Cells[i].ColumnName; + } + count++; + } + } + if (count > 8) + names += "…"; + return count + " 列:" + names; + } + if (Status == DiffStatus.LeftOnly) + return "右侧没有此键"; + if (Status == DiffStatus.RightOnly) + return "左侧没有此键"; + return Message ?? ""; + } + } + } + + public sealed class CompareResult + { + public int LeftRowCount { get; set; } + public int RightRowCount { get; set; } + public int MatchedCount { get; set; } + public int LeftOnlyCount { get; set; } + public int RightOnlyCount { get; set; } + public int DifferentCount { get; set; } + public int DuplicateCount { get; set; } + public int InvalidCount { get; set; } + public RowDiff[] Diffs { get; set; } + } +} diff --git a/src/DataCompare.Core/ScalarValue.cs b/src/DataCompare.Core/ScalarValue.cs new file mode 100644 index 0000000..3183466 --- /dev/null +++ b/src/DataCompare.Core/ScalarValue.cs @@ -0,0 +1,595 @@ +using System; +using System.Globalization; +using System.Security.Cryptography; + +namespace DataCompare.Core +{ + public enum ScalarKind + { + Null = 0, + Boolean = 1, + Integer = 2, + Decimal = 3, + Float = 4, + Date = 5, + Text = 6, + Binary = 7 + } + + public sealed class ScalarValue + { + static readonly char[] Hex = "0123456789ABCDEF".ToCharArray(); + static readonly string[] DateFormats = + { + "yyyy-MM-dd HH:mm:ss.fffffff", + "yyyy-MM-dd HH:mm:ss.ffffff", + "yyyy-MM-dd HH:mm:ss.fff", + "yyyy-MM-dd HH:mm:ss.ff", + "yyyy-MM-dd HH:mm:ss.f", + "yyyy-MM-dd HH:mm:ss", + "yyyy-MM-dd HH:mm", + "yyyy-MM-dd", + "yyyy/MM/dd HH:mm:ss.fff", + "yyyy/MM/dd HH:mm:ss", + "yyyy/MM/dd", + "yyyyMMddHHmmss", + "yyyyMMdd" + }; + + public ScalarKind Kind { get; } + public bool BoolValue { get; } + public long IntegerValue { get; } + public decimal DecimalValue { get; } + public double FloatValue { get; } + public DateTime DateValue { get; } + public string TextValue { get; } + public string BinaryText { get; } + + ScalarValue( + ScalarKind kind, + bool boolValue, + long integerValue, + decimal decimalValue, + double floatValue, + DateTime dateValue, + string textValue, + string binaryText) + { + Kind = kind; + BoolValue = boolValue; + IntegerValue = integerValue; + DecimalValue = decimalValue; + FloatValue = floatValue; + DateValue = dateValue; + TextValue = textValue; + BinaryText = binaryText; + } + + public bool IsNull + { + get { return Kind == ScalarKind.Null; } + } + + public static ScalarValue Null() + { + return new ScalarValue(ScalarKind.Null, false, 0, 0, 0, default(DateTime), null, null); + } + + public static ScalarValue From(object value, CompareOptions options) + { + if (options == null) + options = CompareOptions.CreateDefault(); + if (value == null || value == DBNull.Value) + return Null(); + + if (value is bool) + return Boolean((bool)value); + + if (value is byte || value is sbyte || value is short || value is ushort + || value is int || value is uint || value is long) + return Integer(Convert.ToInt64(value, CultureInfo.InvariantCulture)); + + if (value is ulong) + return Decimal((decimal)(ulong)value); + + if (value is decimal) + return Decimal((decimal)value); + + if (value is float) + return Float((float)value); + + if (value is double) + return Float((double)value); + + if (value is DateTime) + return Date(Truncate((DateTime)value, options.DatePrecision)); + + if (value is DateTimeOffset) + return Date(Truncate(((DateTimeOffset)value).DateTime, options.DatePrecision)); + + if (value is TimeSpan) + return Text(((TimeSpan)value).ToString("c", CultureInfo.InvariantCulture), options); + + if (value is Guid) + return Text(((Guid)value).ToString("D"), options); + + if (value is byte[]) + return Binary((byte[])value); + + var asArray = value as Array; + if (asArray != null && asArray.Rank == 1) + return Text(FormatArray(asArray, options), options); + + return Text(Convert.ToString(value, CultureInfo.InvariantCulture) ?? "", options); + } + + public string ToDisplay() + { + switch (Kind) + { + case ScalarKind.Null: + return "NULL"; + case ScalarKind.Boolean: + return BoolValue ? "true" : "false"; + case ScalarKind.Integer: + return IntegerValue.ToString(CultureInfo.InvariantCulture); + case ScalarKind.Decimal: + return DecimalValue.ToString("0.#############################", CultureInfo.InvariantCulture); + case ScalarKind.Float: + if (double.IsNaN(FloatValue)) + return "NaN"; + if (double.IsPositiveInfinity(FloatValue)) + return "Infinity"; + if (double.IsNegativeInfinity(FloatValue)) + return "-Infinity"; + return FloatValue.ToString("G15", CultureInfo.InvariantCulture); + case ScalarKind.Date: + return FormatDate(DateValue); + case ScalarKind.Text: + return TextValue ?? ""; + case ScalarKind.Binary: + return BinaryText ?? ""; + default: + return ""; + } + } + + public static bool AreEqual(ScalarValue left, ScalarValue right, CompareOptions options, bool valueColumn) + { + if (options == null) + options = CompareOptions.CreateDefault(); + if (left == null) + left = Null(); + if (right == null) + right = Null(); + + if (left.Kind == ScalarKind.Null && right.Kind == ScalarKind.Null) + return true; + if (left.Kind == ScalarKind.Null || right.Kind == ScalarKind.Null) + return false; + + if (BothNumeric(left, right, options)) + return NumbersEqual(left, right, options, valueColumn); + + bool lb; + bool rb; + if (TryBool(left, options, out lb) && TryBool(right, options, out rb) + && (left.Kind == ScalarKind.Boolean || right.Kind == ScalarKind.Boolean)) + return lb == rb; + + DateTime ld; + DateTime rd; + if (TryDate(left, options, out ld) && TryDate(right, options, out rd) + && (left.Kind == ScalarKind.Date || right.Kind == ScalarKind.Date)) + return ld == rd; + + if (left.Kind == ScalarKind.Text && right.Kind == ScalarKind.Text) + { + var cmp = options.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + return string.Equals(left.TextValue, right.TextValue, cmp); + } + + if (left.Kind == ScalarKind.Binary && right.Kind == ScalarKind.Binary) + return string.Equals(left.BinaryText, right.BinaryText, StringComparison.Ordinal); + + return false; + } + + public static int CompareKey(ScalarValue left, ScalarValue right, CompareOptions options) + { + if (options == null) + options = CompareOptions.CreateDefault(); + if (left == null) + left = Null(); + if (right == null) + right = Null(); + if (AreEqual(left, right, options, false)) + return 0; + + decimal ln; + decimal rn; + if (TrySortDecimal(left, options, out ln) && TrySortDecimal(right, options, out rn)) + { + int c = ln.CompareTo(rn); + if (c != 0) + return c; + } + else + { + DateTime ld; + DateTime rd; + if (TryDate(left, options, out ld) && TryDate(right, options, out rd)) + { + int c = DateTime.Compare(ld, rd); + if (c != 0) + return c; + } + else + { + bool lb; + bool rb; + if (TryBool(left, options, out lb) && TryBool(right, options, out rb)) + { + int c = lb.CompareTo(rb); + if (c != 0) + return c; + } + } + } + + int kind = KindRank(left).CompareTo(KindRank(right)); + if (kind != 0) + return kind; + var textCmp = options.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + int text = string.Compare(left.ToDisplay(), right.ToDisplay(), textCmp); + if (text != 0) + return text; + return string.CompareOrdinal(left.SortToken(), right.SortToken()); + } + + static ScalarValue Boolean(bool value) + { + return new ScalarValue(ScalarKind.Boolean, value, 0, 0, 0, default(DateTime), null, null); + } + + static ScalarValue Integer(long value) + { + return new ScalarValue(ScalarKind.Integer, false, value, 0, 0, default(DateTime), null, null); + } + + static ScalarValue Decimal(decimal value) + { + return new ScalarValue(ScalarKind.Decimal, false, 0, value, 0, default(DateTime), null, null); + } + + static ScalarValue Float(double value) + { + return new ScalarValue(ScalarKind.Float, false, 0, 0, value, default(DateTime), null, null); + } + + static ScalarValue Date(DateTime value) + { + return new ScalarValue(ScalarKind.Date, false, 0, 0, 0, value, null, null); + } + + static ScalarValue Text(string value, CompareOptions options) + { + value = value ?? ""; + if (options.TrimStrings) + value = value.Trim(); + if (value.Length == 0 && options.NullEqualsEmpty) + return Null(); + return new ScalarValue(ScalarKind.Text, false, 0, 0, 0, default(DateTime), value, null); + } + + static ScalarValue Binary(byte[] bytes) + { + if (bytes.Length <= 64) + return new ScalarValue(ScalarKind.Binary, false, 0, 0, 0, default(DateTime), null, "0x" + ToHex(bytes)); + + string hash; + using (var sha = SHA256.Create()) + hash = ToHex(sha.ComputeHash(bytes)); + var text = "长度 " + bytes.Length.ToString(CultureInfo.InvariantCulture) + ",SHA256 " + hash; + return new ScalarValue(ScalarKind.Binary, false, 0, 0, 0, default(DateTime), null, text); + } + + static string FormatArray(Array array, CompareOptions options) + { + var parts = new string[array.Length]; + for (int i = 0; i < array.Length; i++) + { + var item = array.GetValue(i); + if (item is Array) + parts[i] = Convert.ToString(item, CultureInfo.InvariantCulture) ?? ""; + else + parts[i] = From(item, options).ToDisplay(); + } + return "{" + string.Join(",", parts) + "}"; + } + + static DateTime Truncate(DateTime value, DatePrecision precision) + { + var unspecified = DateTime.SpecifyKind(value, DateTimeKind.Unspecified); + switch (precision) + { + case DatePrecision.Second: + return new DateTime(unspecified.Year, unspecified.Month, unspecified.Day, + unspecified.Hour, unspecified.Minute, unspecified.Second, DateTimeKind.Unspecified); + case DatePrecision.Millisecond: + var ticks = unspecified.Ticks - (unspecified.Ticks % TimeSpan.TicksPerMillisecond); + return new DateTime(ticks, DateTimeKind.Unspecified); + default: + return unspecified; + } + } + + static string FormatDate(DateTime value) + { + if (value.Ticks % TimeSpan.TicksPerSecond == 0) + return value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); + return value.ToString("yyyy-MM-dd HH:mm:ss.fffffff", CultureInfo.InvariantCulture).TrimEnd('0'); + } + + static bool BothNumeric(ScalarValue left, ScalarValue right, CompareOptions options) + { + return IsNumericKind(left, options) && IsNumericKind(right, options); + } + + static bool IsNumericKind(ScalarValue value, CompareOptions options) + { + if (value.Kind == ScalarKind.Integer || value.Kind == ScalarKind.Decimal || value.Kind == ScalarKind.Float) + return true; + decimal ignored; + return value.Kind == ScalarKind.Text + && options.CoerceNumericStrings + && TryParsePlainDecimal(value.TextValue, out ignored); + } + + static bool NumbersEqual(ScalarValue left, ScalarValue right, CompareOptions options, bool valueColumn) + { + if (valueColumn && (left.Kind == ScalarKind.Float || right.Kind == ScalarKind.Float)) + { + double a = ToDouble(left, options); + double b = ToDouble(right, options); + if (double.IsNaN(a) && double.IsNaN(b)) + return true; + if (double.IsNaN(a) || double.IsNaN(b)) + return false; + if (double.IsInfinity(a) || double.IsInfinity(b)) + return a == b; + decimal tol = options.FloatTolerance; + if (tol < 0) + tol = 0; + return Math.Abs(a - b) <= (double)tol; + } + + decimal da; + decimal db; + if (!TryExactDecimal(left, options, out da) || !TryExactDecimal(right, options, out db)) + { + double a = ToDouble(left, options); + double b = ToDouble(right, options); + if (double.IsNaN(a) && double.IsNaN(b)) + return true; + return a == b; + } + + if (valueColumn && options.DecimalScale >= 0) + { + da = Math.Round(da, options.DecimalScale, MidpointRounding.AwayFromZero); + db = Math.Round(db, options.DecimalScale, MidpointRounding.AwayFromZero); + } + return da == db; + } + + static bool TryExactDecimal(ScalarValue value, CompareOptions options, out decimal number) + { + if (value.Kind == ScalarKind.Integer) + { + number = value.IntegerValue; + return true; + } + if (value.Kind == ScalarKind.Decimal) + { + number = value.DecimalValue; + return true; + } + if (value.Kind == ScalarKind.Text && options.CoerceNumericStrings) + return TryParsePlainDecimal(value.TextValue, out number); + number = 0; + return false; + } + + static bool TrySortDecimal(ScalarValue value, CompareOptions options, out decimal number) + { + if (TryExactDecimal(value, options, out number)) + return true; + if (value.Kind != ScalarKind.Float) + return false; + if (double.IsNaN(value.FloatValue) || double.IsInfinity(value.FloatValue)) + return false; + try + { + number = (decimal)value.FloatValue; + return true; + } + catch (OverflowException) + { + return false; + } + } + + static double ToDouble(ScalarValue value, CompareOptions options) + { + switch (value.Kind) + { + case ScalarKind.Integer: + return value.IntegerValue; + case ScalarKind.Decimal: + return (double)value.DecimalValue; + case ScalarKind.Float: + return value.FloatValue; + case ScalarKind.Text: + decimal parsed; + if (TryParsePlainDecimal(value.TextValue, out parsed)) + return (double)parsed; + break; + } + return double.NaN; + } + + static bool TryBool(ScalarValue value, CompareOptions options, out bool result) + { + if (value.Kind == ScalarKind.Boolean) + { + result = value.BoolValue; + return true; + } + if (!options.CoerceBoolNumbers) + { + result = false; + return false; + } + if (value.Kind == ScalarKind.Integer && (value.IntegerValue == 0 || value.IntegerValue == 1)) + { + result = value.IntegerValue == 1; + return true; + } + if (value.Kind == ScalarKind.Decimal && (value.DecimalValue == 0m || value.DecimalValue == 1m)) + { + result = value.DecimalValue == 1m; + return true; + } + if (value.Kind == ScalarKind.Text) + { + var text = value.TextValue ?? ""; + if (string.Equals(text, "1", StringComparison.OrdinalIgnoreCase) + || string.Equals(text, "true", StringComparison.OrdinalIgnoreCase)) + { + result = true; + return true; + } + if (string.Equals(text, "0", StringComparison.OrdinalIgnoreCase) + || string.Equals(text, "false", StringComparison.OrdinalIgnoreCase)) + { + result = false; + return true; + } + } + result = false; + return false; + } + + static bool TryDate(ScalarValue value, CompareOptions options, out DateTime result) + { + if (value.Kind == ScalarKind.Date) + { + result = value.DateValue; + return true; + } + if (value.Kind == ScalarKind.Text && options.CoerceDateStrings) + { + var text = (value.TextValue ?? "").Trim(); + DateTime parsed; + if (DateTime.TryParseExact(text, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsed) + || DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out parsed)) + { + result = Truncate(parsed, options.DatePrecision); + return true; + } + } + result = default(DateTime); + return false; + } + + static bool TryParsePlainDecimal(string text, out decimal value) + { + value = 0; + if (string.IsNullOrEmpty(text) || !LooksPlain(text)) + return false; + return decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value); + } + + static bool LooksPlain(string text) + { + int i = 0; + if (text[0] == '-' || text[0] == '+') + i++; + if (i >= text.Length || !char.IsDigit(text[i])) + return false; + bool dot = false; + for (; i < text.Length; i++) + { + char c = text[i]; + if (c == '.') + { + if (dot) + return false; + dot = true; + if (i + 1 >= text.Length || !char.IsDigit(text[i + 1])) + return false; + } + else if (!char.IsDigit(c)) + { + return false; + } + } + return true; + } + + static int KindRank(ScalarValue value) + { + switch (value.Kind) + { + case ScalarKind.Null: return 0; + case ScalarKind.Boolean: return 1; + case ScalarKind.Integer: + case ScalarKind.Decimal: + case ScalarKind.Float: + return 2; + case ScalarKind.Date: return 3; + case ScalarKind.Text: return 4; + case ScalarKind.Binary: return 5; + default: return 9; + } + } + + string SortToken() + { + switch (Kind) + { + case ScalarKind.Null: + return "N"; + case ScalarKind.Boolean: + return BoolValue ? "B1" : "B0"; + case ScalarKind.Integer: + return "I" + IntegerValue.ToString(CultureInfo.InvariantCulture); + case ScalarKind.Decimal: + return "D" + DecimalValue.ToString(CultureInfo.InvariantCulture); + case ScalarKind.Float: + return "F" + BitConverter.DoubleToInt64Bits(FloatValue).ToString(CultureInfo.InvariantCulture); + case ScalarKind.Date: + return "T" + DateValue.Ticks.ToString(CultureInfo.InvariantCulture); + case ScalarKind.Text: + return "S" + (TextValue ?? ""); + case ScalarKind.Binary: + return "X" + (BinaryText ?? ""); + default: + return "U"; + } + } + + static string ToHex(byte[] data) + { + var chars = new char[data.Length * 2]; + for (int i = 0; i < data.Length; i++) + { + int b = data[i]; + chars[i * 2] = Hex[b >> 4]; + chars[i * 2 + 1] = Hex[b & 15]; + } + return new string(chars); + } + } +} diff --git a/src/DataCompare.Data/AdoSource.cs b/src/DataCompare.Data/AdoSource.cs new file mode 100644 index 0000000..6eefc4c --- /dev/null +++ b/src/DataCompare.Data/AdoSource.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Globalization; +using System.Threading; +using DataCompare.Core; + +namespace DataCompare.Data +{ + public abstract class AdoSource : IDataSource + { + readonly ConnectionProfile _profile; + protected IDbConnection _connection; + + protected AdoSource(ConnectionProfile profile) + { + if (profile == null) + throw new ArgumentNullException("profile"); + _profile = profile; + } + + protected ConnectionProfile Profile + { + get { return _profile; } + } + + protected abstract IDbConnection CreateConnection(); + + protected abstract string Quote(string identifier); + + protected abstract string SelectPrefix(int? limit); + + protected virtual string SelectSuffix(int? limit) + { + if (!limit.HasValue) + return ""; + return " LIMIT " + limit.Value.ToString(CultureInfo.InvariantCulture); + } + + public void Test() + { + try + { + EnsureOpen(); + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "SELECT 1"; + cmd.CommandTimeout = 15; + cmd.ExecuteScalar(); + } + } + catch (Exception ex) + { + if (ex is InvalidOperationException) + throw; + throw new InvalidOperationException( + DbKindInfo.DisplayName(_profile.Kind) + " 连接失败:" + ex.Message, ex); + } + } + + public virtual IList GetTables() + { + EnsureOpen(); + var sql = @" +SELECT table_schema, table_name +FROM information_schema.tables +WHERE table_type = 'BASE TABLE'"; + sql += TableFilterSql(); + sql += @" +ORDER BY table_schema, table_name"; + + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandTimeout = 60; + BindTableFilter(cmd); + var list = new List(); + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + list.Add(new TableRef + { + Schema = Convert.ToString(reader.GetValue(0)), + Name = Convert.ToString(reader.GetValue(1)) + }); + } + } + return list; + } + } + + public IList GetColumns(TableRef table) + { + if (table == null || string.IsNullOrWhiteSpace(table.Name)) + throw new InvalidOperationException("表名不能为空。"); + EnsureOpen(); + var sql = @" +SELECT column_name, data_type, is_nullable +FROM " + ColumnSource(table) + @" +WHERE table_schema = @schema AND table_name = @table +ORDER BY ordinal_position"; + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandTimeout = 60; + Add(cmd, "@schema", table.Schema ?? ""); + Add(cmd, "@table", table.Name); + var list = new List(); + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + var nullable = string.Equals(Convert.ToString(reader.GetValue(2)), "YES", StringComparison.OrdinalIgnoreCase); + list.Add(new ColumnInfo + { + Name = Convert.ToString(reader.GetValue(0)), + DataType = Convert.ToString(reader.GetValue(1)), + Nullable = nullable + }); + } + } + if (list.Count == 0) + throw new InvalidOperationException("没有读到字段:" + Qualify(table)); + return list; + } + } + + public List ReadRows( + TableRef table, + IList columns, + string filter, + int? limit, + CancellationToken cancellationToken, + IProgress progress) + { + if (columns == null || columns.Count == 0) + throw new InvalidOperationException("没有可读取的列。"); + EnsureOpen(); + var quoted = new string[columns.Count]; + for (int i = 0; i < columns.Count; i++) + { + var name = (columns[i] ?? "").Trim(); + if (name.Length == 0) + throw new InvalidOperationException("列名不能为空。"); + quoted[i] = Quote(name); + } + + var sql = SelectPrefix(limit) + string.Join(", ", quoted) + " FROM " + Qualify(table); + var where = FilterText.Normalize(filter); + if (where != null) + sql += " WHERE " + where; + sql += SelectSuffix(limit); + + try + { + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandTimeout = 180; + using (var reader = cmd.ExecuteReader()) + { + var rows = new List(); + while (reader.Read()) + { + cancellationToken.ThrowIfCancellationRequested(); + var values = new object[columns.Count]; + for (int i = 0; i < columns.Count; i++) + values[i] = reader.IsDBNull(i) ? null : reader.GetValue(i); + rows.Add(values); + if (progress != null && rows.Count % 200 == 0) + progress.Report(rows.Count); + } + if (progress != null) + progress.Report(rows.Count); + return rows; + } + } + } + catch (Exception ex) + { + if (ex is OperationCanceledException || ex is InvalidOperationException) + throw; + throw new InvalidOperationException("读取 " + Qualify(table) + " 失败:" + ex.Message, ex); + } + } + + public void Dispose() + { + if (_connection != null) + { + _connection.Dispose(); + _connection = null; + } + } + + protected abstract string TableFilterSql(); + + protected abstract void BindTableFilter(IDbCommand command); + + protected void EnsureOpen() + { + if (_connection == null) + _connection = CreateConnection(); + if (_connection.State != ConnectionState.Open) + _connection.Open(); + } + + protected virtual string ColumnSource(TableRef table) + { + return "information_schema.columns"; + } + + protected string Qualify(TableRef table) + { + if (table == null || string.IsNullOrWhiteSpace(table.Name)) + throw new InvalidOperationException("表名不能为空。"); + var name = Quote(table.Name.Trim()); + if (!string.IsNullOrWhiteSpace(table.Schema)) + name = Quote(table.Schema.Trim()) + "." + name; + if (!string.IsNullOrWhiteSpace(table.Catalog)) + name = Quote(table.Catalog.Trim()) + "." + name; + return name; + } + + protected static void Add(IDbCommand command, string name, object value) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = name; + parameter.Value = value ?? DBNull.Value; + command.Parameters.Add(parameter); + } + + protected static string AppendExtra(string connectionString, string extra) + { + if (string.IsNullOrWhiteSpace(extra)) + return connectionString; + extra = extra.Trim().TrimStart(';'); + if (extra.IndexOf('\r') >= 0 || extra.IndexOf('\n') >= 0) + throw new InvalidOperationException("附加连接参数不能换行。"); + return connectionString.TrimEnd(';') + ";" + extra; + } + + protected static string Bracket(string name, string open, string close) + { + return open + name.Replace(close, close + close) + close; + } + } +} diff --git a/src/DataCompare.Data/CompareSession.cs b/src/DataCompare.Data/CompareSession.cs new file mode 100644 index 0000000..4f1219d --- /dev/null +++ b/src/DataCompare.Data/CompareSession.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using DataCompare.Core; + +namespace DataCompare.Data +{ + public static class DataSourceFactory + { + public static IDataSource Create(ConnectionProfile profile) + { + if (profile == null) + throw new ArgumentNullException("profile"); + switch (profile.Kind) + { + case DbKind.SqlServer: + return new SqlServerSource(profile); + case DbKind.MySql: + return new MySqlSource(profile); + case DbKind.GaussDb: + return new GaussDbSource(profile); + default: + throw new InvalidOperationException("不支持的数据源类型。"); + } + } + } + + public static class CompareSession + { + public static CompareResult Execute( + ConnectionProfile leftSource, + TableRef leftTable, + string leftFilter, + ConnectionProfile rightSource, + TableRef rightTable, + string rightFilter, + IList mappings, + CompareOptions options, + IProgress progress, + CancellationToken cancellationToken) + { + if (leftTable == null || rightTable == null) + throw new InvalidOperationException("请选择左右两侧的表。"); + if (options == null) + options = CompareOptions.CreateDefault(); + + var columns = CollectColumns(mappings); + CompareEngine.Execute(columns.Left, new object[0][], columns.Right, new object[0][], mappings, options); + Report(progress, "正在读取左侧…"); + List leftRows; + using (var source = DataSourceFactory.Create(leftSource)) + { + leftRows = source.ReadRows( + leftTable, + columns.Left, + leftFilter, + null, + cancellationToken, + Rows("左侧", progress)); + } + + cancellationToken.ThrowIfCancellationRequested(); + Report(progress, "正在读取右侧…"); + List rightRows; + using (var source = DataSourceFactory.Create(rightSource)) + { + rightRows = source.ReadRows( + rightTable, + columns.Right, + rightFilter, + null, + cancellationToken, + Rows("右侧", progress)); + } + + cancellationToken.ThrowIfCancellationRequested(); + Report(progress, "正在对比 " + leftRows.Count + " / " + rightRows.Count + " 行…"); + var result = CompareEngine.Execute(columns.Left, leftRows, columns.Right, rightRows, mappings, options); + Report(progress, "对比完成"); + return result; + } + + static ColumnLists CollectColumns(IList mappings) + { + var left = new List(); + var right = new List(); + var leftSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + var rightSeen = new HashSet(StringComparer.OrdinalIgnoreCase); + if (mappings != null) + { + for (int i = 0; i < mappings.Count; i++) + { + var mapping = mappings[i]; + if (mapping == null || (!mapping.IsKey && !mapping.Compare)) + continue; + var l = (mapping.LeftColumn ?? "").Trim(); + var r = (mapping.RightColumn ?? "").Trim(); + if (l.Length == 0 || r.Length == 0) + continue; + if (leftSeen.Add(l)) + left.Add(l); + if (rightSeen.Add(r)) + right.Add(r); + } + } + if (left.Count == 0 || right.Count == 0) + throw new InvalidOperationException("请至少勾选一个键列。"); + return new ColumnLists { Left = left, Right = right }; + } + + static IProgress Rows(string side, IProgress progress) + { + return new Progress(count => Report(progress, "正在读取" + side + "… " + count + " 行")); + } + + static void Report(IProgress progress, string message) + { + if (progress != null) + progress.Report(message); + } + + sealed class ColumnLists + { + public List Left; + public List Right; + } + } +} diff --git a/src/DataCompare.Data/DataCompare.Data.csproj b/src/DataCompare.Data/DataCompare.Data.csproj new file mode 100644 index 0000000..39bba3c --- /dev/null +++ b/src/DataCompare.Data/DataCompare.Data.csproj @@ -0,0 +1,16 @@ + + + net9.0 + DataCompare.Data + DataCompare.Data + disable + 10.0 + disable + + + + + + + + diff --git a/src/DataCompare.Data/FilterText.cs b/src/DataCompare.Data/FilterText.cs new file mode 100644 index 0000000..957287d --- /dev/null +++ b/src/DataCompare.Data/FilterText.cs @@ -0,0 +1,23 @@ +using System; + +namespace DataCompare.Data +{ + public static class FilterText + { + public static string Normalize(string filter) + { + if (string.IsNullOrWhiteSpace(filter)) + return null; + filter = filter.Trim(); + if (filter.StartsWith("where ", StringComparison.OrdinalIgnoreCase)) + filter = filter.Substring(6).Trim(); + if (filter.Length == 0) + return null; + if (filter.Length > 8000) + throw new InvalidOperationException("筛选条件过长。"); + if (filter.IndexOf(';') >= 0) + throw new InvalidOperationException("筛选条件不能包含分号。"); + return filter; + } + } +} diff --git a/src/DataCompare.Data/GaussDbSource.cs b/src/DataCompare.Data/GaussDbSource.cs new file mode 100644 index 0000000..db459c1 --- /dev/null +++ b/src/DataCompare.Data/GaussDbSource.cs @@ -0,0 +1,59 @@ +using System.Data; +using DataCompare.Core; +using HuaweiCloud.GaussDB; + +namespace DataCompare.Data +{ + public sealed class GaussDbSource : AdoSource + { + public GaussDbSource(ConnectionProfile profile) + : base(profile) + { + } + + protected override IDbConnection CreateConnection() + { + var builder = new GaussDBConnectionStringBuilder + { + Host = (Profile.Host ?? "").Trim(), + Port = Profile.Port > 0 ? Profile.Port : DbKindInfo.DefaultPort(DbKind.GaussDb), + Database = Profile.Database ?? "", + Username = Profile.Username ?? "", + Password = Profile.Password ?? "", + Timeout = 15, + CommandTimeout = 180, + SslMode = SslMode.Disable, + ApplicationName = "DataCompare", + IncludeErrorDetail = true, + NoResetOnClose = true + }; + return new GaussDBConnection(AppendExtra(builder.ConnectionString, Profile.Extra)); + } + + protected override string Quote(string identifier) + { + return Bracket(identifier, "\"", "\""); + } + + protected override string SelectPrefix(int? limit) + { + return "SELECT "; + } + + protected override string TableFilterSql() + { + var sql = @" + AND table_schema NOT IN ('pg_catalog', 'information_schema', 'dbe_perf', 'snapshot', 'db4ai', 'cstore') + AND table_schema NOT LIKE 'pg!_%' ESCAPE '!'"; + if (!string.IsNullOrWhiteSpace(Profile.Schema)) + sql += " AND table_schema = @schema"; + return sql; + } + + protected override void BindTableFilter(IDbCommand command) + { + if (!string.IsNullOrWhiteSpace(Profile.Schema)) + Add(command, "@schema", Profile.Schema.Trim()); + } + } +} diff --git a/src/DataCompare.Data/IDataSource.cs b/src/DataCompare.Data/IDataSource.cs new file mode 100644 index 0000000..201d6d3 --- /dev/null +++ b/src/DataCompare.Data/IDataSource.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using DataCompare.Core; + +namespace DataCompare.Data +{ + public interface IDataSource : IDisposable + { + void Test(); + IList GetTables(); + IList GetColumns(TableRef table); + List ReadRows( + TableRef table, + IList columns, + string filter, + int? limit, + CancellationToken cancellationToken, + IProgress progress); + } +} diff --git a/src/DataCompare.Data/MySqlSource.cs b/src/DataCompare.Data/MySqlSource.cs new file mode 100644 index 0000000..e4d2007 --- /dev/null +++ b/src/DataCompare.Data/MySqlSource.cs @@ -0,0 +1,57 @@ +using System.Data; +using MySqlConnector; +using DataCompare.Core; + +namespace DataCompare.Data +{ + public sealed class MySqlSource : AdoSource + { + public MySqlSource(ConnectionProfile profile) + : base(profile) + { + } + + protected override IDbConnection CreateConnection() + { + var builder = new MySqlConnectionStringBuilder + { + Server = (Profile.Host ?? "").Trim(), + Port = (uint)(Profile.Port > 0 ? Profile.Port : DbKindInfo.DefaultPort(DbKind.MySql)), + Database = Profile.Database ?? "", + UserID = Profile.Username ?? "", + Password = Profile.Password ?? "", + ConnectionTimeout = 15, + DefaultCommandTimeout = 180, + SslMode = MySqlSslMode.None, + CharacterSet = "utf8mb4", + TreatTinyAsBoolean = false, + AllowZeroDateTime = true, + ConvertZeroDateTime = true, + AllowPublicKeyRetrieval = true, + AllowUserVariables = true + }; + return new MySqlConnection(AppendExtra(builder.ConnectionString, Profile.Extra)); + } + + protected override string Quote(string identifier) + { + return Bracket(identifier, "`", "`"); + } + + protected override string SelectPrefix(int? limit) + { + return "SELECT "; + } + + protected override string TableFilterSql() + { + return " AND table_schema = @schema"; + } + + protected override void BindTableFilter(IDbCommand command) + { + var schema = string.IsNullOrWhiteSpace(Profile.Schema) ? Profile.Database : Profile.Schema; + Add(command, "@schema", (schema ?? "").Trim()); + } + } +} diff --git a/src/DataCompare.Data/SqlServerSource.cs b/src/DataCompare.Data/SqlServerSource.cs new file mode 100644 index 0000000..e720f5d --- /dev/null +++ b/src/DataCompare.Data/SqlServerSource.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Data; +using Microsoft.Data.SqlClient; +using System.Globalization; +using DataCompare.Core; + +namespace DataCompare.Data +{ + public sealed class SqlServerSource : AdoSource + { + public SqlServerSource(ConnectionProfile profile) + : base(profile) + { + } + + protected override IDbConnection CreateConnection() + { + var host = (Profile.Host ?? "").Trim(); + if (Profile.Port > 0 && host.IndexOf('\\') < 0 && host.IndexOf(',') < 0) + host = host + "," + Profile.Port.ToString(CultureInfo.InvariantCulture); + + var builder = new SqlConnectionStringBuilder + { + DataSource = host, + InitialCatalog = Profile.Database ?? "", + UserID = Profile.Username ?? "", + Password = Profile.Password ?? "", + ConnectTimeout = 15, + Encrypt = false, + TrustServerCertificate = true, + ApplicationName = "DataCompare" + }; + return new SqlConnection(AppendExtra(builder.ConnectionString, Profile.Extra)); + } + + public override IList GetTables() + { + EnsureOpen(); + var databases = new List(); + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = @" +SELECT name +FROM sys.databases +WHERE state = 0 + AND HAS_DBACCESS(name) = 1 + AND ( + name NOT IN (N'master', N'tempdb', N'model', N'msdb') + OR name = @preferred + ) +ORDER BY name"; + cmd.CommandTimeout = 30; + Add(cmd, "@preferred", string.IsNullOrWhiteSpace(Profile.Database) ? "" : Profile.Database.Trim()); + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + databases.Add(Convert.ToString(reader.GetValue(0))); + } + } + + var tables = new List(); + Exception preferredError = null; + var preferred = (Profile.Database ?? "").Trim(); + for (int i = 0; i < databases.Count; i++) + { + try + { + AppendTables(databases[i], tables); + } + catch (Exception ex) + { + if (string.Equals(databases[i], preferred, StringComparison.OrdinalIgnoreCase)) + preferredError = ex; + } + } + if (tables.Count == 0 && preferredError != null) + throw new InvalidOperationException("读取表失败:" + preferredError.Message, preferredError); + return tables; + } + + protected override string ColumnSource(TableRef table) + { + if (table == null || string.IsNullOrWhiteSpace(table.Catalog)) + return "INFORMATION_SCHEMA.COLUMNS"; + return Quote(table.Catalog.Trim()) + ".INFORMATION_SCHEMA.COLUMNS"; + } + + void AppendTables(string database, List tables) + { + var sql = "SELECT TABLE_SCHEMA, TABLE_NAME FROM " + + Quote(database) + + ".INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'"; + if (!string.IsNullOrWhiteSpace(Profile.Schema)) + sql += " AND TABLE_SCHEMA = @schema"; + sql += " ORDER BY TABLE_SCHEMA, TABLE_NAME"; + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandTimeout = 60; + if (!string.IsNullOrWhiteSpace(Profile.Schema)) + Add(cmd, "@schema", Profile.Schema.Trim()); + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + tables.Add(new TableRef + { + Catalog = database, + Schema = Convert.ToString(reader.GetValue(0)), + Name = Convert.ToString(reader.GetValue(1)) + }); + } + } + } + } + + protected override string Quote(string identifier) + { + return Bracket(identifier, "[", "]"); + } + + protected override string SelectPrefix(int? limit) + { + if (!limit.HasValue) + return "SELECT "; + return "SELECT TOP (" + limit.Value.ToString(CultureInfo.InvariantCulture) + ") "; + } + + protected override string SelectSuffix(int? limit) + { + return ""; + } + + protected override string TableFilterSql() + { + if (string.IsNullOrWhiteSpace(Profile.Schema)) + return ""; + return " AND table_schema = @schema"; + } + + protected override void BindTableFilter(IDbCommand command) + { + if (!string.IsNullOrWhiteSpace(Profile.Schema)) + Add(command, "@schema", Profile.Schema.Trim()); + } + } +} diff --git a/src/DataCompare.Tests/CompareEngineTests.cs b/src/DataCompare.Tests/CompareEngineTests.cs new file mode 100644 index 0000000..bfa068f --- /dev/null +++ b/src/DataCompare.Tests/CompareEngineTests.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using DataCompare.Core; +using DataCompare.Data; +using Xunit; + +namespace DataCompare.Tests +{ + public class CompareEngineTests + { + static ColumnMapping Key(string left, string right = null) + { + return new ColumnMapping + { + LeftColumn = left, + RightColumn = right ?? left, + IsKey = true, + Compare = false + }; + } + + static ColumnMapping Val(string left, string right = null) + { + return new ColumnMapping + { + LeftColumn = left, + RightColumn = right ?? left, + IsKey = false, + Compare = true + }; + } + + static CompareResult Run( + object[][] left, + object[][] right, + ColumnMapping[] mappings, + CompareOptions options = null, + string[] columns = null) + { + columns = columns ?? new[] { "id", "name" }; + return CompareEngine.Execute(columns, left, columns, right, mappings, options ?? CompareOptions.CreateDefault()); + } + + [Fact] + public void Reports_value_difference_and_missing_keys() + { + var result = Run( + new[] + { + new object[] { 1, "a" }, + new object[] { 2, "b" }, + new object[] { 4, "d" } + }, + new[] + { + new object[] { 1, "a" }, + new object[] { 2, "c" }, + new object[] { 3, "c" } + }, + new[] { Key("id"), Val("name") }); + + Assert.Equal(3, result.LeftRowCount); + Assert.Equal(3, result.RightRowCount); + Assert.Equal(1, result.MatchedCount); + Assert.Equal(1, result.DifferentCount); + Assert.Equal(1, result.LeftOnlyCount); + Assert.Equal(1, result.RightOnlyCount); + Assert.Equal(0, result.DuplicateCount); + } + + [Fact] + public void Matches_unsorted_rows_by_key() + { + var left = new List(); + var right = new List(); + for (int i = 0; i < 1000; i++) + { + left.Add(new object[] { i, "L" + i }); + int key = 999 - i; + right.Add(new object[] { key, key % 10 == 0 ? "X" + key : "L" + key }); + } + + var result = Run(left.ToArray(), right.ToArray(), new[] { Key("id"), Val("name") }); + Assert.Equal(900, result.MatchedCount); + Assert.Equal(100, result.DifferentCount); + Assert.Equal(0, result.LeftOnlyCount); + Assert.Equal(0, result.RightOnlyCount); + } + + [Fact] + public void Duplicate_keys_are_not_compared_as_values() + { + var result = Run( + new[] + { + new object[] { 1, "a" }, + new object[] { 1, "b" }, + new object[] { 2, "c" } + }, + new[] + { + new object[] { 1, "a" }, + new object[] { 3, "d" } + }, + new[] { Key("id"), Val("name") }); + + Assert.Equal(1, result.DuplicateCount); + Assert.Equal(1, result.LeftOnlyCount); + Assert.Equal(1, result.RightOnlyCount); + Assert.Equal(0, result.MatchedCount); + } + + [Fact] + public void Null_keys_are_not_paired() + { + var result = Run( + new[] { new object[] { null, "a" } }, + new[] { new object[] { null, "a" } }, + new[] { Key("id"), Val("name") }); + + Assert.Equal(2, result.InvalidCount); + Assert.Equal(0, result.MatchedCount); + } + + [Fact] + public void Trims_padding_and_can_ignore_case() + { + var options = CompareOptions.CreateDefault(); + options.IgnoreCase = true; + var result = Run( + new[] { new object[] { "Ab", "x " } }, + new[] { new object[] { "ab", "x" } }, + new[] { Key("id"), Val("name") }, + options); + Assert.Equal(1, result.MatchedCount); + + options.IgnoreCase = false; + result = Run( + new[] { new object[] { "Ab", "x" } }, + new[] { new object[] { "ab", "x" } }, + new[] { Key("id"), Val("name") }, + options); + Assert.Equal(1, result.LeftOnlyCount); + Assert.Equal(1, result.RightOnlyCount); + } + + [Fact] + public void Coerces_numbers_bools_and_dates() + { + var options = CompareOptions.CreateDefault(); + var result = Run( + new[] { new object[] { 1, true, new DateTime(2020, 1, 1, 8, 0, 0, 400) } }, + new[] { new object[] { "1.0", 1, "2020-01-01 08:00:00" } }, + new[] { Key("id"), Val("name"), Val("flag") }, + options, + new[] { "id", "flag", "name" }); + Assert.Equal(1, result.MatchedCount); + } + + [Fact] + public void Decimal_scale_applies_to_values_not_keys() + { + var options = CompareOptions.CreateDefault(); + options.DecimalScale = 2; + var result = Run( + new[] + { + new object[] { 1, 1.231m }, + new object[] { 1.234m, 1.2m } + }, + new[] + { + new object[] { 1, 1.234m }, + new object[] { 1.235m, 9m } + }, + new[] { Key("id"), Val("name") }, + options); + + Assert.Equal(1, result.MatchedCount); + Assert.Equal(1, result.LeftOnlyCount); + Assert.Equal(1, result.RightOnlyCount); + } + + [Fact] + public void Float_tolerance_does_not_merge_keys() + { + var options = CompareOptions.CreateDefault(); + options.FloatTolerance = 0.0001m; + var columns = new[] { "id", "amount" }; + var result = CompareEngine.Execute( + columns, + new[] { new object[] { 1.0d, 1.00005d } }, + columns, + new[] { new object[] { 1.001d, 1.0d } }, + new[] { Key("id"), Val("amount") }, + options); + Assert.Equal(1, result.LeftOnlyCount); + Assert.Equal(1, result.RightOnlyCount); + + result = CompareEngine.Execute( + columns, + new[] { new object[] { 1, 1.0d } }, + columns, + new[] { new object[] { 1, 1.00005d } }, + new[] { Key("id"), Val("amount") }, + options); + Assert.Equal(1, result.MatchedCount); + } + + [Fact] + public void Empty_string_equals_null_only_when_asked() + { + var options = CompareOptions.CreateDefault(); + options.NullEqualsEmpty = true; + var result = Run( + new[] { new object[] { 1, "" } }, + new[] { new object[] { 1, null } }, + new[] { Key("id"), Val("name") }, + options); + Assert.Equal(1, result.MatchedCount); + + options.NullEqualsEmpty = false; + result = Run( + new[] { new object[] { 1, "" } }, + new[] { new object[] { 1, null } }, + new[] { Key("id"), Val("name") }, + options); + Assert.Equal(1, result.DifferentCount); + } + + [Fact] + public void Mapped_column_names_can_differ() + { + var result = CompareEngine.Execute( + new[] { "Id", "Amount" }, + new[] { new object[] { 5, 10 } }, + new[] { "id", "money" }, + new[] { new object[] { 5, 11 } }, + new[] { Key("Id", "id"), Val("Amount", "money") }, + CompareOptions.CreateDefault()); + Assert.Equal(1, result.DifferentCount); + Assert.Contains("Amount", result.Diffs[0].Summary); + } + + [Fact] + public void Rejects_duplicate_column_selection() + { + var ex = Assert.Throws(() => Run( + new[] { new object[] { 1, "a" } }, + new[] { new object[] { 1, "a" } }, + new[] { Key("id"), Val("id") })); + Assert.Contains("重复", ex.Message); + } + + [Fact] + public void Rejects_semicolon_in_filter() + { + var ex = Assert.Throws(() => FilterText.Normalize("status = 1; DELETE FROM t")); + Assert.Contains("分号", ex.Message); + Assert.Equal("status = 1", FilterText.Normalize(" WHERE status = 1 ")); + } + + [Fact] + public void Providers_can_be_constructed() + { + var profile = new ConnectionProfile + { + Kind = DbKind.GaussDb, + Host = "127.0.0.1", + Port = 5432, + Database = "db", + Username = "u", + Password = "p" + }; + using (DataSourceFactory.Create(profile)) + { + } + profile.Kind = DbKind.MySql; + using (DataSourceFactory.Create(profile)) + { + } + profile.Kind = DbKind.SqlServer; + using (DataSourceFactory.Create(profile)) + { + } + } + } +} diff --git a/src/DataCompare.Tests/DataCompare.Tests.csproj b/src/DataCompare.Tests/DataCompare.Tests.csproj new file mode 100644 index 0000000..6db26f4 --- /dev/null +++ b/src/DataCompare.Tests/DataCompare.Tests.csproj @@ -0,0 +1,18 @@ + + + net9.0 + disable + false + 10.0 + disable + + + + + + + + + + +