feat: 优化界面布局及样式
This commit is contained in:
+1902
-113
File diff suppressed because it is too large
Load Diff
@@ -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<RuleDto> 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<TableMatchRule> Load()
|
||||
{
|
||||
var list = new List<TableMatchRule>();
|
||||
if (!File.Exists(FilePath))
|
||||
return list;
|
||||
RuleFile file;
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(FilePath, Encoding.UTF8);
|
||||
file = JsonSerializer.Deserialize<RuleFile>(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<TableMatchRule> rules)
|
||||
{
|
||||
var dtos = new List<RuleDto>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> columns, IList<object[]> 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++)
|
||||
|
||||
@@ -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<TableMatchRule> _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<TableMatchRule> _others;
|
||||
readonly string _id;
|
||||
|
||||
public TableMatchRule Rule { get; private set; }
|
||||
|
||||
public RuleEditForm(TableMatchRule existing, List<TableMatchRule> others)
|
||||
{
|
||||
AppIcon.Apply(this);
|
||||
_others = others ?? new List<TableMatchRule>();
|
||||
_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
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,26 @@ namespace DataCompare.App
|
||||
get { return SelectedItem as TableRef; }
|
||||
}
|
||||
|
||||
public IList<TableRef> Tables
|
||||
{
|
||||
get { return new List<TableRef>(_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<TableRef> tables)
|
||||
{
|
||||
_all.Clear();
|
||||
|
||||
@@ -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<ColumnMapping> Mappings;
|
||||
public List<ColumnInfo> LeftColumns;
|
||||
public List<ColumnInfo> 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 ?? "";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<TableRef> _left;
|
||||
readonly IList<TableRef> _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<string> _checked = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
int _matched;
|
||||
int _hidden;
|
||||
int _shown;
|
||||
bool _filling;
|
||||
|
||||
public List<TableRef> PickedLeft { get; private set; }
|
||||
public List<TableRef> PickedRight { get; private set; }
|
||||
|
||||
public string KeyText
|
||||
{
|
||||
get { return _keys.Text ?? ""; }
|
||||
}
|
||||
|
||||
public TablePickForm(IList<TableRef> left, IList<TableRef> right, TableMatchRule rule)
|
||||
{
|
||||
AppIcon.Apply(this);
|
||||
_left = left ?? new List<TableRef>();
|
||||
_right = right ?? new List<TableRef>();
|
||||
_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<TableRef>();
|
||||
var right = new List<TableRef>();
|
||||
var seen = new HashSet<string>(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<TableRef> source, IList<TableRef> other, bool fromLeft, List<TableRef> left, List<TableRef> right, HashSet<string> 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<string> Tokens(string text)
|
||||
{
|
||||
var tokens = new List<string>();
|
||||
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<string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DataCompare.Core
|
||||
{
|
||||
public static class ColumnMapper
|
||||
{
|
||||
public static List<ColumnMapping> ByName(
|
||||
IList<ColumnInfo> left,
|
||||
IList<ColumnInfo> right,
|
||||
IList<string> keys,
|
||||
out string missingKeys)
|
||||
{
|
||||
var mappings = new List<ColumnMapping>();
|
||||
var missing = new List<string>();
|
||||
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<ColumnMapping> 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<ColumnMapping> mappings)
|
||||
{
|
||||
var names = new List<string>();
|
||||
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<ColumnMapping> 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<ColumnMapping> 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<ColumnInfo> 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<string> 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<string> names, string name)
|
||||
{
|
||||
for (int i = 0; i < names.Count; i++)
|
||||
{
|
||||
if (string.Equals(names[i], name, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string[]> Rows = new List<string[]>();
|
||||
}
|
||||
|
||||
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<XlsxSheet> Build(IList<ExportTable> tables, int filter)
|
||||
{
|
||||
return Build(tables, filter, MaxRows);
|
||||
}
|
||||
|
||||
public static List<XlsxSheet> Build(IList<ExportTable> tables, int filter, int maxRows)
|
||||
{
|
||||
if (maxRows < 2)
|
||||
maxRows = 2;
|
||||
var sheets = new List<XlsxSheet>();
|
||||
var used = new List<string>();
|
||||
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<XlsxSheet> sheets,
|
||||
List<string> 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<XlsxSheet> sheets, List<string> 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<string> used, string title)
|
||||
{
|
||||
return new XlsxSheet { Name = SheetNames.Make(title, used) };
|
||||
}
|
||||
|
||||
static string Text(string value)
|
||||
{
|
||||
return value ?? "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DataCompare.Core
|
||||
{
|
||||
public static class SheetNames
|
||||
{
|
||||
public static string Make(string name, ICollection<string> 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<string> used, string name)
|
||||
{
|
||||
foreach (var item in used)
|
||||
{
|
||||
if (string.Equals(item, name, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<TableRef> Match(TableRef source, IList<TableRef> candidates, TableMatchRule rule)
|
||||
{
|
||||
var found = new List<TableRef>();
|
||||
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 ?? "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<XlsxSheet> 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",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
|
||||
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
|
||||
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"xl/workbook.xml\"/>"
|
||||
+ "</Relationships>");
|
||||
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("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
|
||||
builder.Append("<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">");
|
||||
builder.Append("<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>");
|
||||
builder.Append("<Default Extension=\"xml\" ContentType=\"application/xml\"/>");
|
||||
builder.Append("<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>");
|
||||
for (int i = 1; i <= count; i++)
|
||||
{
|
||||
builder.Append("<Override PartName=\"/xl/worksheets/sheet");
|
||||
builder.Append(i);
|
||||
builder.Append(".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>");
|
||||
}
|
||||
builder.Append("</Types>");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
static string WorkbookRels(int count)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
|
||||
builder.Append("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">");
|
||||
for (int i = 1; i <= count; i++)
|
||||
{
|
||||
builder.Append("<Relationship Id=\"rId");
|
||||
builder.Append(i);
|
||||
builder.Append("\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/sheet");
|
||||
builder.Append(i);
|
||||
builder.Append(".xml\"/>");
|
||||
}
|
||||
builder.Append("</Relationships>");
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
static void WriteWorkbook(ZipArchive zip, IList<XlsxSheet> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string>();
|
||||
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<CellDiff>();
|
||||
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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<ColumnMapping>
|
||||
{
|
||||
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<ColumnMapping>
|
||||
{
|
||||
new ColumnMapping { LeftColumn = "TrustId" },
|
||||
new ColumnMapping { LeftColumn = "Id" }
|
||||
};
|
||||
Assert.Equal("Id", ColumnMapper.GuessKey(withId));
|
||||
|
||||
var many = new List<ColumnMapping>
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user