初始提交:数据库数据对比工具

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
chenshoulin
2026-11-18 21:21:06 +08:00
co-authored by Cursor
commit 1e3504707a
29 changed files with 5139 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
bin/
obj/
.vs/
publish/
publish.zip
TestResults/
*.user
*.suo
+84
View File
@@ -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
+47
View File
@@ -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;
}
}
}
+244
View File
@@ -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;
}
}
}
}
+176
View File
@@ -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<ConnectionDto> 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<ConnectionProfile> Load(out int unreadablePasswords)
{
unreadablePasswords = 0;
var list = new List<ConnectionProfile>();
if (!File.Exists(FilePath))
return list;
StoreFile file;
try
{
var json = File.ReadAllText(FilePath, Encoding.UTF8);
file = JsonSerializer.Deserialize<StoreFile>(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<ConnectionProfile> profiles)
{
var dtos = new List<ConnectionDto>();
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);
}
}
}
@@ -0,0 +1,70 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework>
<SupportedOSPlatformVersion>6.2</SupportedOSPlatformVersion>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>disable</ImplicitUsings>
<RootNamespace>DataCompare.App</RootNamespace>
<AssemblyName>DataCompare</AssemblyName>
<LangVersion>10.0</LangVersion>
<Nullable>disable</Nullable>
<NoWarn>$(NoWarn);WFO0003</NoWarn>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationIcon>app.ico</ApplicationIcon>
<StartupObject>DataCompare.App.Program</StartupObject>
<Version>1.0.0</Version>
<Product>数据对比</Product>
<AssemblyTitle>数据对比</AssemblyTitle>
<Description>对比两个数据库表的数据差异</Description>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="app.ico" LogicalName="DataCompare.App.app.ico" />
<ProjectReference Include="..\DataCompare.Core\DataCompare.Core.csproj" />
<ProjectReference Include="..\DataCompare.Data\DataCompare.Data.csproj" />
<PackageReference Include="System.Security.Cryptography.ProtectedData" Version="9.0.21" />
</ItemGroup>
<!-- Release 构建后发布 win-x64 自包含单文件。运行时打进 exe,不要求服务器安装 .NET。 -->
<Target Name="PublishSingleExe" AfterTargets="Build" Condition="'$(Configuration)' == 'Release' AND '$(RuntimeIdentifier)' == '' AND '$(DesignTimeBuild)' != 'true' AND '$(PublishSingleFile)' != 'true'">
<PropertyGroup>
<_OutDir>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\..\publish'))</_OutDir>
</PropertyGroup>
<ItemGroup>
<_OldPublish Include="$(_OutDir)\*.*" />
</ItemGroup>
<Delete Files="@(_OldPublish)" />
<Exec Command="dotnet publish &quot;$(MSBuildProjectFullPath)&quot; -c $(Configuration) -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true -o &quot;$(_OutDir)&quot;" />
</Target>
<!--
单文件 exe 的本机启动器在进入托管代码前就要加载 Universal CRT。
Windows Server 2012 默认没有这套 DLL,而且它们不能打进 exe。
放到 exe 旁边即为微软允许的应用本地部署,不写入系统目录。
-->
<Target Name="CopyDownlevelCrt" AfterTargets="Publish" Condition="'$(SelfContained)' == 'true' AND '$(RuntimeIdentifier)' == 'win-x64'">
<PropertyGroup>
<_UcrtDir Condition="Exists('$(MSBuildProgramFiles32)\Windows Kits\10\Redist\ucrt\DLLs\x64\ucrtbase.dll')">$(MSBuildProgramFiles32)\Windows Kits\10\Redist\ucrt\DLLs\x64\</_UcrtDir>
<_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>
<_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>
<_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>
<_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\</_UcrtDir>
</PropertyGroup>
<Warning Condition="'$(_UcrtDir)' == ''" Text="未找到可随程序携带的 Universal CRT。Windows Server 2012 若也没有 VC++ 2015 运行库,程序将无法启动。" />
<ItemGroup Condition="'$(_UcrtDir)' != ''">
<_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" />
</ItemGroup>
<Copy SourceFiles="@(_DownlevelDll)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="true" Condition="'@(_DownlevelDll)' != ''" />
<PropertyGroup>
<_PublishClean>$([System.IO.Path]::GetFullPath('$(PublishDir)'))</_PublishClean>
</PropertyGroup>
<ItemGroup>
<_PublishPdb Include="$(_PublishClean)\*.pdb" />
</ItemGroup>
<Delete Files="@(_PublishPdb)" />
</Target>
</Project>
+186
View File
@@ -0,0 +1,186 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
<xs:element name="Weavers">
<xs:complexType>
<xs:all>
<xs:element name="Costura" minOccurs="0" maxOccurs="1">
<xs:complexType>
<xs:all>
<xs:element minOccurs="0" maxOccurs="1" name="ExcludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="IncludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="ExcludeRuntimeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="IncludeRuntimeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="ExcludeRuntimes" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtimes to exclude from the default action of "embed all Copy Local references", delimited with line breaks</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="IncludeRuntimes" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtimes names to include from the default action of "embed all Copy Local references", delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="Unmanaged32Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>Obsolete, use UnmanagedWinX86Assemblies instead</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="UnmanagedWinX86Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged X86 (32 bit) assembly names to include, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="Unmanaged64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>Obsolete, use UnmanagedWinX64Assemblies instead.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="UnmanagedWinX64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged X64 (64 bit) assembly names to include, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="UnmanagedWinArm64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged Arm64 (64 bit) assembly names to include, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" maxOccurs="1" name="PreloadOrder" type="xs:string">
<xs:annotation>
<xs:documentation>The order of preloaded assemblies, delimited with line breaks.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:all>
<xs:attribute name="CreateTemporaryAssemblies" type="xs:boolean">
<xs:annotation>
<xs:documentation>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.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeDebugSymbols" type="xs:boolean">
<xs:annotation>
<xs:documentation>Controls if .pdbs for reference assemblies are also embedded.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeRuntimeReferences" type="xs:boolean">
<xs:annotation>
<xs:documentation>Controls if runtime assemblies are also embedded.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="UseRuntimeReferencePaths" type="xs:boolean">
<xs:annotation>
<xs:documentation>Controls whether the runtime assemblies are embedded with their full path or only with their assembly name.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="DisableCompression" type="xs:boolean">
<xs:annotation>
<xs:documentation>Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="DisableCleanup" type="xs:boolean">
<xs:annotation>
<xs:documentation>As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="DisableEventSubscription" type="xs:boolean">
<xs:annotation>
<xs:documentation>The attach method no longer subscribes to the `AppDomain.AssemblyResolve` (.NET 4.x) and `AssemblyLoadContext.Resolving` (.NET 6.0+) events.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="LoadAtModuleInit" type="xs:boolean">
<xs:annotation>
<xs:documentation>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.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IgnoreSatelliteAssemblies" type="xs:boolean">
<xs:annotation>
<xs:documentation>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.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="ExcludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with |</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="ExcludeRuntimeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtime assembly names to exclude from the default action of "embed all Copy Local references", delimited with |</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="IncludeRuntimeAssemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of runtime assembly names to include from the default action of "embed all Copy Local references", delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="Unmanaged32Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>Obsolete, use UnmanagedWinX86Assemblies instead</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="UnmanagedWinX86Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged X86 (32 bit) assembly names to include, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="Unmanaged64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>Obsolete, use UnmanagedWinX64Assemblies instead</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="UnmanagedWinX64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged X64 (64 bit) assembly names to include, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="UnmanagedWinArm64Assemblies" type="xs:string">
<xs:annotation>
<xs:documentation>A list of unmanaged Arm64 (64 bit) assembly names to include, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="PreloadOrder" type="xs:string">
<xs:annotation>
<xs:documentation>The order of preloaded assemblies, delimited with |.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:all>
<xs:attribute name="VerifyAssembly" type="xs:boolean">
<xs:annotation>
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
<xs:annotation>
<xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="GenerateXsd" type="xs:boolean">
<xs:annotation>
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>
File diff suppressed because it is too large Load Diff
+102
View File
@@ -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<string> leftColumns,
IList<object[]> leftRows,
string rightTitle,
IList<string> rightColumns,
IList<object[]> 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<string> columns, IList<object[]> 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;
}
}
}
+22
View File
@@ -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());
}
}
}
+283
View File
@@ -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<TableRef> _all = new List<TableRef>();
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<TableRef> 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<TableRef> 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<TableRef> 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<TableRef> Filter(List<TableRef> all, string keyword, out bool truncated)
{
truncated = false;
var tokens = Tokenize(keyword);
if (tokens.Count == 0)
return new List<TableRef>(all);
var direct = new List<TableRef>();
var fuzzy = new List<TableRef>();
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<TableRef>();
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<string> Tokenize(string keyword)
{
var tokens = new List<string>();
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<string> 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<string> 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);
}
}
}
+27
View File
@@ -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);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="DataCompare.app"/>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">System</dpiAwareness>
</windowsSettings>
</application>
</assembly>
+480
View File
@@ -0,0 +1,480 @@
using System;
using System.Collections.Generic;
namespace DataCompare.Core
{
public static class CompareEngine
{
public static CompareResult Execute(
IList<string> leftColumns,
IList<object[]> leftRows,
IList<string> rightColumns,
IList<object[]> rightRows,
IList<ColumnMapping> 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<RowDiff>();
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<PreparedRow> leftGroup,
List<PreparedRow> rightGroup,
Plan plan,
CompareOptions options,
List<RowDiff> 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<RowDiff> 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<PreparedRow> leftGroup, List<PreparedRow> 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<PreparedRow> rows, Plan plan, CompareOptions options, bool isLeft, List<RowDiff> 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<string>();
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<PreparedRow> rows)
{
int n = 0;
for (int i = 0; i < rows.Count; i++)
{
if (rows[i].Invalid)
n++;
}
return n;
}
static List<PreparedRow> ValidOnly(List<PreparedRow> rows)
{
var list = new List<PreparedRow>();
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<List<PreparedRow>> Group(List<PreparedRow> rows, CompareOptions options)
{
var groups = new List<List<PreparedRow>>();
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<PreparedRow>(j - i);
for (int k = i; k < j; k++)
group.Add(rows[k]);
groups.Add(group);
i = j;
}
return groups;
}
static List<PreparedRow> Prepare(
IList<object[]> rows,
IList<string> columns,
int[] keyIndex,
int[] valueIndex,
CompareOptions options)
{
int width = columns == null ? 0 : columns.Count;
var list = new List<PreparedRow>(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<string> leftColumns, IList<string> rightColumns, IList<ColumnMapping> mappings)
{
var active = new List<ColumnMapping>();
var leftSeen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var rightSeen = new HashSet<string>(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<ColumnMapping>();
var valueMaps = new List<ColumnMapping>();
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<ColumnMapping> 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<ColumnMapping> 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<string> columns, List<ColumnMapping> 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<string> 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;
}
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<RootNamespace>DataCompare.Core</RootNamespace>
<AssemblyName>DataCompare.Core</AssemblyName>
<ImplicitUsings>disable</ImplicitUsings>
<LangVersion>10.0</LangVersion>
<Nullable>disable</Nullable>
</PropertyGroup>
</Project>
+34
View File
@@ -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;
}
}
}
}
+194
View File
@@ -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; }
}
}
+595
View File
@@ -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);
}
}
}
+249
View File
@@ -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<TableRef> 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<TableRef>();
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<ColumnInfo> 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<ColumnInfo>();
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<object[]> ReadRows(
TableRef table,
IList<string> columns,
string filter,
int? limit,
CancellationToken cancellationToken,
IProgress<int> 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<object[]>();
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;
}
}
}
+128
View File
@@ -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<ColumnMapping> mappings,
CompareOptions options,
IProgress<string> 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<object[]> leftRows;
using (var source = DataSourceFactory.Create(leftSource))
{
leftRows = source.ReadRows(
leftTable,
columns.Left,
leftFilter,
null,
cancellationToken,
Rows("左侧", progress));
}
cancellationToken.ThrowIfCancellationRequested();
Report(progress, "正在读取右侧…");
List<object[]> 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<ColumnMapping> mappings)
{
var left = new List<string>();
var right = new List<string>();
var leftSeen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var rightSeen = new HashSet<string>(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<int> Rows(string side, IProgress<string> progress)
{
return new Progress<int>(count => Report(progress, "正在读取" + side + "… " + count + " 行"));
}
static void Report(IProgress<string> progress, string message)
{
if (progress != null)
progress.Report(message);
}
sealed class ColumnLists
{
public List<string> Left;
public List<string> Right;
}
}
}
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<RootNamespace>DataCompare.Data</RootNamespace>
<AssemblyName>DataCompare.Data</AssemblyName>
<ImplicitUsings>disable</ImplicitUsings>
<LangVersion>10.0</LangVersion>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HuaweiCloud.GaussDB.Driver" Version="8.0.1" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.1.2" />
<ProjectReference Include="..\DataCompare.Core\DataCompare.Core.csproj" />
<PackageReference Include="MySqlConnector" Version="2.6.1" />
</ItemGroup>
</Project>
+23
View File
@@ -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;
}
}
}
+59
View File
@@ -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());
}
}
}
+21
View File
@@ -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<TableRef> GetTables();
IList<ColumnInfo> GetColumns(TableRef table);
List<object[]> ReadRows(
TableRef table,
IList<string> columns,
string filter,
int? limit,
CancellationToken cancellationToken,
IProgress<int> progress);
}
}
+57
View File
@@ -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());
}
}
}
+148
View File
@@ -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<TableRef> GetTables()
{
EnsureOpen();
var databases = new List<string>();
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<TableRef>();
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<TableRef> 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());
}
}
}
+288
View File
@@ -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<object[]>();
var right = new List<object[]>();
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<InvalidOperationException>(() => 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<InvalidOperationException>(() => 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))
{
}
}
}
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<IsPackable>false</IsPackable>
<LangVersion>10.0</LangVersion>
<Nullable>disable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DataCompare.Core\DataCompare.Core.csproj" />
<ProjectReference Include="..\DataCompare.Data\DataCompare.Data.csproj" />
</ItemGroup>
</Project>