using CliFx; using CliFx.Attributes; using CliFx.Infrastructure; using Dapper; using MySqlConnector; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Chenfeng.MES.Archiver.Commands { [Command("import")] public class ImportSqlCommand : ICommand { [CommandParameter(0, Description = "数据库连接")] public string Connection { get; set; } = ""; [CommandOption("source", Description = "导入文件路径")] public string Source { get; set; } = "./output"; public Action Print { get; set; } = (text) => { }; public MySqlConnection? Db { get; private set; } [CommandOption("clear", Description = "导入前清除表数据")] public bool clear { get; set; } =true; public ValueTask ExecuteAsync(IConsole console) { Print = (text) => console.Output.WriteLine($"{DateTime.Now.ToLongTimeString()} {text}"); Print("开始导入!"); var connBuilder = new MySqlConnectionStringBuilder(this.Connection); connBuilder.SslMode = MySqlSslMode.None; connBuilder.CharacterSet = "utf8"; try { Db = new MySqlConnection(connBuilder.ConnectionString); Db.Open(); var dir = new System.IO.DirectoryInfo(Source); var files = dir.GetFiles(); var result=Db.QueryFirst<(string,string)>("show VARIABLES like '%FOREIGN_KEY_CHECKS'"); if (this.clear&& result.Item2=="ON") { Db.Execute("SET FOREIGN_KEY_CHECKS=0"); } foreach (var file in files) { Print($"导入文件:{file.Name}!"); var startTime = DateTime.Now; ImportFile(file); console.Output.WriteLine("执行耗时:" + (DateTime.Now - startTime).TotalMilliseconds + "ms"); } if (this.clear && result.Item2 == "ON") { Db.Execute("SET FOREIGN_KEY_CHECKS=1"); } Print("操作成功"); } catch (Exception ex) { console.Output.WriteLine(ex.ToString()); } finally { Db?.Close(); } return default; } private void ImportFile(FileInfo fileInfo) { var reg = new Regex("(.+?)\\-p(.+?)\\.(.+?)\\.sql"); var matchs=reg.Matches(fileInfo.Name); if (matchs.Count == 0|| matchs[0].Groups.Count != 4) { return; } var type = matchs[0].Groups[3].ToString(); var table = matchs[0].Groups[1].ToString(); if (this.clear) { Db.Execute($"TRUNCATE TABLE `{table}`"); } var fileStream = File.OpenRead(fileInfo.FullName); Stream deCompressStream; switch (type) { case "gz": case "gzip": deCompressStream = new System.IO.Compression.GZipStream(fileStream,System.IO.Compression.CompressionMode.Decompress); break; case "deflate": deCompressStream = new System.IO.Compression.DeflateStream(fileStream, System.IO.Compression.CompressionMode.Decompress); break; case "br": deCompressStream = new System.IO.Compression.BrotliStream(fileStream, System.IO.Compression.CompressionMode.Decompress); break; case "none": // 不压缩 default: deCompressStream = fileStream; break; } using (deCompressStream) { using (StreamReader streamReader = new StreamReader(deCompressStream)) { var sql=streamReader.ReadToEnd(); this.Db.Execute(sql); //streamWriter.Flush(); } } } } }