using System.Reflection; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SqlSugar; using Volo.Abp; using Volo.Abp.Auditing; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Entities.Events; using Volo.Abp.Guids; using Volo.Abp.MultiTenancy; using Volo.Abp.Users; using Yi.Framework.SqlSugarCore.Abstractions; namespace Yi.Framework.SqlSugarCore { public class SqlSugarDbContext : ISqlSugarDbContext { /// /// SqlSugar 客户端 /// public ISqlSugarClient SqlSugarClient { get; private set; } public ICurrentUser CurrentUser => LazyServiceProvider.GetRequiredService(); private readonly string MasterTenantDbDefaultName = DbConnOptions.MasterTenantDbDefaultName; private IAbpLazyServiceProvider LazyServiceProvider { get; } private IGuidGenerator GuidGenerator => LazyServiceProvider.LazyGetRequiredService(); protected ILoggerFactory Logger => LazyServiceProvider.LazyGetRequiredService(); private ICurrentTenant CurrentTenant => LazyServiceProvider.LazyGetRequiredService(); public IDataFilter DataFilter => LazyServiceProvider.LazyGetRequiredService(); protected virtual bool IsMultiTenantFilterEnabled => DataFilter?.IsEnabled() ?? false; protected virtual bool IsSoftDeleteFilterEnabled => DataFilter?.IsEnabled() ?? false; public IEntityChangeEventHelper EntityChangeEventHelper => LazyServiceProvider.LazyGetService(NullEntityChangeEventHelper.Instance); public DbConnOptions Options => LazyServiceProvider.LazyGetRequiredService>().Value; private ISqlSugarDbConnectionCreator _dbConnectionCreator; public void SetSqlSugarClient(ISqlSugarClient sqlSugarClient) { SqlSugarClient = sqlSugarClient; } public SqlSugarDbContext(IAbpLazyServiceProvider lazyServiceProvider) { LazyServiceProvider = lazyServiceProvider; var connectionCreator = LazyServiceProvider.LazyGetRequiredService(); _dbConnectionCreator = connectionCreator; connectionCreator.OnSqlSugarClientConfig = OnSqlSugarClientConfig; connectionCreator.EntityService = EntityService; connectionCreator.DataExecuting = DataExecuting; connectionCreator.DataExecuted = DataExecuted; connectionCreator.OnLogExecuting = OnLogExecuting; connectionCreator.OnLogExecuted = OnLogExecuted; SqlSugarClient = new SqlSugarClient(connectionCreator.Build()); var connectionStringResolver = LazyServiceProvider.LazyGetRequiredService(); var connectionStr = connectionStringResolver.ResolveAsync().Result; var changedDb = DatabaseChange(this, connectionStr); SqlSugarClient = changedDb.SqlSugarClient; } /// /// db切换多库支持 /// /// /// /// protected virtual SqlSugarDbContext DatabaseChange(SqlSugarDbContext dbContext, string connectionString) { string configId = string.Empty; //没有检测到使用多租户功能,默认使用默认库即可 if (string.IsNullOrWhiteSpace(connectionString)) { connectionString = dbContext.Options.Url; configId = CurrentTenant.Name; } var dbOption = dbContext.Options; var db = dbContext.SqlSugarClient.AsTenant(); //主库的Db切换,当操作的是租户表的时候 if (CurrentTenant.Name == MasterTenantDbDefaultName) { //直接切换 configId = MasterTenantDbDefaultName; var conStrOrNull = dbOption.GetMasterSaasMultiTenancy(); Volo.Abp.Check.NotNull(conStrOrNull, "租户主库未找到"); connectionString = conStrOrNull.Url; } //租户Db的动态切换 //二级缓存 var changed = false; if (!db.IsAnyConnection(configId)) { var config = _dbConnectionCreator.Build(options => { options.DbType = dbOption.DbType!.Value; options.ConfigId = configId;//设置库的唯一标识 options.IsAutoCloseConnection = true; options.ConnectionString = connectionString; }); //添加一个db到当前上下文 (Add部分不线上下文不会共享) db.AddConnection(config); changed = true; } var currentDb = db.GetConnection(configId) as ISqlSugarClient; //设置Aop if (changed) { _dbConnectionCreator.SetDbAop(currentDb); } dbContext.SetSqlSugarClient(currentDb); return dbContext; } /// /// 上下文对象扩展 /// /// protected virtual void OnSqlSugarClientConfig(ISqlSugarClient sqlSugarClient) { //需自定义扩展 if (IsSoftDeleteFilterEnabled) { sqlSugarClient.QueryFilter.AddTableFilter(u => u.IsDeleted == false); } if (IsMultiTenantFilterEnabled) { sqlSugarClient.QueryFilter.AddTableFilter(u => u.TenantId == GuidGenerator.Create()); } CustomDataFilter(sqlSugarClient); } protected virtual void CustomDataFilter(ISqlSugarClient sqlSugarClient) { } protected virtual void DataExecuted(object oldValue, DataAfterModel entityInfo) { } /// /// 数据 /// /// /// protected virtual void DataExecuting(object oldValue, DataFilterModel entityInfo) { //审计日志 switch (entityInfo.OperationType) { case DataFilterType.UpdateByObject: if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.LastModificationTime))) { if (!DateTime.MinValue.Equals(oldValue)) { entityInfo.SetValue(DateTime.Now); } } if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.LastModifierId))) { if (CurrentUser.Id != null) { entityInfo.SetValue(CurrentUser.Id); } } break; case DataFilterType.InsertByObject: if (entityInfo.PropertyName.Equals(nameof(IEntity.Id))) { //主键为空或者为默认最小值 if (Guid.Empty.Equals(oldValue)) { entityInfo.SetValue(GuidGenerator.Create()); } } if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreationTime))) { //为空或者为默认最小值 if (oldValue is null || DateTime.MinValue.Equals(oldValue)) { entityInfo.SetValue(DateTime.Now); } } if (entityInfo.PropertyName.Equals(nameof(IAuditedObject.CreatorId))) { if (CurrentUser.Id != null) { entityInfo.SetValue(CurrentUser.Id); } } //插入时,需要租户id,先预留 if (entityInfo.PropertyName.Equals(nameof(IMultiTenant.TenantId))) { if (CurrentTenant is not null) { entityInfo.SetValue(CurrentTenant.Id); } } break; } //领域事件 switch (entityInfo.OperationType) { case DataFilterType.InsertByObject: if (entityInfo.PropertyName == nameof(IEntity.Id)) { EntityChangeEventHelper.PublishEntityCreatedEvent(entityInfo.EntityValue); } break; case DataFilterType.UpdateByObject: if (entityInfo.PropertyName == nameof(IEntity.Id)) { //软删除,发布的是删除事件 if (entityInfo.EntityValue is ISoftDelete softDelete) { if (softDelete.IsDeleted == true) { EntityChangeEventHelper.PublishEntityDeletedEvent(entityInfo.EntityValue); } } else { EntityChangeEventHelper.PublishEntityUpdatedEvent(entityInfo.EntityValue); } } break; case DataFilterType.DeleteByObject: if (entityInfo.PropertyName == nameof(IEntity.Id)) { EntityChangeEventHelper.PublishEntityDeletedEvent(entityInfo.EntityValue); } break; } } /// /// 日志 /// /// /// protected virtual void OnLogExecuting(string sql, SugarParameter[] pars) { if (Options.EnabledSqlLog) { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine("==========Yi-SQL执行:=========="); sb.AppendLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars)); sb.AppendLine("==============================="); Logger.CreateLogger().LogDebug(sb.ToString()); } } /// /// 日志 /// /// /// protected virtual void OnLogExecuted(string sql, SugarParameter[] pars) { } /// /// 实体配置 /// /// /// protected virtual void EntityService(PropertyInfo property, EntityColumnInfo column) { } public void BackupDataBase() { string directoryName = "database_backup"; string fileName = DateTime.Now.ToString($"yyyyMMdd_HHmmss") + $"_{SqlSugarClient.Ado.Connection.Database}"; if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } switch (Options.DbType) { case DbType.MySql: //MySql SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName)}.sql");//mysql 只支持.net core break; case DbType.Sqlite: //Sqlite SqlSugarClient.DbMaintenance.BackupDataBase(null, $"{fileName}.db"); //sqlite 只支持.net core break; case DbType.SqlServer: //SqlServer SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName)}.bak"/*服务器路径*/);//第一个参数库名 break; default: throw new NotImplementedException("其他数据库备份未实现"); } } } }