Update Core

This commit is contained in:
sunkaixuna
2021-12-20 14:27:20 +08:00
parent 989bba216a
commit d79002e56d
27 changed files with 661 additions and 91 deletions

View File

@@ -441,7 +441,7 @@ namespace SqlSugar
#endregion
#region Private
private List<T> GetListOrCache<T>(string cacheKey, string sql)
protected List<T> GetListOrCache<T>(string cacheKey, string sql)
{
return this.Context.Utilities.GetReflectionInoCacheInstance().GetOrCreate(cacheKey,
() =>

View File

@@ -242,6 +242,10 @@ namespace SqlSugar
}
public IDeleteable<T> Where(List<IConditionalModel> conditionalModels)
{
if (conditionalModels.Count == 0)
{
return Where("1=2");
}
var sql = this.Context.Queryable<T>().SqlBuilder.ConditionalModelToSql(conditionalModels);
var result = this;
result.Where(sql.Key, sql.Value);

View File

@@ -8,7 +8,7 @@ namespace SqlSugar
{
public partial class FastestProvider<T>:IFastest<T> where T:class,new()
{
private SqlSugarProvider context;
internal SqlSugarProvider context;
private ISugarQueryable<T> queryable;
private EntityInfo entityInfo { get; set; }
public bool isLog;
@@ -116,7 +116,7 @@ namespace SqlSugar
this.context.Ado.IsEnableLogEvent = isLog;
if (this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuted != null)
{
this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuted($"End {title} name:{entityInfo.DbTableName} ,count: {datas.Count},current time: {DateTime.Now}" , new SugarParameter[] { });
this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuted($"End {title} name:{GetTableName()} ,count: {datas.Count},current time: {DateTime.Now}" , new SugarParameter[] { });
}
}
@@ -127,7 +127,7 @@ namespace SqlSugar
this.context.Ado.IsEnableLogEvent = false;
if (this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuting != null)
{
this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuting($"Begin {title} name:{entityInfo.DbTableName} ,count: {datas.Count},current time: {DateTime.Now} ", new SugarParameter[] { });
this.context.CurrentConnectionConfig?.AopEvents?.OnLogExecuting($"Begin {title} name:{GetTableName()} ,count: {datas.Count},current time: {DateTime.Now} ", new SugarParameter[] { });
}
}
#endregion

View File

@@ -56,6 +56,7 @@ namespace SqlSugar
}
dt.TableName = GetTableName();
var columns = entityInfo.Columns;
var isMySql = this.context.CurrentConnectionConfig.DbType == DbType.MySql;
foreach (var item in datas)
{
var dr = dt.NewRow();
@@ -71,6 +72,13 @@ namespace SqlSugar
name = column.PropertyName;
}
var value = ValueConverter(column, PropertyCallAdapterProvider<T>.GetInstance(column.PropertyName).InvokeGet(item));
if (isMySql&& column.UnderType==UtilConstants.BoolType)
{
if (value.ObjToBool() == false)
{
value = DBNull.Value;
}
}
dr[name] = value;
}
dt.Rows.Add(dr);
@@ -86,7 +94,7 @@ namespace SqlSugar
}
else
{
return queryable.SqlBuilder.GetTranslationTableName(entityInfo.DbTableName);
return queryable.SqlBuilder.GetTranslationTableName(this.context.EntityMaintenance.GetTableName<T>());
}
}
private object ValueConverter(EntityColumnInfo columnInfo, object value)

View File

@@ -21,5 +21,11 @@ namespace SqlSugar
this.Size = size;
return this;
}
public SplitFastest<T> SplitTable()
{
SplitFastest<T> result = new SplitFastest<T>();
result.FastestProvider = this;
return result;
}
}
}

View File

@@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class SplitFastest<T>where T:class,new()
{
public FastestProvider<T> FastestProvider { get; set; }
public SqlSugarProvider Context { get { return this.FastestProvider.context; } }
public EntityInfo EntityInfo { get { return this.Context.EntityMaintenance.GetEntityInfo<T>(); } }
public int BulkCopy(List<T> datas)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
CreateTable(item.Key);
var addList = item.Select(it => it.Item).ToList();
result += FastestProvider.AS(item.Key).BulkCopy(addList);
this.Context.MappingTables.Add(EntityInfo.EntityName, EntityInfo.DbTableName);
}
return result;
}
public async Task<int> BulkCopyAsync(List<T> datas)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
CreateTable(item.Key);
var addList = item.Select(it => it.Item).ToList();
result +=await FastestProvider.AS(item.Key).BulkCopyAsync(addList);
this.Context.MappingTables.Add(EntityInfo.EntityName, EntityInfo.DbTableName);
}
return result;
}
public int BulkUpdate(List<T> datas)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
CreateTable(item.Key);
var addList = item.Select(it => it.Item).ToList();
result += FastestProvider.AS(item.Key).BulkUpdate(addList);
this.Context.MappingTables.Add(EntityInfo.EntityName, EntityInfo.DbTableName);
}
return result;
}
public async Task<int> BulkUpdateAsync(List<T> datas)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
CreateTable(item.Key);
var addList = item.Select(it => it.Item).ToList();
result += await FastestProvider.AS(item.Key).BulkUpdateAsync(addList);
this.Context.MappingTables.Add(EntityInfo.EntityName, EntityInfo.DbTableName);
}
return result;
}
public int BulkUpdate(List<T> datas,string [] wherColumns,string [] updateColumns)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
var addList = item.Select(it => it.Item).ToList();
result += FastestProvider.AS(item.Key).BulkUpdate(addList,wherColumns,updateColumns); ;
}
return result;
}
public async Task<int> BulkUpdateAsync(List<T> datas, string[] wherColumns, string[] updateColumns)
{
List<GroupModel> groupModels;
int result;
GroupDataList(datas, out groupModels, out result);
foreach (var item in groupModels.GroupBy(it => it.GroupName))
{
var addList = item.Select(it => it.Item).ToList();
result += await FastestProvider.AS(item.Key).BulkUpdateAsync(addList, wherColumns, updateColumns); ;
}
return result;
}
private void CreateTable(string tableName)
{
var isLog = this.Context.Ado.IsEnableLogEvent;
this.Context.Ado.IsEnableLogEvent = false;
if (!this.Context.DbMaintenance.IsAnyTable(tableName, false))
{
this.Context.MappingTables.Add(EntityInfo.EntityName, tableName);
this.Context.CodeFirst.InitTables<T>();
}
this.Context.Ado.IsEnableLogEvent = isLog;
}
private void GroupDataList(List<T> datas, out List<GroupModel> groupModels, out int result)
{
var attribute = typeof(T).GetCustomAttribute<SplitTableAttribute>() as SplitTableAttribute;
Check.Exception(attribute == null, $"{typeof(T).Name} need SplitTableAttribute");
groupModels = new List<GroupModel>();
var db = FastestProvider.context;
foreach (var item in datas)
{
var value = db.SplitHelper<T>().GetValue(attribute.SplitType, item);
var tableName = db.SplitHelper<T>().GetTableName(attribute.SplitType,value);
groupModels.Add(new GroupModel() { GroupName = tableName, Item = item });
}
result = 0;
}
internal class GroupModel
{
public string GroupName { get; set; }
public T Item { get; set; }
}
}
}

View File

@@ -125,7 +125,7 @@ namespace SqlSugar
var other = messageList.Where(it => it.StorageType == StorageType.Other).ToList();
StorageableResult<T> result = new StorageableResult<T>()
{
_IsWhereColumn= this.whereExpression != null,
_WhereColumnList= wherecolumnList,
_AsName =asname,
_Context=this.Context,
AsDeleteable = this.Context.Deleteable<T>().AS(asname),

View File

@@ -0,0 +1,224 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class StorageableDataTable
{
internal DataTable DataTable { get; set; }
internal SqlSugarProvider Context { get; set; }
internal string[] Columns { get; set; } = new string[] { };
internal string SugarGroupId = "SugarGroupId";
internal string SugarUpdateRows = "SugarUpdateRows";
internal string SugarColumns = "SugarColumns";
internal string SugarErrorMessage = "SugarErrorMessage";
internal List<DataRow> dbDataList = new List<DataRow>();
List<KeyValuePair<StorageType, Func<DataRow, bool>,string>> whereFuncs = new List<KeyValuePair<StorageType, Func<DataRow, bool>,string>>();
public StorageableDataTable WhereColumns(string name)
{
return WhereColumns(new string[] { name});
}
public StorageableDataTable WhereColumns(string[] names)
{
this.Columns = names;
var queryable = this.Context.Queryable<object>();
Check.Exception(Columns==null|| Columns.Length==0,"need WhereColums");
var tableName = queryable.SqlBuilder.GetTranslationTableName(DataTable.TableName);
this.Context.Utilities.PageEach(DataTable.Rows.Cast<DataRow>(), 200, itemList =>
{
List<IConditionalModel> conditList = new List<IConditionalModel>();
SetConditList(itemList, Columns, conditList);
var addItem = this.Context.Queryable<object>().AS(tableName).Where(conditList).ToDataTable().Rows.Cast<DataRow>().ToList();
this.dbDataList.AddRange(addItem);
});
return this;
}
public StorageableDataTable WhereColumns(List<string> names)
{
return WhereColumns(names.ToArray());
}
public StorageableDataTable SplitInsert(Func<DataRow, bool> conditions, string message = null)
{
whereFuncs.Add(new KeyValuePair<StorageType, Func<DataRow, bool>, string>(StorageType.Insert, conditions,message));
return this;
}
public StorageableDataTable SplitDelete(Func<DataRow, bool> conditions, string message = null)
{
whereFuncs.Add(new KeyValuePair<StorageType, Func<DataRow, bool>,string>(StorageType.Delete, conditions,message));
return this;
}
public StorageableDataTable SplitUpdate(Func<DataRow, bool> conditions, string message = null)
{
whereFuncs.Add(new KeyValuePair<StorageType, Func<DataRow, bool>,string>(StorageType.Update, conditions,message));
return this;
}
public StorageableDataTable Saveable(string inserMessage = null, string updateMessage = null)
{
SplitUpdate(it => it.Any(), updateMessage);
SplitInsert(it => true, inserMessage);
return this;
}
public StorageableDataTable SplitError(Func<DataRow, bool> conditions, string message = null)
{
whereFuncs.Add(new KeyValuePair<StorageType, Func<DataRow, bool>, string>(StorageType.Error, conditions, message));
return this;
}
public StorageableDataTable SplitIgnore(Func<DataRow, bool> conditions, string message = null)
{
whereFuncs.Add(new KeyValuePair<StorageType, Func<DataRow, bool>, string>(StorageType.Ignore, conditions, message));
return this;
}
public DataTableResult ToStorage()
{
if (whereFuncs == null || whereFuncs.Count == 0)
{
Saveable();
}
foreach (DataRow row in DataTable.Rows)
{
foreach (var item in whereFuncs.OrderByDescending(it => (int)it.key))
{
SplitMethod(item.value1,item.key,row,item.value2);
}
if (row[SugarGroupId] == null || row[SugarGroupId] == DBNull.Value)
{
row[SugarGroupId] = StorageType.Ignore;
}
}
DataTable.Columns.Remove(SugarUpdateRows);
DataTable.Columns.Remove(SugarColumns);
var Groups=DataTable.Rows.Cast<DataRow>()
.Where(it=> it[SugarGroupId]!=null&& it[SugarGroupId] != DBNull.Value)
.GroupBy(it => ((StorageType)it[SugarGroupId]).ToString()).Select(it=>new DataTableGroups{ Type=it.Key,DataTable= it.CopyToDataTable() })
.ToList();
DataTable.Columns.Remove(SugarGroupId);
DataTable.Columns.Remove(SugarErrorMessage);
var inserList = new List<Dictionary<string, object>>();
var updateList = new List<Dictionary<string, object>>();
var DeleteList=Groups.FirstOrDefault(it=>it.Type==StorageType.Delete.ToString());
if (Groups.Any(it => it.Type == StorageType.Insert.ToString()))
{
foreach (var item in Groups)
{
if (item.Type == StorageType.Insert.ToString())
{
item.DataTable.Columns.Remove(SugarGroupId);
item.DataTable.Columns.Remove(SugarErrorMessage);
inserList.AddRange(this.Context.Utilities.DataTableToDictionaryList(item.DataTable));
}
}
}
if (Groups.Any(it => it.Type == StorageType.Update.ToString()))
{
foreach (var item in Groups)
{
if (item.Type == StorageType.Update.ToString())
{
item.DataTable.Columns.Remove(SugarGroupId);
item.DataTable.Columns.Remove(SugarErrorMessage);
updateList.AddRange(this.Context.Utilities.DataTableToDictionaryList(item.DataTable));
}
}
}
List<IConditionalModel> conditionalModels = new List<IConditionalModel>();
if (DeleteList!=null)
{
SetConditList(DeleteList.DataTable.Rows.Cast<DataRow>().ToList(), Columns, conditionalModels);
}
var tableName = this.Context.Queryable<object>().SqlBuilder.GetTranslationTableName(DataTable.TableName);
DataTableResult result = new DataTableResult()
{
DataTableGroups=Groups,
AsDeleteable=this.Context.Deleteable<object>().AS(tableName).Where(conditionalModels),
AsUpdateable= this.Context.Updateable(updateList).AS(tableName).WhereColumns(Columns),
AsInsertable=this.Context.Insertable(inserList).AS(tableName)
};
return result;
}
private void SplitMethod(Func<DataRow, bool> conditions, StorageType type,DataRow item,string message)
{
item[SugarColumns] = Columns;
item[SugarUpdateRows] = dbDataList;
if ((item[SugarGroupId]==null|| item[SugarGroupId] == DBNull.Value) && conditions(item))
{
item[SugarGroupId] = type;
item[SugarErrorMessage] = message;
}
}
private void SetConditList(List<DataRow> itemList, string[] whereColumns, List<IConditionalModel> conditList)
{
;
foreach (var dataItem in itemList)
{
var condition = new ConditionalCollections()
{
ConditionalList = new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()
};
conditList.Add(condition);
int i = 0;
foreach (var name in whereColumns)
{
var value = dataItem[name];
if (value != null && value.GetType().IsEnum())
{
value = Convert.ToInt64(value);
}
condition.ConditionalList.Add(new KeyValuePair<WhereType, ConditionalModel>(i == 0 ? WhereType.Or : WhereType.And, new ConditionalModel()
{
FieldName = name,
ConditionalType = ConditionalType.Equal,
FieldValue = value + "",
FieldValueConvertFunc = this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL ?
UtilMethods.GetTypeConvert(value) : null
}));
++i;
}
}
}
}
public class DataTableResult
{
public List<DataTableGroups> DataTableGroups { get; set; }
public IUpdateable<Dictionary<string, object>> AsUpdateable { get; set; }
public IDeleteable<object> AsDeleteable { get; set; }
public IInsertable<Dictionary<string, object>> AsInsertable { get; set; }
}
public class DataTableGroups
{
public string Type { get; set; }
public DataTable DataTable { get; set; }
}
public static class StorageableDataTableExtensions
{
public static bool Any(this DataRow row)
{
var list=row["SugarUpdateRows"] as List<DataRow>;
var columns = row["SugarColumns"] as string[];
return list.Any(it =>
{
var result = true;
foreach (var name in columns)
{
if (result)
{
result = row[name].ObjToString() == it[name].ObjToString();
if (result == false)
{
break;
}
}
}
return result;
});
}
}
}

View File

@@ -152,6 +152,8 @@ namespace SqlSugar
{
parameterName = parameterName.Replace(this.SqlTranslationLeft, "_");
}
string oldName = item.FieldName;
item.FieldName = GetTranslationColumnName(item.FieldName);
switch (item.ConditionalType)
{
case ConditionalType.Equal:
@@ -248,6 +250,7 @@ namespace SqlSugar
default:
break;
}
item.FieldName = oldName;
}
else
{

View File

@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
/// <summary>
/// Partial SqlSugarScope
/// </summary>
public partial class SqlSugarScope : ISqlSugarClient, ITenant
{
private List<ConnectionConfig> _configs;
private Action<SqlSugarClient> _configAction;
private SqlSugarClient GetContext()
{
SqlSugarClient result = null;
var key = _configs.GetHashCode().ToString();
StackTrace st = new StackTrace(true);
var methods = st.GetFrames();
var isAsync = UtilMethods.IsAnyAsyncMethod(methods);
if (isAsync)
{
result = GetAsyncContext(key);
}
else
{
result = GetThreadContext(key);
}
return result;
}
private SqlSugarClient GetAsyncContext(string key)
{
SqlSugarClient result = CallContextAsync<SqlSugarClient>.GetData(key);
if (result == null)
{
List<ConnectionConfig> configList = GetCopyConfigs();
CallContextAsync<SqlSugarClient>.SetData(key, new SqlSugarClient(configList));
result = CallContextAsync<SqlSugarClient>.GetData(key);
if (this._configAction != null)
{
this._configAction(result);
}
}
return result;
}
private SqlSugarClient GetThreadContext(string key)
{
SqlSugarClient result = CallContextThread<SqlSugarClient>.GetData(key);
if (result == null)
{
List<ConnectionConfig> configList = GetCopyConfigs();
CallContextThread<SqlSugarClient>.SetData(key, new SqlSugarClient(configList));
result = CallContextThread<SqlSugarClient>.GetData(key);
if (this._configAction != null)
{
this._configAction(result);
}
}
return result;
}
private List<ConnectionConfig> 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
},
SlaveConnectionConfigs = it.SlaveConnectionConfigs
}).ToList();
}
}
}

View File

@@ -765,6 +765,18 @@ namespace SqlSugar
{
return Storageable(new List<T>() { data });
}
public StorageableDataTable Storageable(DataTable data)
{
var result = new StorageableDataTable();
Check.Exception(data.TableName.IsNullOrEmpty() || data.TableName == "Table",ErrorMessage.GetThrowMessage( "DataTable data.TableName is null", "参数DataTable没有设置TableName ,参数.TableName=表名"));
result.DataTable = data;
result.Context = this;
data.Columns.Add(new DataColumn("SugarGroupId", typeof(StorageType)));
data.Columns.Add(new DataColumn("SugarUpdateRows", typeof(List<DataRow>)));
data.Columns.Add(new DataColumn("SugarErrorMessage", typeof(string)));
data.Columns.Add(new DataColumn("SugarColumns", typeof(string[])));
return result;
}
#endregion
#region Reportable

View File

@@ -181,19 +181,20 @@ namespace SqlSugar
}
public IUpdateable<T> ReSetValue(Expression<Func<T, bool>> setValueExpression)
public IUpdateable<T> ReSetValue(Action<T> setValueExpression)
{
Check.Exception(!IsSingle, "Batch operation not supported ReSetValue");
var expResult = UpdateBuilder.GetExpressionValue(setValueExpression, ResolveExpressType.WhereSingle);
var resultString = Regex.Match(expResult.GetResultString(), @"\((.+)\)").Groups[1].Value;
LambdaExpression lambda = setValueExpression as LambdaExpression;
var expression = lambda.Body;
Check.Exception(!(expression is BinaryExpression), "Expression format error");
Check.Exception((expression as BinaryExpression).NodeType != ExpressionType.Equal, "Expression format error");
var leftExpression = (expression as BinaryExpression).Left;
Check.Exception(!(leftExpression is MemberExpression), "Expression format error");
var leftResultString = UpdateBuilder.GetExpressionValue(leftExpression, ResolveExpressType.FieldSingle).GetString();
UpdateBuilder.SetValues.Add(new KeyValuePair<string, string>(leftResultString, resultString));
ThrowUpdateByExpression();
if (this.UpdateObjs.HasValue())
{
var oldColumns = this.UpdateBuilder.DbColumnInfoList.Select(it => it.PropertyName).ToList();
foreach (var item in UpdateObjs)
{
setValueExpression(item);
}
this.UpdateBuilder.DbColumnInfoList = new List<DbColumnInfo>();
Init();
this.UpdateBuilder.DbColumnInfoList = this.UpdateBuilder.DbColumnInfoList.Where(it => oldColumns.Contains(it.PropertyName)).ToList();
}
return this;
}
@@ -355,6 +356,11 @@ namespace SqlSugar
CheckTranscodeing();
}
if (columns.ToString().Contains("Subqueryable()."))
{
expResult= expResult.Replace(this.SqlBuilder.SqlTranslationLeft+ (binaryExp.Left as MemberExpression).Expression+this.SqlBuilder.SqlTranslationRight+".",this.UpdateBuilder.GetTableNameString.TrimEnd()+".");
}
UpdateBuilder.SetValues.Add(new KeyValuePair<string, string>(SqlBuilder.GetTranslationColumnName(key), expResult));
this.UpdateBuilder.DbColumnInfoList = this.UpdateBuilder.DbColumnInfoList.Where(it => (UpdateParameterIsNull == false && IsPrimaryKey(it)) || UpdateBuilder.SetValues.Any(v => SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.DbColumnName, StringComparison.CurrentCultureIgnoreCase) || SqlBuilder.GetNoTranslationColumnName(v.Key).Equals(it.PropertyName, StringComparison.CurrentCultureIgnoreCase)) || it.IsPrimarykey == true).ToList();
AppendSets();

View File

@@ -878,14 +878,26 @@ namespace SqlSugar
public string GeDateFormat(string formatString, string value)
{
if (IsOracle()||IsPg())
if (IsOracle() || IsPg())
{
return $"to_char({value},'{formatString}') ";
}
else if (IsMySql()&& formatString == "yyyy-MM-dd")
else if (IsSqlite() && formatString == "yyyy-MM-dd")
{
return $"strftime('%Y-%m-%d', {value})";
}
else if (IsSqlite() && formatString.Contains("%"))
{
return $"strftime('{formatString}', {value})";
}
else if (IsMySql() && formatString == "yyyy-MM-dd")
{
return $"DATE_FORMAT({value}, '%Y-%m-%d')";
}
else if (IsMySql() && formatString.Contains("%"))
{
return $"DATE_FORMAT({value}, '{formatString}')";
}
else if (formatString == "yyyy-MM-dd" && IsSqlServer())
{
return $"CONVERT(varchar(100),convert(datetime,{value}), 23)";

View File

@@ -402,9 +402,24 @@ namespace SqlSugar
if (suagrColumn != null && suagrColumn.IsJson)
{
var key = (typeName + "." + name).ToLower();
if (readerValues.ContainsKey(key)&& readerValues[key]!=null)
if (readerValues.Any(it=>it.Key.EqualCase(key)))
{
var jsonString = readerValues.First(it => it.Key.EqualCase(key)).Value;
if (jsonString != null)
{
if (jsonString.ToString().First() == '{'&& jsonString.ToString().Last() == '}')
{
result.Add(name, this.DeserializeObject<Dictionary<string, object>>(jsonString + ""));
}
else
{
result.Add(name, this.DeserializeObject<List<Dictionary<string, object>>>(jsonString + ""));
}
}
}
else
{
result.Add(name,this.DeserializeObject<List<Dictionary<string,object>>>(readerValues[key]+""));
}
}
else

View File

@@ -5,7 +5,7 @@ using System.Threading.Tasks;
namespace SqlSugar
{
public interface IFastest<T>
public interface IFastest<T> where T:class,new()
{
IFastest<T> AS(string tableName);
IFastest<T> PageSize(int Size);
@@ -16,5 +16,7 @@ namespace SqlSugar
Task<int> BulkUpdateAsync(List<T> datas);
int BulkUpdate(List<T> datas, string[] whereColumns, string[] updateColumns);
Task<int> BulkUpdateAsync(List<T> datas, string[] whereColumns, string[] updateColumns);
SplitFastest<T> SplitTable();
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq.Expressions;
using System.Threading.Tasks;
@@ -122,7 +123,10 @@ namespace SqlSugar
#region Saveable
IStorageable<T> Storageable<T>(List<T> dataList) where T : class, new();
IStorageable<T> Storageable<T>(T data) where T : class, new();
StorageableDataTable Storageable(DataTable data);
[Obsolete("use Storageable")]
ISaveable<T> Saveable<T>(List<T> saveObjects) where T : class, new();
[Obsolete("use Storageable")]
ISaveable<T> Saveable<T>(T saveObject) where T : class, new();
#endregion

View File

@@ -88,7 +88,7 @@ namespace SqlSugar
public IInsertable<T> AsInsertable { get; set; }
public IUpdateable<T> AsUpdateable { get; set; }
public IDeleteable<T> AsDeleteable { get; set; }
internal bool _IsWhereColumn { get; set; }
internal List<EntityColumnInfo> _WhereColumnList { get; set; }
internal string _AsName { get; set; }
internal SqlSugarProvider _Context { get; set; }
@@ -103,13 +103,58 @@ namespace SqlSugar
public int BulkUpdate()
{
Check.Exception(_IsWhereColumn, "Storageable.BulkCopy no support WhereColumns");
return this._Context.Fastest<T>().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList());
var isWhereColums = _WhereColumnList != null && _WhereColumnList.Any();
if (isWhereColums)
{
var updateColumns = this._Context.EntityMaintenance.GetEntityInfo<T>().Columns.Where(it => !it.IsPrimarykey && !it.IsIdentity && !it.IsOnlyIgnoreUpdate && !it.IsIgnore).Select(it => it.DbColumnName ?? it.PropertyName).ToArray();
return BulkUpdate(updateColumns);
}
else
{
return this._Context.Fastest<T>().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList());
}
}
public Task<int> BulkUpdateAsync()
{
Check.Exception(_IsWhereColumn, "Storageable.BulkCopy no support WhereColumns");
return this._Context.Fastest<T>().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList());
var isWhereColums = _WhereColumnList != null && _WhereColumnList.Any();
if (isWhereColums)
{
var updateColumns = this._Context.EntityMaintenance.GetEntityInfo<T>().Columns.Where(it => !it.IsPrimarykey && !it.IsIdentity && !it.IsOnlyIgnoreUpdate && !it.IsIgnore).Select(it => it.DbColumnName ?? it.PropertyName).ToArray();
return BulkUpdateAsync(updateColumns);
}
else
{
return this._Context.Fastest<T>().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList());
}
}
public int BulkUpdate(params string[] UpdateColumns)
{
Check.Exception(UpdateColumns==null, "UpdateColumns is null");
if (_WhereColumnList != null && _WhereColumnList.Any())
{
return this._Context.Fastest<T>().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList(), _WhereColumnList.Select(it => it.DbColumnName).ToArray(), UpdateColumns);
}
else
{
var pkColumns = this._Context.EntityMaintenance.GetEntityInfo<T>().Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToArray();
Check.Exception(pkColumns.Count()==0,"need primary key");
return this._Context.Fastest<T>().AS(_AsName).BulkUpdate(UpdateList.Select(it => it.Item).ToList(), pkColumns, UpdateColumns);
}
}
public async Task<int> BulkUpdateAsync(params string[] UpdateColumns)
{
Check.Exception(UpdateColumns == null, "UpdateColumns is null");
if (_WhereColumnList != null && _WhereColumnList.Any())
{
return await this._Context.Fastest<T>().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList(), _WhereColumnList.Select(it => it.DbColumnName).ToArray(), UpdateColumns);
}
else
{
var pkColumns = this._Context.EntityMaintenance.GetEntityInfo<T>().Columns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName).ToArray();
Check.Exception(pkColumns.Count() == 0, "need primary key");
return await this._Context.Fastest<T>().AS(_AsName).BulkUpdateAsync(UpdateList.Select(it => it.Item).ToList(), pkColumns, UpdateColumns);
}
}
}
}

View File

@@ -86,7 +86,7 @@ namespace SqlSugar
IUpdateable<T> IsEnableUpdateVersionValidation();
IUpdateable<T> EnableDiffLogEvent(object businessData = null);
IUpdateable<T> ReSetValue(Expression<Func<T, bool>> setValueExpression);
IUpdateable<T> ReSetValue(Action<T> setValueExpression);
IUpdateable<T> RemoveDataCache();
IUpdateable<T> RemoveDataCache(string likeString);
IUpdateable<T> CallEntityMethod(Expression<Action<T>> method);

View File

@@ -430,7 +430,7 @@ namespace SqlSugar
{
defaultValue = "";
}
if (defaultValue.ToLower().IsIn("now()", "current_timestamp"))
if (defaultValue.ToLower().IsIn("now()", "current_timestamp")|| defaultValue.ToLower().Contains("current_timestamp"))
{
string template = "ALTER table {0} CHANGE COLUMN {1} {1} {3} default {2}";
var dbColumnInfo = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName).First(it => it.DbColumnName.Equals(columnName, StringComparison.CurrentCultureIgnoreCase));

View File

@@ -119,7 +119,8 @@ namespace SqlSugar
}
else if (parameter.DbType== System.Data.DbType.DateTimeOffset)
{
sqlParameter.Value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)sqlParameter.Value);
if(sqlParameter.Value != DBNull.Value)
sqlParameter.Value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)sqlParameter.Value);
sqlParameter.DbType = System.Data.DbType.DateTime;
}
++index;

View File

@@ -164,7 +164,7 @@ namespace SqlSugar
{
colum = table.Columns[i];
if (i != 0) sb.Append(",");
if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
if (colum.DataType == typeof(string) &&( row[colum].ToString().Contains(",") || row[colum].ToString().Contains("\r")))
{
sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
}

View File

@@ -146,7 +146,8 @@ namespace SqlSugar
}
else if (parameter.DbType == System.Data.DbType.DateTimeOffset)
{
sqlParameter.Value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)parameter.Value);
if (parameter.Value != DBNull.Value)
sqlParameter.Value = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)parameter.Value);
sqlParameter.DbType = System.Data.DbType.DateTime;
}
else if (parameter.DbType == System.Data.DbType.Boolean)
@@ -182,7 +183,7 @@ namespace SqlSugar
if (parameter.Direction != 0)
sqlParameter.Direction = parameter.Direction;
result[index] = sqlParameter;
if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput,ParameterDirection.ReturnValue))
if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue))
{
if (this.OutputParameters == null) this.OutputParameters = new List<IDataParameter>();
this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName);

View File

@@ -354,11 +354,11 @@ namespace SqlSugar
{
item.Length = 1;
}
if (dataType == "uuid")
{
item.Length = 50;
dataType = "varchar";
}
//if (dataType == "uuid")
//{
// item.Length = 50;
// dataType = "varchar";
//}
string dataSize = item.Length > 0 ? string.Format("({0})", item.Length) : null;
if (item.DecimalDigits > 0&&item.Length>0 && dataType == "numeric")
{
@@ -394,6 +394,42 @@ namespace SqlSugar
if (result == null || result.Count() == 0)
{
result = base.GetColumnInfosByTableName(tableName, isCache);
}
try
{
string sql = $@"select
kcu.column_name as key_column
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
on kcu.constraint_name = tco.constraint_name
and kcu.constraint_schema = tco.constraint_schema
and kcu.constraint_name = tco.constraint_name
where tco.constraint_type = 'PRIMARY KEY'
and kcu.table_schema='public' and
upper(kcu.table_name)=upper('{tableName.TrimEnd('"').TrimStart('"')}')";
List<string> pkList = new List<string>();
if (isCache)
{
pkList=GetListOrCache<string>("GetColumnInfosByTableName_N_Pk"+tableName, sql);
}
else
{
pkList = this.Context.Ado.SqlQuery<string>(sql);
}
if (pkList.Count >1)
{
foreach (var item in result)
{
if (pkList.Select(it=>it.ToUpper()).Contains(item.DbColumnName.ToUpper()))
{
item.IsPrimarykey = true;
}
}
}
}
catch
{
}
return result;
}

View File

@@ -210,6 +210,12 @@ namespace SqlSugar
return string.Format(" ( to_char({0},'yyyy-MM-dd')=to_char({1},'yyyy-MM-dd') ) ", parameter.MemberName, parameter2.MemberName); ;
}
public override string HasValue(MethodCallExpressionModel model)
{
var parameter = model.Args[0];
return string.Format("( {0} IS NOT NULL )", parameter.MemberName);
}
public override string DateIsSameByType(MethodCallExpressionModel model)
{
var parameter = model.Args[0];

View File

@@ -171,7 +171,7 @@ namespace SqlSugar
var parameter = model.Args[0].MemberName;
var parameter2 = model.Args[1].MemberName;
int time = 1;
return string.Format(" date({0}, 'localtime', 'start of day')= date({1}, 'localtime', 'start of day') ", parameter, parameter2, time);
return string.Format(" strftime('%Y-%m-%d', {0})= strftime('%Y-%m-%d', {1}) ", parameter, parameter2, time);
}
public override string DateIsSameByType(MethodCallExpressionModel model)
{

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
@@ -345,6 +346,10 @@ namespace SqlSugar
#endregion
#region Saveable
public StorageableDataTable Storageable(DataTable data)
{
return this.Context.Storageable(data);
}
public IStorageable<T> Storageable<T>(List<T> dataList) where T : class, new()
{

View File

@@ -1,17 +1,17 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class SqlSugarScope: ISqlSugarClient, ITenant
public partial class SqlSugarScope: ISqlSugarClient, ITenant
{
private List<ConnectionConfig> _configs;
private Action<SqlSugarClient> _configAction;
private SqlSugarScope()
{
@@ -540,6 +540,10 @@ namespace SqlSugar
{
return ScopedContext.Storageable(data);
}
public StorageableDataTable Storageable(DataTable data)
{
return ScopedContext.Storageable(data);
}
public ISugarQueryable<T> Union<T>(List<ISugarQueryable<T>> queryables) where T : class, new()
{
@@ -645,53 +649,5 @@ namespace SqlSugar
{
return ScopedContext.Fastest<T>();
}
private SqlSugarClient GetContext()
{
SqlSugarClient result = null;
var key = _configs.GetHashCode().ToString();
StackTrace st = new StackTrace(true);
var methods = st.GetFrames();
var isAsync = UtilMethods.IsAnyAsyncMethod(methods);
if (isAsync)
{
result = GetAsyncContext(key);
}
else
{
result = GetThreadContext(key);
}
return result;
}
private SqlSugarClient GetAsyncContext(string key)
{
SqlSugarClient result = CallContextAsync<SqlSugarClient>.GetData(key);
if (result == null)
{
CallContextAsync<SqlSugarClient>.SetData(key, new SqlSugarClient(_configs));
result = CallContextAsync<SqlSugarClient>.GetData(key);
if (this._configAction != null)
{
this._configAction(result);
}
}
return result;
}
private SqlSugarClient GetThreadContext(string key)
{
SqlSugarClient result = CallContextThread<SqlSugarClient>.GetData(key);
if (result == null)
{
CallContextThread<SqlSugarClient>.SetData(key, new SqlSugarClient(_configs));
result = CallContextThread<SqlSugarClient>.GetData(key);
if (this._configAction != null)
{
this._configAction(result);
}
}
return result;
}
}
}