Update core

This commit is contained in:
sunkaixuan
2019-01-12 19:28:16 +08:00
parent 1d69d62918
commit cf43725b2d
20 changed files with 259 additions and 39 deletions

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
@@ -284,6 +285,7 @@ namespace SqlSugar
{
try
{
InitParameters(ref sql, parameters);
if (FormatSql != null)
sql = FormatSql(sql);
SetConnectionStart(sql);
@@ -313,6 +315,7 @@ namespace SqlSugar
{
try
{
InitParameters(ref sql, parameters);
if (FormatSql != null)
sql = FormatSql(sql);
SetConnectionStart(sql);
@@ -341,6 +344,7 @@ namespace SqlSugar
{
try
{
InitParameters(ref sql, parameters);
if (FormatSql != null)
sql = FormatSql(sql);
SetConnectionStart(sql);
@@ -373,6 +377,7 @@ namespace SqlSugar
{
try
{
InitParameters(ref sql,parameters);
if (FormatSql != null)
sql = FormatSql(sql);
SetConnectionStart(sql);
@@ -791,6 +796,37 @@ namespace SqlSugar
{
ErrorEvent(new SqlSugarException(this.Context,ex, sql, parameters));
}
private void InitParameters(ref string sql, SugarParameter[] parameters)
{
if (parameters.HasValue())
{
foreach (var item in parameters)
{
if (item.Value != null)
{
var type = item.Value.GetType();
if ((type != UtilConstants.ByteArrayType && type.IsArray) || type.FullName.IsCollectionsList())
{
var newValues = new List<string>();
foreach (var inValute in item.Value as IEnumerable)
{
newValues.Add(inValute.ObjToString());
}
if (newValues.IsNullOrEmpty())
{
newValues.Add("-1");
}
if (item.ParameterName.Substring(0, 1) == ":")
{
sql = sql.Replace("@"+item.ParameterName.Substring(1), newValues.ToArray().ToJoinSqlInVals());
}
sql = sql.Replace(item.ParameterName, newValues.ToArray().ToJoinSqlInVals());
item.Value = DBNull.Value;
}
}
}
}
}
#endregion
}
}

View File

@@ -462,7 +462,7 @@ namespace SqlSugar
List<DiffLogTableInfo> result = new List<DiffLogTableInfo>();
var whereSql = string.Empty;
List<IConditionalModel> cons = new List<IConditionalModel>();
if (identity != null&&identity>0)
if (identity != null&&identity>0 && GetIdentityKeys().HasValue())
{
var fieldName = GetIdentityKeys().Last();
cons.Add(new ConditionalModel() { ConditionalType=ConditionalType.Equal, FieldName= fieldName, FieldValue=identity.ToString() });

View File

@@ -570,7 +570,16 @@ namespace SqlSugar
}
public virtual string ToJson()
{
return this.Context.Utilities.SerializeObject(this.ToList());
if (IsCache)
{
var cacheService = this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService;
var result = CacheSchemeMain.GetOrCreate<string>(cacheService, this.QueryBuilder, () => { return this.Context.Utilities.SerializeObject(this.ToList()); }, CacheTime, this.Context);
return result;
}
else
{
return this.Context.Utilities.SerializeObject(this.ToList());
}
}
public virtual string ToJsonPage(int pageIndex, int pageSize)
{
@@ -586,7 +595,16 @@ namespace SqlSugar
InitMapping();
var sqlObj = this.ToSql();
RestoreMapping();
var result = this.Db.GetDataTable(sqlObj.Key, sqlObj.Value.ToArray());
DataTable result = null;
if (IsCache)
{
var cacheService = this.Context.CurrentConnectionConfig.ConfigureExternalServices.DataInfoCacheService;
result = CacheSchemeMain.GetOrCreate<DataTable>(cacheService, this.QueryBuilder, () => { return this.Db.GetDataTable(sqlObj.Key, sqlObj.Value.ToArray()); }, CacheTime, this.Context);
}
else
{
result = this.Db.GetDataTable(sqlObj.Key, sqlObj.Value.ToArray());
}
return result;
}
public virtual DataTable ToDataTablePage(int pageIndex, int pageSize)
@@ -1298,6 +1316,10 @@ namespace SqlSugar
var asyncContext = this.Context.Utilities.CopyContext(true);
asyncContext.CurrentConnectionConfig.IsAutoCloseConnection = true;
var asyncQueryable = asyncContext.Queryable<ExpandoObject>().Select<T>(string.Empty).WithCacheIF(IsCache, CacheTime);
if (this.MapperAction != null)
asyncQueryable.Mapper(MapperAction);
if (this.MapperActionWithCache != null)
asyncQueryable.Mapper(MapperActionWithCache);
CopyQueryBuilder(asyncQueryable.QueryBuilder); return asyncQueryable;
}

View File

@@ -395,8 +395,15 @@ namespace SqlSugar
{
var expression = this.SelectValue as Expression;
var result = GetExpressionValue(expression, this.SelectType).GetResultString();
this.SelectCacheKey = result;
return result;
if (result.Contains(".*") && this.IsSingle())
{
return "*";
}
else
{
this.SelectCacheKey = result;
return result;
}
}
public virtual string GetSelectValueByString()
{

View File

@@ -22,5 +22,6 @@ namespace SqlSugar
public string FieldName { get; set; }
public string FieldValue { get; set; }
public ConditionalType ConditionalType { get; set; }
public Func<string,object> FieldValueConvertFunc { get; set; }
}
}

View File

@@ -337,7 +337,8 @@ namespace SqlSugar
if (this.Context.Result.IsLockCurrentParameter == false)
{
var expression = ((UnaryExpression)item).Operand as MemberExpression;
if (expression.Expression == null)
var isDateTimeNow = ((UnaryExpression)item).Operand.ToString() == "DateTime.Now";
if (expression.Expression == null&&!isDateTimeNow)
{
this.Context.Result.CurrentParameter = parameter;
this.Context.Result.IsLockCurrentParameter = true;
@@ -348,7 +349,7 @@ namespace SqlSugar
this.Context.Result.Append(this.Context.GetAsString(asName, parameter.CommonTempData.ObjToString()));
this.Context.Result.CurrentParameter = null;
}
else if (expression.Expression is ConstantExpression)
else if (expression.Expression is ConstantExpression||isDateTimeNow)
{
string parameterName = this.Context.SqlParameterKeyWord + "constant" + this.Context.ParameterIndex;
this.Context.ParameterIndex++;

View File

@@ -50,7 +50,7 @@ namespace SqlSugar
}
var isWhere= Convert.ToBoolean(value);
if (!Convert.ToBoolean(isWhere)) {
return "";
return "WHERE 1=1 ";
}
var argExp = exp.Arguments[1];
var result = "WHERE " + SubTools.GetMethodValue(Context, argExp, ResolveExpressType.WhereMultiple); ;

View File

@@ -48,6 +48,8 @@ namespace SqlSugar
var newContext = context.GetCopyContext();
newContext.MappingColumns = context.MappingColumns;
newContext.MappingTables = context.MappingTables;
newContext.InitMappingInfo = context.InitMappingInfo;
newContext.RefreshMapping = context.RefreshMapping;
newContext.IgnoreComumnList = context.IgnoreComumnList;
newContext.SqlFuncServices = context.SqlFuncServices;
newContext.Resolve(item, type);

View File

@@ -90,7 +90,7 @@ namespace SqlSugar
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public Dictionary<string, object> DataReaderToDictionary(IDataReader reader,Type type)
public Dictionary<string, object> DataReaderToDictionary(IDataReader reader, Type type)
{
Dictionary<string, object> result = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
@@ -98,7 +98,7 @@ namespace SqlSugar
string name = reader.GetName(i);
try
{
name = this.Context.EntityMaintenance.GetPropertyName(name,type);
name = this.Context.EntityMaintenance.GetPropertyName(name, type);
var addItem = reader.GetValue(i);
if (addItem == DBNull.Value)
addItem = null;
@@ -129,7 +129,7 @@ namespace SqlSugar
{
while (reader.Read())
{
var readerValues = DataReaderToDictionary(reader,tType);
var readerValues = DataReaderToDictionary(reader, tType);
var result = new Dictionary<string, object>();
foreach (var item in classProperties)
{
@@ -143,7 +143,7 @@ namespace SqlSugar
{
if (readerValues.Any(it => it.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase)))
{
var addValue = readerValues.ContainsKey(name) ? readerValues[name] : readerValues.First(it=>it.Key.Equals(name,StringComparison.CurrentCultureIgnoreCase)).Value;
var addValue = readerValues.ContainsKey(name) ? readerValues[name] : readerValues.First(it => it.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase)).Value;
if (addValue == DBNull.Value)
{
if (item.PropertyType.IsIn(UtilConstants.IntType, UtilConstants.DecType, UtilConstants.DobType, UtilConstants.ByteType))
@@ -207,13 +207,14 @@ namespace SqlSugar
else
{
var key = typeName + "." + name;
var info = readerValues.Select(it=>it.Key).FirstOrDefault(it=>it.ToLower() == key.ToLower());
if (info!=null)
var info = readerValues.Select(it => it.Key).FirstOrDefault(it => it.ToLower() == key.ToLower());
if (info != null)
{
var addItem = readerValues[info];
if (addItem == DBNull.Value)
addItem = null;
if (prop.PropertyType == UtilConstants.IntType) {
if (prop.PropertyType == UtilConstants.IntType)
{
addItem = addItem.ObjToInt();
}
result.Add(name, addItem);
@@ -269,7 +270,7 @@ namespace SqlSugar
public SqlSugarClient CopyContext(bool isCopyEvents = false)
{
var newClient = new SqlSugarClient(this.TranslateCopy(Context.CurrentConnectionConfig));
newClient.CurrentConnectionConfig.ConfigureExternalServices=Context.CurrentConnectionConfig.ConfigureExternalServices;
newClient.CurrentConnectionConfig.ConfigureExternalServices = Context.CurrentConnectionConfig.ConfigureExternalServices;
newClient.MappingColumns = this.TranslateCopy(Context.MappingColumns);
newClient.MappingTables = this.TranslateCopy(Context.MappingTables);
newClient.IgnoreColumns = this.TranslateCopy(Context.IgnoreColumns);
@@ -349,7 +350,7 @@ namespace SqlSugar
#endregion
#region Query
public KeyValuePair<string, SugarParameter[]> ConditionalModelToSql(List<IConditionalModel> models,int beginIndex=0)
public KeyValuePair<string, SugarParameter[]> ConditionalModelToSql(List<IConditionalModel> models, int beginIndex = 0)
{
if (models.IsNullOrEmpty()) return new KeyValuePair<string, SugarParameter[]>();
StringBuilder builder = new StringBuilder();
@@ -360,21 +361,23 @@ namespace SqlSugar
if (model is ConditionalModel)
{
var item = model as ConditionalModel;
var index = models.IndexOf(item)+ beginIndex;
var index = models.IndexOf(item) + beginIndex;
var type = index == 0 ? "" : "AND";
if (beginIndex > 0) {
if (beginIndex > 0)
{
type = null;
}
string temp = " {0} {1} {2} {3} ";
string parameterName = string.Format("{0}Conditional{1}{2}", sqlBuilder.SqlParameterKeyWord, item.FieldName, index);
if (parameterName.Contains(".")) {
if (parameterName.Contains("."))
{
parameterName = parameterName.Replace(".", "_");
}
switch (item.ConditionalType)
{
case ConditionalType.Equal:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName);
parameters.Add(new SugarParameter(parameterName, item.FieldValue));
parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
break;
case ConditionalType.Like:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName);
@@ -382,19 +385,19 @@ namespace SqlSugar
break;
case ConditionalType.GreaterThan:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">", parameterName);
parameters.Add(new SugarParameter(parameterName, item.FieldValue));
parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
break;
case ConditionalType.GreaterThanOrEqual:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">=", parameterName);
parameters.Add(new SugarParameter(parameterName, item.FieldValue));
parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
break;
case ConditionalType.LessThan:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<", parameterName);
parameters.Add(new SugarParameter(parameterName, item.FieldValue));
parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
break;
case ConditionalType.LessThanOrEqual:
builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<=", parameterName);
parameters.Add(new SugarParameter(parameterName, item.FieldValue));
parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
break;
case ConditionalType.In:
if (item.FieldValue == null) item.FieldValue = string.Empty;
@@ -459,8 +462,9 @@ namespace SqlSugar
}
List<IConditionalModel> conModels = new List<IConditionalModel>();
conModels.Add(con.Value);
var childSqlInfo = ConditionalModelToSql(conModels,1000*(1+index));
if (!isFirst) {
var childSqlInfo = ConditionalModelToSql(conModels, 1000 * (1 + index));
if (!isFirst)
{
builder.AppendFormat(" {0} ", con.Key.ToString().ToUpper());
}
@@ -470,7 +474,8 @@ namespace SqlSugar
{
builder.Append(" ) ");
}
else {
else
{
}
}
@@ -479,6 +484,14 @@ namespace SqlSugar
}
return new KeyValuePair<string, SugarParameter[]>(builder.ToString(), parameters.ToArray());
}
private static object GetFieldValue(ConditionalModel item)
{
if (item.FieldValueConvertFunc != null)
return item.FieldValueConvertFunc(item.FieldValue);
else
return item.FieldValue;
}
#endregion
}
}

View File

@@ -20,7 +20,7 @@ namespace SqlSugar
var name = parameter.ParameterName;
if (!sql.Contains(name) && Regex.IsMatch(sql, "(" + name + "$)" + "|(" + name + @"[ ,\,])", RegexOptions.IgnoreCase))
{
parameter.ParameterName = Regex.Match(sql, "(" + name + "$)" + "|(" + name + @"[ ,\,])", RegexOptions.IgnoreCase).Value;
parameter.ParameterName = Regex.Match(sql, "(" + name + "$)" + "|(" + name + @"[ ,\,])", RegexOptions.IgnoreCase).Value.Trim();
}
}
}

View File

@@ -1,4 +1,6 @@
namespace SqlSugar
using System;
namespace SqlSugar
{
public class MySqlInsertBuilder : InsertBuilder
{
@@ -23,5 +25,55 @@
}
}
}
public override object FormatValue(object value)
{
if (value == null)
{
return "NULL";
}
else
{
var type = value.GetType();
if (type == UtilConstants.DateType)
{
var date = value.ObjToDate();
if (date < Convert.ToDateTime("1900-1-1"))
{
date = Convert.ToDateTime("1900-1-1");
}
return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
}
else if (type == UtilConstants.ByteArrayType)
{
string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
return bytesString;
}
else if (type.IsEnum())
{
return Convert.ToInt64(value);
}
else if (type == UtilConstants.BoolType)
{
return value.ObjToBool() ? "1" : "0";
}
else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
{
return "N'" + GetString(value).ToSqlFilter() + "'";
}
else
{
return "N'" + GetString(value) + "'";
}
}
}
private string GetString(object value)
{
var result = value.ToString();
if (result.HasValue() && result.Contains("\\"))
{
result = result.Replace("\\", "\\\\");
}
return result;
}
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -87,5 +88,55 @@ namespace SqlSugar
}
return batchUpdateSql.ToString();
}
public override object FormatValue(object value)
{
if (value == null)
{
return "NULL";
}
else
{
var type = value.GetType();
if (type == UtilConstants.DateType)
{
var date = value.ObjToDate();
if (date < Convert.ToDateTime("1900-1-1"))
{
date = Convert.ToDateTime("1900-1-1");
}
return "'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
}
else if (type == UtilConstants.ByteArrayType)
{
string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
return bytesString;
}
else if (type.IsEnum())
{
return Convert.ToInt64(value);
}
else if (type == UtilConstants.BoolType)
{
return value.ObjToBool() ? "1" : "0";
}
else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
{
return "N'" + GetString(value).ToSqlFilter() + "'";
}
else
{
return "N'" + GetString(value) + "'";
}
}
}
private string GetString(object value)
{
var result = value.ToString();
if (result.HasValue() && result.Contains("\\"))
{
result = result.Replace("\\", "\\\\");
}
return result;
}
}
}

View File

@@ -131,6 +131,39 @@ namespace SqlSugar
this.Context = context;
}
public ISugarQueryable<T> AsQueryable()
{
return Context.Queryable<T>();
}
public IInsertable<T> AsInsertable(T insertObj)
{
return Context.Insertable<T>(insertObj);
}
public IInsertable<T> AsInsertable(T[] insertObjs)
{
return Context.Insertable<T>(insertObjs);
}
public IInsertable<T> AsInsertable(List<T> insertObjs)
{
return Context.Insertable<T>(insertObjs);
}
public IUpdateable<T> AsUpdateable(T updateObj)
{
return Context.Updateable<T>(updateObj);
}
public IUpdateable<T> AsUpdateable(T[] updateObjs)
{
return Context.Updateable<T>(updateObjs);
}
public IUpdateable<T> AsUpdateable(List<T> updateObjs)
{
return Context.Updateable<T>(updateObjs);
}
public IDeleteable<T> AsDeleteable()
{
return Context.Deleteable<T>();
}
public T GetById(dynamic id)
{
return Context.Queryable<T>().InSingle(id);
@@ -154,7 +187,7 @@ namespace SqlSugar
page.PageCount = count;
return result;
}
public List<T> GetPageList(Expression<Func<T, bool>> whereExpression, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
public 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);
@@ -168,7 +201,7 @@ namespace SqlSugar
page.PageCount = count;
return result;
}
public List<T> GetPageList(List<IConditionalModel> conditionalList, PageModel page, Expression<Func<T, object>> orderByExpression = null, OrderByType orderByType = OrderByType.Asc)
public 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);
@@ -205,7 +238,7 @@ namespace SqlSugar
{
return this.Context.Updateable(updateObj).ExecuteCommand() > 0;
}
public bool UpdateRange(T [] updateObjs)
public bool UpdateRange(T[] updateObjs)
{
return this.Context.Updateable(updateObjs).ExecuteCommand() > 0;
}

View File

@@ -11,7 +11,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.Sqlite" Version="2.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="2.2.1" />
<PackageReference Include="MySql.Data" Version="6.10.4" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Npgsql" Version="3.2.7" />

View File

@@ -78,7 +78,7 @@ namespace SqlSugar
//Compatible with.NET CORE parameters case
var name = parameter.ParameterName;
string newName = name +append+ addIndex;
appendSql = appendSql.Replace(name, newName);
appendSql =Regex.Replace(appendSql,name,newName,RegexOptions.IgnoreCase);
parameter.ParameterName = newName;
}
}

View File

@@ -8,6 +8,6 @@ namespace OrmTest
{
public class Config
{
public static string ConnectionString = @"DataSource=F:\GIT\SqlSugar\Src\Asp.NetCore2\SqlSeverTest\SqliteTest\DataBase\SqlSugar4xTest.sqlite";
public static string ConnectionString = @"DataSource=F:\MyOpenSource\SqlSugar4.XNew\SqlSugar\Src\Asp.NetCore2\SqlSeverTest\SqliteTest\DataBase\SqlSugar4xTest.sqlite";
}
}

View File

@@ -191,6 +191,7 @@ namespace OrmTest.Demo
var t1 = db.Ado.SqlQuery<string>("select 'a'");
var t2 = db.Ado.GetInt("select 1");
var t3 = db.Ado.GetDataTable("select 1 as id");
var t4= db.Ado.GetDataTable("select @id id",new { ID=1});
db.Ado.CommitTran();
//more
//db.Ado.GetXXX...

View File

@@ -12,7 +12,7 @@ namespace OrmTest.Demo
public static void Init()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = Config.ConnectionString, DbType = DbType.Sqlite, IsAutoCloseConnection = true });
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { InitKeyType= InitKeyType.Attribute,ConnectionString = Config.ConnectionString, DbType = DbType.Sqlite, IsAutoCloseConnection = true });
db.Aop.OnLogExecuted = (sql, pars) =>

View File

@@ -16,7 +16,8 @@ namespace OrmTest.Models
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
/// </summary>
[SqlSugar.SugarColumn(IsPrimaryKey =true)]
public Guid PK {get;set;}
/// <summary>