Learn.Archives/Learn.Archives.Core/Common/Expand/SqlSugarExpand.cs

182 lines
6.9 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MySqlConnector;
using SqlSugar;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Yitter.IdGenerator;
namespace Learn.Archives.Core.Common.Expand
{
public static class SqlSugarExpand
{
public static bool ShowSQL = false;
public static void AddSqlSugarExpand(this IServiceCollection services)
{
services.AddHttpContextAccessor();
Console.WriteLine($"{DateTime.Now}=>初始化 YitId雪花ID");
var options = new IdGeneratorOptions(ushort.Parse(AppCommon.Config.ID));
YitIdHelper.SetIdGenerator(options);
#region SqlSugar注入
var dbList = new List<IocConfig>() {
new IocConfig()
{
ConfigId =1,
ConnectionString = AppCommon.Config.DB.ConnectionString,
DbType =AppCommon.Config.DB.SqlType,
IsAutoCloseConnection = true//自动释放
},
};
dbList.AddRange(AppCommon.Config.OtherDBArr.Select(s => new IocConfig()
{
ConfigId = s.ConfigId,
ConnectionString = s.ConnectionString,
DbType = s.SqlType,
IsAutoCloseConnection = true
}));
services.AddTransient(typeof(Repository<>));
//注入SqlSugar 主库
services.AddSqlSugar(dbList);
#endregion
services.ConfigurationSugar(SetDbAop);
}
/// <summary>
/// 配置Aop
/// </summary>
/// <param name="db"></param>
/// <param name="setOrgEntityFilter">配置 学校数据 sql过滤 <para>默认true</para></param>
public static void SetDbAop(ISqlSugarClient db)
{
if (db.Ado.CommandTimeOut == 61)
{
return;
}
var config = db.CurrentConnectionConfig;
// 设置超时时间
db.Ado.CommandTimeOut = 61;
#if DEBUG
// 打印SQL语句
db.Aop.OnLogExecuting = (sql, pars) =>
{
if (!ShowSQL) return;
Console.WriteLine($"【{DateTime.Now}——执行SQL - [{config.ConfigId}]】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
};
#endif
db.Aop.OnError = (ex) =>
{
if (ex.Parametres == null) return;
Console.WriteLine($"【{DateTime.Now}——错误SQL - [{config.ConfigId}]】\r\n" + ex.Message + "\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
Console.WriteLine();
};
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.EntityValue is null)
entityInfo.SetValue(DateTime.Now);
}
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
}
};
// 超管时排除各种过滤器
//if (App.User?.FindFirst(ClaimEnum.Role)?.Value == "1")
//return;
// 配置用户机构(数据范围)过滤器
//SetOrgEntityFilter(db);
}
public static void UseSqlSugarExpand(this IApplicationBuilder app)
{
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.Sugar.CodeFirst.InitTables(t);
Console.WriteLine($"【√】");
}
Console.WriteLine($"【1】数量{entityTypes.Count()} 执行完毕");
ShowSQL = true;
}
}
}