Update Core

This commit is contained in:
sunkaixuna
2021-08-01 17:17:09 +08:00
parent 24e6800195
commit 2e42c230e4
41 changed files with 602 additions and 52 deletions

View File

@@ -19,5 +19,6 @@ namespace SqlSugar
public Action<string, SugarParameter[]> OnLogExecuting { set { this.Context.CurrentConnectionConfig.AopEvents.OnLogExecuting= value; } }
public Action<string, SugarParameter[]> OnLogExecuted { set { this.Context.CurrentConnectionConfig.AopEvents.OnLogExecuted = value; } }
public Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> OnExecutingChangeSql { set { this.Context.CurrentConnectionConfig.AopEvents.OnExecutingChangeSql = value; } }
public virtual Action<object, DataFilterModel> DataExecuting { set { this.Context.CurrentConnectionConfig.AopEvents.DataExecuting = value; } }
}
}

View File

@@ -230,14 +230,6 @@ namespace SqlSugar
return this;
}
public IDeleteable<T> Where(List<IConditionalModel> conditionalModels)
{
var sql = this.Context.Queryable<T>().SqlBuilder.ConditionalModelToSql(conditionalModels);
var result = this;
result.Where(sql.Key, sql.Value);
return result;
}
public IDeleteable<T> RemoveDataCache()
{
this.RemoveCacheFunc = () =>

View File

@@ -85,7 +85,66 @@ namespace SqlSugar
return result;
}
public virtual long ExecuteReturnSnowflakeId()
{
var id = SnowFlakeSingle.instance.getID();
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
var snowProperty=entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType);
Check.Exception(snowProperty==null, "The entity sets the primary key and is long");
Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true");
foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it=>it.PropertyName==snowProperty.PropertyName))
{
item.Value = id;
}
this.ExecuteCommand();
return id;
}
public List<long> ExecuteReturnSnowflakeIdList()
{
List<long> result = new List<long>();
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType);
Check.Exception(snowProperty == null, "The entity sets the primary key and is long");
Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true");
foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName))
{
var id = SnowFlakeSingle.instance.getID();
item.Value = id;
result.Add(id);
}
this.ExecuteCommand();
return result;
}
public async Task<long> ExecuteReturnSnowflakeIdAsync()
{
var id = SnowFlakeSingle.instance.getID();
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType);
Check.Exception(snowProperty == null, "The entity sets the primary key and is long");
Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true");
foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName))
{
item.Value = id;
}
await this.ExecuteCommandAsync();
return id;
}
public async Task<List<long>> ExecuteReturnSnowflakeIdListAsync()
{
List<long> result = new List<long>();
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
var snowProperty = entity.Columns.FirstOrDefault(it => it.IsPrimarykey && it.PropertyInfo.PropertyType == UtilConstants.LongType);
Check.Exception(snowProperty == null, "The entity sets the primary key and is long");
Check.Exception(snowProperty.IsIdentity == true, "SnowflakeId IsIdentity can't true");
foreach (var item in this.InsertBuilder.DbColumnInfoList.Where(it => it.PropertyName == snowProperty.PropertyName))
{
var id = SnowFlakeSingle.instance.getID();
item.Value = id;
result.Add(id);
}
await this.ExecuteCommandAsync();
return result;
}
public virtual T ExecuteReturnEntity()
{
@@ -439,12 +498,26 @@ namespace SqlSugar
}
else
{
DataAop(item);
SetInsertItemByEntity(i, item, insertItem);
}
this.InsertBuilder.DbColumnInfoList.AddRange(insertItem);
++i;
}
}
private void DataAop(T item)
{
var dataEvent=this.Context.CurrentConnectionConfig.AopEvents?.DataExecuting;
if (dataEvent != null && item != null)
{
foreach (var columnInfo in this.EntityInfo.Columns)
{
dataEvent(columnInfo.PropertyInfo.GetValue(item, null), new DataFilterModel() { OperationType = DataFilterType.InsertByObject,EntityValue=item, EntityColumnInfo = columnInfo });
}
}
}
private void SetInsertItemByDic(int i, T item, List<DbColumnInfo> insertItem)
{
foreach (var column in item as Dictionary<string, object>)

View File

@@ -395,12 +395,20 @@ namespace SqlSugar
}
}
cons.ConditionalList.Add(new KeyValuePair<WhereType, ConditionalModel>(WhereType, new ConditionalModel()
var data = new KeyValuePair<WhereType, ConditionalModel>(WhereType, new ConditionalModel()
{
ConditionalType = ConditionalType.Equal,
FieldName = column.DbColumnName,
FieldValue = value.ObjToString()
}));
});
cons.ConditionalList.Add(data);
if (this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL)
{
data.Value.FieldValueConvertFunc = it =>
{
return UtilMethods.ChangeType2(it, value.GetType());
};
}
}
}
if (cons.HasValue())
@@ -926,6 +934,22 @@ namespace SqlSugar
var list= this.ToPivotList(columnSelector, rowSelector, dataSelector);
return this.Context.Utilities.SerializeObject(list);
}
public List<T> ToChildList(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue)
{
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
Check.Exception(entity.Columns.Where(it => it.IsPrimarykey).Count() == 0, "No Primary key");
var pk = entity.Columns.Where(it => it.IsPrimarykey).First().PropertyName;
var list = this.ToList();
return GetChildList(parentIdExpression, pk, list, primaryKeyValue);
}
public async Task<List<T>> ToChildListAsync(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue)
{
var entity = this.Context.EntityMaintenance.GetEntityInfo<T>();
Check.Exception(entity.Columns.Where(it => it.IsPrimarykey).Count() == 0, "No Primary key");
var pk = entity.Columns.Where(it => it.IsPrimarykey).First().PropertyName;
var list = await this.ToListAsync();
return GetChildList(parentIdExpression,pk,list, primaryKeyValue);
}
public List<T> ToParentList(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue)
{
List<T> result = new List<T>() { };
@@ -1031,9 +1055,9 @@ namespace SqlSugar
public virtual DataTable ToDataTablePage(int pageIndex, int pageSize, ref int totalNumber)
{
_RestoreMapping = false;
totalNumber = this.Count();
totalNumber = this.Clone().Count();
_RestoreMapping = true;
var result = ToDataTablePage(pageIndex, pageSize);
var result = this.Clone().ToDataTablePage(pageIndex, pageSize);
return result;
}
public virtual DataTable ToDataTablePage(int pageIndex, int pageSize, ref int totalNumber, ref int totalPage)
@@ -1440,6 +1464,41 @@ namespace SqlSugar
#endregion
#region Private Methods
private List<T> GetChildList(Expression<Func<T, object>> parentIdExpression, string pkName, List<T> list, object rootValue,bool isRoot=true)
{
var exp = (parentIdExpression as LambdaExpression).Body;
if (exp is UnaryExpression)
{
exp = (exp as UnaryExpression).Operand;
}
var parentIdName = (exp as MemberExpression).Member.Name;
List<T> result = list.Where(it =>
{
var parentValue = it.GetType().GetProperty(parentIdName).GetValue(it);
return parentValue.ObjToString() == rootValue.ObjToString();
}).ToList();
if (result != null && result.Count > 0)
{
List<T> childList = new List<T>();
foreach (var item in result)
{
var pkValue = item.GetType().GetProperty(pkName).GetValue(item);
childList.AddRange(GetChildList(parentIdExpression, pkName, list, pkValue,false));
}
result.AddRange(childList);
}
if (isRoot)
{
result.AddRange(list.Where(it =>
{
var pkValue = it.GetType().GetProperty(pkName).GetValue(it);
return pkValue.ObjToString() == rootValue.ObjToString();
}).ToList());
}
return result;
}
private List<T> GetTreeRoot(Expression<Func<T, IEnumerable<object>>> childListExpression, Expression<Func<T, object>> parentIdExpression, string pk, List<T> list,object rootValue)
{
var childName = ((childListExpression as LambdaExpression).Body as MemberExpression).Member.Name;
@@ -1531,6 +1590,10 @@ namespace SqlSugar
result.SqlBuilder = this.SqlBuilder;
result.SqlBuilder.QueryBuilder.Parameters = QueryBuilder.Parameters;
result.SqlBuilder.QueryBuilder.SelectValue = expression;
if (this.IsCache)
{
result.WithCache(this.CacheTime);
}
return result;
}
protected void _Where(Expression expression)
@@ -2340,8 +2403,8 @@ namespace SqlSugar
asyncQueryableBuilder.WhereIndex = this.QueryBuilder.WhereIndex;
asyncQueryableBuilder.HavingInfos = this.QueryBuilder.HavingInfos;
asyncQueryableBuilder.LambdaExpressions.ParameterIndex = this.QueryBuilder.LambdaExpressions.ParameterIndex;
asyncQueryableBuilder.IgnoreColumns = this.QueryBuilder.IgnoreColumns;
asyncQueryableBuilder.AsTables = this.QueryBuilder.AsTables;
asyncQueryableBuilder.IgnoreColumns = this.Context.Utilities.TranslateCopy(this.QueryBuilder.IgnoreColumns);
asyncQueryableBuilder.AsTables = this.Context.Utilities.TranslateCopy(this.QueryBuilder.AsTables);
asyncQueryableBuilder.DisableTop = this.QueryBuilder.DisableTop;
asyncQueryableBuilder.Offset = this.QueryBuilder.Offset;
}

View File

@@ -74,9 +74,11 @@ namespace SqlSugar
private void Each<Y>(StringBuilder sb, List<Y> list)
{
int i = 0;
foreach (var item in list)
{
var isLast = list.IndexOf(item) == list.Count - 1;
++i;
var isLast = i == list.Count ;
var isClass = typeof(T).IsClass();
if (isClass)
{

View File

@@ -189,7 +189,7 @@ namespace SqlSugar
}
}
private static void SetConditList(List<StorageableInfo<T>> itemList, List<EntityColumnInfo> whereColumns, List<IConditionalModel> conditList)
private void SetConditList(List<StorageableInfo<T>> itemList, List<EntityColumnInfo> whereColumns, List<IConditionalModel> conditList)
{
;
foreach (var dataItem in itemList)
@@ -202,11 +202,14 @@ namespace SqlSugar
int i = 0;
foreach (var item in whereColumns)
{
var value = item.PropertyInfo.GetValue(dataItem.Item, null);
condition.ConditionalList.Add(new KeyValuePair<WhereType, ConditionalModel>(i==0?WhereType.Or :WhereType.And, new ConditionalModel()
{
FieldName = item.DbColumnName,
ConditionalType = ConditionalType.Equal,
FieldValue = item.PropertyInfo.GetValue(dataItem.Item, null) + ""
FieldValue = value + "",
FieldValueConvertFunc=this.Context.CurrentConnectionConfig.DbType==DbType.PostgreSQL?
UtilMethods.GetTypeConvert(value):null
}));
++i;
}

View File

@@ -357,6 +357,8 @@ namespace SqlSugar
}
else if (isMain)
{
if (TableShortName == null)
return;
var shortName = this.Builder.GetTranslationColumnName(TableShortName) + ".";
sql = sql.Replace(itName, shortName);
}
@@ -646,6 +648,10 @@ namespace SqlSugar
private string GetTableName(string entityName)
{
if (this.AsTables != null && this.AsTables.Any(it=>it.Key==entityName))
{
entityName = this.AsTables.First(it => it.Key == entityName).Value;
}
var result = this.Context.EntityMaintenance.GetTableName(entityName);
return this.Builder.GetTranslationTableName(result);
}

View File

@@ -390,6 +390,7 @@ namespace SqlSugar
ILambdaExpressions expressionContext = sqlBuilder.QueryBuilder.LambdaExpressions;
expressionContext.MappingColumns = this.MappingColumns;
expressionContext.MappingTables = this.MappingTables;
expressionContext.IsSingle = false;
if (this.Context.CurrentConnectionConfig.MoreSettings != null)
{
expressionContext.PgSqlIsAutoToLower = this.Context.CurrentConnectionConfig.MoreSettings.PgSqlIsAutoToLower;

View File

@@ -345,14 +345,6 @@ namespace SqlSugar
UpdateBuilder.WhereValues.Add(whereString);
return this;
}
public IUpdateable<T> Where(List<IConditionalModel> conditionalModels)
{
Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Length > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns"));
var sql = this.Context.Queryable<T>().SqlBuilder.ConditionalModelToSql(conditionalModels);
var result = this;
result.Where(sql.Key, sql.Value);
return result;
}
public IUpdateable<T> Where(string whereSql, object parameters = null)
{
Check.Exception(UpdateObjectNotWhere() && UpdateObjs.Length > 1, ErrorMessage.GetThrowMessage("update List no support where", "集合更新不支持Where请使用WhereColumns"));
@@ -448,12 +440,26 @@ namespace SqlSugar
}
else
{
DataAop(item);
SetUpdateItemByEntity(i, item, updateItem);
}
++i;
}
this.columns = this.UpdateBuilder.DbColumnInfoList;
}
private void DataAop(T item)
{
var dataEvent = this.Context.CurrentConnectionConfig.AopEvents?.DataExecuting;
if (dataEvent != null && item != null)
{
foreach (var columnInfo in this.EntityInfo.Columns)
{
dataEvent(columnInfo.PropertyInfo.GetValue(item, null), new DataFilterModel() { OperationType = DataFilterType.UpdateByObject, EntityValue = item, EntityColumnInfo = columnInfo });
}
}
}
private void CheckTranscodeing(bool checkIsJson = true)
{
if (this.EntityInfo.Columns.Any(it => it.IsTranscoding))

View File

@@ -0,0 +1,21 @@
using System;
namespace SqlSugar.DistributedSystem.Snowflake
{
public class DisposableAction : IDisposable
{
readonly Action _action;
public DisposableAction(Action action)
{
if (action == null)
throw new ArgumentNullException("action");
_action = action;
}
public void Dispose()
{
_action();
}
}
}

View File

@@ -0,0 +1,118 @@
/** Copyright 2010-2012 Twitter, Inc.*/
/**
* An object that generates IDs.
* This is broken into a separate class in case
* we ever want to support multiple worker threads
* per process
*/
using System;
namespace SqlSugar.DistributedSystem.Snowflake
{
public class IdWorker
{
public const long Twepoch = 1288834974657L;
const int WorkerIdBits = 5;
const int DatacenterIdBits = 5;
const int SequenceBits = 12;
const long MaxWorkerId = -1L ^ (-1L << WorkerIdBits);
const long MaxDatacenterId = -1L ^ (-1L << DatacenterIdBits);
private const int WorkerIdShift = SequenceBits;
private const int DatacenterIdShift = SequenceBits + WorkerIdBits;
public const int TimestampLeftShift = SequenceBits + WorkerIdBits + DatacenterIdBits;
private const long SequenceMask = -1L ^ (-1L << SequenceBits);
private long _sequence = 0L;
private long _lastTimestamp = -1L;
public IdWorker(long workerId, long datacenterId, long sequence = 0L)
{
WorkerId = workerId;
DatacenterId = datacenterId;
_sequence = sequence;
// sanity check for workerId
if (workerId > MaxWorkerId || workerId < 0)
{
throw new ArgumentException( String.Format("worker Id can't be greater than {0} or less than 0", MaxWorkerId) );
}
if (datacenterId > MaxDatacenterId || datacenterId < 0)
{
throw new ArgumentException( String.Format("datacenter Id can't be greater than {0} or less than 0", MaxDatacenterId));
}
//log.info(
// String.Format("worker starting. timestamp left shift {0}, datacenter id bits {1}, worker id bits {2}, sequence bits {3}, workerid {4}",
// TimestampLeftShift, DatacenterIdBits, WorkerIdBits, SequenceBits, workerId)
// );
}
public long WorkerId {get; protected set;}
public long DatacenterId {get; protected set;}
public long Sequence
{
get { return _sequence; }
internal set { _sequence = value; }
}
// def get_timestamp() = System.currentTimeMillis
readonly object _lock = new Object();
public virtual long NextId()
{
lock(_lock)
{
var timestamp = TimeGen();
if (timestamp < _lastTimestamp)
{
//exceptionCounter.incr(1);
//log.Error("clock is moving backwards. Rejecting requests until %d.", _lastTimestamp);
throw new InvalidSystemClock(String.Format(
"Clock moved backwards. Refusing to generate id for {0} milliseconds", _lastTimestamp - timestamp));
}
if (_lastTimestamp == timestamp)
{
_sequence = (_sequence + 1) & SequenceMask;
if (_sequence == 0)
{
timestamp = TilNextMillis(_lastTimestamp);
}
} else {
_sequence = 0;
}
_lastTimestamp = timestamp;
var id = ((timestamp - Twepoch) << TimestampLeftShift) |
(DatacenterId << DatacenterIdShift) |
(WorkerId << WorkerIdShift) | _sequence;
return id;
}
}
protected virtual long TilNextMillis(long lastTimestamp)
{
var timestamp = TimeGen();
while (timestamp <= lastTimestamp)
{
timestamp = TimeGen();
}
return timestamp;
}
protected virtual long TimeGen()
{
return System.CurrentTimeMillis();
}
}
}

View File

@@ -0,0 +1,9 @@
using System;
namespace SqlSugar.DistributedSystem.Snowflake
{
public class InvalidSystemClock : Exception
{
public InvalidSystemClock(string message) : base(message) { }
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public sealed class SnowFlakeSingle
{
public static readonly SnowFlakeSingle instance = new SnowFlakeSingle();
private SnowFlakeSingle()
{
worker = new DistributedSystem.Snowflake.IdWorker(1, 1);
}
static SnowFlakeSingle() { }
public static SnowFlakeSingle Instance
{
get { return instance; }
}
private DistributedSystem.Snowflake.IdWorker worker;
public long getID()
{
return worker.NextId();
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
namespace SqlSugar.DistributedSystem.Snowflake
{
public static class System
{
public static Func<long> currentTimeFunc = InternalCurrentTimeMillis;
public static long CurrentTimeMillis()
{
return currentTimeFunc();
}
public static IDisposable StubCurrentTime(Func<long> func)
{
currentTimeFunc = func;
return new DisposableAction(() =>
{
currentTimeFunc = InternalCurrentTimeMillis;
});
}
public static IDisposable StubCurrentTime(long millis)
{
currentTimeFunc = () => millis;
return new DisposableAction(() =>
{
currentTimeFunc = InternalCurrentTimeMillis;
});
}
private static readonly DateTime Jan1st1970 = new DateTime
(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static long InternalCurrentTimeMillis()
{
return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
}
}
}

View File

@@ -22,8 +22,6 @@ namespace SqlSugar
public string FieldName { get; set; }
public string FieldValue { get; set; }
public ConditionalType ConditionalType { get; set; }
[System.Text.Json.Serialization.JsonIgnoreAttribute]
[Newtonsoft.Json.JsonIgnoreAttribute]
public Func<string,object> FieldValueConvertFunc { get; set; }
}
}

View File

@@ -65,6 +65,8 @@ namespace SqlSugar
public Action<string, SugarParameter[]> OnLogExecuting { get; set; }
public Action<string, SugarParameter[]> OnLogExecuted { get; set; }
public Func<string, SugarParameter[], KeyValuePair<string, SugarParameter[]>> OnExecutingChangeSql { get; set; }
public Action<object, DataFilterModel> DataExecuting { get; set; }
}
public class ConfigureExternalServices
{

View File

@@ -13,6 +13,6 @@ namespace SqlSugar
/// <summary>
/// output
/// </summary>
public int PageCount { get; set; }
public int TotalCount { get; set; }
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public enum DataFilterType
{
UpdateByObject = 0,
InsertByObject = 1
}
public class DataFilterModel
{
public DataFilterType OperationType { get; set; }
public EntityColumnInfo EntityColumnInfo { get; set; }
public object EntityValue { get; set; }
public string PropertyName { get { return EntityColumnInfo.PropertyInfo.Name; } }
public string EntityName { get { return EntityColumnInfo.EntityName; } }
public void SetValue(object value)
{
var type = EntityColumnInfo.PropertyInfo.PropertyType;
if (value != null && value.GetType() != type)
{
value = UtilMethods.ChangeType2(value, type);
}
this.EntityColumnInfo.PropertyInfo.SetValue(EntityValue, value);
}
}
}

View File

@@ -470,5 +470,12 @@ namespace SqlSugar
var parameter3 = model.Args[2];
return string.Format(" DATEDIFF({0},{1},{2}) ", parameter.MemberValue?.ToString().ToSqlFilter(), parameter2.MemberName, parameter3.MemberName); ;
}
public string Format(MethodCallExpressionModel model)
{
var str = model.Args[0].MemberValue.ObjToString();
var array = model.Args.Skip(1).Select(it => it.IsMember?it.MemberName:it.MemberValue).ToArray();
return string.Format("'"+str+ "'", array);
}
}
}

View File

@@ -72,5 +72,6 @@ namespace SqlSugar
string Oracle_ToDate(MethodCallExpressionModel model);
string Oracle_ToChar(MethodCallExpressionModel model);
string SqlServer_DateDiff(MethodCallExpressionModel model);
string Format(MethodCallExpressionModel model);
}
}

View File

@@ -115,7 +115,15 @@ namespace SqlSugar
case ResolveExpressType.ArrayMultiple:
case ResolveExpressType.ArraySingle:
fieldName = GetName(parameter, expression, isLeft, parameter.Context.ResolveType == ResolveExpressType.ArraySingle);
base.Context.Result.Append(fieldName);
var fieldIsCommonTemp3 = IsFieldIsCommonTemp(isSetTempData, parameter);
if (fieldIsCommonTemp3)
{
baseParameter.CommonTempData = fieldName;
}
else
{
base.Context.Result.Append(fieldName);
}
break;
default:
break;
@@ -128,7 +136,8 @@ namespace SqlSugar
return false;
var childExpression= parameter.BaseParameter.ChildExpression.ObjToString();
var expression=parameter.BaseParameter.CurrentExpression.ObjToString();
return isSetTempData&&((childExpression+".Date")==expression);
var datevaluelist = UtilConstants.DateTypeStringList.Select(it => childExpression+"." + it);
return isSetTempData&& datevaluelist.Contains(expression);
}
#endregion

View File

@@ -87,7 +87,7 @@ namespace SqlSugar
var result = this.Context.DbMehtods.IIF(new MethodCallExpressionModel()
{
Args = new List<MethodCallExpressionArgs>() {
new MethodCallExpressionArgs(){ IsMember=true, MemberName=parameter.CommonTempData.ObjToString()+"=1" },
new MethodCallExpressionArgs(){ IsMember=true, MemberName=parameter.CommonTempData.ObjToString()+"=1",Type=UtilConstants.BoolType },
new MethodCallExpressionArgs(){ IsMember=true,MemberName=AppendParameter(0) },
new MethodCallExpressionArgs(){ IsMember=true, MemberName=AppendParameter(1) }
}

View File

@@ -753,6 +753,10 @@ namespace SqlSugar
var isValid = model.Args[0].IsMember && model.Args[1].IsMember == false;
//Check.Exception(!isValid, "SqlFunc.MappingColumn parameters error, The property name on the left, string value on the right");
this.Context.Parameters.RemoveAll(it => it.ParameterName == model.Args[1].MemberName.ObjToString());
if (mappingColumnResult == "")
{
return model.Args[1].MemberName.ObjToString().TrimStart('\'').TrimEnd('\'');
}
return mappingColumnResult;
case "IsNull":
return this.Context.DbMehtods.IsNull(model);
@@ -780,6 +784,11 @@ namespace SqlSugar
return this.Context.DbMehtods.Oracle_ToDate(model);
case "SqlServer_DateDiff":
return this.Context.DbMehtods.SqlServer_DateDiff(model);
case "Format":
var xx=base.BaseParameter;
var result = this.Context.DbMehtods.Format(model);
this.Context.Parameters.RemoveAll(it => model.Args.Select(x=>x.MemberName.ObjToString()).Contains(it.ParameterName) );
return result;
default:
break;
}
@@ -802,6 +811,10 @@ namespace SqlSugar
{
return true;
}
if (expression.Method.Name == "Format" && expression.Method.DeclaringType == UtilConstants.StringType)
{
return true;
}
if (IsExtMethod(expression.Method.Name))
return true;
if (IsParseMethod(expression))

View File

@@ -150,7 +150,7 @@ namespace SqlSugar
var result= this.Context.DbMehtods.IIF(new MethodCallExpressionModel()
{
Args = new List<MethodCallExpressionArgs>() {
new MethodCallExpressionArgs(){ IsMember=true, MemberName=parameter.CommonTempData.ObjToString()+"=1" },
new MethodCallExpressionArgs(){ IsMember=true, MemberName=parameter.CommonTempData.ObjToString()+"=1",Type=UtilConstants.BoolType },
new MethodCallExpressionArgs(){ IsMember=true,MemberName=AppendParameter(0) },
new MethodCallExpressionArgs(){ IsMember=true, MemberName=AppendParameter(1) }
}

View File

@@ -30,7 +30,6 @@ namespace SqlSugar
IDeleteable<T> Where(string whereString, SugarParameter[] parameters);
IDeleteable<T> Where(string whereString, List<SugarParameter> parameters);
IDeleteable<T> WhereColumns(Expression<Func<T, object>> columns);
IDeleteable<T> Where(List<IConditionalModel> conditionalModels);
IDeleteable<T> EnableDiffLogEvent(object businessData = null);
IDeleteable<T> RemoveDataCache();
IDeleteable<T> RemoveDataCache(string likeString);

View File

@@ -143,6 +143,8 @@ namespace SqlSugar
string ToJsonPage(int pageIndex, int pageSize, ref int totalNumber);
Task<string> ToJsonPageAsync(int pageIndex, int pageSize, RefAsync<int> totalNumber);
KeyValuePair<string, List<SugarParameter>> ToSql();
List<T> ToChildList(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue);
Task<List<T>> ToChildListAsync(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue);
List<T> ToParentList(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue);
Task<List<T>> ToParentListAsync(Expression<Func<T, object>> parentIdExpression, object primaryKeyValue);
List<T> ToTree(Expression<Func<T,IEnumerable<object>>> childListExpression, Expression<Func<T,object>> parentIdExpression,object rootValue);

View File

@@ -37,6 +37,10 @@ namespace SqlSugar
bool InsertRange(T[] insertObjs);
int InsertReturnIdentity(T insertObj);
long InsertReturnBigIdentity(T insertObj);
long InsertReturnSnowflakeId(T insertObj);
List<long> InsertReturnSnowflakeId(List<T> insertObjs);
bool IsAny(Expression<Func<T, bool>> whereExpression);
bool Update(Expression<Func<T, T>> columns, Expression<Func<T, bool>> whereExpression);
bool Update(T updateObj);
@@ -64,6 +68,9 @@ namespace SqlSugar
Task<bool> InsertRangeAsync(T[] insertObjs);
Task<int> InsertReturnIdentityAsync(T insertObj);
Task<long> InsertReturnBigIdentityAsync(T insertObj);
Task<long> InsertReturnSnowflakeIdAsync(T insertObj);
Task<List<long>> InsertReturnSnowflakeIdAsync(List<T> insertObjs);
Task<bool> IsAnyAsync(Expression<Func<T, bool>> whereExpression);
Task<bool> UpdateAsync(Expression<Func<T, T>> columns, Expression<Func<T, bool>> whereExpression);
Task<bool> UpdateAsync(T updateObj);

View File

@@ -20,6 +20,7 @@ namespace SqlSugar
Task<DbResult<T>> UseTranAsync<T>(Func<T> action, Action<Exception> errorCallBack = null);
void AddConnection(ConnectionConfig connection);
SqlSugarProvider GetConnection(dynamic configId);
bool IsAnyConnection(dynamic configId);
void Close();
void Open();

View File

@@ -43,7 +43,6 @@ namespace SqlSugar
IUpdateable<T> WhereColumns(Expression<Func<T, object>> columns);
IUpdateable<T> WhereColumns(string columnName);
IUpdateable<T> WhereColumns(params string [] columnNames);
IUpdateable<T> Where(List<IConditionalModel> conditionalModels);
/// <summary>
/// .UpdateColumns(it=>new{ it.Name,it.Price})

View File

@@ -12,6 +12,10 @@ namespace SqlSugar
InsertBuilder InsertBuilder { get; set; }
int ExecuteCommand();
Task<int> ExecuteCommandAsync();
long ExecuteReturnSnowflakeId();
List<long> ExecuteReturnSnowflakeIdList();
Task<long> ExecuteReturnSnowflakeIdAsync();
Task<List<long>> ExecuteReturnSnowflakeIdListAsync();
int ExecuteReturnIdentity();
Task<int> ExecuteReturnIdentityAsync();
T ExecuteReturnEntity();

View File

@@ -81,6 +81,8 @@ namespace SqlSugar
public static List<KeyValuePair<string, CSharpDataType>> MappingTypesConst = new List<KeyValuePair<string, CSharpDataType>>()
{
new KeyValuePair<string, CSharpDataType>("int",CSharpDataType.@int),
new KeyValuePair<string, CSharpDataType>("bigint",CSharpDataType.@long),
new KeyValuePair<string, CSharpDataType>("tinyint",CSharpDataType.@short),
new KeyValuePair<string, CSharpDataType>("integer",CSharpDataType.@int),
new KeyValuePair<string, CSharpDataType>("interval year to month",CSharpDataType.@int),
new KeyValuePair<string, CSharpDataType>("interval day to second",CSharpDataType.@int),

View File

@@ -28,7 +28,10 @@ namespace SqlSugar
{
get
{
return @"SELECT table_name name from user_tables where
return @"SELECT table_name name ,
(select COMMENTS from user_tab_comments where t.table_name=table_name ) as Description
from user_tables t where
table_name!='HELP'
AND table_name NOT LIKE '%$%'
AND table_name NOT LIKE 'LOGMNRC_%'

View File

@@ -47,7 +47,7 @@ namespace SqlSugar
{
externalOrderBy = " ORDER BY "+ this.Builder.SqlDateNow + " ";
}
result = string.Format("SELECT *,ROW_NUMBER() OVER({0}) AS RowIndex2 FROM ({1}) ExternalTable ", GetExternalOrderBy(externalOrderBy), result);
result = string.Format("SELECT ExternalTable.*,ROW_NUMBER() OVER({0}) AS RowIndex2 FROM ({1}) ExternalTable ", GetExternalOrderBy(externalOrderBy), result);
result = ToPageSql2(result, ExternalPageIndex, ExternalPageSize, true);
}
this.OrderByValue = oldOrderBy;

View File

@@ -27,6 +27,11 @@ namespace SqlSugar
}
else if (propertyTypes == null || propertyTypes.Count() == 0)
{
if (dbTypeName.StartsWith("_"))
{
var dbTypeName2 = dbTypeName.TrimStart('_');
return MappingTypes.Where(it => it.Value.ToString().ToLower() == dbTypeName2 || it.Key.ToLower() == dbTypeName2).Select(it => it.Value + "[]").First();
}
Check.ThrowNotSupportedException(string.Format(" \"{0}\" Type NotSupported, DbBindProvider.GetPropertyTypeName error.", dbTypeName));
return null;
}

View File

@@ -53,6 +53,14 @@ namespace SqlSugar
else if (isMapping)
{
var mappingInfo = this.MappingTables.FirstOrDefault(it => it.EntityName.Equals(entityName, StringComparison.CurrentCultureIgnoreCase));
var tableName = mappingInfo.DbTableName+"";
if (tableName.Contains("."))
{
tableName = string.Join(UtilConstants.Dot, tableName.Split(UtilConstants.DotChar).Select(it => GetTranslationText(it)));
return tableName;
}
return SqlTranslationLeft + (mappingInfo == null ? entityName : mappingInfo.DbTableName).ToLower(isAutoToLower) + SqlTranslationRight;
}
else if (isComplex)
@@ -96,6 +104,19 @@ namespace SqlSugar
}
public class PostgreSQLMethod : DefaultDbMethod, IDbMethods
{
public override string IIF(MethodCallExpressionModel model)
{
var parameter = model.Args[0];
var parameter2 = model.Args[1];
var parameter3 = model.Args[2];
if (parameter.Type == UtilConstants.BoolType)
{
parameter.MemberName = parameter.MemberName.ToString().Replace("=1", "=true");
parameter2.MemberName = false;
parameter3.MemberName = true;
}
return string.Format("( CASE WHEN {0} THEN {1} ELSE {2} END )", parameter.MemberName, parameter2.MemberName, parameter3.MemberName);
}
public override string DateValue(MethodCallExpressionModel model)
{
var parameter = model.Args[0];

View File

@@ -313,6 +313,21 @@ namespace SqlSugar
#endregion
#region Methods
public override bool AddDefaultValue(string tableName, string columnName, string defaultValue)
{
if (defaultValue == "''")
{
defaultValue = "";
}
var template = AddDefaultValueSql;
if (defaultValue != null && defaultValue.ToLower() == "getdate()")
{
template = template.Replace("'{2}'", "{2}");
}
string sql = string.Format(template, tableName, columnName, defaultValue);
this.Context.Ado.ExecuteCommand(sql);
return true;
}
/// <summary>
///by current connection string

View File

@@ -102,28 +102,28 @@ namespace SqlSugar
{
int count = 0;
var result = Context.Queryable<T>().Where(whereExpression).ToPageList(page.PageIndex, page.PageSize, ref count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
int count = 0;
var result = Context.Queryable<T>().OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToPageList(page.PageIndex, page.PageSize, ref count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual List<T> GetPageList(List<IConditionalModel> conditionalList, PageModel page)
{
int count = 0;
var result = Context.Queryable<T>().Where(conditionalList).ToPageList(page.PageIndex, page.PageSize, ref count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual List<T> GetPageList(List<IConditionalModel> conditionalList, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
int count = 0;
var result = Context.Queryable<T>().OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(conditionalList).ToPageList(page.PageIndex, page.PageSize, ref count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual bool IsAny(Expression<Func<T, bool>> whereExpression)
@@ -148,6 +148,22 @@ namespace SqlSugar
{
return this.Context.Insertable(insertObj).ExecuteReturnBigIdentity();
}
public virtual long InsertReturnSnowflakeId(T insertObj)
{
return this.Context.Insertable(insertObj).ExecuteReturnSnowflakeId();
}
public virtual List<long> InsertReturnSnowflakeId(List<T> insertObjs)
{
return this.Context.Insertable(insertObjs).ExecuteReturnSnowflakeIdList();
}
public virtual Task<long> InsertReturnSnowflakeIdAsync(T insertObj)
{
return this.Context.Insertable(insertObj).ExecuteReturnSnowflakeIdAsync();
}
public virtual Task<List<long>> InsertReturnSnowflakeIdAsync(List<T> insertObjs)
{
return this.Context.Insertable(insertObjs).ExecuteReturnSnowflakeIdListAsync();
}
public virtual bool InsertRange(T[] insertObjs)
{
return this.Context.Insertable(insertObjs).ExecuteCommand() > 0;
@@ -212,28 +228,28 @@ namespace SqlSugar
{
RefAsync<int> count = 0;
var result =await Context.Queryable<T>().Where(whereExpression).ToPageListAsync(page.PageIndex, page.PageSize, count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual async Task<List<T>> GetPageListAsync(Expression<Func<T, bool>> whereExpression, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
RefAsync<int> count = 0;
var result =await Context.Queryable<T>().OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(whereExpression).ToPageListAsync(page.PageIndex, page.PageSize, count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual async Task<List<T>> GetPageListAsync(List<IConditionalModel> conditionalList, PageModel page)
{
RefAsync<int> count = 0;
var result =await Context.Queryable<T>().Where(conditionalList).ToPageListAsync(page.PageIndex, page.PageSize, count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual async Task<List<T>> GetPageListAsync(List<IConditionalModel> conditionalList, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
{
RefAsync<int> count = 0;
var result =await Context.Queryable<T>().OrderByIF(orderByExpression != null, orderByExpression, orderByType).Where(conditionalList).ToPageListAsync(page.PageIndex, page.PageSize, count);
page.PageCount = count;
page.TotalCount = count;
return result;
}
public virtual Task<bool> IsAnyAsync(Expression<Func<T, bool>> whereExpression)

View File

@@ -610,6 +610,13 @@ namespace SqlSugar
}
return db.Context;
}
public bool IsAnyConnection(dynamic configId)
{
InitTenant();
var db = this._AllClients.FirstOrDefault(it => Convert.ToString(it.ConnectionConfig.ConfigId) == Convert.ToString(configId));
return db != null;
}
public void ChangeDatabase(dynamic configId)
{
configId =Convert.ToString(configId);

View File

@@ -671,5 +671,10 @@ namespace SqlSugar
{
return ScopedContext.UseTranAsync(action, errorCallBack);
}
public bool IsAnyConnection(dynamic configId)
{
return ScopedContext.IsAnyConnection(configId);
}
}
}

View File

@@ -56,5 +56,18 @@ namespace SqlSugar
typeof(short),
typeof(ushort),
};
internal static string[] DateTypeStringList = new string[]
{
"Year",
"Month",
"Day",
"Hour",
"Second" ,
"Minute",
"Millisecond",
"Date"
};
}
}

View File

@@ -73,7 +73,7 @@ namespace SqlSugar
return true;
}
}
var name= method.Name;
var name = method.Name;
if (name.Contains("OutputAsyncCausalityEvents"))
{
return true;
@@ -86,7 +86,7 @@ namespace SqlSugar
{
return true;
}
Type attType = typeof(AsyncStateMachineAttribute);
Type attType = typeof(AsyncStateMachineAttribute);
var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);
return (attrib != null);
}
@@ -101,7 +101,7 @@ namespace SqlSugar
for (int i = 0; i < st.FrameCount; i++)
{
var frame = st.GetFrame(i);
if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll"&& frame.GetMethod().Name.First()!='<')
if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll" && frame.GetMethod().Name.First() != '<')
{
info.MyStackTraceList.Add(new StackTraceInfoItem()
{
@@ -139,11 +139,11 @@ namespace SqlSugar
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\,", "\\" + itemParameter.ParameterName), newName + ",", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}$", "\\" + itemParameter.ParameterName), newName, RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\+{0}\+", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName +" ", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName)," "+ newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName + " ", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName), " " + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\|\|{0}\|\|", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\={0}\+", "\\" + itemParameter.ParameterName), "=" + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "+", RegexOptions.IgnoreCase);
return itemSql;
}
internal static Type GetRootBaseType(Type entityType)
@@ -191,7 +191,7 @@ namespace SqlSugar
}
return returnObj;
}
public static object ChangeType2(object value, Type type)
public static object ChangeType2(object value, Type type)
{
if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
if (value == null) return null;
@@ -252,6 +252,31 @@ namespace SqlSugar
return string.Format(" ({0}) {1} ", sql, shortName);
}
public static Func<string, object> GetTypeConvert(object value)
{
if (value is int || value is uint || value is int? || value is uint?)
{
return x => Convert.ToInt32(x);
}
else if (value is short || value is ushort || value is short? || value is ushort?)
{
return x => Convert.ToInt16(x);
}
else if (value is long || value is long? || value is ulong? || value is long?)
{
return x => Convert.ToInt64(x);
}
else if (value is DateTime|| value is DateTime?)
{
return x => Convert.ToDateTime(x);
}
else if (value is bool||value is bool?)
{
return x => Convert.ToBoolean(x);
}
return null;
}
internal static string GetParenthesesValue(string dbTypeName)
{
if (Regex.IsMatch(dbTypeName, @"\(.+\)"))