From bb294878242eb70058ae497b9b6f189c6fe486b1 Mon Sep 17 00:00:00 2001 From: sunkaixuan <610262374@qq.com> Date: Fri, 6 May 2022 13:02:38 +0800 Subject: [PATCH] Update Core --- .../CodeFirstProvider/CodeFirstProvider.cs | 52 ++++++ .../TableDifferenceProvider.cs | 174 ++++++++++++++++++ .../QueryableProvider/MappingFieldsHelper.cs | 16 ++ .../QueryableProvider/NavigatManager.cs | 33 +++- .../SugarProvider/SqlSugarCoreProvider.cs | 36 +--- .../Subquery/SubqueryableN.cs | 24 +++ .../SqlSugar/Interface/ICodeFirst.cs | 2 + .../SqlSugar/Utilities/CommonExtensions.cs | 4 + .../SqlSugar/Utilities/UtilMethods.cs | 57 ++++++ 9 files changed, 363 insertions(+), 35 deletions(-) create mode 100644 Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/TableDifferenceProvider.cs diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs index 7c78012c8..4d2df7c25 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/CodeFirstProvider.cs @@ -118,9 +118,61 @@ namespace SqlSugar } } } + public TableDifferenceProvider GetDifferenceTables() + { + var type = typeof(T); + return GetDifferenceTables(type); + } + + public TableDifferenceProvider GetDifferenceTables(params Type[] types) + { + TableDifferenceProvider result = new TableDifferenceProvider(); + foreach (var type in types) + { + GetDifferenceTables(result, type); + } + return result; + } #endregion #region Core Logic + private void GetDifferenceTables(TableDifferenceProvider result, Type type) + { + var tempTableName = "TempDiff" + DateTime.Now.ToString("yyMMssHHmmssfff"); + var oldTableName = this.Context.EntityMaintenance.GetEntityInfo(type).DbTableName; + var db = new SqlSugarProvider(UtilMethods.CopyConfig(this.Context.CurrentConnectionConfig)); + UtilMethods.IsNullReturnNew(db.CurrentConnectionConfig.ConfigureExternalServices); + db.CurrentConnectionConfig.ConfigureExternalServices.EntityNameService += (x, p) => + { + p.IsDisabledUpdateAll = true;//Disabled update + }; + db.MappingTables = new MappingTableList(); + db.MappingTables.Add(type.Name, tempTableName); + try + { + db.CodeFirst.InitTables(type); + var tables = db.DbMaintenance.GetTableInfoList(false); + var oldTableInfo = tables.FirstOrDefault(it=>it.Name.EqualCase(oldTableName)); + var newTableInfo = tables.FirstOrDefault(it => it.Name.EqualCase(oldTableName)); + var oldTable = db.DbMaintenance.GetColumnInfosByTableName(oldTableName, false); + var tempTable = db.DbMaintenance.GetColumnInfosByTableName(tempTableName, false); + result.tableInfos.Add(new DiffTableInfo() + { + OldTableInfo= oldTableInfo, + NewTableInfo = newTableInfo, + OldColumnInfos = oldTable, + NewColumnInfos = tempTable + }); + } + catch (Exception ex) + { + throw ex; + } + finally + { + db.DbMaintenance.DropTable(tempTableName); + } + } protected virtual void Execute(Type entityType) { var entityInfo = this.Context.EntityMaintenance.GetEntityInfoNoCache(entityType); diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/TableDifferenceProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/TableDifferenceProvider.cs new file mode 100644 index 000000000..823ab625f --- /dev/null +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/CodeFirstProvider/TableDifferenceProvider.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Linq; +namespace SqlSugar +{ + public class TableDifferenceProvider + { + internal List tableInfos = new List(); + public string ToDiffString() + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine(); + var diffTables = this.ToDiffList(); + if (diffTables.IsNullOrEmpty()) + { + sb.AppendLine("No change"); + } + else + { + foreach (var item in diffTables) + { + sb.AppendLine($"----Table:{ item.TableName }----"); + if (item.AddColums.HasValue()) + { + sb.AppendLine($"Add column: "); + foreach (var addItem in item.AddColums) + { + sb.AppendLine($"{addItem.Message} "); + } + } + if (item.UpdateColums.HasValue()) + { + sb.AppendLine($"Update column: "); + foreach (var addItem in item.UpdateColums) + { + sb.AppendLine($"{addItem.Message} "); + } + } + if (item.DeleteColums.HasValue()) + { + sb.AppendLine($"Delete column: "); + foreach (var addItem in item.DeleteColums) + { + sb.AppendLine($"{addItem.Message} "); + } + } + } + } + sb.AppendLine(); + sb.AppendLine(); + return sb.ToString(); + } + + public List ToDiffList() + { + List result = new List(); + foreach (var tableInfo in tableInfos) + { + TableDifferenceInfo addItem = new TableDifferenceInfo(); + addItem.TableName = tableInfo.OldTableInfo.Name; + addItem.AddColums = GetAddColumn(tableInfo); + addItem.UpdateColums = GetUpdateColumn(tableInfo); + addItem.DeleteColums = GetDeleteColumn(tableInfo); + if (addItem.IsDiff) + result.Add(addItem); + } + return result; + } + + private static List GetDeleteColumn(DiffTableInfo tableInfo) + { + List result = new List(); + var columns = tableInfo.OldColumnInfos.Where(z => !tableInfo.NewColumnInfos.Any(y => y.DbColumnName.EqualCase(z.DbColumnName))).ToList(); + return columns.Select(it => new DiffColumsInfo() { Message= GetColumnString(it) }).ToList(); + } + + private List GetUpdateColumn(DiffTableInfo tableInfo) + { + List result = new List(); + result = tableInfo.NewColumnInfos + .Where(z => tableInfo.OldColumnInfos.Any(y => y.DbColumnName.EqualCase(z.DbColumnName) && ( + z.Length != y.Length || + z.ColumnDescription != y.ColumnDescription || + z.DataType != y.DataType || + z.DecimalDigits != y.DecimalDigits + ))).Select(it => new DiffColumsInfo() + { + Message= GetUpdateColumnString(it, tableInfo.OldColumnInfos.FirstOrDefault(y => y.DbColumnName.EqualCase(it.DbColumnName))) + }).ToList(); + return result; + } + + private static List GetAddColumn(DiffTableInfo tableInfo) + { + List result = new List(); + var columns = tableInfo.NewColumnInfos.Where(z => !tableInfo.OldColumnInfos.Any(y => y.DbColumnName.EqualCase(z.DbColumnName))).ToList(); + return columns.Select(it => new DiffColumsInfo() { Message = GetColumnString(it) }).ToList(); + } + + private static string GetColumnString(DbColumnInfo it) + { + return $"{it.DbColumnName} {it.DataType} {it.Length} {it.Scale} default:{it.DefaultValue} description:{it.ColumnDescription} pk:{it.IsPrimarykey} nullable:{it.IsNullable} identity:{it.IsIdentity} "; + } + + private static string GetUpdateColumnString(DbColumnInfo it,DbColumnInfo old) + { + var result= $"{it.DbColumnName} changes: "; + if (it.DataType != old.DataType) + { + result += $" [DataType:{old.DataType}->{it.DataType}] "; + } + if (it.Length != old.Length) + { + result += $" [Length:{old.Length}->{it.Length}] "; + } + if (it.Scale != old.Scale) + { + result += $" [Scale:{old.Scale}->{it.Scale}] "; + } + if (it.ColumnDescription != old.ColumnDescription) + { + result += $" [Description:{old.ColumnDescription}->{it.ColumnDescription}] "; + } + if (it.IsPrimarykey != old.IsPrimarykey) + { + result += $" [Pk:{old.IsPrimarykey}->{it.IsPrimarykey}] "; + } + if (it.IsNullable != old.IsNullable) + { + result += $" [Nullable:{old.IsNullable}->{it.IsNullable}] "; + } + if (it.IsIdentity != old.IsIdentity) + { + result += $" [Identity:{old.IsIdentity}->{it.IsIdentity}] "; + } + return result; + } + } + public class TableDifferenceInfo + { + public List DeleteColums { get; set; } = new List(); + public List UpdateColums { get; set; } = new List(); + public List AddColums { get; set; } = new List(); + public List UpdateRemark { get; set; } = new List(); + public bool IsDiff + { + get + { + return + (DeleteColums.Count>0 || + UpdateColums.Count > 0 || + AddColums.Count > 0 || + UpdateRemark.Count > 0) ; + } + } + + public string TableName { get; set; } + } + + public class DiffColumsInfo + { + public string SqlTemplate { get; set; } + public string Message { get; set; } + } + + public class DiffTableInfo + { + public DbTableInfo OldTableInfo { get; set; } + public DbTableInfo NewTableInfo { get; set; } + public List OldColumnInfos { get; set; } + public List NewColumnInfos { get; set; } + } +} diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/MappingFieldsHelper.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/MappingFieldsHelper.cs index a5f915ecb..2263ff724 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/MappingFieldsHelper.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/MappingFieldsHelper.cs @@ -72,6 +72,22 @@ namespace SqlSugar } } + public void SetChildItem(EntityColumnInfo navColumnInfo, object item, List list, List mappingFieldsExpressions) + { + if (item != null) + { + //var expable =Expressionable.Create(); + List setList = GetSetList(item, list, mappingFieldsExpressions); + //navColumnInfo.PropertyInfo.SetValue(); + var instance = Activator.CreateInstance(navColumnInfo.PropertyInfo.PropertyType, true); + var ilist = instance as IList; + foreach (var value in setList) + { + navColumnInfo.PropertyInfo.SetValue(item, value); + } + + } + } public List GetSetList(object item, List list, List mappingFieldsExpressions) { foreach (var field in mappingFieldsExpressions) diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/NavigatManager.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/NavigatManager.cs index b41c19352..8e33b8607 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/NavigatManager.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/QueryableProvider/NavigatManager.cs @@ -342,7 +342,13 @@ namespace SqlSugar private void Dynamic(List list, Func, List> selector, EntityInfo listItemEntity, System.Reflection.PropertyInfo navObjectNamePropety, EntityColumnInfo navObjectNameColumnInfo) { - var navEntity = navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments()[0]; + var args = navObjectNameColumnInfo.PropertyInfo.PropertyType.GetGenericArguments(); + if (args.Length == 0) + { + DynamicOneToOne(list,selector,listItemEntity, navObjectNamePropety, navObjectNameColumnInfo); + return; + } + var navEntity = args[0]; var navEntityInfo = this.Context.EntityMaintenance.GetEntityInfo(navEntity); var sqlObj = GetWhereSql(navObjectNameColumnInfo.Navigat.Name); Check.ExceptionEasy(sqlObj.MappingExpressions.IsNullOrEmpty(), $"Dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"自定义映射需要 MappingFields ,例子: Includes(it => it.Books.MappingFields(z=>z.studenId,()=>it.StudentId).ToList())"); @@ -364,6 +370,31 @@ namespace SqlSugar } } + + private void DynamicOneToOne(List list, Func, List> selector, EntityInfo listItemEntity, System.Reflection.PropertyInfo navObjectNamePropety, EntityColumnInfo navObjectNameColumnInfo) + { + var navEntity = navObjectNameColumnInfo.PropertyInfo.PropertyType; + var navEntityInfo = this.Context.EntityMaintenance.GetEntityInfo(navEntity); + var sqlObj = GetWhereSql(navObjectNameColumnInfo.Navigat.Name); + Check.ExceptionEasy(sqlObj.MappingExpressions.IsNullOrEmpty(), $"Dynamic need MappingField ,Demo: Includes(it => it.Books.MappingField(z=>z.studenId,()=>it.StudentId).ToList())", $"自定义映射需要 MappingFields ,例子: Includes(it => it.Books.MappingFields(z=>z.studenId,()=>it.StudentId).ToList())"); + if (list.Any() && navObjectNamePropety.GetValue(list.First()) == null) + { + MappingFieldsHelper helper = new MappingFieldsHelper(); + helper.Context = this.Context; + helper.NavEntity = navEntityInfo; + helper.RootEntity = this.Context.EntityMaintenance.GetEntityInfo(); + var whereSql = helper.GetMppingSql(list, sqlObj.MappingExpressions); + var navList = selector(this.Context.Queryable().AS(navEntityInfo.DbTableName).AddParameters(sqlObj.Parameters).Where(whereSql, true).WhereIF(sqlObj.WhereString.HasValue(), sqlObj.WhereString).Select(sqlObj.SelectString).OrderByIF(sqlObj.OrderByString.HasValue(), sqlObj.OrderByString)); + if (navList.HasValue()) + { + foreach (var item in list) + { + helper.SetChildItem(navObjectNameColumnInfo, item, navList, sqlObj.MappingExpressions); + } + } + } + } + private SqlInfo GetWhereSql(string properyName=null) { if (_ListCallFunc == null|| _ListCallFunc.Count==0) return new SqlInfo(); diff --git a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarCoreProvider.cs b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarCoreProvider.cs index 6bd48d727..90e18a2cf 100644 --- a/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarCoreProvider.cs +++ b/Src/Asp.NetCore2/SqlSugar/Abstract/SugarProvider/SqlSugarCoreProvider.cs @@ -66,40 +66,8 @@ namespace SqlSugar } private List GetCopyConfigs() { - return _configs.Select(it => new ConnectionConfig() - { - AopEvents = it.AopEvents, - ConfigId = it.ConfigId, - ConfigureExternalServices = it.ConfigureExternalServices, - ConnectionString = it.ConnectionString, - DbType = it.DbType, - IndexSuffix = it.IndexSuffix, - InitKeyType = it.InitKeyType, - IsAutoCloseConnection = it.IsAutoCloseConnection, - LanguageType = it.LanguageType, - MoreSettings = it.MoreSettings == null ? null : new ConnMoreSettings() - { - DefaultCacheDurationInSeconds = it.MoreSettings.DefaultCacheDurationInSeconds, - DisableNvarchar = it.MoreSettings.DisableNvarchar, - PgSqlIsAutoToLower = it.MoreSettings.PgSqlIsAutoToLower, - IsAutoRemoveDataCache = it.MoreSettings.IsAutoRemoveDataCache, - IsWithNoLockQuery = it.MoreSettings.IsWithNoLockQuery, - TableEnumIsString=it.MoreSettings.TableEnumIsString, - DisableMillisecond=it.MoreSettings.DisableMillisecond - }, - SqlMiddle=it.SqlMiddle==null?null:new SqlMiddle { - IsSqlMiddle=it.SqlMiddle.IsSqlMiddle, - ExecuteCommand=it.SqlMiddle.ExecuteCommand, - ExecuteCommandAsync=it.SqlMiddle.ExecuteCommandAsync, - GetDataReader=it.SqlMiddle.GetDataReader, - GetDataReaderAsync=it.SqlMiddle.GetDataReaderAsync, - GetDataSetAll=it.SqlMiddle.GetDataSetAll, - GetDataSetAllAsync=it.SqlMiddle.GetDataSetAllAsync, - GetScalar=it.SqlMiddle.GetScalar, - GetScalarAsync=it.SqlMiddle.GetScalarAsync - }, - SlaveConnectionConfigs = it.SlaveConnectionConfigs - }).ToList(); + return _configs.Select(it =>UtilMethods.CopyConfig(it)).ToList(); } + } } diff --git a/Src/Asp.NetCore2/SqlSugar/ExpressionsToSql/Subquery/SubqueryableN.cs b/Src/Asp.NetCore2/SqlSugar/ExpressionsToSql/Subquery/SubqueryableN.cs index 138fbc6d8..24db36a4e 100644 --- a/Src/Asp.NetCore2/SqlSugar/ExpressionsToSql/Subquery/SubqueryableN.cs +++ b/Src/Asp.NetCore2/SqlSugar/ExpressionsToSql/Subquery/SubqueryableN.cs @@ -240,6 +240,14 @@ namespace SqlSugar { return default(string); } + public Subqueryable OrderBy(Func expression) + { + return this; + } + public Subqueryable GroupBy(Func expression) + { + return this; + } } public class Subqueryable : Subqueryable where T1 : class, new() { @@ -267,6 +275,14 @@ namespace SqlSugar { return this; } + public Subqueryable OrderBy(Func expression) + { + return this; + } + public Subqueryable GroupBy(Func expression) + { + return this; + } public TResult Select(Func expression) where TResult : struct { return default(TResult); @@ -294,6 +310,14 @@ namespace SqlSugar { return this; } + public Subqueryable OrderBy(Func expression) + { + return this; + } + public Subqueryable GroupBy(Func expression) + { + return this; + } public Subqueryable WhereIF(bool isWhere, Func expression) { return this; diff --git a/Src/Asp.NetCore2/SqlSugar/Interface/ICodeFirst.cs b/Src/Asp.NetCore2/SqlSugar/Interface/ICodeFirst.cs index 6eb0e6a4c..9483e7b36 100644 --- a/Src/Asp.NetCore2/SqlSugar/Interface/ICodeFirst.cs +++ b/Src/Asp.NetCore2/SqlSugar/Interface/ICodeFirst.cs @@ -18,5 +18,7 @@ namespace SqlSugar void InitTables(); void InitTables(); SplitCodeFirstProvider SplitTables(); + TableDifferenceProvider GetDifferenceTables(); + TableDifferenceProvider GetDifferenceTables(params Type[] types); } } diff --git a/Src/Asp.NetCore2/SqlSugar/Utilities/CommonExtensions.cs b/Src/Asp.NetCore2/SqlSugar/Utilities/CommonExtensions.cs index b77e8f834..42dbc0373 100644 --- a/Src/Asp.NetCore2/SqlSugar/Utilities/CommonExtensions.cs +++ b/Src/Asp.NetCore2/SqlSugar/Utilities/CommonExtensions.cs @@ -24,5 +24,9 @@ namespace SqlSugar { return thisValue; } + public static List MappingField(this T thisValue, Func leftField, Func rightField) where T:class + { + return new List() { thisValue }; + } } } diff --git a/Src/Asp.NetCore2/SqlSugar/Utilities/UtilMethods.cs b/Src/Asp.NetCore2/SqlSugar/Utilities/UtilMethods.cs index 4fa83e252..987363c16 100644 --- a/Src/Asp.NetCore2/SqlSugar/Utilities/UtilMethods.cs +++ b/Src/Asp.NetCore2/SqlSugar/Utilities/UtilMethods.cs @@ -69,6 +69,63 @@ namespace SqlSugar return isAsync; } + + public static ConnectionConfig CopyConfig(ConnectionConfig it) + { + return new ConnectionConfig() + { + AopEvents =it.AopEvents==null?null:new AopEvents() { + DataExecuting=it.AopEvents?.DataExecuting, + OnDiffLogEvent=it.AopEvents?.OnDiffLogEvent, + OnError=it.AopEvents?.OnError, + OnExecutingChangeSql=it.AopEvents?.OnExecutingChangeSql, + OnLogExecuted=it.AopEvents?.OnLogExecuted, + OnLogExecuting= it.AopEvents?.OnLogExecuting, + }, + ConfigId = it.ConfigId, + ConfigureExternalServices =it.ConfigureExternalServices==null?null:new ConfigureExternalServices() { + AppendDataReaderTypeMappings=it.ConfigureExternalServices.AppendDataReaderTypeMappings, + DataInfoCacheService=it.ConfigureExternalServices.DataInfoCacheService, + EntityNameService=it.ConfigureExternalServices.EntityNameService, + EntityService=it.ConfigureExternalServices.EntityService, + RazorService=it.ConfigureExternalServices.RazorService, + ReflectionInoCacheService=it.ConfigureExternalServices.ReflectionInoCacheService, + SerializeService=it.ConfigureExternalServices.SerializeService, + SplitTableService=it.ConfigureExternalServices.SplitTableService, + SqlFuncServices=it.ConfigureExternalServices.SqlFuncServices + }, + ConnectionString = it.ConnectionString, + DbType = it.DbType, + IndexSuffix = it.IndexSuffix, + InitKeyType = it.InitKeyType, + IsAutoCloseConnection = it.IsAutoCloseConnection, + LanguageType = it.LanguageType, + MoreSettings = it.MoreSettings == null ? null : new ConnMoreSettings() + { + DefaultCacheDurationInSeconds = it.MoreSettings.DefaultCacheDurationInSeconds, + DisableNvarchar = it.MoreSettings.DisableNvarchar, + PgSqlIsAutoToLower = it.MoreSettings.PgSqlIsAutoToLower, + IsAutoRemoveDataCache = it.MoreSettings.IsAutoRemoveDataCache, + IsWithNoLockQuery = it.MoreSettings.IsWithNoLockQuery, + TableEnumIsString = it.MoreSettings.TableEnumIsString, + DisableMillisecond = it.MoreSettings.DisableMillisecond + }, + SqlMiddle = it.SqlMiddle == null ? null : new SqlMiddle + { + IsSqlMiddle = it.SqlMiddle.IsSqlMiddle, + ExecuteCommand = it.SqlMiddle.ExecuteCommand, + ExecuteCommandAsync = it.SqlMiddle.ExecuteCommandAsync, + GetDataReader = it.SqlMiddle.GetDataReader, + GetDataReaderAsync = it.SqlMiddle.GetDataReaderAsync, + GetDataSetAll = it.SqlMiddle.GetDataSetAll, + GetDataSetAllAsync = it.SqlMiddle.GetDataSetAllAsync, + GetScalar = it.SqlMiddle.GetScalar, + GetScalarAsync = it.SqlMiddle.GetScalarAsync + }, + SlaveConnectionConfigs = it.SlaveConnectionConfigs + }; + } + public static bool IsAsyncMethod(MethodBase method) { if (method == null)