Files
tnb.server/common/Tnb.SqlSugar/Repositories/SqlSugarRepository.cs
2023-03-27 19:09:57 +08:00

111 lines
4.3 KiB
C#

using JNPF;
using JNPF.DataEncryption;
using JNPF.FriendlyException;
using JNPF.JsonSerialization;
using JNPF.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Text.RegularExpressions;
namespace SqlSugar;
/// <summary>
/// SqlSugar 仓储实现类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public partial class SqlSugarRepository<TEntity> : SimpleClient<TEntity>, ISqlSugarRepository<TEntity>
where TEntity : class, new()
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="context"></param>
public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
{
// 获取数据库连接选项
ConnectionStringsOptions connectionStrings = App.GetConfig<ConnectionStringsOptions>("ConnectionStrings", true);
// 获取多租户选项
TenantOptions tenant = App.GetConfig<TenantOptions>("Tenant", true);
var httpContext = App.HttpContext;
base.Context = (SqlSugarScope)context;
string tenantId = connectionStrings.ConfigId;
if (httpContext?.GetEndpoint()?.Metadata?.GetMetadata<AllowAnonymousAttribute>() == null || !string.IsNullOrEmpty(httpContext?.Request.Query["token"]))
{
if (tenant.MultiTenancy && httpContext != null)
{
var connectionConfig = new ConnectionConfigOptions();
if (httpContext.Request.Headers.ContainsKey("Authorization"))
{
connectionConfig = JSON.Deserialize<ConnectionConfigOptions>(httpContext?.User.FindFirst("ConnectionConfig")?.Value);
tenantId = connectionConfig.ConfigId;
}
else if (!httpContext.Request.Headers.ContainsKey("Authorization"))
{
var token = Regex.Match(httpContext.Request.QueryString.Value, @"[?&]token=Bearer%20([\w\.-]+)($|&)").Groups[1].Value;
var claims = JWTEncryption.ReadJwtToken(token.Replace("Bearer ", "").Replace("bearer ", ""))?.Claims;
connectionConfig = JSON.Deserialize<ConnectionConfigOptions>(claims.FirstOrDefault(e => e.Type == "ConnectionConfig").Value);
tenantId = connectionConfig.ConfigId;
}
if (!base.Context.AsTenant().IsAnyConnection(connectionConfig.ConfigId))
{
base.Context.AsTenant().AddConnection(JNPFTenantExtensions.GetConfig(connectionConfig));
}
base.Context = base.Context.AsTenant().GetConnectionScope(connectionConfig.ConfigId);
if (!base.Context.Ado.IsValidConnection())
{
throw Oops.Oh("数据库连接错误");
}
}
else
{
base.Context = base.Context.AsTenant().GetConnectionScope(tenantId);
}
}
// 设置超时时间
base.Context.Ado.CommandTimeOut = 30;
base.Context.Aop.OnLogExecuted = (sql, pars) =>
{
// 在控制台输出sql语句
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;
var finalSql = UtilMethods.GetSqlString(Context.CurrentConnectionConfig.DbType, sql, pars);
Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{Context.Ado.SqlExecutionTime.TotalMilliseconds} ms");
Console.WriteLine(finalSql);
Console.ForegroundColor = oldColor;
if (Context.Ado.SqlExecutionTime.TotalMilliseconds > 3000)
{
Log.Warning($"慢查询: {Context.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql);
}
Console.WriteLine();
//App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + base.Context.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
base.Context.Aop.OnError = (ex) =>
{
Log.Error(UtilMethods.GetSqlString(base.Context.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres));
//App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
};
if (base.Context.CurrentConnectionConfig.DbType == DbType.Oracle)
{
base.Context.Aop.OnExecutingChangeSql = (sql, pars) =>
{
if (pars != null)
{
foreach (var item in pars)
{
//如果是DbTppe=string设置成OracleDbType.Nvarchar2
item.IsNvarchar2 = true;
}
};
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
};
}
}
}