From 3f02f4c704cf16aa161fa14391c23bc7f0be1041 Mon Sep 17 00:00:00 2001 From: chenshoulin Date: Thu, 19 Nov 2026 00:58:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E5=B8=83=E5=B1=80=E5=8F=8A=E6=A0=B7=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DataCompare.App/MainForm.cs | 2015 ++++++++++++++++++-- src/DataCompare.App/MatchRuleStore.cs | 118 ++ src/DataCompare.App/PreviewForm.cs | 55 +- src/DataCompare.App/RuleForms.cs | 324 ++++ src/DataCompare.App/TableCombo.cs | 20 + src/DataCompare.App/TableJob.cs | 64 + src/DataCompare.App/TablePickForm.cs | 464 +++++ src/DataCompare.Core/ColumnMapper.cs | 160 ++ src/DataCompare.Core/DiffWorkbook.cs | 187 ++ src/DataCompare.Core/SheetNames.cs | 63 + src/DataCompare.Core/TableMatch.cs | 108 ++ src/DataCompare.Core/XlsxFile.cs | 190 ++ src/DataCompare.Tests/DiffWorkbookTests.cs | 162 ++ src/DataCompare.Tests/TableMatchTests.cs | 190 ++ 14 files changed, 4000 insertions(+), 120 deletions(-) create mode 100644 src/DataCompare.App/MatchRuleStore.cs create mode 100644 src/DataCompare.App/RuleForms.cs create mode 100644 src/DataCompare.App/TableJob.cs create mode 100644 src/DataCompare.App/TablePickForm.cs create mode 100644 src/DataCompare.Core/ColumnMapper.cs create mode 100644 src/DataCompare.Core/DiffWorkbook.cs create mode 100644 src/DataCompare.Core/SheetNames.cs create mode 100644 src/DataCompare.Core/TableMatch.cs create mode 100644 src/DataCompare.Core/XlsxFile.cs create mode 100644 src/DataCompare.Tests/DiffWorkbookTests.cs create mode 100644 src/DataCompare.Tests/TableMatchTests.cs diff --git a/src/DataCompare.App/MainForm.cs b/src/DataCompare.App/MainForm.cs index 78405de..6a43bb8 100644 --- a/src/DataCompare.App/MainForm.cs +++ b/src/DataCompare.App/MainForm.cs @@ -20,6 +20,8 @@ namespace DataCompare.App readonly List _profiles = new List(); readonly List _view = new List(); + readonly List _jobs = new List(); + readonly List _run = new List(); TabControl _tabs; DataGridView _connGrid; @@ -41,9 +43,28 @@ namespace DataCompare.App TextBox _tolerance; Button _btnRead; Button _btnMatch; + Button _btnFilter; Button _btnPreview; Button _btnCompare; + Button _btnCompareOne; Button _btnCancel; + Button _btnToggleOptions; + ComboBox _ruleBox; + CheckBox _autoMatch; + Button _btnRules; + Button _btnAddJob; + Button _btnPickJobs; + Button _btnUpdateJob; + Button _btnRemoveJob; + Button _btnClearJobs; + DataGridView _batchGrid; + Label _guide; + Label _batchCaption; + Panel _batchHost; + Panel _optionHost; + FlowLayoutPanel _optionFlow; + ComboBox _resultTable; + Button _btnExcel; ToolStripStatusLabel _status; readonly ToolTip _tips = new ToolTip(); DataGridView _diffGrid; @@ -60,7 +81,16 @@ namespace DataCompare.App bool _suppress; int _leftGen; int _rightGen; + int _columnLoad; int _badPasswords; + bool _busy; + bool _optionsOpen; + bool _fittingOptions; + bool _columnPending; + bool _pendingFromLeft; + bool _loadingBatchJob; + Guid? _acceptedLeftId; + Guid? _acceptedRightId; string _loadError; public static Font UiFont() @@ -92,7 +122,7 @@ namespace DataCompare.App AutoScaleMode = AutoScaleMode.None; UiMetrics.Bind(this); StartPosition = FormStartPosition.CenterScreen; - ClientSize = new Size(UiMetrics.Px(1180), UiMetrics.Px(760)); + ClientSize = new Size(UiMetrics.Px(1180), UiMetrics.Px(800)); MinimumSize = new Size(UiMetrics.Px(1020), UiMetrics.Px(680)); _tabs = new TabControl { Dock = DockStyle.Fill }; @@ -122,11 +152,13 @@ namespace DataCompare.App } FillConnectionGrid(); FillConnectionCombos(); + _tabs.SelectedIndex = _profiles.Count > 0 ? 1 : 0; } protected override void OnShown(EventArgs e) { base.OnShown(e); + FitPrimaryButton(); if (!string.IsNullOrEmpty(_loadError)) MessageBox.Show(this, _loadError, "连接配置", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (_badPasswords > 0) @@ -156,21 +188,31 @@ namespace DataCompare.App EditConnection(); }; + var hint = new Label + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(28), + TextAlign = ContentAlignment.MiddleLeft, + ForeColor = Color.FromArgb(70, 80, 90), + Text = "先把要用的库存下来。建好后到「对比」里选左侧和右侧。" + }; var bar = new FlowLayoutPanel { - Dock = DockStyle.Bottom, + Dock = DockStyle.Top, AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, FlowDirection = FlowDirection.LeftToRight, WrapContents = false, - Padding = new Padding(0, UiMetrics.Px(8), 0, UiMetrics.Px(4)) + Padding = new Padding(0, 0, 0, UiMetrics.Px(8)) }; bar.Controls.Add(MakeButton("新建", delegate { EditConnection(null); })); bar.Controls.Add(MakeButton("编辑", delegate { EditConnection(); })); bar.Controls.Add(MakeButton("删除", delegate { DeleteConnection(); })); bar.Controls.Add(MakeButton("测试连接", delegate { TestStoredConnection(); })); + bar.Controls.Add(MakeButton("去对比", delegate { _tabs.SelectedIndex = 1; })); page.Controls.Add(_connGrid); page.Controls.Add(bar); + page.Controls.Add(hint); return page; } @@ -191,16 +233,20 @@ namespace DataCompare.App _tips.SetToolTip(_rightFilter, filterTip); _leftConn.SelectedIndexChanged += async delegate { - if (!_suppress) - await LoadTablesAsync(_leftTable, SelectedProfile(_leftConn), true); + if (_suppress || !AcceptConnectionChange(_leftConn, true)) + return; + await LoadTablesAsync(_leftTable, SelectedProfile(_leftConn), true); }; _rightConn.SelectedIndexChanged += async delegate { - if (!_suppress) - await LoadTablesAsync(_rightTable, SelectedProfile(_rightConn), false); + if (_suppress || !AcceptConnectionChange(_rightConn, false)) + return; + await LoadTablesAsync(_rightTable, SelectedProfile(_rightConn), false); }; - _leftTable.TableChanged += delegate { if (!_suppress) ClearMapping(); }; - _rightTable.TableChanged += delegate { if (!_suppress) ClearMapping(); }; + _leftTable.TableChanged += delegate { OnTableChanged(true); }; + _rightTable.TableChanged += delegate { OnTableChanged(false); }; + _leftTable.DropDownClosed += delegate { FlushPendingTableChange(); }; + _rightTable.DropDownClosed += delegate { FlushPendingTableChange(); }; _leftTable.FilterChanged += delegate { ShowTableFilter("左侧", _leftTable); }; _rightTable.FilterChanged += delegate { ShowTableFilter("右侧", _rightTable); }; @@ -233,15 +279,22 @@ namespace DataCompare.App HeaderText = "右侧列", FlatStyle = FlatStyle.Flat, DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton, + DisplayStyleForCurrentCellOnly = false, FillWeight = 140, ValueType = typeof(string) }; + rightName.DefaultCellStyle.Padding = Padding.Empty; + rightName.DefaultCellStyle.SelectionForeColor = Color.Black; + rightName.DefaultCellStyle.SelectionBackColor = Color.FromArgb(210, 227, 246); rightName.Items.Add(""); _mapGrid.Columns.Add(rightName); + _mapGrid.EditingControlShowing += StyleColumnPick; + _mapGrid.CellClick += OpenColumnPick; _mapGrid.Columns.Add(TextColumn("右类型", 90, "RightType")); _mapGrid.Columns["LeftName"].ReadOnly = true; _mapGrid.Columns["LeftType"].ReadOnly = true; _mapGrid.Columns["RightType"].ReadOnly = true; + _mapGrid.Columns["Key"].ToolTipText = "用来把两侧的行对齐,至少勾一个"; _mapGrid.CurrentCellDirtyStateChanged += delegate { if (_mapGrid.IsCurrentCellDirty) @@ -264,91 +317,300 @@ namespace DataCompare.App _decimalScale.SelectedIndex = 0; _tolerance = new TextBox { Text = "0.0001", Width = UiMetrics.Fit("0.0001", Font, 16) }; - var options = new FlowLayoutPanel + _optionFlow = new FlowLayoutPanel { Dock = DockStyle.Fill, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, WrapContents = true, FlowDirection = FlowDirection.LeftToRight, Padding = new Padding(0), Margin = new Padding(0) }; - options.Controls.Add(_trim); - options.Controls.Add(_ignoreCase); - options.Controls.Add(_nullEmpty); - options.Controls.Add(_coerceNumber); - options.Controls.Add(_coerceBool); - options.Controls.Add(_coerceDate); - options.Controls.Add(InlineLabel("时间精度")); - options.Controls.Add(_datePrecision); - options.Controls.Add(InlineLabel("小数位")); - options.Controls.Add(_decimalScale); - options.Controls.Add(InlineLabel("浮点容差")); - options.Controls.Add(_tolerance); + _optionFlow.Controls.Add(_trim); + _optionFlow.Controls.Add(_ignoreCase); + _optionFlow.Controls.Add(_nullEmpty); + _optionFlow.Controls.Add(_coerceNumber); + _optionFlow.Controls.Add(_coerceBool); + _optionFlow.Controls.Add(_coerceDate); + _optionFlow.Controls.Add(InlineLabel("时间精度")); + _optionFlow.Controls.Add(_datePrecision); + _optionFlow.Controls.Add(InlineLabel("小数位")); + _optionFlow.Controls.Add(_decimalScale); + _optionFlow.Controls.Add(InlineLabel("浮点容差")); + _optionFlow.Controls.Add(_tolerance); - _btnRead = MakeButton("读取字段", async delegate { await ReadColumnsAsync(); }); + _btnRead = MakeButton("重新读取", async delegate { await ReadColumnsAsync(true, ++_columnLoad); }); _btnMatch = MakeButton("按列名匹配", delegate { ApplyNameMatch(true); }); + _btnFilter = MakeButton("筛选条件", delegate { EditFilters(); }); _btnPreview = MakeButton("预览前 100 行", async delegate { await PreviewAsync(); }); - _btnCompare = MakeButton("开始对比", async delegate { await CompareAsync(); }); - _btnCompare.BackColor = Color.FromArgb(37, 99, 168); - _btnCompare.ForeColor = Color.White; - _btnCompare.FlatStyle = FlatStyle.Flat; - _btnCompare.FlatAppearance.BorderSize = 0; + _btnCompare = MakeButton("对比当前表", async delegate { await ComparePrimaryAsync(); }); + StylePrimary(_btnCompare); + _btnCompareOne = MakeButton("只对比当前表", async delegate { await CompareOneAsync(); }); + _btnCompareOne.Visible = false; _btnCancel = MakeButton("取消", delegate { if (_cts != null) _cts.Cancel(); }); _btnCancel.Enabled = false; - var buttons = new FlowLayoutPanel + _tips.SetToolTip(_btnRead, "两侧的表选好后会自动读取。这里用来再读一次"); + _tips.SetToolTip(_btnFilter, "给左右两侧加行条件。不要写 WHERE,不要写分号"); + _tips.SetToolTip(_btnPreview, "按当前筛选和勾选的列,各看前 100 行"); + _tips.SetToolTip(_btnCompare, "批次为空时对比当前这一对;有批次时对比批次里可运行的表"); + _tips.SetToolTip(_btnCompareOne, "不管批次,只对比屏幕上这一对表"); + + _ruleBox = new ComboBox + { + DropDownStyle = ComboBoxStyle.DropDownList, + Width = UiMetrics.Fit("模式前缀", Font, 48), + Margin = new Padding(0, 0, UiMetrics.Px(12), 0), + Anchor = AnchorStyles.Left + }; + _tips.SetToolTip(_ruleBox, "用这条规则把一侧选中的表对应到另一侧"); + _ruleBox.SelectedIndexChanged += delegate + { + if (!_suppress && Rematch(true)) + ScheduleColumnLoad(); + }; + _autoMatch = Check("选表时自动配对", true); + _tips.SetToolTip(_autoMatch, "选择一侧的表时,自动选中另一侧规则对应的那张表"); + _autoMatch.CheckedChanged += delegate + { + if (!_suppress && _autoMatch.Checked && Rematch(true)) + ScheduleColumnLoad(); + }; + _btnRules = MakeButton("管理规则", delegate { ManageRules(); }); + _btnPickJobs = MakeButton("批量选表", async delegate { await PickTablesAsync(); }); + _autoMatch.Margin = new Padding(0, 0, UiMetrics.Px(12), 0); + _autoMatch.Anchor = AnchorStyles.Left; + _btnRules.Margin = new Padding(0, 0, UiMetrics.Px(8), 0); + _btnRules.Anchor = AnchorStyles.Left; + _btnPickJobs.Margin = new Padding(0); + _btnPickJobs.Anchor = AnchorStyles.Left; + var ruleLabel = InlineLabel("配对规则"); + ruleLabel.Margin = new Padding(0, 0, UiMetrics.Px(8), 0); + ruleLabel.Anchor = AnchorStyles.Left; + var ruleRowPanel = new TableLayoutPanel { Dock = DockStyle.Fill, - WrapContents = false, - FlowDirection = FlowDirection.LeftToRight + ColumnCount = 5, + RowCount = 1, + Margin = new Padding(0), + Padding = new Padding(0) }; - buttons.Controls.Add(_btnRead); - buttons.Controls.Add(_btnMatch); - buttons.Controls.Add(_btnPreview); - buttons.Controls.Add(_btnCompare); - buttons.Controls.Add(_btnCancel); + ruleRowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + ruleRowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + ruleRowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + ruleRowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + ruleRowPanel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + ruleRowPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + ruleRowPanel.Controls.Add(ruleLabel, 0, 0); + ruleRowPanel.Controls.Add(_ruleBox, 1, 0); + ruleRowPanel.Controls.Add(_autoMatch, 2, 0); + ruleRowPanel.Controls.Add(_btnRules, 3, 0); + ruleRowPanel.Controls.Add(_btnPickJobs, 4, 0); - int line = Math.Max(_leftConn.PreferredHeight, _leftTable.PreferredHeight) + UiMetrics.Px(8); - int groupRow = line * 2 + UiMetrics.Px(40); - int filterRow = line * 2; - int optionRow = UiMetrics.Px(112); - int buttonRow = UiMetrics.Px(46); + _btnAddJob = MakeButton("放入批次", delegate { AddCurrentJob(); }); + _btnUpdateJob = MakeButton("写回选中行", delegate { UpdateCurrentJob(); }); + _btnRemoveJob = MakeButton("移除", delegate { RemoveCurrentJob(); }); + _btnClearJobs = MakeButton("清空", delegate { AskClearBatch(); }); + _tips.SetToolTip(_btnAddJob, "把屏幕上这一对表放进批次。同一对已在批次里时,改为更新它"); + _tips.SetToolTip(_btnPickJobs, "按配对规则勾选多张表,一次放进批次"); + _tips.SetToolTip(_btnUpdateJob, "把当前的键列、对比列和筛选写回批次里选中的那一行"); + _batchGrid = CreateGrid(true); + _batchGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + _batchGrid.Columns.Add(TextColumn("左侧表", 260)); + _batchGrid.Columns.Add(TextColumn("右侧表", 260)); + _batchGrid.Columns.Add(TextColumn("状态", 70)); + _batchGrid.Columns.Add(TextColumn("说明", 280)); + _batchGrid.SelectionChanged += delegate + { + if (!_suppress) + LoadSelectedJob(); + }; + _batchGrid.CellFormatting += BatchCellFormatting; + _batchCaption = new Label + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(24), + TextAlign = ContentAlignment.MiddleLeft, + ForeColor = Color.FromArgb(70, 80, 90), + Text = "批次为空。右侧按钮只对比当前这一对表。" + }; + var batchLine = new Panel + { + Dock = DockStyle.Top, + Height = 1, + BackColor = Color.FromArgb(214, 218, 224) + }; + _batchHost = new Panel { Dock = DockStyle.Bottom, Height = UiMetrics.Px(25) }; + _batchGrid.Visible = false; + _batchHost.Controls.Add(_batchGrid); + _batchHost.Controls.Add(_batchCaption); + _batchHost.Controls.Add(batchLine); + _guide = new Label + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(28), + TextAlign = ContentAlignment.MiddleLeft, + ForeColor = Color.FromArgb(40, 70, 110), + BackColor = Color.FromArgb(232, 240, 248), + Padding = new Padding(UiMetrics.Px(8), 0, UiMetrics.Px(8), 0), + AutoEllipsis = true, + Text = "先选择左右两侧的连接和表。选好后会自动读取字段。" + }; + + int line = Math.Max(_leftConn.PreferredHeight, _leftTable.PreferredHeight) + UiMetrics.Px(6); + int sourceRow = line + UiMetrics.Px(30); + int ruleRow = Math.Max(_ruleBox.PreferredHeight, _btnRules.GetPreferredSize(Size.Empty).Height) + UiMetrics.Px(6); var layout = new TableLayoutPanel { Dock = DockStyle.Top, - Height = groupRow + filterRow + optionRow + buttonRow, + Height = sourceRow + ruleRow, ColumnCount = 2, - RowCount = 4, - Padding = new Padding(0, 0, 0, UiMetrics.Px(4)) + RowCount = 2, + Padding = new Padding(0) }; layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); - layout.RowStyles.Add(new RowStyle(SizeType.Absolute, groupRow)); - layout.RowStyles.Add(new RowStyle(SizeType.Absolute, filterRow)); - layout.RowStyles.Add(new RowStyle(SizeType.Absolute, optionRow)); - layout.RowStyles.Add(new RowStyle(SizeType.Absolute, buttonRow)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, sourceRow)); + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, ruleRow)); layout.Controls.Add(SideBox("左侧", _leftConn, _leftTable, line), 0, 0); layout.Controls.Add(SideBox("右侧", _rightConn, _rightTable, line), 1, 0); + layout.Controls.Add(ruleRowPanel, 0, 1); + layout.SetColumnSpan(ruleRowPanel, 2); - var filters = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; - filters.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("左侧筛选", Font, 16))); - filters.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); - filters.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); - filters.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); - filters.Controls.Add(FieldLabel("左侧筛选"), 0, 0); - filters.Controls.Add(_leftFilter, 1, 0); - filters.Controls.Add(FieldLabel("右侧筛选"), 0, 1); - filters.Controls.Add(_rightFilter, 1, 1); - PlaceField(_leftFilter); - PlaceField(_rightFilter); - layout.Controls.Add(filters, 0, 1); - layout.SetColumnSpan(filters, 2); - layout.Controls.Add(options, 0, 2); - layout.SetColumnSpan(options, 2); - layout.Controls.Add(buttons, 0, 3); - layout.SetColumnSpan(buttons, 2); + _btnToggleOptions = new Button + { + Text = "比较选项", + AutoSize = true, + FlatStyle = FlatStyle.Flat, + ForeColor = Color.FromArgb(37, 99, 168), + TextAlign = ContentAlignment.MiddleLeft, + Padding = new Padding(0, UiMetrics.Px(2), UiMetrics.Px(8), UiMetrics.Px(2)), + Margin = new Padding(0), + Cursor = Cursors.Hand + }; + _btnToggleOptions.FlatAppearance.BorderSize = 0; + _btnToggleOptions.FlatAppearance.MouseOverBackColor = Color.FromArgb(232, 240, 248); + _btnToggleOptions.Click += delegate { ToggleOptions(); }; + _tips.SetToolTip(_btnToggleOptions, "空格、大小写、数字和日期怎么算相同"); + var toggleBar = new Panel + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(30) + }; + toggleBar.Controls.Add(_btnToggleOptions); - page.Controls.Add(_mapGrid); + var optionBody = new TableLayoutPanel + { + Dock = DockStyle.Top, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + ColumnCount = 1, + RowCount = 1, + Margin = new Padding(0) + }; + optionBody.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + optionBody.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + optionBody.Controls.Add(_optionFlow, 0, 0); + _optionHost = new Panel + { + Dock = DockStyle.Top, + Height = 0, + Visible = false, + Padding = Padding.Empty + }; + _optionHost.Controls.Add(optionBody); + + var mapActions = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Padding = new Padding(0), + Margin = new Padding(0), + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink + }; + mapActions.Controls.Add(_btnRead); + mapActions.Controls.Add(_btnMatch); + mapActions.Controls.Add(_btnFilter); + mapActions.Controls.Add(_btnPreview); + var mapCaption = new Label + { + Dock = DockStyle.Fill, + TextAlign = ContentAlignment.MiddleLeft, + ForeColor = Color.FromArgb(40, 48, 56), + Text = "字段对照 「键」用来对齐行,「对比」决定要比的列" + }; + var mapBar = new TableLayoutPanel + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(40), + ColumnCount = 2, + RowCount = 1, + Margin = new Padding(0) + }; + mapBar.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + mapBar.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + mapBar.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + mapBar.Controls.Add(mapCaption, 0, 0); + mapBar.Controls.Add(mapActions, 1, 0); + + var work = new Panel { Dock = DockStyle.Fill }; + work.Controls.Add(_mapGrid); + work.Controls.Add(mapBar); + work.Controls.Add(_guide); + + var batchActions = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Padding = new Padding(0), + Margin = new Padding(0) + }; + batchActions.Controls.Add(_btnAddJob); + batchActions.Controls.Add(_btnUpdateJob); + batchActions.Controls.Add(_btnRemoveJob); + batchActions.Controls.Add(_btnClearJobs); + var runActions = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + FlowDirection = FlowDirection.RightToLeft, + WrapContents = false, + Padding = new Padding(0), + Margin = new Padding(0) + }; + runActions.Controls.Add(_btnCompare); + runActions.Controls.Add(_btnCompareOne); + runActions.Controls.Add(_btnCancel); + var footer = new TableLayoutPanel + { + Dock = DockStyle.Bottom, + Height = UiMetrics.Px(46), + ColumnCount = 2, + RowCount = 1, + Padding = new Padding(0, UiMetrics.Px(4), 0, 0), + Margin = new Padding(0) + }; + footer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); + footer.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); + footer.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + footer.Controls.Add(batchActions, 0, 0); + footer.Controls.Add(runActions, 1, 0); + + page.Controls.Add(work); + page.Controls.Add(_batchHost); + page.Controls.Add(footer); + page.Controls.Add(_optionHost); + page.Controls.Add(toggleBar); page.Controls.Add(layout); + _optionFlow.SizeChanged += delegate { FitOptionHost(); }; + ReloadRules("prefix"); + UpdateGuide(); return page; } @@ -358,9 +620,13 @@ namespace DataCompare.App _stats = new Label { Dock = DockStyle.Top, - Height = UiMetrics.Px(28), + Height = UiMetrics.Px(32), TextAlign = ContentAlignment.MiddleLeft, - Text = "尚未对比" + ForeColor = Color.FromArgb(40, 48, 56), + BackColor = Color.FromArgb(245, 246, 248), + Padding = new Padding(UiMetrics.Px(8), 0, UiMetrics.Px(8), 0), + AutoEllipsis = true, + Text = "尚未对比。在「对比」里选好表之后,结果会出现在这里。" }; _statusFilter = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = UiMetrics.Fit("内容不同", Font, 32) }; _statusFilter.Items.AddRange(new object[] { "全部差异", "仅左侧", "仅右侧", "内容不同", "键问题" }); @@ -368,16 +634,31 @@ namespace DataCompare.App _statusFilter.SelectedIndexChanged += delegate { if (!_suppress) BindView(); }; _onlyDiffCells = Check("明细只显示不同列", true); _onlyDiffCells.CheckedChanged += delegate { ShowCurrentDetail(); }; - var export = MakeButton("导出 CSV", delegate { ExportCsv(); }); + _resultTable = new ComboBox + { + DropDownStyle = ComboBoxStyle.DropDownList, + Width = UiMetrics.Px(460) + }; + _resultTable.SelectedIndexChanged += delegate { if (!_suppress) BindView(); }; + var export = MakeButton("此表 CSV", delegate { ExportCsv(); }); + _btnExcel = MakeButton("全部 Excel", delegate { ExportExcel(); }); + var back = MakeButton("返回对比", delegate { _tabs.SelectedIndex = 1; }); + _tips.SetToolTip(export, "导出当前这张表、当前筛选下的差异"); + _tips.SetToolTip(_btnExcel, "把这次对比的每一张表各写一个工作表,沿用上面的筛选"); var showLabel = InlineLabel("显示"); - var header = new Panel { Dock = DockStyle.Top, Height = UiMetrics.Px(72) }; + var header = new Panel { Dock = DockStyle.Top, Height = UiMetrics.Px(76) }; var bar = new CenterRow(header); - bar.Add(showLabel, 0); + bar.Add(back, 0); + bar.Add(InlineLabel("表"), UiMetrics.Px(12)); + bar.Add(_resultTable, UiMetrics.Px(6)); + bar.Add(showLabel, UiMetrics.Px(12)); bar.Add(_statusFilter, UiMetrics.Px(6)); bar.Add(_onlyDiffCells, UiMetrics.Px(16)); bar.Add(export, UiMetrics.Px(12)); + bar.Add(_btnExcel, UiMetrics.Px(8)); header.Controls.Add(bar); header.Controls.Add(_stats); + page.Resize += delegate { FitResultTable(); }; _diffGrid = CreateGrid(true); _diffGrid.VirtualMode = true; @@ -425,17 +706,21 @@ namespace DataCompare.App page.Controls.Add(split); page.Controls.Add(header); - page.Enter += delegate - { - if (split.Height > 200 && split.SplitterDistance < 80) - split.SplitterDistance = 240; - }; - Load += delegate + bool placed = false; + split.Resize += delegate { + if (placed || split.Height < 260) + return; + int want = Math.Max(UiMetrics.Px(360), (int)(split.Height * 0.46)); + int max = split.Height - UiMetrics.Px(200); + if (want > max) + want = max; + if (want < UiMetrics.Px(160)) + return; try { - if (split.Height > 220) - split.SplitterDistance = Math.Min(280, split.Height / 2); + split.SplitterDistance = want; + placed = true; } catch (InvalidOperationException) { @@ -477,6 +762,7 @@ namespace DataCompare.App { _suppress = false; } + RememberConnections(); } void FillCombo(ComboBox box) @@ -618,10 +904,13 @@ namespace DataCompare.App } box.SetTables(tables); _suppress = false; + if (_autoMatch != null && _autoMatch.Checked) + Rematch(!left); var summary = (left ? "左侧" : "右侧") + "已读取 " + tables.Count + " 张表"; if (catalogs.Count > 1) summary += ",来自 " + catalogs.Count + " 个库"; _status.Text = summary; + ScheduleColumnLoad(); } catch (Exception ex) { @@ -634,23 +923,30 @@ namespace DataCompare.App } } - async Task ReadColumnsAsync() + async Task ReadColumnsAsync(bool manual, int ticket) { + if (ticket != _columnLoad) + return; var leftProfile = SelectedProfile(_leftConn); var rightProfile = SelectedProfile(_rightConn); var leftTable = _leftTable.SelectedTable; var rightTable = _rightTable.SelectedTable; if (leftProfile == null || rightProfile == null || leftTable == null || rightTable == null) { - MessageBox.Show(this, "请先选择两侧的连接和表。", "读取字段", MessageBoxButtons.OK, MessageBoxIcon.Information); + if (manual && !IsDisposed) + MessageBox.Show(this, "请先选择两侧的连接和表。", "读取字段", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } var leftSnap = ConnectionStore.Clone(leftProfile); var rightSnap = ConnectionStore.Clone(rightProfile); var leftRef = CopyTable(leftTable); var rightRef = CopyTable(rightTable); + var started = false; try { + if (ticket != _columnLoad) + return; + started = true; SetBusy(true); _status.Text = "正在读取字段…"; var loaded = await Task.Run(() => @@ -663,7 +959,9 @@ namespace DataCompare.App rightCols = source.GetColumns(rightRef); return new ColumnPair { Left = leftCols, Right = rightCols }; }); - if (IsDisposed) + if (IsDisposed || ticket != _columnLoad) + return; + if (!TableMatcher.SameTable(_leftTable.SelectedTable, leftTable) || !TableMatcher.SameTable(_rightTable.SelectedTable, rightTable)) return; _leftColumns = loaded.Left; _rightColumns = loaded.Right; @@ -672,7 +970,7 @@ namespace DataCompare.App } catch (Exception ex) { - if (!IsDisposed) + if (!IsDisposed && ticket == _columnLoad) { _status.Text = "读取字段失败"; MessageBox.Show(this, ex.Message, "读取字段失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -680,7 +978,7 @@ namespace DataCompare.App } finally { - if (!IsDisposed) + if (started && !IsDisposed && ticket == _columnLoad) SetBusy(false); } } @@ -709,11 +1007,13 @@ namespace DataCompare.App row.Cells["RightName"].Value = match == null ? "" : match.Name; row.Cells["RightType"].Value = match == null ? "" : match.DataType; } + ApplyGuessedKeyToGrid(); } finally { _suppress = false; } + UpdateGuide(); } void ApplyNameMatch(bool overwriteCompare) @@ -741,6 +1041,55 @@ namespace DataCompare.App } } + void OpenColumnPick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0) + return; + if (_mapGrid.Columns[e.ColumnIndex].Name != "RightName") + return; + + _mapGrid.BeginEdit(true); + var combo = _mapGrid.EditingControl as ComboBox; + if (combo == null) + return; + BeginInvoke(new Action(delegate + { + if (!combo.IsDisposed && !combo.DroppedDown) + combo.DroppedDown = true; + })); + } + + void StyleColumnPick(object sender, DataGridViewEditingControlShowingEventArgs e) + { + var combo = e.Control as ComboBox; + var cell = _mapGrid.CurrentCell; + if (combo == null || cell == null + || _mapGrid.Columns[cell.ColumnIndex].Name != "RightName") + return; + combo.DropDownStyle = ComboBoxStyle.DropDownList; + combo.FlatStyle = FlatStyle.Flat; + combo.Font = _mapGrid.Font; + combo.Margin = Padding.Empty; + combo.Padding = Padding.Empty; + combo.Dock = DockStyle.Fill; + combo.IntegralHeight = false; + combo.MaxDropDownItems = 16; + combo.BackColor = Color.FromArgb(210, 227, 246); + combo.ForeColor = Color.Black; + var cellRect = _mapGrid.GetCellDisplayRectangle( + cell.ColumnIndex, cell.RowIndex, false); + int width = cellRect.Width; + for (int i = 0; i < combo.Items.Count; i++) + { + int text = TextRenderer.MeasureText( + Convert.ToString(combo.Items[i]) ?? "", combo.Font).Width + + UiMetrics.Px(28); + if (text > width) + width = text; + } + combo.DropDownWidth = Math.Min(Math.Max(width, combo.Width), UiMetrics.Px(480)); + } + void MapCellChanged(object sender, DataGridViewCellEventArgs e) { if (_suppress || e.RowIndex < 0) @@ -759,6 +1108,7 @@ namespace DataCompare.App _rightColumns = null; if (_mapGrid != null) _mapGrid.Rows.Clear(); + UpdateGuide(); } async Task PreviewAsync() @@ -807,7 +1157,17 @@ namespace DataCompare.App } } - async Task CompareAsync() + async Task ComparePrimaryAsync() + { + if (_jobs.Count > 0) + { + await CompareBatchAsync(); + return; + } + await CompareOneAsync(); + } + + async Task CompareOneAsync() { CompareRequest request; try @@ -844,9 +1204,22 @@ namespace DataCompare.App token)); if (IsDisposed) return; - _result = result; - _tabs.SelectedIndex = 2; - BindView(); + SetRun(new[] + { + new TableJob + { + LeftTable = request.LeftTable, + RightTable = request.RightTable, + LeftFilter = request.LeftFilter, + RightFilter = request.RightFilter, + Mappings = CopyMappings(request.Mappings), + LeftColumns = CopyColumns(_leftColumns), + RightColumns = CopyColumns(_rightColumns), + Status = TableJobStatus.Done, + Result = result + } + }); + ShowResults(); _status.Text = "对比完成,耗时 " + watch.Elapsed.TotalSeconds.ToString("0.0") + " 秒"; } catch (OperationCanceledException) @@ -1027,6 +1400,8 @@ namespace DataCompare.App void BindView() { + var job = CurrentViewJob(); + _result = job == null ? null : job.Result; _view.Clear(); if (_result != null && _result.Diffs != null) { @@ -1036,15 +1411,23 @@ namespace DataCompare.App _view.Add(_result.Diffs[i]); } } - _stats.Text = _result == null - ? "尚未对比" - : "左侧 " + _result.LeftRowCount + " 行 右侧 " + _result.RightRowCount - + " 行 值相同 " + _result.MatchedCount - + " 仅左侧 " + _result.LeftOnlyCount - + " 仅右侧 " + _result.RightOnlyCount - + " 内容不同 " + _result.DifferentCount - + " 键重复 " + _result.DuplicateCount - + " 键无效 " + _result.InvalidCount; + var title = job != null && job.LeftTable != null ? job.LeftTable.Display + " " : ""; + if (job != null && job.Status != TableJobStatus.Done) + { + _stats.Text = title + job.StatusText + (string.IsNullOrEmpty(job.Error) ? "" : " " + job.Error); + } + else + { + _stats.Text = _result == null + ? "尚未对比。在「对比」里选好表之后,结果会出现在这里。" + : title + "左 " + _result.LeftRowCount + " 行 · 右 " + _result.RightRowCount + + " 行 · 相同 " + _result.MatchedCount + + " · 仅左侧 " + _result.LeftOnlyCount + + " · 仅右侧 " + _result.RightOnlyCount + + " · 内容不同 " + _result.DifferentCount + + " · 键重复 " + _result.DuplicateCount + + " · 键无效 " + _result.InvalidCount; + } _suppress = true; _diffGrid.RowCount = 0; @@ -1067,14 +1450,7 @@ namespace DataCompare.App bool PassFilter(RowDiff diff) { - switch (_statusFilter.SelectedIndex) - { - case 1: return diff.Status == DiffStatus.LeftOnly; - case 2: return diff.Status == DiffStatus.RightOnly; - case 3: return diff.Status == DiffStatus.Different; - case 4: return diff.Status == DiffStatus.DuplicateKey || diff.Status == DiffStatus.InvalidKey; - default: return true; - } + return DiffWorkbook.Include(diff, _statusFilter.SelectedIndex); } void DiffCellValueNeeded(object sender, DataGridViewCellValueEventArgs e) @@ -1217,14 +1593,1109 @@ namespace DataCompare.App } } + void ExportExcel() + { + if (_run.Count == 0) + { + MessageBox.Show(this, "没有可导出的结果。", "导出", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + using (var dialog = new SaveFileDialog()) + { + dialog.Filter = "Excel 文件|*.xlsx"; + dialog.FileName = "差异.xlsx"; + if (dialog.ShowDialog(this) != DialogResult.OK) + return; + try + { + var tables = new List(); + for (int i = 0; i < _run.Count; i++) + tables.Add(ToExport(_run[i])); + XlsxFile.Save(dialog.FileName, DiffWorkbook.Build(tables, _statusFilter.SelectedIndex)); + _status.Text = "已导出 " + dialog.FileName; + } + catch (Exception ex) + { + _status.Text = "导出失败"; + MessageBox.Show(this, ex.Message, "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + } + + async Task CompareBatchAsync() + { + ConnectionProfile leftProfile; + ConnectionProfile rightProfile; + DataCompare.Core.CompareOptions options; + try + { + leftProfile = SelectedProfile(_leftConn); + rightProfile = SelectedProfile(_rightConn); + if (leftProfile == null || rightProfile == null) + throw new InvalidOperationException("请选择左右两侧的连接。"); + options = ReadOptions(); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "无法开始对比", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + AdoptSelectedMapping(); + int runnable = 0; + for (int i = 0; i < _jobs.Count; i++) + { + if (!_jobs[i].CanRun) + continue; + _jobs[i].Status = TableJobStatus.Pending; + _jobs[i].Result = null; + _jobs[i].Error = ""; + runnable++; + } + if (runnable == 0) + { + RefreshBatchGrid(null); + MessageBox.Show(this, "这些表还不能对比。点中一行,在字段表勾选「键」,再点「对比批次」。键用来把两侧的行对齐。", "无法开始对比", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + RefreshBatchGrid(null); + + var leftSnap = ConnectionStore.Clone(leftProfile); + var rightSnap = ConnectionStore.Clone(rightProfile); + _cts = new CancellationTokenSource(); + var token = _cts.Token; + var watch = Stopwatch.StartNew(); + int finished = 0; + try + { + SetBusy(true); + for (int i = 0; i < _jobs.Count; i++) + { + var job = _jobs[i]; + if (!job.CanRun) + continue; + if (token.IsCancellationRequested) + break; + int index = i + 1; + var label = ShortName(job.LeftTable); + var progress = new Progress(text => + { + if (!IsDisposed) + _status.Text = "正在对比 " + index + "/" + _jobs.Count + " " + label + "… " + text; + }); + if (!IsDisposed) + _status.Text = "正在对比 " + index + "/" + _jobs.Count + " " + label + "…"; + try + { + var result = await Task.Run(() => CompareSession.Execute( + leftSnap, + job.LeftTable, + job.LeftFilter, + rightSnap, + job.RightTable, + job.RightFilter, + job.Mappings, + options, + progress, + token)); + job.Result = result; + job.Error = ""; + job.Status = TableJobStatus.Done; + finished++; + } + catch (OperationCanceledException) + { + job.Result = null; + job.Status = TableJobStatus.Canceled; + job.Error = "已取消"; + break; + } + catch (Exception ex) + { + job.Result = null; + if (token.IsCancellationRequested) + { + job.Status = TableJobStatus.Canceled; + job.Error = "已取消"; + break; + } + job.Status = TableJobStatus.Failed; + job.Error = ex.Message; + } + if (!IsDisposed) + RefreshBatchGrid(job); + } + if (IsDisposed) + return; + SetRun(_jobs); + ShowResults(); + _status.Text = token.IsCancellationRequested + ? "已取消,完成 " + finished + " 张" + : "对比完成 " + finished + " 张,耗时 " + watch.Elapsed.TotalSeconds.ToString("0.0") + " 秒"; + } + finally + { + if (_cts != null) + { + _cts.Dispose(); + _cts = null; + } + if (!IsDisposed) + SetBusy(false); + } + } + + void ShowResults() + { + _suppress = true; + try + { + _resultTable.Items.Clear(); + int select = 0; + bool found = false; + for (int i = 0; i < _run.Count; i++) + { + _resultTable.Items.Add(new RunItem(_run[i])); + if (!found && _run[i].Status == TableJobStatus.Done) + { + select = i; + found = true; + } + } + if (_resultTable.Items.Count > 0) + _resultTable.SelectedIndex = select; + } + finally + { + _suppress = false; + } + FitResultTable(); + _tabs.SelectedIndex = 2; + BindView(); + } + + void FitResultTable() + { + if (_resultTable == null || _resultTable.IsDisposed) + return; + int longest = UiMetrics.Px(460); + for (int i = 0; i < _resultTable.Items.Count; i++) + { + int text = TextRenderer.MeasureText(Convert.ToString(_resultTable.Items[i]), _resultTable.Font).Width + UiMetrics.Px(36); + if (text > longest) + longest = text; + } + int room = ClientSize.Width - UiMetrics.Px(620); + if (room < UiMetrics.Px(320)) + room = UiMetrics.Px(320); + int width = longest > room ? room : longest; + _resultTable.DropDownWidth = Math.Min(Math.Max(longest, width), UiMetrics.Px(960)); + if (_resultTable.Width == width) + return; + _resultTable.Width = width; + if (_resultTable.Parent != null) + _resultTable.Parent.PerformLayout(); + } + + void SetRun(IList jobs) + { + _run.Clear(); + if (jobs == null) + return; + for (int i = 0; i < jobs.Count; i++) + _run.Add(jobs[i]); + } + + TableJob CurrentViewJob() + { + if (_resultTable == null) + return null; + var item = _resultTable.SelectedItem as RunItem; + return item == null ? null : item.Job; + } + + void OnTableChanged(bool fromLeft) + { + if (_suppress) + return; + if (_leftTable.DroppedDown || _rightTable.DroppedDown) + { + _columnPending = true; + _pendingFromLeft = fromLeft; + return; + } + ApplyTableChange(fromLeft); + } + + void FlushPendingTableChange() + { + if (_suppress || !_columnPending) + return; + if (_leftTable.DroppedDown || _rightTable.DroppedDown) + return; + ApplyTableChange(_pendingFromLeft); + } + + void ApplyTableChange(bool fromLeft) + { + _columnPending = false; + ClearMapping(); + Rematch(fromLeft); + ScheduleColumnLoad(); + } + + bool Rematch(bool fromLeft) + { + if (_suppress || _autoMatch == null || !_autoMatch.Checked) + return false; + var sourceBox = fromLeft ? _leftTable : _rightTable; + var targetBox = fromLeft ? _rightTable : _leftTable; + var source = sourceBox.SelectedTable; + if (source == null || targetBox.Tables.Count == 0) + return false; + var matches = TableMatcher.Match(source, targetBox.Tables, SelectedRule()); + if (matches.Count == 1) + { + if (!TableMatcher.SameTable(targetBox.SelectedTable, matches[0])) + { + _suppress = true; + targetBox.SelectTable(matches[0]); + _suppress = false; + ClearMapping(); + _status.Text = "已匹配 " + matches[0].Display; + return true; + } + _status.Text = "已匹配 " + matches[0].Display; + return false; + } + if (matches.Count == 0) + _status.Text = "另一侧没有对应表"; + else + _status.Text = "对应到 " + matches.Count + " 张,请继续选择"; + return false; + } + + void ReloadRules(string selectId) + { + var rules = MatchRuleStore.Load(); + _suppress = true; + try + { + _ruleBox.Items.Clear(); + _ruleBox.Items.Add(new RuleItem(TableMatchRule.SameName())); + _ruleBox.Items.Add(new RuleItem(TableMatchRule.SchemaPrefix())); + for (int i = 0; i < rules.Count; i++) + _ruleBox.Items.Add(new RuleItem(rules[i])); + int index = 1; + if (!string.IsNullOrEmpty(selectId)) + { + for (int i = 0; i < _ruleBox.Items.Count; i++) + { + var item = _ruleBox.Items[i] as RuleItem; + if (item != null && string.Equals(item.Rule.Id, selectId, StringComparison.OrdinalIgnoreCase)) + index = i; + } + } + _ruleBox.SelectedIndex = index; + } + finally + { + _suppress = false; + } + } + + TableMatchRule SelectedRule() + { + var item = _ruleBox == null ? null : _ruleBox.SelectedItem as RuleItem; + if (item == null || item.Rule == null) + return TableMatchRule.SchemaPrefix(); + return item.Rule; + } + + void ManageRules() + { + var current = SelectedRule(); + using (var form = new RuleListForm()) + form.ShowDialog(this); + ReloadRules(current == null ? "prefix" : current.Id); + if (_autoMatch.Checked && Rematch(true)) + ScheduleColumnLoad(); + } + + void AddCurrentJob() + { + CompareRequest request; + try + { + request = CaptureRequest(true); + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "放入批次", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + var existing = FindPair(request.LeftTable, request.RightTable); + var job = existing ?? new TableJob(); + FillJob(job, request); + job.Status = TableJobStatus.Pending; + job.Error = ""; + job.Result = null; + if (existing == null) + _jobs.Add(job); + RefreshBatchGrid(job); + _status.Text = existing == null + ? "已加入批次,共 " + _jobs.Count + " 张" + : "已更新批次中的同一对表"; + } + + void UpdateCurrentJob() + { + var job = SelectedBatchJob(); + if (job == null) + { + MessageBox.Show(this, "请先在批次中选择一张表。", "批次", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + if ((_leftTable.SelectedTable == null || _rightTable.SelectedTable == null) && job.LeftTable != null && job.RightTable != null) + { + _suppress = true; + try + { + _leftTable.SelectTable(job.LeftTable); + _rightTable.SelectTable(job.RightTable); + } + finally + { + _suppress = false; + } + } + CompareRequest request; + try + { + request = CaptureRequest(true); + } + catch (InvalidOperationException ex) + { + if (job.LeftTable == null || job.RightTable == null || _leftColumns == null || _rightColumns == null + || (_leftTable.SelectedTable != null && _rightTable.SelectedTable != null)) + { + MessageBox.Show(this, ex.Message, "更新批次", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + try + { + var mappings = ReadMappings(); + job.LeftFilter = _leftFilter.Text ?? ""; + job.RightFilter = _rightFilter.Text ?? ""; + job.Mappings = CopyMappings(mappings); + job.LeftColumns = CopyColumns(_leftColumns); + job.RightColumns = CopyColumns(_rightColumns); + job.Status = TableJobStatus.Pending; + job.Error = ""; + job.Result = null; + RefreshBatchGrid(job); + _status.Text = "已更新批次"; + } + catch (Exception inner) + { + MessageBox.Show(this, inner.Message, "更新批次", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + return; + } + catch (Exception ex) + { + MessageBox.Show(this, ex.Message, "更新批次", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + var other = FindPair(request.LeftTable, request.RightTable); + if (other != null && other != job) + { + MessageBox.Show(this, "批次里已有这一对表。", "更新批次", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + FillJob(job, request); + job.Status = TableJobStatus.Pending; + job.Error = ""; + job.Result = null; + RefreshBatchGrid(job); + _status.Text = "已更新批次"; + } + + void RemoveCurrentJob() + { + var job = SelectedBatchJob(); + if (job == null) + return; + _jobs.Remove(job); + RefreshBatchGrid(null); + _status.Text = "批次还剩 " + _jobs.Count + " 张"; + } + + void AskClearBatch() + { + if (_jobs.Count == 0) + return; + if (MessageBox.Show(this, "清空批次中的 " + _jobs.Count + " 张表?", "批次", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + return; + ClearBatch("批次已清空"); + } + + void ClearBatch(string status) + { + if (_jobs.Count == 0) + return; + _jobs.Clear(); + RefreshBatchGrid(null); + if (!string.IsNullOrEmpty(status) && !IsDisposed) + _status.Text = status; + } + + async Task PickTablesAsync() + { + if (_leftTable.Tables.Count == 0 || _rightTable.Tables.Count == 0) + { + MessageBox.Show(this, "请先选择两侧连接,并等待表列表加载完成。", "批量选表", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + var leftProfile = SelectedProfile(_leftConn); + var rightProfile = SelectedProfile(_rightConn); + if (leftProfile == null || rightProfile == null) + { + MessageBox.Show(this, "请选择左右两侧的连接。", "批量选表", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + List pickedLeft; + List pickedRight; + List keys; + using (var form = new TablePickForm(_leftTable.Tables, _rightTable.Tables, SelectedRule())) + { + if (form.ShowDialog(this) != DialogResult.OK) + return; + pickedLeft = form.PickedLeft; + pickedRight = form.PickedRight; + keys = SplitKeys(form.KeyText); + } + var pairs = new List(); + for (int i = 0; i < pickedLeft.Count; i++) + pairs.Add(new[] { CopyTable(pickedLeft[i]), CopyTable(pickedRight[i]) }); + var leftSnap = ConnectionStore.Clone(leftProfile); + var rightSnap = ConnectionStore.Clone(rightProfile); + _cts = new CancellationTokenSource(); + var token = _cts.Token; + var progress = new Progress(text => + { + if (!IsDisposed) + _status.Text = text; + }); + try + { + SetBusy(true); + var created = await Task.Run(() => ReadPairColumns(leftSnap, rightSnap, pairs, keys, progress, token)); + if (IsDisposed) + return; + int added = 0; + int updated = 0; + int missing = 0; + int failed = 0; + for (int i = 0; i < created.Count; i++) + { + var job = created[i]; + var existing = FindPair(job.LeftTable, job.RightTable); + if (existing == null) + { + _jobs.Add(job); + added++; + } + else + { + existing.Mappings = job.Mappings; + existing.LeftColumns = job.LeftColumns; + existing.RightColumns = job.RightColumns; + existing.LeftFilter = ""; + existing.RightFilter = ""; + existing.Status = job.Status; + existing.Error = job.Error; + existing.Result = null; + updated++; + } + if (job.Status == TableJobStatus.MissingKey) + missing++; + else if (job.Status == TableJobStatus.Failed) + failed++; + } + RefreshBatchGrid(_jobs.Count == 0 ? null : _jobs[_jobs.Count - 1]); + _status.Text = token.IsCancellationRequested + ? "已取消,加入 " + added + " 张" + : "已加入 " + added + " 张,更新 " + updated + " 张,缺键 " + missing + " 张,失败 " + failed + " 张"; + } + catch (Exception ex) + { + if (!IsDisposed) + { + _status.Text = "读取字段失败"; + MessageBox.Show(this, ex.Message, "批量选表", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + finally + { + if (_cts != null) + { + _cts.Dispose(); + _cts = null; + } + if (!IsDisposed) + SetBusy(false); + } + } + + static List ReadPairColumns( + ConnectionProfile leftProfile, + ConnectionProfile rightProfile, + List pairs, + List keys, + IProgress progress, + CancellationToken token) + { + var created = new List(); + using (var left = DataSourceFactory.Create(leftProfile)) + using (var right = DataSourceFactory.Create(rightProfile)) + { + for (int i = 0; i < pairs.Count; i++) + { + if (token.IsCancellationRequested) + break; + if (progress != null) + progress.Report("正在读取字段 " + (i + 1) + "/" + pairs.Count + " " + ShortName(pairs[i][0]) + "…"); + var job = new TableJob + { + LeftTable = pairs[i][0], + RightTable = pairs[i][1], + LeftFilter = "", + RightFilter = "" + }; + try + { + job.LeftColumns = CopyColumns(left.GetColumns(job.LeftTable)); + job.RightColumns = CopyColumns(right.GetColumns(job.RightTable)); + string missing; + job.Mappings = ColumnMapper.ByName(job.LeftColumns, job.RightColumns, keys, out missing); + var guessed = ColumnMapper.HasKey(job.Mappings) ? null : ColumnMapper.GuessKey(job.Mappings); + if (guessed != null) + ColumnMapper.MarkKey(job.Mappings, guessed); + if (ColumnMapper.HasKey(job.Mappings) && missing.Length == 0) + { + job.Status = TableJobStatus.Pending; + job.Error = guessed == null ? "" : "键列:" + guessed; + } + else if (guessed != null) + { + job.Status = TableJobStatus.Pending; + var asked = missing.StartsWith("缺少键列:") ? missing.Substring("缺少键列:".Length) : missing; + job.Error = "没有 " + asked + ",已改用 " + guessed; + } + else + { + job.Status = TableJobStatus.MissingKey; + job.Error = (missing.Length > 0 ? missing : "缺少键列") + "。" + ColumnMapper.KeyHint(job.Mappings); + } + } + catch (Exception ex) + { + if (token.IsCancellationRequested) + break; + job.Status = TableJobStatus.Failed; + job.Error = ex.Message; + } + created.Add(job); + } + } + return created; + } + + void FillJob(TableJob job, CompareRequest request) + { + job.LeftTable = request.LeftTable; + job.RightTable = request.RightTable; + job.LeftFilter = request.LeftFilter ?? ""; + job.RightFilter = request.RightFilter ?? ""; + job.Mappings = CopyMappings(request.Mappings); + job.LeftColumns = CopyColumns(_leftColumns); + job.RightColumns = CopyColumns(_rightColumns); + } + + void LoadSelectedJob() + { + if (_loadingBatchJob) + return; + var job = SelectedBatchJob(); + if (job == null) + return; + _loadingBatchJob = true; + try + { + _suppress = true; + bool leftOk = false; + bool rightOk = false; + try + { + leftOk = _leftTable.SelectTable(job.LeftTable); + rightOk = _rightTable.SelectTable(job.RightTable); + _leftFilter.Text = job.LeftFilter ?? ""; + _rightFilter.Text = job.RightFilter ?? ""; + _leftColumns = job.LeftColumns; + _rightColumns = job.RightColumns; + } + finally + { + _suppress = false; + } + FillMappingFrom(job.Mappings); + if (job.Status == TableJobStatus.MissingKey && GridHasKey()) + { + try + { + var mappings = ReadMappings(); + job.Mappings = CopyMappings(mappings); + job.Status = TableJobStatus.Pending; + job.Error = "键列:" + FirstKey(mappings); + RefreshBatchGrid(job); + } + catch (InvalidOperationException) + { + } + } + if (!leftOk || !rightOk) + _status.Text = "批次中的表不在当前列表里"; + UpdateGuide(); + } + finally + { + _loadingBatchJob = false; + } + } + + void FillMappingFrom(List mappings) + { + if (_leftColumns == null || _rightColumns == null) + { + if (_mapGrid != null) + _mapGrid.Rows.Clear(); + return; + } + FillMapping(); + if (mappings == null) + mappings = new List(); + _suppress = true; + try + { + var combo = (DataGridViewComboBoxColumn)_mapGrid.Columns["RightName"]; + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + row.Cells["Key"].Value = false; + row.Cells["Compare"].Value = false; + row.Cells["RightName"].Value = ""; + row.Cells["RightType"].Value = ""; + var left = Convert.ToString(row.Cells["LeftName"].Value); + ColumnMapping found = null; + for (int i = 0; i < mappings.Count; i++) + { + if (string.Equals(mappings[i].LeftColumn, left, StringComparison.OrdinalIgnoreCase)) + found = mappings[i]; + } + if (found == null) + continue; + var rightName = found.RightColumn ?? ""; + for (int i = 0; i < combo.Items.Count; i++) + { + var item = Convert.ToString(combo.Items[i]); + if (string.Equals(item, rightName, StringComparison.OrdinalIgnoreCase)) + { + rightName = item; + break; + } + } + if (rightName.Length > 0 && !combo.Items.Contains(rightName)) + combo.Items.Add(rightName); + row.Cells["RightName"].Value = rightName; + var match = FindColumn(_rightColumns, rightName); + row.Cells["RightType"].Value = match == null ? "" : match.DataType; + row.Cells["Key"].Value = found.IsKey; + row.Cells["Compare"].Value = found.Compare; + } + ApplyGuessedKeyToGrid(); + } + finally + { + _suppress = false; + } + UpdateGuide(); + } + + void RefreshBatchGrid(TableJob select) + { + _suppress = true; + try + { + if (select == null && _batchGrid.CurrentRow != null) + select = _batchGrid.CurrentRow.Tag as TableJob; + _batchGrid.Rows.Clear(); + int selectIndex = -1; + for (int i = 0; i < _jobs.Count; i++) + { + var job = _jobs[i]; + int index = _batchGrid.Rows.Add( + job.LeftTable == null ? "" : job.LeftTable.Display, + job.RightTable == null ? "" : job.RightTable.Display, + job.StatusText, + job.Note); + _batchGrid.Rows[index].Tag = job; + if (select == job) + selectIndex = index; + } + if (selectIndex >= 0) + _batchGrid.CurrentCell = _batchGrid.Rows[selectIndex].Cells[0]; + } + finally + { + _suppress = false; + } + UpdateGuide(); + if (!_loadingBatchJob && SelectedBatchJob() != null) + LoadSelectedJob(); + } + + void UpdateGuide() + { + if (_guide == null || _btnCompare == null) + return; + RefreshFilterButton(); + int runnable = 0; + int missing = 0; + for (int i = 0; i < _jobs.Count; i++) + { + if (_jobs[i].CanRun) + runnable++; + else if (_jobs[i].Status == TableJobStatus.MissingKey) + missing++; + } + var selected = _batchGrid == null ? null : SelectedBatchJob(); + if (_btnCompareOne != null) + _btnCompareOne.Visible = _jobs.Count > 0; + if (!_busy) + { + if (_btnUpdateJob != null) + _btnUpdateJob.Enabled = selected != null; + if (_btnRemoveJob != null) + _btnRemoveJob.Enabled = selected != null; + if (_btnClearJobs != null) + _btnClearJobs.Enabled = _jobs.Count > 0; + } + LayoutBatch(); + FitPrimaryButton(); + if (_jobs.Count > 0) + { + _btnCompare.Text = runnable > 0 ? "对比批次 (" + runnable + ")" : "对比批次"; + if (selected != null && selected.Status == TableJobStatus.MissingKey) + _guide.Text = "这一行还不能对比。" + selected.Error + " 勾选「键」后点「写回选中行」,再点「对比批次」。"; + else if (runnable == 0) + _guide.Text = "批次里还没有可对比的表。点中一行,勾选「键」,再点「对比批次」。"; + else if (missing > 0) + _guide.Text = "将对比 " + runnable + " 张,另有 " + missing + " 张要先勾选键。点一行可以改。"; + else + _guide.Text = "将按批次对比 " + runnable + " 张。没放进批次的修改,用「只对比当前表」。"; + return; + } + _btnCompare.Text = "对比当前表"; + bool ready = _leftTable != null && _rightTable != null && _leftTable.SelectedTable != null && _rightTable.SelectedTable != null; + if (!ready || _leftColumns == null || _rightColumns == null) + { + bool failed = ready && _status != null && _status.Text != null && _status.Text.IndexOf("失败", StringComparison.Ordinal) >= 0; + _guide.Text = !ready + ? "先选择左右两侧的连接和表。要一次加入多张,点「批量选表」。" + : failed + ? "读取字段失败。点「重新读取」再试一次。" + : "正在读取字段。若字段表一直是空的,点「重新读取」。"; + } + else if (!GridHasKey()) + _guide.Text = "勾选至少一个「键」,用来对齐两侧的行,然后点「对比当前表」。"; + else + _guide.Text = "可以对比当前这一对。要连同其他表一起跑,点「放入批次」或「批量选表」。"; + } + + void LayoutBatch() + { + if (_batchHost == null || _batchGrid == null || _batchCaption == null) + return; + if (_jobs.Count == 0) + { + _batchGrid.Visible = false; + _batchCaption.Text = "批次为空。右下角只对比当前这一对表。"; + int collapsed = _batchCaption.Height + 1; + if (_batchHost.Height != collapsed) + _batchHost.Height = collapsed; + return; + } + _batchGrid.Visible = true; + int rows = Math.Min(_jobs.Count, 4); + int height = _batchCaption.Height + 1 + _batchGrid.ColumnHeadersHeight + rows * _batchGrid.RowTemplate.Height + UiMetrics.Px(8); + _batchCaption.Text = "批次 " + _jobs.Count + " 张。点一行载入到上面,改完点「写回选中行」。"; + if (_batchHost.Height != height) + _batchHost.Height = height; + } + + void ApplyGuessedKeyToGrid() + { + if (_mapGrid == null || GridHasKey()) + return; + var mappings = new List(); + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + var left = (Convert.ToString(row.Cells["LeftName"].Value) ?? "").Trim(); + var right = (Convert.ToString(row.Cells["RightName"].Value) ?? "").Trim(); + if (left.Length == 0 || right.Length == 0) + continue; + mappings.Add(new ColumnMapping + { + LeftColumn = left, + RightColumn = right, + Compare = true + }); + } + var guessed = ColumnMapper.GuessKey(mappings); + if (string.IsNullOrEmpty(guessed)) + return; + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (row.IsNewRow) + continue; + var left = Convert.ToString(row.Cells["LeftName"].Value); + if (!string.Equals(left, guessed, StringComparison.OrdinalIgnoreCase)) + continue; + row.Cells["Key"].Value = true; + var right = (Convert.ToString(row.Cells["RightName"].Value) ?? "").Trim(); + if (right.Length > 0) + row.Cells["Compare"].Value = true; + } + } + + void AdoptSelectedMapping() + { + var job = SelectedBatchJob(); + if (job == null || _leftColumns == null || _rightColumns == null) + return; + if (!TableMatcher.SameTable(_leftTable.SelectedTable, job.LeftTable) + || !TableMatcher.SameTable(_rightTable.SelectedTable, job.RightTable)) + return; + try + { + var mappings = ReadMappings(); + job.Mappings = CopyMappings(mappings); + job.LeftColumns = CopyColumns(_leftColumns); + job.RightColumns = CopyColumns(_rightColumns); + job.LeftFilter = _leftFilter.Text ?? ""; + job.RightFilter = _rightFilter.Text ?? ""; + job.Status = TableJobStatus.Pending; + job.Error = ""; + job.Result = null; + } + catch (InvalidOperationException) + { + } + } + + void BatchCellFormatting(object sender, DataGridViewCellFormattingEventArgs e) + { + if (e.RowIndex < 0 || e.RowIndex >= _batchGrid.Rows.Count) + return; + var job = _batchGrid.Rows[e.RowIndex].Tag as TableJob; + if (job == null || job.Status == TableJobStatus.Pending) + return; + Color color; + switch (job.Status) + { + case TableJobStatus.MissingKey: color = Color.FromArgb(255, 246, 220); break; + case TableJobStatus.Failed: color = Color.FromArgb(255, 228, 228); break; + case TableJobStatus.Done: color = Color.FromArgb(226, 244, 226); break; + default: color = Color.FromArgb(245, 245, 245); break; + } + PaintCell(e, color); + } + + bool GridHasKey() + { + if (_mapGrid == null) + return false; + foreach (DataGridViewRow row in _mapGrid.Rows) + { + if (!row.IsNewRow && Checked(row, "Key")) + return true; + } + return false; + } + + static string FirstKey(List mappings) + { + if (mappings == null) + return ""; + for (int i = 0; i < mappings.Count; i++) + { + if (mappings[i] != null && mappings[i].IsKey) + return mappings[i].LeftColumn ?? ""; + } + return ""; + } + + TableJob SelectedBatchJob() + { + if (_batchGrid.CurrentRow == null) + return null; + return _batchGrid.CurrentRow.Tag as TableJob; + } + + TableJob FindPair(TableRef left, TableRef right) + { + for (int i = 0; i < _jobs.Count; i++) + { + if (TableMatcher.SameTable(_jobs[i].LeftTable, left) && TableMatcher.SameTable(_jobs[i].RightTable, right)) + return _jobs[i]; + } + return null; + } + + static ExportTable ToExport(TableJob job) + { + var completed = job.Status == TableJobStatus.Done && job.Result != null; + return new ExportTable + { + SheetTitle = job.LeftTable == null || string.IsNullOrWhiteSpace(job.LeftTable.Name) ? "表" : job.LeftTable.Name, + Label = PairLabel(job.LeftTable, job.RightTable), + Status = job.StatusText, + Note = completed ? "" : (job.Error ?? ""), + Result = completed ? job.Result : null, + Completed = completed + }; + } + + static string PairLabel(TableRef left, TableRef right) + { + if (left == null) + return right == null ? "" : right.Display; + if (right == null || string.Equals(left.Display, right.Display, StringComparison.OrdinalIgnoreCase)) + return left.Display; + return left.Display + " → " + right.Display; + } + + static string ShortName(TableRef table) + { + if (table == null) + return ""; + if (!string.IsNullOrEmpty(table.Schema)) + return table.Schema + "." + table.Name; + return table.Name ?? ""; + } + + static List SplitKeys(string text) + { + var list = new List(); + var parts = (text ?? "").Split(new[] { ',', ',', ';', ';' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < parts.Length; i++) + { + var name = parts[i].Trim(); + if (name.Length == 0) + continue; + bool exists = false; + for (int j = 0; j < list.Count; j++) + { + if (string.Equals(list[j], name, StringComparison.OrdinalIgnoreCase)) + exists = true; + } + if (!exists) + list.Add(name); + } + return list; + } + + static List CopyColumns(IList columns) + { + var list = new List(); + if (columns == null) + return list; + for (int i = 0; i < columns.Count; i++) + { + var column = columns[i]; + if (column == null) + continue; + list.Add(new ColumnInfo + { + Name = column.Name, + DataType = column.DataType, + Nullable = column.Nullable + }); + } + return list; + } + + static List CopyMappings(IList mappings) + { + var list = new List(); + if (mappings == null) + return list; + for (int i = 0; i < mappings.Count; i++) + { + var mapping = mappings[i]; + if (mapping == null) + continue; + list.Add(new ColumnMapping + { + LeftColumn = mapping.LeftColumn, + RightColumn = mapping.RightColumn, + IsKey = mapping.IsKey, + Compare = mapping.Compare + }); + } + return list; + } + void SetBusy(bool busy) { + _busy = busy; _btnCompare.Enabled = !busy; + if (_btnCompareOne != null) + _btnCompareOne.Enabled = !busy; _btnPreview.Enabled = !busy; + if (_btnFilter != null) + _btnFilter.Enabled = !busy; _btnRead.Enabled = !busy; _btnMatch.Enabled = !busy; _btnCancel.Enabled = busy; + _btnAddJob.Enabled = !busy; + _btnPickJobs.Enabled = !busy; + _btnRules.Enabled = !busy; + if (_btnToggleOptions != null) + _btnToggleOptions.Enabled = !busy; + _ruleBox.Enabled = !busy; + _autoMatch.Enabled = !busy; + _leftConn.Enabled = !busy; + _rightConn.Enabled = !busy; + _leftTable.Enabled = !busy; + _rightTable.Enabled = !busy; + _leftFilter.ReadOnly = busy; + _rightFilter.ReadOnly = busy; + _mapGrid.Enabled = !busy; + _batchGrid.Enabled = !busy; UseWaitCursor = busy; + if (!busy) + UpdateGuide(); + else + { + _btnUpdateJob.Enabled = false; + _btnRemoveJob.Enabled = false; + _btnClearJobs.Enabled = false; + } } static void PaintCell(DataGridViewCellFormattingEventArgs e, Color color) @@ -1405,11 +2876,151 @@ namespace DataCompare.App }; } + void EditFilters() + { + using (var form = new FilterForm(_leftFilter.Text, _rightFilter.Text)) + { + if (form.ShowDialog(this) != DialogResult.OK) + return; + _leftFilter.Text = form.LeftText; + _rightFilter.Text = form.RightText; + } + RefreshFilterButton(); + } + + void RefreshFilterButton() + { + if (_btnFilter == null) + return; + bool filled = (_leftFilter.Text ?? "").Trim().Length > 0 || (_rightFilter.Text ?? "").Trim().Length > 0; + _btnFilter.Text = filled ? "筛选条件*" : "筛选条件"; + var tip = "给左右两侧加行条件。不要写 WHERE,不要写分号"; + if (filled) + { + tip += "\r\n左侧:" + ((_leftFilter.Text ?? "").Trim().Length == 0 ? "(空)" : _leftFilter.Text.Trim()); + tip += "\r\n右侧:" + ((_rightFilter.Text ?? "").Trim().Length == 0 ? "(空)" : _rightFilter.Text.Trim()); + } + _tips.SetToolTip(_btnFilter, tip); + } + + void ToggleOptions() + { + _optionsOpen = !_optionsOpen; + RefreshOptionButton(); + FitOptionHost(); + } + + void RefreshOptionButton() + { + if (_btnToggleOptions == null) + return; + _btnToggleOptions.Text = _optionsOpen ? "收起比较选项" : "比较选项"; + } + + void FitOptionHost() + { + if (_fittingOptions || _optionHost == null || _optionFlow == null) + return; + _fittingOptions = true; + try + { + if (!_optionsOpen) + { + _optionHost.Visible = false; + if (_optionHost.Height != 0) + _optionHost.Height = 0; + return; + } + _optionHost.Visible = true; + int width = _optionHost.ClientSize.Width; + if (width < 40) + width = ClientSize.Width; + int optionHeight = _optionFlow.GetPreferredSize(new Size(width, 0)).Height; + int next = Math.Max(UiMetrics.Px(28), optionHeight); + if (_optionHost.Height != next) + _optionHost.Height = next; + } + finally + { + _fittingOptions = false; + } + } + + void ScheduleColumnLoad() + { + int ticket = ++_columnLoad; + if (_leftTable.SelectedTable == null || _rightTable.SelectedTable == null) + { + UpdateGuide(); + return; + } + if (!IsHandleCreated) + return; + BeginInvoke(new Func(() => ReadColumnsAsync(false, ticket))); + } + + bool AcceptConnectionChange(ComboBox box, bool left) + { + var previous = left ? _acceptedLeftId : _acceptedRightId; + var current = ProfileId(box); + if (SameId(previous, current)) + return false; + if (_jobs.Count > 0) + { + if (MessageBox.Show( + this, + "更换连接会清空批次里的 " + _jobs.Count + " 张表。要继续吗?", + "更换连接", + MessageBoxButtons.OKCancel, + MessageBoxIcon.Question) != DialogResult.OK) + { + RestoreConnection(box, previous); + return false; + } + ClearBatch("已更换连接,批次已清空"); + } + if (left) + _acceptedLeftId = current; + else + _acceptedRightId = current; + return true; + } + + void RestoreConnection(ComboBox box, Guid? id) + { + _suppress = true; + try + { + if (!id.HasValue) + box.SelectedIndex = -1; + else + Reselect(box, id); + } + finally + { + _suppress = false; + } + } + + void RememberConnections() + { + _acceptedLeftId = ProfileId(_leftConn); + _acceptedRightId = ProfileId(_rightConn); + } + + static bool SameId(Guid? left, Guid? right) + { + if (!left.HasValue || !right.HasValue) + return left.HasValue == right.HasValue; + return left.Value == right.Value; + } + static Button MakeButton(string text, EventHandler click) { var button = new Button { Text = text, + Font = UiFont(), AutoSize = true, AutoSizeMode = AutoSizeMode.GrowAndShrink, Padding = new Padding(UiMetrics.Px(12), UiMetrics.Px(3), UiMetrics.Px(12), UiMetrics.Px(3)), @@ -1420,6 +3031,41 @@ namespace DataCompare.App return button; } + static void StylePrimary(Button button) + { + button.BackColor = Color.FromArgb(37, 99, 168); + button.ForeColor = Color.White; + button.UseVisualStyleBackColor = false; + button.FlatStyle = FlatStyle.Flat; + button.FlatAppearance.BorderSize = 0; + button.FlatAppearance.MouseOverBackColor = Color.FromArgb(28, 82, 145); + button.FlatAppearance.MouseDownBackColor = Color.FromArgb(22, 68, 122); + } + + void FitPrimaryButton() + { + if (_btnCompare == null || _btnCancel == null) + return; + int side = UiMetrics.Px(16); + int vertical = UiMetrics.Px(4); + _btnCompare.AutoSize = true; + _btnCompare.AutoSizeMode = AutoSizeMode.GrowAndShrink; + _btnCompare.Padding = new Padding(side, vertical, side, vertical); + _btnCompare.Margin = new Padding(0, UiMetrics.Px(4), UiMetrics.Px(8), 0); + int flat = _btnCompare.GetPreferredSize(Size.Empty).Height; + int sample = _btnCancel.GetPreferredSize(Size.Empty).Height; + int extra = flat - sample; + if (extra > 0) + { + int min = UiMetrics.Px(2); + int top = Math.Max(min, vertical - extra / 2); + int bottom = Math.Max(min, vertical - (extra - extra / 2)); + _btnCompare.Padding = new Padding(side, top, side, bottom); + } + if (_btnCompare.Parent != null) + _btnCompare.Parent.PerformLayout(); + } + static Control SideBox(string title, ComboBox connection, ComboBox table, int line) { PlaceField(connection); @@ -1428,17 +3074,28 @@ namespace DataCompare.App { Text = title, Dock = DockStyle.Fill, - Padding = new Padding(UiMetrics.Px(8), UiMetrics.Px(4), UiMetrics.Px(8), UiMetrics.Px(4)) + Padding = new Padding(UiMetrics.Px(8), UiMetrics.Px(2), UiMetrics.Px(8), UiMetrics.Px(2)) }; - var inner = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, RowCount = 2 }; - inner.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("连接", UiFont(), 16))); - inner.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); - inner.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); - inner.RowStyles.Add(new RowStyle(SizeType.Absolute, line)); + var inner = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = 4, + RowCount = 1, + Margin = new Padding(0) + }; + int connLabel = UiMetrics.Fit("连接", UiFont(), 8); + int tableLabel = UiMetrics.Fit("表", UiFont(), 18); + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, connLabel)); + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 42)); + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, tableLabel)); + inner.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 58)); + inner.RowStyles.Add(new RowStyle(SizeType.Absolute, Math.Max(line, UiMetrics.Px(28)))); + var tableCaption = FieldLabel("表"); + tableCaption.Padding = new Padding(UiMetrics.Px(10), 0, 0, 0); inner.Controls.Add(FieldLabel("连接"), 0, 0); inner.Controls.Add(connection, 1, 0); - inner.Controls.Add(FieldLabel("表"), 0, 1); - inner.Controls.Add(table, 1, 1); + inner.Controls.Add(tableCaption, 2, 0); + inner.Controls.Add(table, 3, 0); box.Controls.Add(inner); return box; } @@ -1523,6 +3180,37 @@ namespace DataCompare.App } } + sealed class RuleItem + { + public readonly TableMatchRule Rule; + + public RuleItem(TableMatchRule rule) + { + Rule = rule; + } + + public override string ToString() + { + return Rule.Name; + } + } + + sealed class RunItem + { + public readonly TableJob Job; + + public RunItem(TableJob job) + { + Job = job; + } + + public override string ToString() + { + var name = Job.LeftTable == null ? "表" : Job.LeftTable.Display; + return name + "(" + Job.StatusText + ")"; + } + } + sealed class ColumnPair { public IList Left; @@ -1535,6 +3223,107 @@ namespace DataCompare.App public List Right; } + sealed class FilterForm : Form + { + readonly TextBox _left = new TextBox(); + readonly TextBox _right = new TextBox(); + + public string LeftText { get { return _left.Text ?? ""; } } + public string RightText { get { return _right.Text ?? ""; } } + + public FilterForm(string left, string right) + { + AppIcon.Apply(this); + Text = "筛选条件"; + FormBorderStyle = FormBorderStyle.FixedDialog; + StartPosition = FormStartPosition.CenterParent; + MinimizeBox = false; + MaximizeBox = false; + ShowInTaskbar = false; + Font = UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + ClientSize = new Size(UiMetrics.Px(560), UiMetrics.Px(188)); + + _left.Text = left ?? ""; + _right.Text = right ?? ""; + int labelWidth = UiMetrics.Fit("右侧", Font, 16); + int row = Math.Max(_left.PreferredHeight, UiMetrics.Px(23)) + UiMetrics.Px(8); + var grid = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = 2, + RowCount = 4, + Padding = new Padding(UiMetrics.Px(14), UiMetrics.Px(12), UiMetrics.Px(14), UiMetrics.Px(8)) + }; + grid.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, labelWidth)); + grid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + grid.RowStyles.Add(new RowStyle(SizeType.Absolute, UiMetrics.Px(40))); + grid.RowStyles.Add(new RowStyle(SizeType.Absolute, row)); + grid.RowStyles.Add(new RowStyle(SizeType.Absolute, row)); + grid.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + var hint = new Label + { + Dock = DockStyle.Fill, + TextAlign = ContentAlignment.MiddleLeft, + ForeColor = Color.FromArgb(70, 80, 90), + Text = "不要写 WHERE,不要写分号。两侧可以不同。例如 status = 1 AND city = '上海'" + }; + int buttonGap = UiMetrics.Px(8); + var pad = new Padding(UiMetrics.Px(12), UiMetrics.Px(3), UiMetrics.Px(12), UiMetrics.Px(3)); + var ok = new Button + { + Text = "确定", + Font = Font, + DialogResult = DialogResult.OK, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + Padding = pad, + Margin = Padding.Empty + }; + var cancel = new Button + { + Text = "取消", + Font = Font, + DialogResult = DialogResult.Cancel, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + Padding = pad, + Margin = Padding.Empty, + UseVisualStyleBackColor = true + }; + StylePrimary(ok); + int buttonWidth = Math.Max(ok.GetPreferredSize(Size.Empty).Width, cancel.GetPreferredSize(Size.Empty).Width); + int buttonHeight = Math.Max(ok.GetPreferredSize(Size.Empty).Height, cancel.GetPreferredSize(Size.Empty).Height); + ok.AutoSize = false; + cancel.AutoSize = false; + ok.Size = new Size(buttonWidth, buttonHeight); + cancel.Size = new Size(buttonWidth, buttonHeight); + var buttons = new Panel { Dock = DockStyle.Fill, Margin = Padding.Empty }; + buttons.Controls.Add(ok); + buttons.Controls.Add(cancel); + buttons.Resize += delegate + { + int y = Math.Max(0, (buttons.ClientSize.Height - buttonHeight) / 2); + int right = buttons.ClientSize.Width; + ok.SetBounds(right - buttonWidth, y, buttonWidth, buttonHeight); + cancel.SetBounds(right - buttonWidth - buttonGap - buttonWidth, y, buttonWidth, buttonHeight); + }; + PlaceField(_left); + PlaceField(_right); + grid.Controls.Add(hint, 0, 0); + grid.SetColumnSpan(hint, 2); + grid.Controls.Add(FieldLabel("左侧"), 0, 1); + grid.Controls.Add(_left, 1, 1); + grid.Controls.Add(FieldLabel("右侧"), 0, 2); + grid.Controls.Add(_right, 1, 2); + grid.Controls.Add(buttons, 1, 3); + Controls.Add(grid); + AcceptButton = ok; + CancelButton = cancel; + } + } + sealed class CompareRequest { public ConnectionProfile LeftProfile; diff --git a/src/DataCompare.App/MatchRuleStore.cs b/src/DataCompare.App/MatchRuleStore.cs new file mode 100644 index 0000000..fd96581 --- /dev/null +++ b/src/DataCompare.App/MatchRuleStore.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; +using DataCompare.Core; + +namespace DataCompare.App +{ + sealed class RuleFile + { + public int Version { get; set; } + public List Rules { get; set; } + } + + sealed class RuleDto + { + public string Id { get; set; } + public string Name { get; set; } + public bool IgnoreCase { get; set; } + public bool StripSchemaPrefix { get; set; } + public string Separator { get; set; } + public bool NameOnly { get; set; } + } + + static class MatchRuleStore + { + static readonly JsonSerializerOptions StoreJson = new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + WriteIndented = true + }; + + public static string FilePath + { + get + { + return Path.Combine( + Path.GetDirectoryName(ConnectionStore.FilePath), + "table-rules.json"); + } + } + + public static List Load() + { + var list = new List(); + if (!File.Exists(FilePath)) + return list; + RuleFile file; + try + { + var json = File.ReadAllText(FilePath, Encoding.UTF8); + file = JsonSerializer.Deserialize(json, StoreJson); + } + catch (Exception) + { + return list; + } + if (file == null || file.Rules == null) + return list; + for (int i = 0; i < file.Rules.Count; i++) + { + var dto = file.Rules[i]; + if (dto == null || string.IsNullOrWhiteSpace(dto.Name)) + continue; + var rule = new TableMatchRule + { + Id = string.IsNullOrWhiteSpace(dto.Id) ? Guid.NewGuid().ToString("D") : dto.Id.Trim(), + Name = dto.Name.Trim(), + IgnoreCase = dto.IgnoreCase, + StripSchemaPrefix = dto.StripSchemaPrefix, + Separator = string.IsNullOrEmpty(dto.Separator) ? "_" : dto.Separator, + NameOnly = dto.NameOnly + }; + if (rule.IsBuiltIn) + continue; + list.Add(rule); + } + return list; + } + + public static void Save(IList rules) + { + var dtos = new List(); + if (rules != null) + { + for (int i = 0; i < rules.Count; i++) + { + var rule = rules[i]; + if (rule == null || rule.IsBuiltIn || string.IsNullOrWhiteSpace(rule.Name)) + continue; + dtos.Add(new RuleDto + { + Id = string.IsNullOrWhiteSpace(rule.Id) ? Guid.NewGuid().ToString("D") : rule.Id, + Name = rule.Name.Trim(), + IgnoreCase = rule.IgnoreCase, + StripSchemaPrefix = rule.StripSchemaPrefix, + Separator = string.IsNullOrEmpty(rule.Separator) ? "_" : rule.Separator, + NameOnly = rule.NameOnly + }); + } + } + var json = JsonSerializer.Serialize(new RuleFile + { + Version = 1, + Rules = 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); + } + } +} diff --git a/src/DataCompare.App/PreviewForm.cs b/src/DataCompare.App/PreviewForm.cs index 28bf625..58cff9a 100644 --- a/src/DataCompare.App/PreviewForm.cs +++ b/src/DataCompare.App/PreviewForm.cs @@ -19,8 +19,10 @@ namespace DataCompare.App Text = "预览前 100 行"; StartPosition = FormStartPosition.CenterParent; Font = MainForm.UiFont(); - ClientSize = new Size(1100, 640); - MinimumSize = new Size(800, 480); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + ClientSize = new Size(UiMetrics.Px(960), UiMetrics.Px(640)); + MinimumSize = new Size(UiMetrics.Px(720), UiMetrics.Px(480)); var split = new SplitContainer { @@ -33,19 +35,53 @@ namespace DataCompare.App Controls.Add(split); Load += delegate { + FitToOwner(); split.SplitterDistance = Math.Max(200, split.Width / 2); }; } + void FitToOwner() + { + var owner = Owner; + if (owner == null || owner.Width < 200 || owner.Height < 200) + return; + int width = (int)Math.Round(owner.Width * 0.92); + int height = (int)Math.Round(owner.Height * 0.92); + int minW = MinimumSize.Width; + int minH = MinimumSize.Height; + if (width < minW) + width = Math.Min(owner.Width - UiMetrics.Px(24), minW); + if (height < minH) + height = Math.Min(owner.Height - UiMetrics.Px(24), minH); + if (width > owner.Width - UiMetrics.Px(16)) + width = owner.Width - UiMetrics.Px(16); + if (height > owner.Height - UiMetrics.Px(16)) + height = owner.Height - UiMetrics.Px(16); + Size = new Size(width, height); + var area = Screen.FromControl(owner).WorkingArea; + int x = owner.Left + (owner.Width - Width) / 2; + int y = owner.Top + (owner.Height - Height) / 2; + if (x < area.Left) + x = area.Left; + if (y < area.Top) + y = area.Top; + if (x + Width > area.Right) + x = Math.Max(area.Left, area.Right - Width); + if (y + Height > area.Bottom) + y = Math.Max(area.Top, area.Bottom - Height); + Location = new Point(x, y); + } + static Control Build(string title, IList columns, IList rows) { var root = new Panel { Dock = DockStyle.Fill }; var header = new Label { Dock = DockStyle.Top, - Height = 28, + Height = UiMetrics.Px(36), TextAlign = ContentAlignment.MiddleLeft, - Padding = new Padding(8, 0, 0, 0), + AutoEllipsis = true, + Padding = new Padding(UiMetrics.Px(8), 0, UiMetrics.Px(8), 0), Text = title + " " + (rows == null ? 0 : rows.Count) + " 行" }; var grid = new DataGridView @@ -60,10 +96,15 @@ namespace DataCompare.App BackgroundColor = Color.White, BorderStyle = BorderStyle.None, Font = MainForm.UiFont(), - AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None, + EnableHeadersVisualStyles = false }; - grid.ColumnHeadersHeight = 28; - grid.RowTemplate.Height = 24; + int headerText = TextRenderer.MeasureText("字段Ag", grid.Font).Height; + grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + grid.ColumnHeadersHeight = headerText + UiMetrics.Px(16); + grid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft; + grid.ColumnHeadersDefaultCellStyle.Padding = new Padding(UiMetrics.Px(4), UiMetrics.Px(2), UiMetrics.Px(4), UiMetrics.Px(2)); + grid.RowTemplate.Height = headerText + UiMetrics.Px(10); if (columns != null) { for (int i = 0; i < columns.Count; i++) diff --git a/src/DataCompare.App/RuleForms.cs b/src/DataCompare.App/RuleForms.cs new file mode 100644 index 0000000..475afb3 --- /dev/null +++ b/src/DataCompare.App/RuleForms.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using DataCompare.Core; + +namespace DataCompare.App +{ + sealed class RuleListForm : Form + { + readonly DataGridView _grid; + readonly List _rules; + + public RuleListForm() + { + AppIcon.Apply(this); + Text = "表名规则"; + FormBorderStyle = FormBorderStyle.FixedDialog; + StartPosition = FormStartPosition.CenterParent; + MinimizeBox = false; + MaximizeBox = false; + ShowInTaskbar = false; + Font = MainForm.UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + ClientSize = new Size(UiMetrics.Px(560), UiMetrics.Px(420)); + + var note = new Label + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(48), + Text = "内置规则「同名」「模式前缀」始终可用。这里只管理自定义规则。" + }; + _grid = new DataGridView + { + Dock = DockStyle.Fill, + ReadOnly = true, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, + RowHeadersVisible = false, + MultiSelect = false, + SelectionMode = DataGridViewSelectionMode.FullRowSelect, + BackgroundColor = Color.White, + BorderStyle = BorderStyle.None, + AutoGenerateColumns = false, + Font = Font + }; + _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "Name", HeaderText = "名称", Width = UiMetrics.Px(140) }); + _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "How", HeaderText = "对齐方式", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill }); + _grid.CellDoubleClick += delegate + { + if (_grid.CurrentRow != null && _grid.CurrentRow.Index >= 0) + EditCurrent(); + }; + + int buttonHeight = TextRenderer.MeasureText("新建", Font).Height + UiMetrics.Px(16); + var bar = new Panel + { + Dock = DockStyle.Bottom, + Height = UiMetrics.Px(8) + buttonHeight + UiMetrics.Px(12), + Padding = new Padding(0, UiMetrics.Px(8), 0, UiMetrics.Px(12)) + }; + var actions = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Margin = Padding.Empty, + Padding = Padding.Empty + }; + actions.Controls.Add(Button("新建", delegate { AddRule(); })); + actions.Controls.Add(Button("编辑", delegate { EditCurrent(); })); + actions.Controls.Add(Button("删除", delegate { DeleteCurrent(); })); + actions.Controls.Add(Button("关闭", delegate { Close(); })); + bar.Controls.Add(actions); + + Controls.Add(_grid); + Controls.Add(bar); + Controls.Add(note); + + _rules = MatchRuleStore.Load(); + Fill(); + } + + void AddRule() + { + using (var form = new RuleEditForm(null, _rules)) + { + if (form.ShowDialog(this) != DialogResult.OK || form.Rule == null) + return; + _rules.Add(form.Rule); + MatchRuleStore.Save(_rules); + Fill(); + } + } + + void EditCurrent() + { + var rule = Selected(); + if (rule == null) + { + MessageBox.Show(this, "请先选择一条自定义规则。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + using (var form = new RuleEditForm(rule, _rules)) + { + if (form.ShowDialog(this) != DialogResult.OK || form.Rule == null) + return; + rule.Name = form.Rule.Name; + rule.IgnoreCase = form.Rule.IgnoreCase; + rule.StripSchemaPrefix = form.Rule.StripSchemaPrefix; + rule.Separator = form.Rule.Separator; + rule.NameOnly = form.Rule.NameOnly; + MatchRuleStore.Save(_rules); + Fill(); + } + } + + void DeleteCurrent() + { + var rule = Selected(); + if (rule == null) + { + MessageBox.Show(this, "请先选择一条自定义规则。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + if (MessageBox.Show(this, "删除规则「" + rule.Name + "」?", "表名规则", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) + return; + _rules.Remove(rule); + MatchRuleStore.Save(_rules); + Fill(); + } + + TableMatchRule Selected() + { + if (_grid.CurrentRow == null) + return null; + return _grid.CurrentRow.Tag as TableMatchRule; + } + + void Fill() + { + _grid.Rows.Clear(); + for (int i = 0; i < _rules.Count; i++) + { + var rule = _rules[i]; + int index = _grid.Rows.Add(rule.Name, Describe(rule)); + _grid.Rows[index].Tag = rule; + } + } + + static string Describe(TableMatchRule rule) + { + var text = rule.IgnoreCase ? "忽略大小写" : "区分大小写"; + if (rule.NameOnly) + text += ",只比表名"; + else + text += ",模式加表名"; + if (rule.StripSchemaPrefix) + text += ",去掉前缀 " + (string.IsNullOrEmpty(rule.Separator) ? "_" : rule.Separator); + return text; + } + + static Button Button(string text, EventHandler click) + { + var button = new Button + { + Text = text, + AutoSize = true, + Padding = new Padding(UiMetrics.Px(12), UiMetrics.Px(3), UiMetrics.Px(12), UiMetrics.Px(3)), + Margin = new Padding(0, 0, UiMetrics.Px(8), 0) + }; + button.Click += click; + return button; + } + } + + sealed class RuleEditForm : Form + { + readonly TextBox _name = new TextBox(); + readonly CheckBox _ignoreCase = new CheckBox(); + readonly CheckBox _strip = new CheckBox(); + readonly TextBox _separator = new TextBox(); + readonly CheckBox _nameOnly = new CheckBox(); + readonly List _others; + readonly string _id; + + public TableMatchRule Rule { get; private set; } + + public RuleEditForm(TableMatchRule existing, List others) + { + AppIcon.Apply(this); + _others = others ?? new List(); + _id = existing == null || string.IsNullOrWhiteSpace(existing.Id) ? Guid.NewGuid().ToString("D") : existing.Id; + Text = existing == null ? "新建规则" : "编辑规则"; + FormBorderStyle = FormBorderStyle.FixedDialog; + StartPosition = FormStartPosition.CenterParent; + MinimizeBox = false; + MaximizeBox = false; + ShowInTaskbar = false; + Font = MainForm.UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + ClientSize = new Size(UiMetrics.Px(420), UiMetrics.Px(230)); + + _name.Text = existing == null ? "" : existing.Name; + _ignoreCase.Text = "忽略大小写"; + _ignoreCase.Checked = existing == null || existing.IgnoreCase; + _strip.Text = "去掉模式前缀"; + _strip.Checked = existing == null || existing.StripSchemaPrefix; + _separator.Text = existing == null || string.IsNullOrEmpty(existing.Separator) ? "_" : existing.Separator; + _nameOnly.Text = "只比表名"; + _nameOnly.Checked = existing != null && existing.NameOnly; + _ignoreCase.AutoSize = true; + _strip.AutoSize = true; + _nameOnly.AutoSize = true; + + var layout = new TableLayoutPanel + { + Dock = DockStyle.Top, + Height = UiMetrics.Px(168), + ColumnCount = 2, + RowCount = 4, + Padding = new Padding(UiMetrics.Px(8)) + }; + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("去掉模式前缀", Font, 16))); + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + for (int i = 0; i < 4; i++) + layout.RowStyles.Add(new RowStyle(SizeType.Absolute, UiMetrics.Px(36))); + layout.Controls.Add(LabelOf("名称"), 0, 0); + layout.Controls.Add(_name, 1, 0); + layout.Controls.Add(_ignoreCase, 1, 1); + layout.Controls.Add(_strip, 0, 2); + layout.Controls.Add(_separator, 1, 2); + layout.Controls.Add(_nameOnly, 1, 3); + _name.Dock = DockStyle.Fill; + _separator.Dock = DockStyle.Left; + _separator.Width = UiMetrics.Px(80); + + var bar = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + FlowDirection = FlowDirection.RightToLeft, + Height = UiMetrics.Px(44), + Padding = new Padding(UiMetrics.Px(8)) + }; + var cancel = new Button { Text = "取消", DialogResult = DialogResult.Cancel, AutoSize = true }; + var ok = new Button { Text = "确定", AutoSize = true }; + ok.Click += delegate { SaveRule(); }; + bar.Controls.Add(cancel); + bar.Controls.Add(ok); + AcceptButton = ok; + CancelButton = cancel; + Controls.Add(layout); + Controls.Add(bar); + } + + void SaveRule() + { + var name = (_name.Text ?? "").Trim(); + if (name.Length == 0) + { + MessageBox.Show(this, "请填写规则名称。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + if (string.Equals(name, "同名", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "模式前缀", StringComparison.OrdinalIgnoreCase)) + { + MessageBox.Show(this, "这个名称留给内置规则。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + for (int i = 0; i < _others.Count; i++) + { + if (string.Equals(_others[i].Id, _id, StringComparison.OrdinalIgnoreCase)) + continue; + if (string.Equals(_others[i].Name, name, StringComparison.OrdinalIgnoreCase)) + { + MessageBox.Show(this, "已有同名规则。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + } + var separator = _separator.Text ?? ""; + if (_strip.Checked && separator.Trim().Length == 0) + { + MessageBox.Show(this, "去掉前缀时要填写分隔符。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + if (separator.Length > 8) + { + MessageBox.Show(this, "分隔符不要超过 8 个字符。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + for (int i = 0; i < separator.Length; i++) + { + if (separator[i] < ' ') + { + MessageBox.Show(this, "分隔符里不能有换行或控制字符。", "表名规则", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + } + Rule = new TableMatchRule + { + Id = _id, + Name = name, + IgnoreCase = _ignoreCase.Checked, + StripSchemaPrefix = _strip.Checked, + Separator = separator.Length == 0 ? "_" : separator, + NameOnly = _nameOnly.Checked + }; + DialogResult = DialogResult.OK; + Close(); + } + + static Label LabelOf(string text) + { + return new Label + { + Text = text, + AutoSize = true, + Anchor = AnchorStyles.Left + }; + } + } +} diff --git a/src/DataCompare.App/TableCombo.cs b/src/DataCompare.App/TableCombo.cs index 7b8b326..22d2e43 100644 --- a/src/DataCompare.App/TableCombo.cs +++ b/src/DataCompare.App/TableCombo.cs @@ -34,6 +34,26 @@ namespace DataCompare.App get { return SelectedItem as TableRef; } } + public IList Tables + { + get { return new List(_all); } + } + + public bool SelectTable(TableRef table) + { + if (table == null) + return false; + for (int i = 0; i < _all.Count; i++) + { + if (Same(_all[i], table)) + { + Fill(_all, _all[i], false); + return true; + } + } + return false; + } + public void SetTables(IList tables) { _all.Clear(); diff --git a/src/DataCompare.App/TableJob.cs b/src/DataCompare.App/TableJob.cs new file mode 100644 index 0000000..e6f29c1 --- /dev/null +++ b/src/DataCompare.App/TableJob.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using DataCompare.Core; + +namespace DataCompare.App +{ + enum TableJobStatus + { + Pending = 0, + MissingKey = 1, + Done = 2, + Failed = 3, + Canceled = 4 + } + + sealed class TableJob + { + public TableRef LeftTable; + public TableRef RightTable; + public string LeftFilter; + public string RightFilter; + public List Mappings; + public List LeftColumns; + public List RightColumns; + public TableJobStatus Status; + public string Error; + public CompareResult Result; + + public bool CanRun + { + get { return Status != TableJobStatus.MissingKey && ColumnMapper.HasKey(Mappings); } + } + + public string StatusText + { + get + { + switch (Status) + { + case TableJobStatus.Pending: return "待对比"; + case TableJobStatus.MissingKey: return "缺键"; + case TableJobStatus.Done: return "完成"; + case TableJobStatus.Failed: return "失败"; + case TableJobStatus.Canceled: return "已取消"; + default: return ""; + } + } + } + + public string Note + { + get + { + if (Status == TableJobStatus.Done && Result != null) + { + return "仅左 " + Result.LeftOnlyCount + + " 仅右 " + Result.RightOnlyCount + + " 不同 " + Result.DifferentCount; + } + return Error ?? ""; + } + } + } +} diff --git a/src/DataCompare.App/TablePickForm.cs b/src/DataCompare.App/TablePickForm.cs new file mode 100644 index 0000000..0e3f8f6 --- /dev/null +++ b/src/DataCompare.App/TablePickForm.cs @@ -0,0 +1,464 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; +using DataCompare.Core; + +namespace DataCompare.App +{ + sealed class TablePickForm : Form + { + readonly IList _left; + readonly IList _right; + readonly TableMatchRule _rule; + readonly DataGridView _grid; + readonly TextBox _search = new TextBox(); + readonly TextBox _keys = new TextBox(); + readonly RadioButton _fromLeft = new RadioButton(); + readonly RadioButton _fromRight = new RadioButton(); + readonly CheckBox _onlyMatched = new CheckBox(); + readonly Label _count = new Label(); + readonly Label _hint = new Label(); + readonly HashSet _checked = new HashSet(StringComparer.OrdinalIgnoreCase); + int _matched; + int _hidden; + int _shown; + bool _filling; + + public List PickedLeft { get; private set; } + public List PickedRight { get; private set; } + + public string KeyText + { + get { return _keys.Text ?? ""; } + } + + public TablePickForm(IList left, IList right, TableMatchRule rule) + { + AppIcon.Apply(this); + _left = left ?? new List(); + _right = right ?? new List(); + _rule = rule ?? TableMatchRule.SchemaPrefix(); + Text = "选择多张表"; + StartPosition = FormStartPosition.CenterParent; + MinimizeBox = false; + ShowInTaskbar = false; + Font = MainForm.UiFont(); + AutoScaleMode = AutoScaleMode.None; + UiMetrics.Bind(this); + ClientSize = new Size(UiMetrics.Px(860), UiMetrics.Px(560)); + MinimumSize = new Size(UiMetrics.Px(720), UiMetrics.Px(480)); + Padding = new Padding(UiMetrics.Px(12), UiMetrics.Px(10), UiMetrics.Px(12), UiMetrics.Px(12)); + + var ruleName = string.IsNullOrWhiteSpace(_rule.Name) ? "模式前缀" : _rule.Name; + int row = UiMetrics.Px(36); + var header = new TableLayoutPanel + { + Dock = DockStyle.Top, + Height = row * 3 + UiMetrics.Px(8), + ColumnCount = 2, + RowCount = 3, + Padding = new Padding(0, 0, 0, UiMetrics.Px(8)), + Margin = new Padding(0) + }; + header.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, UiMetrics.Fit("键列", Font, 16))); + header.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + header.RowStyles.Add(new RowStyle(SizeType.Absolute, row)); + header.RowStyles.Add(new RowStyle(SizeType.Absolute, row)); + header.RowStyles.Add(new RowStyle(SizeType.Absolute, row)); + + _fromLeft.Text = "从左侧选"; + _fromRight.Text = "从右侧选"; + _fromLeft.Checked = true; + _fromLeft.AutoSize = true; + _fromRight.AutoSize = true; + _fromLeft.Margin = new Padding(0, 0, UiMetrics.Px(16), 0); + _fromRight.Margin = new Padding(0, 0, UiMetrics.Px(20), 0); + var ruleLabel = new Label + { + Text = "规则:" + ruleName, + AutoSize = true, + Margin = new Padding(0) + }; + var side = CenterLine(_fromLeft, _fromRight, ruleLabel); + _fromLeft.CheckedChanged += delegate { if (_fromLeft.Checked) Rebuild(); }; + _fromRight.CheckedChanged += delegate { if (_fromRight.Checked) Rebuild(); }; + + _onlyMatched.Text = "只显示已匹配"; + _onlyMatched.Checked = true; + _onlyMatched.AutoSize = true; + _onlyMatched.Margin = new Padding(UiMetrics.Px(12), 0, 0, 0); + _onlyMatched.CheckedChanged += delegate { Rebuild(); }; + _search.Margin = new Padding(0, 0, 0, 0); + _search.Anchor = AnchorStyles.Left | AnchorStyles.Right; + var filterLine = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = 2, + RowCount = 1, + Margin = new Padding(0), + Padding = new Padding(0) + }; + filterLine.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + filterLine.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + filterLine.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + filterLine.Controls.Add(_search, 0, 0); + filterLine.Controls.Add(_onlyMatched, 1, 0); + _onlyMatched.Anchor = AnchorStyles.Left; + + _keys.Width = UiMetrics.Px(220); + _keys.Text = "Id"; + _keys.Margin = new Padding(0, 0, UiMetrics.Px(12), 0); + var keyHint = new Label + { + Text = "可留空。没有 Id 时,自动改用唯一的 TrustId 这类列", + AutoSize = true, + Margin = new Padding(0) + }; + var keyLine = CenterLine(_keys, keyHint); + + header.Controls.Add(LabelOf("来源"), 0, 0); + header.Controls.Add(side, 1, 0); + header.Controls.Add(LabelOf("筛选"), 0, 1); + header.Controls.Add(filterLine, 1, 1); + header.Controls.Add(LabelOf("键列"), 0, 2); + header.Controls.Add(keyLine, 1, 2); + _search.TextChanged += delegate { Rebuild(); }; + + _grid = new DataGridView + { + Dock = DockStyle.Fill, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + AllowUserToResizeRows = false, + RowHeadersVisible = false, + MultiSelect = false, + SelectionMode = DataGridViewSelectionMode.FullRowSelect, + BackgroundColor = Color.White, + BorderStyle = BorderStyle.None, + AutoGenerateColumns = false, + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, + Font = Font + }; + _grid.Columns.Add(new DataGridViewCheckBoxColumn + { + Name = "Pick", + HeaderText = "选", + FillWeight = 28, + MinimumWidth = 42 + }); + _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "Source", HeaderText = "本侧表", FillWeight = 160, ReadOnly = true }); + _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "Other", HeaderText = "对侧表", FillWeight = 160, ReadOnly = true }); + _grid.Columns.Add(new DataGridViewTextBoxColumn { Name = "State", HeaderText = "状态", FillWeight = 70, ReadOnly = true }); + _grid.CurrentCellDirtyStateChanged += delegate + { + if (_grid.IsCurrentCellDirty) + _grid.CommitEdit(DataGridViewDataErrorContexts.Commit); + }; + _grid.CellValueChanged += OnCheckChanged; + _grid.CellFormatting += ColorRow; + _grid.DataError += delegate { }; + + _hint.Dock = DockStyle.Top; + _hint.Height = UiMetrics.Px(26); + _hint.TextAlign = ContentAlignment.MiddleLeft; + _hint.ForeColor = Color.FromArgb(40, 70, 110); + _hint.Text = "勾选要加入批次的表,或点「全选已匹配」。对不上的表已隐藏。"; + + _count.Dock = DockStyle.Bottom; + _count.Height = UiMetrics.Px(24); + _count.TextAlign = ContentAlignment.MiddleLeft; + + var bar = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + AutoSize = true, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Padding = new Padding(0, UiMetrics.Px(10), 0, 0), + Margin = new Padding(0) + }; + var ok = DialogButton("确定", delegate { AcceptPick(); }, true); + var cancel = DialogButton("取消", delegate { DialogResult = DialogResult.Cancel; Close(); }, false); + bar.Controls.Add(DialogButton("全选已匹配", delegate { CheckMatched(); }, false)); + bar.Controls.Add(ok); + bar.Controls.Add(cancel); + Shown += delegate { MatchButtonHeight(ok, cancel); }; + + Controls.Add(_grid); + Controls.Add(_count); + Controls.Add(bar); + Controls.Add(_hint); + Controls.Add(header); + Rebuild(); + } + + void Rebuild() + { + var source = _fromLeft.Checked ? _left : _right; + var other = _fromLeft.Checked ? _right : _left; + var tokens = Tokens(_search.Text); + _filling = true; + _grid.Rows.Clear(); + int matched = 0; + int hidden = 0; + int shown = 0; + for (int i = 0; i < source.Count; i++) + { + var table = source[i]; + if (table == null || !Hit(table.Display, tokens)) + continue; + var matches = TableMatcher.Match(table, other, _rule); + string otherText; + string state; + bool canCheck; + if (matches.Count == 1) + { + otherText = matches[0].Display; + state = "已匹配"; + canCheck = true; + matched++; + } + else if (matches.Count == 0) + { + otherText = ""; + state = "未找到"; + canCheck = false; + } + else + { + otherText = matches[0].Display + " 等 " + matches.Count + " 张"; + state = "多个"; + canCheck = false; + } + if (_onlyMatched.Checked && !canCheck) + { + hidden++; + continue; + } + int index = _grid.Rows.Add(_checked.Contains(Identity(table)) && canCheck, table.Display, otherText, state); + var row = _grid.Rows[index]; + row.Tag = new PickPair + { + Source = table, + CanCheck = canCheck + }; + row.Cells["Pick"].ReadOnly = !canCheck; + shown++; + } + _matched = matched; + _hidden = hidden; + _shown = shown; + _filling = false; + PublishCount(matched, hidden, shown); + } + + void PublishCount(int matched, int hidden, int shown) + { + var text = "已匹配 " + matched + " 张"; + if (hidden > 0) + text += ",已隐藏 " + hidden + " 张对不上的"; + text += "。当前显示 " + shown + " 张,已勾选 " + _checked.Count + " 张"; + _count.Text = text; + } + + void ColorRow(object sender, DataGridViewCellFormattingEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0) + return; + var pair = _grid.Rows[e.RowIndex].Tag as PickPair; + if (pair == null || pair.CanCheck) + return; + e.CellStyle.ForeColor = Color.FromArgb(140, 140, 140); + e.CellStyle.SelectionForeColor = Color.FromArgb(80, 80, 80); + } + + void OnCheckChanged(object sender, DataGridViewCellEventArgs e) + { + if (_filling || e.RowIndex < 0 || _grid.Columns[e.ColumnIndex].Name != "Pick") + return; + var row = _grid.Rows[e.RowIndex]; + var pair = row.Tag as PickPair; + if (pair == null) + return; + bool check = row.Cells["Pick"].Value is bool && (bool)row.Cells["Pick"].Value; + if (check && !pair.CanCheck) + { + _filling = true; + row.Cells["Pick"].Value = false; + _filling = false; + return; + } + var id = Identity(pair.Source); + if (check) + _checked.Add(id); + else + _checked.Remove(id); + PublishCount(_matched, _hidden, _shown); + } + + void CheckMatched() + { + _filling = true; + foreach (DataGridViewRow row in _grid.Rows) + { + var pair = row.Tag as PickPair; + if (pair == null || !pair.CanCheck) + continue; + row.Cells["Pick"].Value = true; + _checked.Add(Identity(pair.Source)); + } + _filling = false; + Rebuild(); + } + + void AcceptPick() + { + var left = new List(); + var right = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + Collect(_left, _right, true, left, right, seen); + Collect(_right, _left, false, left, right, seen); + if (left.Count == 0) + { + MessageBox.Show(this, "请勾选要加入批次的表。列表里默认只显示能对上的表。", "选择多张表", MessageBoxButtons.OK, MessageBoxIcon.Information); + return; + } + PickedLeft = left; + PickedRight = right; + DialogResult = DialogResult.OK; + Close(); + } + + void Collect(IList source, IList other, bool fromLeft, List left, List right, HashSet seen) + { + for (int i = 0; i < source.Count; i++) + { + var table = source[i]; + if (table == null || !_checked.Contains(Identity(table))) + continue; + var matches = TableMatcher.Match(table, other, _rule); + if (matches.Count != 1) + continue; + TableRef leftTable = fromLeft ? table : matches[0]; + TableRef rightTable = fromLeft ? matches[0] : table; + var key = Identity(leftTable) + "|" + Identity(rightTable); + if (!seen.Add(key)) + continue; + left.Add(leftTable); + right.Add(rightTable); + } + } + + static string Identity(TableRef table) + { + return (table.Catalog ?? "") + "\0" + (table.Schema ?? "") + "\0" + (table.Name ?? ""); + } + + static List Tokens(string text) + { + var tokens = new List(); + if (string.IsNullOrWhiteSpace(text)) + return tokens; + var parts = text.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < parts.Length; i++) + tokens.Add(parts[i]); + return tokens; + } + + static bool Hit(string display, List tokens) + { + if (tokens.Count == 0) + return true; + display = display ?? ""; + for (int i = 0; i < tokens.Count; i++) + { + if (display.IndexOf(tokens[i], StringComparison.OrdinalIgnoreCase) < 0) + return false; + } + return true; + } + + static Label LabelOf(string text) + { + return new Label + { + Text = text, + AutoSize = true, + Anchor = AnchorStyles.Left, + Margin = new Padding(0) + }; + } + + static TableLayoutPanel CenterLine(params Control[] controls) + { + var row = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = controls.Length, + RowCount = 1, + Margin = new Padding(0), + Padding = new Padding(0) + }; + row.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); + for (int i = 0; i < controls.Length; i++) + { + var control = controls[i]; + control.Anchor = AnchorStyles.Left; + row.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); + row.Controls.Add(control, i, 0); + } + return row; + } + + static Button DialogButton(string text, EventHandler click, bool primary) + { + var button = new Button + { + Text = text, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + Padding = new Padding(UiMetrics.Px(12), UiMetrics.Px(3), UiMetrics.Px(12), UiMetrics.Px(3)), + Margin = new Padding(0, 0, UiMetrics.Px(8), 0), + UseVisualStyleBackColor = !primary + }; + if (primary) + { + button.FlatStyle = FlatStyle.Flat; + button.BackColor = Color.FromArgb(37, 99, 168); + button.ForeColor = Color.White; + button.FlatAppearance.BorderSize = 0; + } + button.Click += click; + return button; + } + + static void MatchButtonHeight(Button primary, Button sample) + { + int side = UiMetrics.Px(16); + int vertical = UiMetrics.Px(4); + primary.AutoSize = true; + primary.AutoSizeMode = AutoSizeMode.GrowAndShrink; + primary.Padding = new Padding(side, vertical, side, vertical); + int flat = primary.GetPreferredSize(Size.Empty).Height; + int other = sample.GetPreferredSize(Size.Empty).Height; + int extra = flat - other; + if (extra > 0) + { + int min = UiMetrics.Px(2); + int top = Math.Max(min, vertical - extra / 2); + int bottom = Math.Max(min, vertical - (extra - extra / 2)); + primary.Padding = new Padding(side, top, side, bottom); + } + primary.Margin = new Padding(0, 0, UiMetrics.Px(8), 0); + if (primary.Parent != null) + primary.Parent.PerformLayout(); + } + + sealed class PickPair + { + public TableRef Source; + public bool CanCheck; + } + } +} diff --git a/src/DataCompare.Core/ColumnMapper.cs b/src/DataCompare.Core/ColumnMapper.cs new file mode 100644 index 0000000..c5512b4 --- /dev/null +++ b/src/DataCompare.Core/ColumnMapper.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; + +namespace DataCompare.Core +{ + public static class ColumnMapper + { + public static List ByName( + IList left, + IList right, + IList keys, + out string missingKeys) + { + var mappings = new List(); + var missing = new List(); + var keyNames = keys ?? new string[0]; + if (left != null) + { + for (int i = 0; i < left.Count; i++) + { + var leftColumn = left[i]; + if (leftColumn == null || string.IsNullOrWhiteSpace(leftColumn.Name)) + continue; + var rightColumn = Find(right, leftColumn.Name); + if (rightColumn == null) + continue; + mappings.Add(new ColumnMapping + { + LeftColumn = leftColumn.Name, + RightColumn = rightColumn.Name, + IsKey = Contains(keyNames, leftColumn.Name), + Compare = true + }); + } + } + for (int i = 0; i < keyNames.Count; i++) + { + var key = (keyNames[i] ?? "").Trim(); + if (key.Length == 0 || Listed(missing, key)) + continue; + if (Find(left, key) == null || Find(right, key) == null) + missing.Add(key); + } + missingKeys = missing.Count == 0 ? "" : "缺少键列:" + string.Join(",", missing); + return mappings; + } + + public static string GuessKey(IList mappings) + { + if (mappings == null) + return null; + string exact = null; + string suffix = null; + int suffixCount = 0; + for (int i = 0; i < mappings.Count; i++) + { + var name = mappings[i] == null ? null : mappings[i].LeftColumn; + if (string.IsNullOrWhiteSpace(name)) + continue; + if (string.Equals(name, "id", StringComparison.OrdinalIgnoreCase)) + { + if (exact == null) + exact = name; + continue; + } + if (name.Length > 2 && name.EndsWith("id", StringComparison.OrdinalIgnoreCase)) + { + suffixCount++; + suffix = name; + } + } + if (exact != null) + return exact; + if (suffixCount == 1) + return suffix; + return null; + } + + public static string KeyHint(IList mappings) + { + var names = new List(); + if (mappings != null) + { + for (int i = 0; i < mappings.Count; i++) + { + var name = mappings[i] == null ? null : mappings[i].LeftColumn; + if (string.IsNullOrWhiteSpace(name)) + continue; + if (string.Equals(name, "id", StringComparison.OrdinalIgnoreCase) + || (name.Length > 2 && name.EndsWith("id", StringComparison.OrdinalIgnoreCase))) + names.Add(name); + } + } + if (names.Count == 0) + return "请在字段表中勾选「键」。"; + if (names.Count == 1) + return "可勾选「" + names[0] + "」作为键。"; + return "可选键列:" + string.Join("、", names) + "。请勾选其中一个。"; + } + + public static void MarkKey(IList mappings, string leftName) + { + if (mappings == null || string.IsNullOrWhiteSpace(leftName)) + return; + for (int i = 0; i < mappings.Count; i++) + { + if (mappings[i] != null && string.Equals(mappings[i].LeftColumn, leftName, StringComparison.OrdinalIgnoreCase)) + mappings[i].IsKey = true; + } + } + + public static bool HasKey(IList mappings) + { + if (mappings == null) + return false; + for (int i = 0; i < mappings.Count; i++) + { + var mapping = mappings[i]; + if (mapping != null + && mapping.IsKey + && !string.IsNullOrWhiteSpace(mapping.LeftColumn) + && !string.IsNullOrWhiteSpace(mapping.RightColumn)) + return true; + } + return false; + } + + static ColumnInfo Find(IList columns, string name) + { + if (columns == null || string.IsNullOrWhiteSpace(name)) + return null; + for (int i = 0; i < columns.Count; i++) + { + if (columns[i] != null && string.Equals(columns[i].Name, name, StringComparison.OrdinalIgnoreCase)) + return columns[i]; + } + return null; + } + + static bool Contains(IList names, string name) + { + for (int i = 0; i < names.Count; i++) + { + if (string.Equals((names[i] ?? "").Trim(), name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + static bool Listed(List names, string name) + { + for (int i = 0; i < names.Count; i++) + { + if (string.Equals(names[i], name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + } +} diff --git a/src/DataCompare.Core/DiffWorkbook.cs b/src/DataCompare.Core/DiffWorkbook.cs new file mode 100644 index 0000000..e8990b9 --- /dev/null +++ b/src/DataCompare.Core/DiffWorkbook.cs @@ -0,0 +1,187 @@ +using System.Collections.Generic; + +namespace DataCompare.Core +{ + public sealed class ExportTable + { + public string SheetTitle { get; set; } + public string Label { get; set; } + public string Status { get; set; } + public string Note { get; set; } + public CompareResult Result { get; set; } + public bool Completed { get; set; } + } + + public sealed class XlsxSheet + { + public string Name; + public readonly List Rows = new List(); + } + + public static class DiffWorkbook + { + public const int MaxRows = 1048576; + + public static bool Include(RowDiff diff, int filter) + { + if (diff == null) + return false; + switch (filter) + { + case 1: return diff.Status == DiffStatus.LeftOnly; + case 2: return diff.Status == DiffStatus.RightOnly; + case 3: return diff.Status == DiffStatus.Different; + case 4: return diff.Status == DiffStatus.DuplicateKey || diff.Status == DiffStatus.InvalidKey; + default: return true; + } + } + + public static List Build(IList tables, int filter) + { + return Build(tables, filter, MaxRows); + } + + public static List Build(IList tables, int filter, int maxRows) + { + if (maxRows < 2) + maxRows = 2; + var sheets = new List(); + var used = new List(); + var summary = Begin(used, "汇总"); + summary.Rows.Add(new[] + { + "表", "状态", "左侧行数", "右侧行数", "相同", "仅左", "仅右", "内容不同", "键重复", "键无效", "说明" + }); + if (tables != null) + { + for (int i = 0; i < tables.Count; i++) + { + var table = tables[i]; + if (table == null) + continue; + if (summary.Rows.Count >= maxRows) + { + sheets.Add(summary); + summary = Begin(used, "汇总"); + summary.Rows.Add(new[] + { + "表", "状态", "左侧行数", "右侧行数", "相同", "仅左", "仅右", "内容不同", "键重复", "键无效", "说明" + }); + } + summary.Rows.Add(SummaryRow(table)); + } + } + sheets.Add(summary); + + if (tables != null) + { + for (int i = 0; i < tables.Count; i++) + { + var table = tables[i]; + if (table == null || !table.Completed || table.Result == null) + continue; + var sheet = Begin(used, table.SheetTitle); + sheet.Rows.Add(DiffHeader()); + var diffs = table.Result.Diffs; + if (diffs != null) + { + for (int d = 0; d < diffs.Length; d++) + { + if (!Include(diffs[d], filter)) + continue; + AddDiff(sheets, used, ref sheet, table.SheetTitle, diffs[d], maxRows); + } + } + sheets.Add(sheet); + } + } + return sheets; + } + + static void AddDiff( + List sheets, + List used, + ref XlsxSheet sheet, + string title, + RowDiff diff, + int maxRows) + { + if (diff.Cells == null || diff.Cells.Length == 0) + { + sheet = Room(sheets, used, sheet, title, maxRows); + sheet.Rows.Add(new[] + { + Text(diff.StatusText), Text(diff.KeyText), Text(diff.Summary), "", "", "", "" + }); + return; + } + for (int c = 0; c < diff.Cells.Length; c++) + { + var cell = diff.Cells[c]; + sheet = Room(sheets, used, sheet, title, maxRows); + if (cell == null) + { + sheet.Rows.Add(new[] + { + Text(diff.StatusText), Text(diff.KeyText), Text(diff.Summary), "", "", "", "" + }); + continue; + } + sheet.Rows.Add(new[] + { + Text(diff.StatusText), + Text(diff.KeyText), + Text(diff.Summary), + Text(cell.ColumnName), + Text(cell.LeftText), + Text(cell.RightText), + cell.IsDifferent ? "是" : "否" + }); + } + } + + static XlsxSheet Room(List sheets, List used, XlsxSheet sheet, string title, int maxRows) + { + if (sheet.Rows.Count < maxRows) + return sheet; + sheets.Add(sheet); + var next = Begin(used, title); + next.Rows.Add(DiffHeader()); + return next; + } + + static string[] DiffHeader() + { + return new[] { "状态", "键", "摘要", "列", "左侧", "右侧", "是否不同" }; + } + + static string[] SummaryRow(ExportTable table) + { + var result = table.Completed ? table.Result : null; + return new[] + { + Text(table.Label), + Text(table.Status), + result == null ? "" : result.LeftRowCount.ToString(), + result == null ? "" : result.RightRowCount.ToString(), + result == null ? "" : result.MatchedCount.ToString(), + result == null ? "" : result.LeftOnlyCount.ToString(), + result == null ? "" : result.RightOnlyCount.ToString(), + result == null ? "" : result.DifferentCount.ToString(), + result == null ? "" : result.DuplicateCount.ToString(), + result == null ? "" : result.InvalidCount.ToString(), + Text(table.Note) + }; + } + + static XlsxSheet Begin(List used, string title) + { + return new XlsxSheet { Name = SheetNames.Make(title, used) }; + } + + static string Text(string value) + { + return value ?? ""; + } + } +} diff --git a/src/DataCompare.Core/SheetNames.cs b/src/DataCompare.Core/SheetNames.cs new file mode 100644 index 0000000..2a88dc3 --- /dev/null +++ b/src/DataCompare.Core/SheetNames.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +namespace DataCompare.Core +{ + public static class SheetNames + { + public static string Make(string name, ICollection used) + { + var clean = Clean(name); + if (used == null) + return clean; + var unique = clean; + if (Contains(used, unique)) + { + for (int n = 2; n < 10000; n++) + { + var suffix = "_" + n.ToString(); + var headLength = 31 - suffix.Length; + if (headLength < 1) + headLength = 1; + var head = clean.Length <= headLength ? clean : clean.Substring(0, headLength); + unique = head + suffix; + if (!Contains(used, unique)) + break; + } + } + used.Add(unique); + return unique; + } + + public static string Clean(string name) + { + if (string.IsNullOrWhiteSpace(name)) + name = "表"; + var chars = name.Trim().ToCharArray(); + for (int i = 0; i < chars.Length; i++) + { + char c = chars[i]; + if (c < ' ' || c == '\\' || c == '/' || c == '?' || c == '*' || c == '[' || c == ']' || c == ':') + chars[i] = '_'; + } + var text = new string(chars).Trim().Trim('\''); + if (text.Length == 0) + text = "表"; + if (string.Equals(text, "History", StringComparison.OrdinalIgnoreCase)) + text = "History_"; + if (text.Length > 31) + text = text.Substring(0, 31); + return text; + } + + static bool Contains(ICollection used, string name) + { + foreach (var item in used) + { + if (string.Equals(item, name, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + } +} diff --git a/src/DataCompare.Core/TableMatch.cs b/src/DataCompare.Core/TableMatch.cs new file mode 100644 index 0000000..0a84a08 --- /dev/null +++ b/src/DataCompare.Core/TableMatch.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; + +namespace DataCompare.Core +{ + public sealed class TableMatchRule + { + public string Id { get; set; } + public string Name { get; set; } + public bool IgnoreCase { get; set; } + public bool StripSchemaPrefix { get; set; } + public string Separator { get; set; } + public bool NameOnly { get; set; } + + public bool IsBuiltIn + { + get { return Id == "same" || Id == "prefix"; } + } + + public static TableMatchRule SameName() + { + return new TableMatchRule + { + Id = "same", + Name = "同名", + IgnoreCase = true, + StripSchemaPrefix = false, + Separator = "_", + NameOnly = false + }; + } + + public static TableMatchRule SchemaPrefix() + { + return new TableMatchRule + { + Id = "prefix", + Name = "模式前缀", + IgnoreCase = true, + StripSchemaPrefix = true, + Separator = "_", + NameOnly = false + }; + } + } + + public static class TableMatcher + { + public static string Key(TableRef table, TableMatchRule rule) + { + if (table == null) + return ""; + if (rule == null) + rule = TableMatchRule.SchemaPrefix(); + + var schema = SchemaOf(table); + var name = table.Name ?? ""; + var separator = string.IsNullOrEmpty(rule.Separator) ? "_" : rule.Separator; + if (rule.IgnoreCase) + { + schema = schema.ToLowerInvariant(); + name = name.ToLowerInvariant(); + separator = separator.ToLowerInvariant(); + } + if (rule.StripSchemaPrefix && schema.Length > 0 && separator.Length > 0) + { + var prefix = schema + separator; + if (name.StartsWith(prefix, StringComparison.Ordinal)) + name = name.Substring(prefix.Length); + } + if (rule.NameOnly) + return "\0" + name; + return schema + "\0" + name; + } + + public static List Match(TableRef source, IList candidates, TableMatchRule rule) + { + var found = new List(); + if (source == null || candidates == null) + return found; + var key = Key(source, rule); + if (key.Length == 0 || key == "\0") + return found; + for (int i = 0; i < candidates.Count; i++) + { + if (string.Equals(Key(candidates[i], rule), key, StringComparison.Ordinal)) + found.Add(candidates[i]); + } + return found; + } + + public static bool SameTable(TableRef left, TableRef right) + { + if (left == null || right == null) + return false; + 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); + } + + static string SchemaOf(TableRef table) + { + if (!string.IsNullOrEmpty(table.Schema)) + return table.Schema; + return table.Catalog ?? ""; + } + } +} diff --git a/src/DataCompare.Core/XlsxFile.cs b/src/DataCompare.Core/XlsxFile.cs new file mode 100644 index 0000000..9669207 --- /dev/null +++ b/src/DataCompare.Core/XlsxFile.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Text; +using System.Xml; + +namespace DataCompare.Core +{ + public static class XlsxFile + { + const int MaxCell = 32767; + + public static void Save(string path, IList sheets) + { + if (string.IsNullOrWhiteSpace(path)) + throw new InvalidOperationException("请选择导出文件。"); + if (sheets == null || sheets.Count == 0) + throw new InvalidOperationException("没有可写入的工作表。"); + + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + if (File.Exists(path)) + File.Delete(path); + + using (var zip = ZipFile.Open(path, ZipArchiveMode.Create)) + { + WriteText(zip, "[Content_Types].xml", ContentTypes(sheets.Count)); + WriteText(zip, "_rels/.rels", + "" + + "" + + "" + + ""); + WriteText(zip, "xl/_rels/workbook.xml.rels", WorkbookRels(sheets.Count)); + WriteWorkbook(zip, sheets); + for (int i = 0; i < sheets.Count; i++) + WriteSheet(zip, sheets[i], i + 1); + } + } + + static string ContentTypes(int count) + { + var builder = new StringBuilder(); + builder.Append(""); + builder.Append(""); + builder.Append(""); + builder.Append(""); + builder.Append(""); + for (int i = 1; i <= count; i++) + { + builder.Append(""); + } + builder.Append(""); + return builder.ToString(); + } + + static string WorkbookRels(int count) + { + var builder = new StringBuilder(); + builder.Append(""); + builder.Append(""); + for (int i = 1; i <= count; i++) + { + builder.Append(""); + } + builder.Append(""); + return builder.ToString(); + } + + static void WriteWorkbook(ZipArchive zip, IList sheets) + { + var entry = zip.CreateEntry("xl/workbook.xml", CompressionLevel.Optimal); + using (var stream = entry.Open()) + using (var writer = Xml(stream)) + { + writer.WriteStartElement("workbook", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + writer.WriteAttributeString("xmlns", "r", null, "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + writer.WriteStartElement("sheets"); + for (int i = 0; i < sheets.Count; i++) + { + writer.WriteStartElement("sheet"); + writer.WriteAttributeString("name", SheetNames.Clean(sheets[i].Name)); + writer.WriteAttributeString("sheetId", (i + 1).ToString()); + writer.WriteAttributeString("r", "id", "http://schemas.openxmlformats.org/officeDocument/2006/relationships", "rId" + (i + 1)); + writer.WriteEndElement(); + } + writer.WriteEndElement(); + writer.WriteEndElement(); + } + } + + static void WriteSheet(ZipArchive zip, XlsxSheet sheet, int index) + { + var entry = zip.CreateEntry("xl/worksheets/sheet" + index + ".xml", CompressionLevel.Optimal); + using (var stream = entry.Open()) + using (var writer = Xml(stream)) + { + writer.WriteStartElement("worksheet", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + writer.WriteStartElement("sheetData"); + var rows = sheet == null ? null : sheet.Rows; + int count = rows == null ? 0 : rows.Count; + for (int r = 0; r < count; r++) + { + var values = rows[r] ?? new string[0]; + writer.WriteStartElement("row"); + writer.WriteAttributeString("r", (r + 1).ToString()); + for (int c = 0; c < values.Length; c++) + { + writer.WriteStartElement("c"); + writer.WriteAttributeString("r", ColumnName(c + 1) + (r + 1)); + writer.WriteAttributeString("t", "inlineStr"); + writer.WriteStartElement("is"); + writer.WriteStartElement("t"); + var text = CellText(values[c]); + if (text.Length > 0 && (text[0] == ' ' || text[text.Length - 1] == ' ' || text.IndexOf('\n') >= 0 || text.IndexOf('\r') >= 0)) + writer.WriteAttributeString("xml", "space", "http://www.w3.org/XML/1998/namespace", "preserve"); + writer.WriteString(text); + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndElement(); + } + writer.WriteEndElement(); + } + writer.WriteEndElement(); + writer.WriteEndElement(); + } + } + + static void WriteText(ZipArchive zip, string name, string text) + { + var entry = zip.CreateEntry(name, CompressionLevel.Optimal); + using (var stream = entry.Open()) + using (var writer = new StreamWriter(stream, new UTF8Encoding(false))) + writer.Write(text); + } + + static XmlWriter Xml(Stream stream) + { + var settings = new XmlWriterSettings + { + Encoding = new UTF8Encoding(false), + OmitXmlDeclaration = false, + CloseOutput = false + }; + return XmlWriter.Create(stream, settings); + } + + static string ColumnName(int index) + { + var text = ""; + while (index > 0) + { + index--; + text = (char)('A' + (index % 26)) + text; + index /= 26; + } + return text; + } + + static string CellText(string value) + { + if (string.IsNullOrEmpty(value)) + return ""; + var builder = new StringBuilder(Math.Min(value.Length, MaxCell)); + for (int i = 0; i < value.Length && builder.Length < MaxCell; i++) + { + char c = value[i]; + if (char.IsSurrogate(c)) + { + if (builder.Length + 2 > MaxCell || i + 1 >= value.Length || !char.IsSurrogatePair(c, value[i + 1])) + continue; + builder.Append(c); + builder.Append(value[i + 1]); + i++; + continue; + } + if (c == '\t' || c == '\n' || c == '\r' || c >= ' ') + builder.Append(c); + } + return builder.ToString(); + } + } +} diff --git a/src/DataCompare.Tests/DiffWorkbookTests.cs b/src/DataCompare.Tests/DiffWorkbookTests.cs new file mode 100644 index 0000000..964fc0d --- /dev/null +++ b/src/DataCompare.Tests/DiffWorkbookTests.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Text; +using DataCompare.Core; +using Xunit; + +namespace DataCompare.Tests +{ + public class DiffWorkbookTests + { + [Fact] + public void Sheet_name_drops_invalid_characters_and_dedupes() + { + var used = new List(); + Assert.Equal("Order_Item", SheetNames.Make("Order:Item", used)); + Assert.Equal("Order_Item_2", SheetNames.Make("Order/Item", used)); + var longName = new string('A', 40); + var trimmed = SheetNames.Make(longName, used); + Assert.Equal(31, trimmed.Length); + } + + [Fact] + public void Builds_summary_and_one_sheet_per_completed_table() + { + var tables = new[] + { + Done("TrustTransactionInput", "仅左侧", 2), + new ExportTable + { + SheetTitle = "TrustAccount", + Label = "TrustAccount", + Status = "缺键", + Note = "缺少键列:Id", + Completed = false + } + }; + var sheets = DiffWorkbook.Build(tables, 0, 20); + Assert.Equal(2, sheets.Count); + Assert.Equal("汇总", sheets[0].Name); + Assert.Equal("TrustTransactionInput", sheets[1].Name); + Assert.Equal("缺键", sheets[0].Rows[2][1]); + Assert.Equal("缺少键列:Id", sheets[0].Rows[2][10]); + Assert.Equal("2", sheets[0].Rows[1][2]); + Assert.Equal("1", sheets[0].Rows[1][5]); + Assert.Equal("仅左侧", sheets[1].Rows[1][0]); + Assert.Equal("Amount", sheets[1].Rows[1][3]); + } + + [Fact] + public void Filter_limits_rows_on_every_sheet() + { + var sheets = DiffWorkbook.Build(new[] { Done("Order", "内容不同", 1) }, 1, 20); + Assert.Equal(2, sheets.Count); + Assert.Single(sheets[1].Rows); + } + + [Fact] + public void Splits_a_sheet_when_row_limit_is_reached() + { + var sheets = DiffWorkbook.Build(new[] { Done("Order", "内容不同", 0) }, 0, 2); + Assert.Equal(3, sheets.Count); + Assert.Equal("Order", sheets[1].Name); + Assert.Equal("Order_2", sheets[2].Name); + Assert.Equal(2, sheets[1].Rows.Count); + Assert.Equal(2, sheets[2].Rows.Count); + } + + [Fact] + public void Writes_a_workbook_excel_can_open() + { + var sheets = DiffWorkbook.Build(new[] { Done("Order", "仅左侧", 1) }, 0, 20); + var path = Path.Combine(Path.GetTempPath(), "datacompare-" + Guid.NewGuid().ToString("N") + ".xlsx"); + try + { + XlsxFile.Save(path, sheets); + using (var zip = ZipFile.OpenRead(path)) + { + Assert.NotNull(zip.GetEntry("[Content_Types].xml")); + Assert.NotNull(zip.GetEntry("xl/workbook.xml")); + Assert.NotNull(zip.GetEntry("xl/worksheets/sheet1.xml")); + Assert.NotNull(zip.GetEntry("xl/worksheets/sheet2.xml")); + string workbook = Read(zip, "xl/workbook.xml"); + Assert.Contains("name=\"汇总\"", workbook); + Assert.Contains("name=\"Order\"", workbook); + string sheet = Read(zip, "xl/worksheets/sheet2.xml"); + Assert.Contains("仅左侧", sheet); + Assert.Contains("inlineStr", sheet); + } + } + finally + { + if (File.Exists(path)) + File.Delete(path); + } + } + + static string Read(ZipArchive zip, string name) + { + using (var stream = zip.GetEntry(name).Open()) + using (var reader = new StreamReader(stream, Encoding.UTF8)) + return reader.ReadToEnd(); + } + + static ExportTable Done(string name, string keepStatus, int differentCells) + { + var cells = new List(); + cells.Add(new CellDiff + { + ColumnName = "Amount", + LeftText = "1", + RightText = "2", + IsDifferent = true + }); + if (differentCells > 0) + { + cells.Add(new CellDiff + { + ColumnName = "Name", + LeftText = "a", + RightText = "a", + IsDifferent = false + }); + } + var diff = new RowDiff + { + Status = keepStatus == "仅左侧" ? DiffStatus.LeftOnly : DiffStatus.Different, + KeyText = "1", + Cells = cells.ToArray() + }; + return new ExportTable + { + SheetTitle = name, + Label = name, + Status = "完成", + Completed = true, + Result = new CompareResult + { + LeftRowCount = 2, + RightRowCount = 2, + MatchedCount = 1, + LeftOnlyCount = keepStatus == "仅左侧" ? 1 : 0, + DifferentCount = keepStatus == "仅左侧" ? 0 : 1, + Diffs = new[] + { + diff, + new RowDiff + { + Status = DiffStatus.RightOnly, + KeyText = "9", + Cells = new[] + { + new CellDiff { ColumnName = "Amount", LeftText = "", RightText = "3", IsDifferent = true } + } + } + } + } + }; + } + } +} diff --git a/src/DataCompare.Tests/TableMatchTests.cs b/src/DataCompare.Tests/TableMatchTests.cs new file mode 100644 index 0000000..5288e64 --- /dev/null +++ b/src/DataCompare.Tests/TableMatchTests.cs @@ -0,0 +1,190 @@ +using System.Collections.Generic; +using DataCompare.Core; +using Xunit; + +namespace DataCompare.Tests +{ + public class TableMatchTests + { + static TableRef SqlServer() + { + return new TableRef + { + Catalog = "TrustManagement", + Schema = "TrustManagement", + Name = "TrustTransactionInput" + }; + } + + static TableRef Gauss() + { + return new TableRef + { + Schema = "trustmanagement", + Name = "trustmanagement_trusttransactioninput" + }; + } + + [Fact] + public void Schema_prefix_matches_both_directions() + { + var rule = TableMatchRule.SchemaPrefix(); + var left = SqlServer(); + var right = Gauss(); + Assert.Equal(TableMatcher.Key(left, rule), TableMatcher.Key(right, rule)); + + var fromLeft = TableMatcher.Match(left, new[] { right }, rule); + Assert.Single(fromLeft); + Assert.Same(right, fromLeft[0]); + + var fromRight = TableMatcher.Match(right, new[] { left }, rule); + Assert.Single(fromRight); + Assert.Same(left, fromRight[0]); + } + + [Fact] + public void Same_name_rule_keeps_the_prefix() + { + var rule = TableMatchRule.SameName(); + Assert.NotEqual(TableMatcher.Key(SqlServer(), rule), TableMatcher.Key(Gauss(), rule)); + Assert.Empty(TableMatcher.Match(SqlServer(), new[] { Gauss() }, rule)); + } + + [Fact] + public void Schema_prefix_still_matches_identical_names() + { + var rule = TableMatchRule.SchemaPrefix(); + var left = new TableRef { Schema = "dbo", Name = "Users" }; + var right = new TableRef { Schema = "DBO", Name = "users" }; + Assert.Equal(TableMatcher.Key(left, rule), TableMatcher.Key(right, rule)); + } + + [Fact] + public void Does_not_split_pascal_case_into_underscores() + { + var rule = TableMatchRule.SchemaPrefix(); + var snake = new TableRef + { + Schema = "trustmanagement", + Name = "trustmanagement_trust_transaction_input" + }; + Assert.NotEqual(TableMatcher.Key(SqlServer(), rule), TableMatcher.Key(snake, rule)); + } + + [Fact] + public void Prefix_strip_uses_the_table_schema() + { + var rule = TableMatchRule.SchemaPrefix(); + var other = new TableRef + { + Schema = "other", + Name = "trustmanagement_trusttransactioninput" + }; + Assert.NotEqual(TableMatcher.Key(SqlServer(), rule), TableMatcher.Key(other, rule)); + } + + [Fact] + public void Multiple_matches_are_all_returned() + { + var rule = TableMatchRule.SchemaPrefix(); + var first = Gauss(); + var second = new TableRef + { + Schema = "TrustManagement", + Name = "trustmanagement_trusttransactioninput" + }; + var found = TableMatcher.Match(SqlServer(), new[] { first, second }, rule); + Assert.Equal(2, found.Count); + } + + [Fact] + public void Name_only_ignores_schema_after_stripping_prefix() + { + var rule = new TableMatchRule + { + Id = "custom", + Name = "只比表名", + IgnoreCase = true, + StripSchemaPrefix = true, + Separator = "_", + NameOnly = true + }; + var left = new TableRef { Schema = "dbo", Name = "TrustTransactionInput" }; + var right = Gauss(); + Assert.Equal(TableMatcher.Key(left, rule), TableMatcher.Key(right, rule)); + } + + [Fact] + public void Case_sensitive_rule_distinguishes_names() + { + var rule = new TableMatchRule + { + Id = "custom", + Name = "区分大小写", + IgnoreCase = false, + StripSchemaPrefix = false, + Separator = "_", + NameOnly = false + }; + var left = new TableRef { Schema = "dbo", Name = "Users" }; + var right = new TableRef { Schema = "dbo", Name = "users" }; + Assert.NotEqual(TableMatcher.Key(left, rule), TableMatcher.Key(right, rule)); + } + + [Fact] + public void ByName_marks_keys_and_reports_missing() + { + var left = new[] + { + new ColumnInfo { Name = "Id" }, + new ColumnInfo { Name = "Amount" } + }; + var right = new[] + { + new ColumnInfo { Name = "id" }, + new ColumnInfo { Name = "Amount" } + }; + string missing; + var mappings = ColumnMapper.ByName(left, right, new[] { "Id", "TenantId" }, out missing); + Assert.Equal("缺少键列:TenantId", missing); + Assert.Equal(2, mappings.Count); + Assert.True(mappings[0].IsKey); + Assert.Equal("id", mappings[0].RightColumn); + Assert.False(mappings[1].IsKey); + Assert.True(mappings[1].Compare); + } + + [Fact] + public void Guesses_the_only_id_suffix_when_id_is_absent() + { + var mappings = new List + { + new ColumnMapping { LeftColumn = "TrustId", RightColumn = "trustid", Compare = true }, + new ColumnMapping { LeftColumn = "Amount", RightColumn = "amount", Compare = true } + }; + Assert.Equal("TrustId", ColumnMapper.GuessKey(mappings)); + ColumnMapper.MarkKey(mappings, "TrustId"); + Assert.True(mappings[0].IsKey); + } + + [Fact] + public void Prefers_exact_id_and_refuses_several_suffixes() + { + var withId = new List + { + new ColumnMapping { LeftColumn = "TrustId" }, + new ColumnMapping { LeftColumn = "Id" } + }; + Assert.Equal("Id", ColumnMapper.GuessKey(withId)); + + var many = new List + { + new ColumnMapping { LeftColumn = "TrustId" }, + new ColumnMapping { LeftColumn = "UserId" } + }; + Assert.Null(ColumnMapper.GuessKey(many)); + Assert.Contains("TrustId", ColumnMapper.KeyHint(many)); + Assert.Contains("UserId", ColumnMapper.KeyHint(many)); + } + } +}