using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SqlSugar; using WmsLite.Api.Infrastructure.HttpLogging; namespace WmsLite.Api.Infrastructure; public static class SqlSugarSetup { public static IServiceCollection AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration) { var connectionString = ConnectionStringConfiguration.ResolvePostgreSql(configuration); services.AddScoped(sp => { var httpContextAccessor = sp.GetRequiredService(); var config = new ConnectionConfig { ConnectionString = connectionString, DbType = DbType.PostgreSQL, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute, ConfigureExternalServices = new ConfigureExternalServices { EntityService = (property, column) => { if (property.PropertyType == typeof(Dictionary) || property.PropertyType == typeof(Dictionary)) { column.IsJson = true; SetJsonbColumnType(column); } } }, AopEvents = new AopEvents { OnLogExecuting = (sql, parameters) => { var executable = TryFormatExecutableSql(DbType.PostgreSQL, sql, parameters); HttpSqlLogContext.Append(httpContextAccessor.HttpContext, executable); } } }; return new SqlSugarClient(config); }); return services; } /// /// 生成可在客户端直接执行的 SQL(参数已代入);失败时退回原始 SQL + 参数列表。 /// private static string TryFormatExecutableSql(DbType dbType, string sql, SugarParameter[]? parameters) { if (string.IsNullOrEmpty(sql)) { return string.Empty; } try { return UtilMethods.GetSqlString(dbType, sql, parameters); } catch { var sb = new StringBuilder(); sb.Append(sql); if (parameters is { Length: > 0 }) { sb.AppendLine(); sb.Append("-- params:"); foreach (var p in parameters) { sb.Append(' ').Append(p.ParameterName).Append('=').Append(p.Value); } } return sb.ToString(); } } private static void SetJsonbColumnType(EntityColumnInfo column) { // Different SqlSugar versions expose this property with different names. const string jsonb = "jsonb"; var columnTypeProperty = column.GetType().GetProperty("ColumnDataType", BindingFlags.Public | BindingFlags.Instance) ?? column.GetType().GetProperty("DataType", BindingFlags.Public | BindingFlags.Instance); if (columnTypeProperty?.CanWrite == true && columnTypeProperty.PropertyType == typeof(string)) { columnTypeProperty.SetValue(column, jsonb); } } }