Learn.VideoAnalysis/VideoAnalysisCore/Common/SqlSugarExpand.cs

154 lines
6.5 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MySqlConnector;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using VideoAnalysisCore.Common;
namespace VideoAnalysisCore.Common
{
public static class SqlSugarExpand
{
public static bool ShowSQL = false;
public static void InitSqlSugar( this IServiceCollection services)
{
#region SqlSugar注入
var dbList = new List<IocConfig>() {
new IocConfig()
{
ConfigId =1,
ConnectionString = AppCommon.Config.DB.ConnectionString,
DbType =AppCommon.Config.DB.SqlType,
IsAutoCloseConnection = true//自动释放
},
};
services.AddSingleton(typeof(Repository<>));
//注入SqlSugar 主库
services.AddSqlSugar(dbList);
services.ConfigurationSugar(db =>
{
var config = db.CurrentConnectionConfig;
// 设置超时时间
db.Ado.CommandTimeOut = 61;
#if DEBUG
// 打印SQL语句
db.Aop.OnLogExecuting = (sql, pars) =>
{
if (!ShowSQL) return;
//var originColor = Console.ForegroundColor;
//if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
// Console.ForegroundColor = ConsoleColor.Green;
//if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
// Console.ForegroundColor = ConsoleColor.Yellow;
//if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
// Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"【{DateTime.Now}——执行SQL - [{config.ConfigId}]】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
//Console.ForegroundColor = originColor;
};
#endif
db.Aop.OnError = (ex) =>
{
if (ex.Parametres == null) return;
//var originColor = Console.ForegroundColor;
//Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine($"【{DateTime.Now}——错误SQL - [{config.ConfigId}]】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
//Console.ForegroundColor = originColor;
};
db.Aop.DataExecuting = (oldValue, entityInfo) =>
{
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
// 主键(long类型)且没有值的---赋值雪花Id
if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
//if (id == null || (long)id == 0)
// entityInfo.SetValue(YitIdHelper.NextId());
}
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
}
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
}
};
});
#endregion
}
public static void InitDB()
{
ShowSQL = false;
var builder = new MySqlConnectionStringBuilder(AppCommon.Config.DB.ConnectionString);
var dbName = builder.Database;
builder.Database = "mysql";
using SqlSugarClient dbMysql = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = builder.ConnectionString,
DbType = DbType.MySql,
IsAutoCloseConnection = true,
});
var dataBaseList = dbMysql.DbMaintenance.GetDataBaseList();
if (dataBaseList.Contains(dbName))
{
Console.WriteLine($"【0】数据库 {dbName} 已存在 【√】");
}
else
{
Console.WriteLine($"【0】创建数据库{dbName} ... ");
var res = dbMysql.Ado.ExecuteCommand($"CREATE DATABASE `{dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
try
{
dbMysql.Ado.ExecuteCommand($"alter database `{dbName}` character set utf8mb4;" +
$"alter database `{dbName}` character set utf8mb4 collate utf8mb4_general_ci;");
//res 没有权限
dbMysql.Ado.ExecuteCommand($"SET GLOBAL local_infile=1;");
Console.WriteLine($"【0】数据库 {dbName} 创建完成 【√】");
}
catch (Exception ex)
{
Console.WriteLine("【0】主库初始化配置 出现异常 " + ex.Message);
}
}
InitDbTable();
}
public static void InitDbTable()
{
if (!AppCommon.Config.DB.UpdateTable)
{
Console.WriteLine($"【1】初始化主库表 跳过....");
ShowSQL = true;
return;
}
Console.WriteLine($"【1】初始化主库表 执行中....");
var entityTypes = AppCommon.DbMatserType;
Console.WriteLine($"【1】数量{entityTypes.Count()} ....");
if (!entityTypes.Any()) return;
var i = 0;
var totalCount = entityTypes.Count().ToString().Length;
foreach (var t in entityTypes)
{
Console.Write($"【1】{entityTypes.Count()}/{(++i).ToString().PadLeft(totalCount, '0')} 执行 {t.FullName}".PadRight(60, ' '));
DbScoped.SugarScope.CodeFirst.InitTables(t);
Console.WriteLine($"【√】");
}
Console.WriteLine($"【1】数量{entityTypes.Count()} 执行完毕");
ShowSQL = true;
}
}
}