73 lines
2.5 KiB
C#
73 lines
2.5 KiB
C#
using JNPF.Logging;
|
|
using Mapster;
|
|
using SqlSugar;
|
|
using Yitter.IdGenerator;
|
|
|
|
namespace Tnb.Vengine.DataAccess;
|
|
|
|
public class SugarHelper
|
|
{
|
|
/// <summary>
|
|
/// 创建SugarClient实例
|
|
/// </summary>
|
|
public static ISqlSugarClient CreateSugarClient(string dbCode, string dbType, string dbConnection, Action<ConnectionConfig>? configConnection = null, Action<ISqlSugarClient>? configSugar = null)
|
|
{
|
|
var config = new ConnectionConfig
|
|
{
|
|
ConnectionString = dbConnection,
|
|
DbType = dbType.Adapt<DbType>(),
|
|
IsAutoCloseConnection = true,
|
|
ConfigId = dbCode,
|
|
InitKeyType = InitKeyType.Attribute,
|
|
MoreSettings = new ConnMoreSettings()
|
|
{
|
|
IsAutoRemoveDataCache = true, // 自动清理缓存
|
|
IsAutoToUpper = false,
|
|
PgSqlIsAutoToLower = false,
|
|
DisableNvarchar = true
|
|
},
|
|
};
|
|
configConnection?.Invoke(config);
|
|
var sugar = new SqlSugarScope(config, configSugar == null ? ConfigSugar : configSugar);
|
|
return sugar;
|
|
}
|
|
|
|
/// <summary>
|
|
/// SqlSugar默认配置
|
|
/// </summary>
|
|
/// <param name="db"></param>
|
|
public static void ConfigSugar(ISqlSugarClient db)
|
|
{
|
|
// 设置超时时间
|
|
db.Ado.CommandTimeOut = 30;
|
|
db.Aop.OnLogExecuted = (sql, pars) =>
|
|
{
|
|
var finalSql = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars);
|
|
if (db.Ado.SqlExecutionTime.TotalMilliseconds > 3000)
|
|
{
|
|
Log.Warning($"慢查询: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql);
|
|
}
|
|
else
|
|
{
|
|
var oldColor = Console.ForegroundColor;
|
|
Console.ForegroundColor = ConsoleColor.Green;
|
|
Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{db.Ado.SqlExecutionTime.TotalMilliseconds} ms");
|
|
Console.WriteLine(finalSql);
|
|
Console.ForegroundColor = oldColor;
|
|
Console.WriteLine();
|
|
}
|
|
};
|
|
db.Aop.OnError = (ex) =>
|
|
{
|
|
Log.Error(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres));
|
|
};
|
|
}
|
|
|
|
public static void CustomSnowId()
|
|
{
|
|
StaticConfig.CustomSnowFlakeFunc = () =>
|
|
{
|
|
return YitIdHelper.NextId();
|
|
};
|
|
}
|
|
} |