mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-19 20:38:16 +08:00
Merge branch 'master' of https://github.com/dotnetcore/FreeSql
This commit is contained in:
@ -40,8 +40,9 @@ namespace FreeSql
|
||||
if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Oracle"));
|
||||
break;
|
||||
case "SQLiteConnection":
|
||||
case "SqliteConnection":
|
||||
providerType = Type.GetType("FreeSql.Sqlite.SqliteProvider`1,FreeSql.Provider.Sqlite")?.MakeGenericType(connType);
|
||||
if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Sqlite"));
|
||||
if (providerType == null) throw new Exception(CoreStrings.Missing_FreeSqlProvider_Package("Sqlite/SqliteCore"));
|
||||
break;
|
||||
case "DmConnection":
|
||||
providerType = Type.GetType("FreeSql.Dameng.DamengProvider`1,FreeSql.Provider.Dameng")?.MakeGenericType(connType);
|
||||
@ -423,4 +424,4 @@ namespace FreeSql
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
|
458
FreeSql/Extensions/DynamicEntityExtensions.cs
Normal file
458
FreeSql/Extensions/DynamicEntityExtensions.cs
Normal file
@ -0,0 +1,458 @@
|
||||
// by: Daily
|
||||
|
||||
#if net40 || NETSTANDARD2_0
|
||||
#else
|
||||
|
||||
using FreeSql;
|
||||
using FreeSql.DataAnnotations;
|
||||
using FreeSql.Extensions.DynamicEntity;
|
||||
using FreeSql.Internal.CommonProvider;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Xml.Serialization;
|
||||
|
||||
public static class FreeSqlGlobalDynamicEntityExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 动态构建Class Type
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static DynamicCompileBuilder DynamicEntity(this ICodeFirst codeFirst, string className,
|
||||
params Attribute[] attributes)
|
||||
{
|
||||
return new DynamicCompileBuilder((codeFirst as CodeFirstProvider)._orm, className, attributes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据字典,创建 table 对应的实体对象
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="dict"></param>
|
||||
/// <returns></returns>
|
||||
public static object CreateInstance(this TableInfo table, Dictionary<string, object> dict)
|
||||
{
|
||||
if (table == null || dict == null) return null;
|
||||
var instance = table.Type.CreateInstanceGetDefaultValue();
|
||||
//加载默认值
|
||||
var defaultValueInit = table.Type.GetMethod("DefaultValueInit");
|
||||
if (defaultValueInit != null)
|
||||
{
|
||||
defaultValueInit.Invoke(instance, new object[0]);
|
||||
}
|
||||
foreach (var key in table.ColumnsByCs.Keys)
|
||||
{
|
||||
if (dict.ContainsKey(key) == false) continue;
|
||||
table.ColumnsByCs[key].SetValue(instance, dict[key]);
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据实体对象,创建 table 对应的字典
|
||||
/// </summary>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="instance"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<string, object> CreateDictionary(this TableInfo table, object instance)
|
||||
{
|
||||
if (table == null || instance == null) return null;
|
||||
var dict = new Dictionary<string, object>();
|
||||
foreach (var key in table.ColumnsByCs.Keys)
|
||||
dict[key] = table.ColumnsByCs[key].GetValue(instance);
|
||||
return dict;
|
||||
}
|
||||
}
|
||||
|
||||
namespace FreeSql.Extensions.DynamicEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// 动态创建实体类型
|
||||
/// </summary>
|
||||
public class DynamicCompileBuilder
|
||||
{
|
||||
private string _className = string.Empty;
|
||||
private Attribute[] _tableAttributes = null;
|
||||
private List<DynamicPropertyInfo> _properties = new List<DynamicPropertyInfo>();
|
||||
private Type _superClass = null;
|
||||
private IFreeSql _fsql = null;
|
||||
|
||||
/// <summary>
|
||||
/// 配置Class
|
||||
/// </summary>
|
||||
/// <param name="className">类名</param>
|
||||
/// <param name="attributes">类标记的特性[Table(Name = "xxx")] [Index(xxxx)]</param>
|
||||
/// <returns></returns>
|
||||
public DynamicCompileBuilder(IFreeSql fsql, string className, params Attribute[] attributes)
|
||||
{
|
||||
_fsql = fsql;
|
||||
_className = className;
|
||||
_tableAttributes = attributes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置属性
|
||||
/// </summary>
|
||||
/// <param name="propertyName">属性名称</param>
|
||||
/// <param name="propertyType">属性类型</param>
|
||||
/// <param name="attributes">属性标记的特性-支持多个</param>
|
||||
/// <returns></returns>
|
||||
public DynamicCompileBuilder Property(string propertyName, Type propertyType,
|
||||
params Attribute[] attributes)
|
||||
{
|
||||
_properties.Add(new DynamicPropertyInfo()
|
||||
{
|
||||
PropertyName = propertyName,
|
||||
PropertyType = propertyType,
|
||||
DefaultValue = null,
|
||||
Attributes = attributes
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置属性
|
||||
/// </summary>
|
||||
/// <param name="propertyName">属性名称</param>
|
||||
/// <param name="propertyType">属性类型</param>
|
||||
/// <param name="isOverride">该属性是否重写父类属性</param>
|
||||
/// <param name="attributes">属性标记的特性-支持多个</param>
|
||||
/// <returns></returns>
|
||||
public DynamicCompileBuilder Property(string propertyName, Type propertyType, bool isOverride,
|
||||
params Attribute[] attributes)
|
||||
{
|
||||
_properties.Add(new DynamicPropertyInfo()
|
||||
{
|
||||
PropertyName = propertyName,
|
||||
PropertyType = propertyType,
|
||||
DefaultValue = null,
|
||||
IsOverride = isOverride,
|
||||
Attributes = attributes
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置属性
|
||||
/// </summary>
|
||||
/// <param name="propertyName">属性名称</param>
|
||||
/// <param name="propertyType">属性类型</param>
|
||||
/// <param name="isOverride">该属性是否重写父类属性</param>
|
||||
/// <param name="defaultValue">属性默认值</param>
|
||||
/// <param name="attributes">属性标记的特性-支持多个</param>
|
||||
/// <returns></returns>
|
||||
public DynamicCompileBuilder Property(string propertyName, Type propertyType, bool isOverride,
|
||||
object defaultValue, params Attribute[] attributes)
|
||||
{
|
||||
_properties.Add(new DynamicPropertyInfo()
|
||||
{
|
||||
PropertyName = propertyName,
|
||||
PropertyType = propertyType,
|
||||
DefaultValue = defaultValue,
|
||||
IsOverride = isOverride,
|
||||
Attributes = attributes
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置父类
|
||||
/// </summary>
|
||||
/// <param name="superClass">父类类型</param>
|
||||
/// <returns></returns>
|
||||
public DynamicCompileBuilder Extend(Type superClass)
|
||||
{
|
||||
_superClass = superClass;
|
||||
return this;
|
||||
}
|
||||
|
||||
private void SetTableAttribute(ref TypeBuilder typeBuilder)
|
||||
{
|
||||
if (_tableAttributes == null) return;
|
||||
|
||||
foreach (var tableAttribute in _tableAttributes)
|
||||
{
|
||||
var propertyValues = new ArrayList();
|
||||
|
||||
if (tableAttribute == null) continue;
|
||||
|
||||
var classCtorInfo = tableAttribute.GetType().GetConstructor(Type.EmptyTypes);
|
||||
|
||||
var propertyInfos = tableAttribute.GetType().GetProperties().Where(p => p.CanWrite == true).ToArray();
|
||||
|
||||
foreach (var propertyInfo in propertyInfos)
|
||||
propertyValues.Add(propertyInfo.GetValue(tableAttribute));
|
||||
|
||||
//可能存在有参构造
|
||||
if (classCtorInfo == null)
|
||||
{
|
||||
var constructorTypes = propertyInfos.Select(p => p.PropertyType);
|
||||
classCtorInfo = tableAttribute.GetType().GetConstructor(constructorTypes.ToArray());
|
||||
var customAttributeBuilder = new CustomAttributeBuilder(classCtorInfo, propertyValues.ToArray());
|
||||
typeBuilder.SetCustomAttribute(customAttributeBuilder);
|
||||
}
|
||||
else
|
||||
{
|
||||
var customAttributeBuilder = new CustomAttributeBuilder(classCtorInfo, new object[0], propertyInfos,
|
||||
propertyValues.ToArray());
|
||||
typeBuilder.SetCustomAttribute(customAttributeBuilder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void SetPropertys(ref TypeBuilder typeBuilder)
|
||||
{
|
||||
var defaultValues = new Dictionary<FieldBuilder, object>();
|
||||
foreach (var pinfo in _properties)
|
||||
{
|
||||
if (pinfo == null)
|
||||
continue;
|
||||
var propertyName = pinfo.PropertyName;
|
||||
var propertyType = pinfo.PropertyType;
|
||||
//设置字段
|
||||
var field = typeBuilder.DefineField($"_{FirstCharToLower(propertyName)}", propertyType,
|
||||
FieldAttributes.Private | FieldAttributes.HasDefault);
|
||||
var firstCharToUpper = FirstCharToUpper(propertyName);
|
||||
|
||||
MethodAttributes maAttributes = MethodAttributes.Public;
|
||||
|
||||
//是否重写
|
||||
if (pinfo.IsOverride)
|
||||
{
|
||||
maAttributes = MethodAttributes.Public | MethodAttributes.Virtual;
|
||||
}
|
||||
|
||||
//设置属性方法
|
||||
var methodGet = typeBuilder.DefineMethod($"get_{firstCharToUpper}", maAttributes, propertyType, null);
|
||||
var methodSet = typeBuilder.DefineMethod($"set_{firstCharToUpper}", maAttributes, null,
|
||||
new Type[] { propertyType });
|
||||
|
||||
var ilOfGet = methodGet.GetILGenerator();
|
||||
ilOfGet.Emit(OpCodes.Ldarg_0);
|
||||
ilOfGet.Emit(OpCodes.Ldfld, field);
|
||||
ilOfGet.Emit(OpCodes.Ret);
|
||||
|
||||
var ilOfSet = methodSet.GetILGenerator();
|
||||
ilOfSet.Emit(OpCodes.Ldarg_0);
|
||||
ilOfSet.Emit(OpCodes.Ldarg_1);
|
||||
ilOfSet.Emit(OpCodes.Stfld, field);
|
||||
ilOfSet.Emit(OpCodes.Ret);
|
||||
|
||||
|
||||
//是否重写
|
||||
if (pinfo.IsOverride)
|
||||
{
|
||||
//重写Get、Set方法
|
||||
OverrideProperty(ref typeBuilder, methodGet, PropertyMethodEnum.GET, pinfo.PropertyName);
|
||||
OverrideProperty(ref typeBuilder, methodSet, PropertyMethodEnum.SET, pinfo.PropertyName);
|
||||
}
|
||||
|
||||
//设置属性
|
||||
var propertyBuilder =
|
||||
typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);
|
||||
propertyBuilder.SetGetMethod(methodGet);
|
||||
propertyBuilder.SetSetMethod(methodSet);
|
||||
|
||||
foreach (var pinfoAttribute in pinfo.Attributes)
|
||||
{
|
||||
//设置特性
|
||||
SetPropertyAttribute(ref propertyBuilder, pinfoAttribute);
|
||||
}
|
||||
|
||||
if (pinfo.DefaultValue != null)
|
||||
{
|
||||
defaultValues.Add(field, pinfo.DefaultValue);
|
||||
}
|
||||
}
|
||||
|
||||
//动态构建方法,设置默认值
|
||||
var methodDefaultValue = typeBuilder.DefineMethod($"DefaultValueInit", MethodAttributes.Public, null, null);
|
||||
var methodDefaultValueLlGenerator = methodDefaultValue.GetILGenerator();
|
||||
foreach (var kv in defaultValues)
|
||||
{
|
||||
methodDefaultValueLlGenerator.Emit(OpCodes.Ldarg_0);
|
||||
OpCodesAdapter(ref methodDefaultValueLlGenerator, kv.Key, kv.Value);
|
||||
methodDefaultValueLlGenerator.Emit(OpCodes.Stfld, kv.Key);
|
||||
}
|
||||
|
||||
methodDefaultValueLlGenerator.Emit(OpCodes.Ret);
|
||||
}
|
||||
|
||||
//IL命令类型适配
|
||||
private void OpCodesAdapter(ref ILGenerator generator, FieldInfo info, object value)
|
||||
{
|
||||
var fieldTypeName = info.FieldType.Name;
|
||||
switch (fieldTypeName)
|
||||
{
|
||||
case "Int32":
|
||||
generator.Emit(OpCodes.Ldc_I4, Convert.ToInt32(value));
|
||||
break;
|
||||
case "Boolean":
|
||||
generator.Emit(OpCodes.Ldc_I4, Convert.ToInt32(value));
|
||||
break;
|
||||
case "Char":
|
||||
generator.Emit(OpCodes.Ldc_I4, Convert.ToChar(value));
|
||||
break;
|
||||
case "String":
|
||||
generator.Emit(OpCodes.Ldstr, Convert.ToString(value));
|
||||
break;
|
||||
case "DateTime":
|
||||
generator.Emit(OpCodes.Ldstr, Convert.ToString(value));
|
||||
generator.Emit(OpCodes.Call, typeof(DateTime).GetMethod("Parse", new[] { typeof(string) }));
|
||||
break;
|
||||
case "Int64":
|
||||
generator.Emit(OpCodes.Ldc_I4, Convert.ToString(value));
|
||||
generator.Emit(OpCodes.Conv_I8);
|
||||
break;
|
||||
case "Double":
|
||||
generator.Emit(OpCodes.Ldc_R8, Convert.ToDouble(value));
|
||||
break;
|
||||
case "Single":
|
||||
generator.Emit(OpCodes.Ldc_R4, Convert.ToSingle(value));
|
||||
break;
|
||||
case "Decimal":
|
||||
Console.WriteLine(Convert.ToString(value));
|
||||
generator.Emit(OpCodes.Ldstr, Convert.ToString(value));
|
||||
generator.Emit(OpCodes.Call, typeof(Decimal).GetMethod("Parse", new[] { typeof(string) }));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetPropertyAttribute<T>(ref PropertyBuilder propertyBuilder, T tAttribute)
|
||||
{
|
||||
if (tAttribute == null) return;
|
||||
var propertyInfos = tAttribute.GetType().GetProperties().Where(p => p.CanWrite == true).ToArray();
|
||||
var constructor = tAttribute.GetType().GetConstructor(Type.EmptyTypes);
|
||||
var propertyValues = new ArrayList();
|
||||
foreach (var propertyInfo in propertyInfos)
|
||||
propertyValues.Add(propertyInfo.GetValue(tAttribute));
|
||||
|
||||
//可能存在有参构造
|
||||
//if (constructor == null)
|
||||
//{
|
||||
// var constructorTypes = propertyInfos.Select(p => p.PropertyType).ToList();
|
||||
// constructor = tAttribute.GetType().GetConstructor(constructorTypes.ToArray());
|
||||
// var customAttributeBuilder = new CustomAttributeBuilder(constructor, constructorTypes.ToArray(),
|
||||
// propertyInfos, propertyValues.ToArray());
|
||||
// propertyBuilder.SetCustomAttribute(customAttributeBuilder);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
var customAttributeBuilder = new CustomAttributeBuilder(constructor, new object[0], propertyInfos,
|
||||
propertyValues.ToArray());
|
||||
propertyBuilder.SetCustomAttribute(customAttributeBuilder);
|
||||
// }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Override属性
|
||||
/// </summary>
|
||||
/// <param name="typeBuilder"></param>
|
||||
private void OverrideProperty(ref TypeBuilder typeBuilder, MethodBuilder methodBuilder,
|
||||
PropertyMethodEnum methodEnum,
|
||||
string propertyName)
|
||||
{
|
||||
//查找父类的属性信息
|
||||
var propertyInfo = typeBuilder.BaseType.GetProperty(propertyName);
|
||||
if (propertyInfo == null) return;
|
||||
var pm = methodEnum == PropertyMethodEnum.GET ? propertyInfo.GetGetMethod() : propertyInfo.GetSetMethod();
|
||||
//重写父类GET SET 方法
|
||||
typeBuilder.DefineMethodOverride(methodBuilder, pm);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Emit动态创建出Class - Type
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public TableInfo Build()
|
||||
{
|
||||
//初始化AssemblyName的一个实例
|
||||
var assemblyName = new AssemblyName("FreeSql.DynamicCompileBuilder");
|
||||
//设置程序集的名称
|
||||
var defineDynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
|
||||
//动态在程序集内创建一个模块
|
||||
var defineDynamicModule =
|
||||
defineDynamicAssembly.DefineDynamicModule("FreeSql.DynamicCompileBuilder.Dynamics");
|
||||
//动态的在模块内创建一个类
|
||||
var typeBuilder =
|
||||
defineDynamicModule.DefineType(_className, TypeAttributes.Public | TypeAttributes.Class, _superClass);
|
||||
|
||||
//设置TableAttribute
|
||||
SetTableAttribute(ref typeBuilder);
|
||||
|
||||
//设置属性
|
||||
SetPropertys(ref typeBuilder);
|
||||
|
||||
//创建类的Type对象
|
||||
var type = typeBuilder.CreateType();
|
||||
|
||||
return _fsql.CodeFirst.GetTableByEntity(type);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首字母小写
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
private string FirstCharToLower(string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
return input;
|
||||
string str = input.First().ToString().ToLower() + input.Substring(1);
|
||||
return str;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首字母大写
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
private string FirstCharToUpper(string input)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input))
|
||||
return input;
|
||||
string str = input.First().ToString().ToUpper() + input.Substring(1);
|
||||
return str;
|
||||
}
|
||||
|
||||
private static string Md5Encryption(string inputStr)
|
||||
{
|
||||
var result = string.Empty;
|
||||
//32位大写
|
||||
using (var md5 = MD5.Create())
|
||||
{
|
||||
var resultBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(inputStr));
|
||||
result = BitConverter.ToString(resultBytes);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
class DynamicPropertyInfo
|
||||
{
|
||||
public string PropertyName { get; set; } = string.Empty;
|
||||
public Type PropertyType { get; set; }
|
||||
public object DefaultValue { get; set; }
|
||||
public bool IsOverride { get; set; } = false;
|
||||
public Attribute[] Attributes { get; set; }
|
||||
}
|
||||
|
||||
enum PropertyMethodEnum
|
||||
{
|
||||
GET,
|
||||
SET
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
@ -188,6 +188,17 @@ namespace FreeSql
|
||||
expContext.Value.Result = $"{expContext.Value.ParsedContent["value1"]} <= {expContext.Value.ParsedContent["value2"]}";
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// value1 IS NULL
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="value1"></param>
|
||||
/// <returns></returns>
|
||||
public static bool EqualIsNull<TValue>(TValue value1)
|
||||
{
|
||||
expContext.Value.Result = $"{expContext.Value.ParsedContent["value1"]} IS NULL";
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
|
@ -1,5 +1,6 @@
|
||||
using FreeSql;
|
||||
using FreeSql.DataAnnotations;
|
||||
using FreeSql.Internal;
|
||||
using FreeSql.Internal.CommonProvider;
|
||||
using FreeSql.Internal.Model;
|
||||
using FreeSql.Internal.ObjectPool;
|
||||
@ -137,8 +138,27 @@ public static partial class FreeSqlGlobalExtensions
|
||||
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
|
||||
.Append('>');
|
||||
|
||||
sb.Append('(').Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(')');
|
||||
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => LocalDisplayCsharpParameter(a)))).Append(")");
|
||||
return sb.ToString();
|
||||
|
||||
string LocalDisplayCsharpParameter(ParameterInfo lp)
|
||||
{
|
||||
var pstr = "";
|
||||
object[] pattrs = new object[0];
|
||||
try { pattrs = lp.GetCustomAttributes(false); } catch { }
|
||||
if (pattrs.Any(a => a is ParamArrayAttribute)) pstr = "params ";
|
||||
pstr = $"{pstr}{lp.ParameterType.DisplayCsharp()} {lp.Name}";
|
||||
#if net40
|
||||
if (pattrs.Any(a => a is System.Runtime.InteropServices.OptionalAttribute) == false) return pstr;
|
||||
#else
|
||||
if (lp.HasDefaultValue == false) return pstr;
|
||||
#endif
|
||||
if (lp.DefaultValue == null) return $"{pstr} = null";
|
||||
if (lp.ParameterType == typeof(string)) return $"{pstr} = \"{lp.DefaultValue.ToString().Replace("\"", "\\\"").Replace("\r\n", "\\r\\n").Replace("\n", "\\n")}\"";
|
||||
if (lp.ParameterType == typeof(bool) || lp.ParameterType == typeof(bool?)) return $"{pstr} = {lp.DefaultValue.ToString().Replace("False", "false").Replace("True", "true")}";
|
||||
if (lp.ParameterType.IsEnum) return $"{pstr} = {lp.ParameterType.DisplayCsharp(false)}.{lp.DefaultValue}";
|
||||
return $"{pstr} = {lp.DefaultValue}";
|
||||
}
|
||||
}
|
||||
public static object CreateInstanceGetDefaultValue(this Type that)
|
||||
{
|
||||
@ -1311,4 +1331,5 @@ SELECT ");
|
||||
return NativeTuple.Create(query, af, sql);
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
@ -17,7 +17,7 @@
|
||||
<SignAssembly>true</SignAssembly>
|
||||
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
|
||||
<DelaySign>false</DelaySign>
|
||||
<Version>3.2.694-preview20230331</Version>
|
||||
<Version>3.2.697</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -1073,6 +1073,82 @@
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="T:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder">
|
||||
<summary>
|
||||
动态创建实体类型
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.#ctor(IFreeSql,System.String,System.Attribute[])">
|
||||
<summary>
|
||||
配置Class
|
||||
</summary>
|
||||
<param name="className">类名</param>
|
||||
<param name="attributes">类标记的特性[Table(Name = "xxx")] [Index(xxxx)]</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.Property(System.String,System.Type,System.Attribute[])">
|
||||
<summary>
|
||||
配置属性
|
||||
</summary>
|
||||
<param name="propertyName">属性名称</param>
|
||||
<param name="propertyType">属性类型</param>
|
||||
<param name="attributes">属性标记的特性-支持多个</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.Property(System.String,System.Type,System.Boolean,System.Attribute[])">
|
||||
<summary>
|
||||
配置属性
|
||||
</summary>
|
||||
<param name="propertyName">属性名称</param>
|
||||
<param name="propertyType">属性类型</param>
|
||||
<param name="isOverride">该属性是否重写父类属性</param>
|
||||
<param name="attributes">属性标记的特性-支持多个</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.Property(System.String,System.Type,System.Boolean,System.Object,System.Attribute[])">
|
||||
<summary>
|
||||
配置属性
|
||||
</summary>
|
||||
<param name="propertyName">属性名称</param>
|
||||
<param name="propertyType">属性类型</param>
|
||||
<param name="isOverride">该属性是否重写父类属性</param>
|
||||
<param name="defaultValue">属性默认值</param>
|
||||
<param name="attributes">属性标记的特性-支持多个</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.Extend(System.Type)">
|
||||
<summary>
|
||||
配置父类
|
||||
</summary>
|
||||
<param name="superClass">父类类型</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.OverrideProperty(System.Reflection.Emit.TypeBuilder@,System.Reflection.Emit.MethodBuilder,FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.PropertyMethodEnum,System.String)">
|
||||
<summary>
|
||||
Override属性
|
||||
</summary>
|
||||
<param name="typeBuilder"></param>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.Build">
|
||||
<summary>
|
||||
Emit动态创建出Class - Type
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.FirstCharToLower(System.String)">
|
||||
<summary>
|
||||
首字母小写
|
||||
</summary>
|
||||
<param name="input"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileBuilder.FirstCharToUpper(System.String)">
|
||||
<summary>
|
||||
首字母大写
|
||||
</summary>
|
||||
<param name="input"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.Extensions.EntityUtil.EntityUtilExtensions.GetEntityKeyString(IFreeSql,System.Type,System.Object,System.Boolean,System.String)">
|
||||
<summary>
|
||||
获取实体的主键值,以 "*|_,[,_|*" 分割,当任意一个主键属性无值时,返回 null
|
||||
@ -1301,6 +1377,14 @@
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.SqlExt.EqualIsNull``1(``0)">
|
||||
<summary>
|
||||
value1 IS NULL
|
||||
</summary>
|
||||
<typeparam name="TValue"></typeparam>
|
||||
<param name="value1"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.SqlExt.Case">
|
||||
<summary>
|
||||
case when .. then .. end
|
||||
@ -1837,6 +1921,16 @@
|
||||
<param name="columns">属性名,或者字段名</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.IInsertOrUpdate`1.UpdateSet``1(System.Linq.Expressions.Expression{System.Func{`0,`0,``0}})">
|
||||
<summary>
|
||||
设置列的联表值,格式:<para></para>
|
||||
UpdateSet((a, b) => a.Clicks == b.xxx)<para></para>
|
||||
UpdateSet((a, b) => a.Clicks == a.Clicks + 1)
|
||||
</summary>
|
||||
<typeparam name="TMember"></typeparam>
|
||||
<param name="exp"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.IInsertOrUpdate`1.AsTable(System.Func{System.String,System.String})">
|
||||
<summary>
|
||||
设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名;
|
||||
@ -5692,6 +5786,28 @@
|
||||
请使用 fsql.InsertDict(dict) 方法插入字典数据
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSqlGlobalDynamicEntityExtensions.DynamicEntity(FreeSql.ICodeFirst,System.String,System.Attribute[])">
|
||||
<summary>
|
||||
动态构建Class Type
|
||||
</summary>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSqlGlobalDynamicEntityExtensions.CreateInstance(FreeSql.Internal.Model.TableInfo,System.Collections.Generic.Dictionary{System.String,System.Object})">
|
||||
<summary>
|
||||
根据字典,创建 table 对应的实体对象
|
||||
</summary>
|
||||
<param name="table"></param>
|
||||
<param name="dict"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSqlGlobalDynamicEntityExtensions.CreateDictionary(FreeSql.Internal.Model.TableInfo,System.Object)">
|
||||
<summary>
|
||||
根据实体对象,创建 table 对应的字典
|
||||
</summary>
|
||||
<param name="table"></param>
|
||||
<param name="instance"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSqlGlobalExpressionCallExtensions.Between(System.DateTime,System.DateTime,System.DateTime)">
|
||||
<summary>
|
||||
C#: that >= between && that <= and<para></para>
|
||||
|
@ -86,6 +86,16 @@ namespace FreeSql
|
||||
/// <returns></returns>
|
||||
IInsertOrUpdate<T1> UpdateColumns(string[] columns);
|
||||
|
||||
/// <summary>
|
||||
/// 设置列的联表值,格式:<para></para>
|
||||
/// UpdateSet((a, b) => a.Clicks == b.xxx)<para></para>
|
||||
/// UpdateSet((a, b) => a.Clicks == a.Clicks + 1)
|
||||
/// </summary>
|
||||
/// <typeparam name="TMember"></typeparam>
|
||||
/// <param name="exp"></param>
|
||||
/// <returns></returns>
|
||||
IInsertOrUpdate<T1> UpdateSet<TMember>(Expression<Func<T1, T1, TMember>> exp);
|
||||
|
||||
/// <summary>
|
||||
/// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名;
|
||||
/// </summary>
|
||||
|
@ -71,7 +71,16 @@ namespace FreeSql.Internal
|
||||
field.Append(_common.FieldAsAlias(parent.DbNestedField));
|
||||
}
|
||||
else if (isdiymemexp && diymemexp?.ParseExpMapResult != null)
|
||||
{
|
||||
parent.DbNestedField = diymemexp.ParseExpMapResult.DbNestedField;
|
||||
if (EndsWithDbNestedField(parent.DbField, $" {parent.DbNestedField}") == false && //#1510 group by 产生的 DbField 自带 alias,因此需要此行判断
|
||||
string.IsNullOrEmpty(parent.CsName) == false && localIndex == ReadAnonymousFieldAsCsName)
|
||||
{
|
||||
parent.DbNestedField = GetFieldAsCsName(parent.CsName);
|
||||
if (EndsWithDbNestedField(parent.DbField, parent.DbNestedField) == false) //DbField 和 CsName 相同的时候,不处理
|
||||
field.Append(_common.FieldAsAlias(parent.DbNestedField));
|
||||
}
|
||||
}
|
||||
else if (string.IsNullOrEmpty(parent.CsName) == false)
|
||||
{
|
||||
parent.DbNestedField = GetFieldAsCsName(parent.CsName);
|
||||
@ -1739,7 +1748,7 @@ namespace FreeSql.Internal
|
||||
if (oper2.NodeType == ExpressionType.Parameter)
|
||||
{
|
||||
var oper2Parm = oper2 as ParameterExpression;
|
||||
if (exp2.Type.IsAbstract || exp2.Type.IsInterface || exp2.Type.IsAssignableFrom(oper2Parm.Type))
|
||||
if (oper2Parm.Type != typeof(object) && (exp2.Type.IsAbstract || exp2.Type.IsInterface || exp2.Type.IsAssignableFrom(oper2Parm.Type)))
|
||||
expStack.Push(oper2Parm);
|
||||
else if (oper2Parm.Type != typeof(object) && oper2Parm.Type.IsAssignableFrom(exp2.Type))
|
||||
expStack.Push(oper2Parm);
|
||||
|
@ -196,8 +196,9 @@ namespace FreeSql.Internal.CommonProvider
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (_table.AsTableImpl != null)
|
||||
if (_table.AsTableImpl != null && string.IsNullOrWhiteSpace(_tableRule?.Invoke(_table.DbName)) == true)
|
||||
{
|
||||
var oldTableRule = _tableRule;
|
||||
var names = _table.AsTableImpl.GetTableNamesBySqlWhere(newwhere.ToString(), _params, new SelectTableInfo { Table = _table }, _commonUtils);
|
||||
foreach (var name in names)
|
||||
{
|
||||
@ -206,6 +207,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
_interceptSql?.Invoke(sb);
|
||||
fetch(sb);
|
||||
}
|
||||
_tableRule = oldTableRule;
|
||||
return;
|
||||
}
|
||||
|
||||
@ -229,8 +231,9 @@ namespace FreeSql.Internal.CommonProvider
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (_table.AsTableImpl != null)
|
||||
if (_table.AsTableImpl != null && string.IsNullOrWhiteSpace(_tableRule?.Invoke(_table.DbName)) == true)
|
||||
{
|
||||
var oldTableRule = _tableRule;
|
||||
var names = _table.AsTableImpl.GetTableNamesBySqlWhere(newwhere.ToString(), _params, new SelectTableInfo { Table = _table }, _commonUtils);
|
||||
foreach (var name in names)
|
||||
{
|
||||
@ -239,6 +242,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
_interceptSql?.Invoke(sb);
|
||||
await fetchAsync(sb);
|
||||
}
|
||||
_tableRule = oldTableRule;
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -23,6 +23,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
public bool _doNothing = false;
|
||||
public Dictionary<string, bool> _updateIgnore = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
|
||||
public Dictionary<string, bool> _auditValueChangedDict = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase);
|
||||
public Dictionary<string, string> _updateSetDict = new Dictionary<string, string>();
|
||||
public TableInfo _table;
|
||||
public ColumnInfo[] _tempPrimarys;
|
||||
public Func<string, string> _tableRule;
|
||||
@ -87,6 +88,55 @@ namespace FreeSql.Internal.CommonProvider
|
||||
return this;
|
||||
}
|
||||
|
||||
public IInsertOrUpdate<T1> UpdateSet<TMember>(Expression<Func<T1, T1, TMember>> exp)
|
||||
{
|
||||
var body = exp?.Body;
|
||||
var nodeType = body?.NodeType;
|
||||
if (nodeType == ExpressionType.Convert)
|
||||
{
|
||||
body = (body as UnaryExpression)?.Operand;
|
||||
nodeType = body?.NodeType;
|
||||
}
|
||||
switch (nodeType)
|
||||
{
|
||||
case ExpressionType.Equal:
|
||||
break;
|
||||
default:
|
||||
throw new Exception("格式错了,请使用 .Set((a,b) => a.name == b.xname)");
|
||||
}
|
||||
|
||||
var equalBinaryExp = body as BinaryExpression;
|
||||
var cols = new List<SelectColumnInfo>();
|
||||
_commonExpression.ExpressionSelectColumn_MemberAccess(null, null, cols, SelectTableInfoType.From, equalBinaryExp.Left, true, null);
|
||||
if (cols.Count != 1) return this;
|
||||
var col = cols[0].Column;
|
||||
var valueSql = "";
|
||||
|
||||
if (equalBinaryExp.Right.IsParameter())
|
||||
{
|
||||
var tmpQuery = _orm.Select<T1, T1>();
|
||||
var tmpQueryProvider = tmpQuery as Select0Provider;
|
||||
tmpQueryProvider._tables[0].Alias = "t1";
|
||||
tmpQueryProvider._tables[0].Parameter = exp.Parameters[0];
|
||||
tmpQueryProvider._tables[1].Alias = "t2";
|
||||
tmpQueryProvider._tables[1].Parameter = exp.Parameters[1];
|
||||
var valueExp = Expression.Lambda<Func<T1, T1, object>>(Expression.Convert(equalBinaryExp.Right, typeof(object)), exp.Parameters);
|
||||
tmpQuery.GroupBy(valueExp);
|
||||
valueSql = tmpQueryProvider._groupby?.Remove(0, " \r\nGROUP BY ".Length);
|
||||
}
|
||||
else
|
||||
{
|
||||
valueSql = _commonExpression.ExpressionLambdaToSql(equalBinaryExp.Right, new CommonExpression.ExpTSC
|
||||
{
|
||||
isQuoteName = true,
|
||||
mapType = equalBinaryExp.Right is BinaryExpression ? null : col.Attribute.MapType
|
||||
});
|
||||
}
|
||||
if (string.IsNullOrEmpty(valueSql)) return this;
|
||||
_updateSetDict[col.Attribute.Name] = valueSql;
|
||||
return this;
|
||||
}
|
||||
|
||||
public static void AuditDataValue(object sender, IEnumerable<T1> data, IFreeSql orm, TableInfo table, Dictionary<string, bool> changedDict)
|
||||
{
|
||||
if (data?.Any() != true) return;
|
||||
|
@ -342,6 +342,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
[typeof(string)] = typeof(DbDataReader).GetMethod("GetString", new Type[] { typeof(int) }),
|
||||
//[typeof(Guid)] = typeof(DbDataReader).GetMethod("GetGuid", new Type[] { typeof(int) }) 有些驱动不兼容
|
||||
};
|
||||
public static Dictionary<DataType, Dictionary<Type, MethodInfo>> _dicMethodDataReaderGetValueOverride = new Dictionary<DataType, Dictionary<Type, MethodInfo>>();
|
||||
|
||||
public static MethodInfo MethodStringContains = typeof(string).GetMethod("Contains", new[] { typeof(string) });
|
||||
public static MethodInfo MethodStringStartsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
|
||||
|
@ -744,8 +744,11 @@ namespace FreeSql.Internal.CommonProvider
|
||||
_orm.Aop.AuditDataReaderHandler == null &&
|
||||
_dicMethodDataReaderGetValue.TryGetValue(col.Attribute.MapType.NullableTypeOrThis(), out var drGetValueMethod))
|
||||
{
|
||||
if (_dicMethodDataReaderGetValueOverride.TryGetValue(_orm.Ado.DataType, out var drDictOverride) && drDictOverride.TryGetValue(col.Attribute.MapType.NullableTypeOrThis(), out var drDictOverrideGetValueMethod))
|
||||
drGetValueMethod = drDictOverrideGetValueMethod;
|
||||
|
||||
Expression drvalExp = Expression.Call(rowExp, drGetValueMethod, Expression.Constant(colidx));
|
||||
if (col.CsType.IsNullableType()) drvalExp = Expression.Convert(drvalExp, col.CsType);
|
||||
if (col.CsType.IsNullableType() || drGetValueMethod.ReturnType != col.CsType) drvalExp = Expression.Convert(drvalExp, col.CsType);
|
||||
drvalExp = Expression.Condition(Expression.Call(rowExp, _MethodDataReaderIsDBNull, Expression.Constant(colidx)), Expression.Default(col.CsType), drvalExp);
|
||||
|
||||
if (drvalType.IsArray || drvalType.IsEnum || Utils.dicExecuteArrayRowReadClassOrTuple.ContainsKey(drvalType))
|
||||
|
@ -174,7 +174,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
if (equalBinaryExp.Right.IsParameter())
|
||||
{
|
||||
_query2Provider._groupby = null;
|
||||
var valueExp = Expression.Lambda<Func<T1, T2, object>>(equalBinaryExp.Right, exp.Parameters);
|
||||
var valueExp = Expression.Lambda<Func<T1, T2, object>>(Expression.Convert(equalBinaryExp.Right, typeof(object)), exp.Parameters);
|
||||
_query2.GroupBy(valueExp);
|
||||
valueSql = _query2Provider._groupby?.Remove(0, " \r\nGROUP BY ".Length);
|
||||
}
|
||||
|
@ -894,28 +894,32 @@ namespace FreeSql.Internal.CommonProvider
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ");
|
||||
|
||||
string valsqlOld = null;
|
||||
var valsqlOldStats = 1; //start 1
|
||||
var nullStats = 0;
|
||||
var cwsb = new StringBuilder().Append(cw);
|
||||
foreach (var d in _source)
|
||||
var valsameIf = col.Attribute.MapType.IsNumberType() ||
|
||||
new[] { typeof(string), typeof(DateTime), typeof(DateTime?) }.Contains(col.Attribute.MapType) ||
|
||||
col.Attribute.MapType.NullableTypeOrThis().IsEnum;
|
||||
var ds = _source.Select(a => col.GetDbValue(a)).ToArray();
|
||||
if (valsameIf && ds.All(a => object.Equals(a, ds[0])))
|
||||
{
|
||||
cwsb.Append(" \r\nWHEN ");
|
||||
ToSqlWhen(cwsb, _tempPrimarys, d);
|
||||
cwsb.Append(" THEN ");
|
||||
var val = col.GetDbValue(d);
|
||||
var valsql = thenValue(_commonUtils.RewriteColumn(col, _commonUtils.GetNoneParamaterSqlValue(_paramsSource, "u", col, col.Attribute.MapType, val)));
|
||||
cwsb.Append(valsql);
|
||||
if (valsqlOld == null) valsqlOld = valsql;
|
||||
else if (valsqlOld == valsql) valsqlOldStats++;
|
||||
if (val == null || val == DBNull.Value) nullStats++;
|
||||
var val = ds.First();
|
||||
var colsql = thenValue(_commonUtils.RewriteColumn(col, _commonUtils.GetNoneParamaterSqlValue(_paramsSource, "u", col, col.Attribute.MapType, val)));
|
||||
sb.Append(colsql);
|
||||
}
|
||||
else
|
||||
{
|
||||
var cwsb = new StringBuilder().Append(cw);
|
||||
foreach (var d in _source)
|
||||
{
|
||||
cwsb.Append(" \r\nWHEN ");
|
||||
ToSqlWhen(cwsb, _tempPrimarys, d);
|
||||
cwsb.Append(" THEN ");
|
||||
var val = col.GetDbValue(d);
|
||||
var colsql = thenValue(_commonUtils.RewriteColumn(col, _commonUtils.GetNoneParamaterSqlValue(_paramsSource, "u", col, col.Attribute.MapType, val)));
|
||||
cwsb.Append(colsql);
|
||||
}
|
||||
cwsb.Append(" END");
|
||||
sb.Append(cwsb);
|
||||
cwsb.Clear();
|
||||
}
|
||||
cwsb.Append(" END");
|
||||
if (nullStats == _source.Count) sb.Append("NULL");
|
||||
else if (valsqlOldStats == _source.Count) sb.Append(valsqlOld);
|
||||
else sb.Append(cwsb);
|
||||
cwsb.Clear();
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
@ -1004,8 +1008,9 @@ namespace FreeSql.Internal.CommonProvider
|
||||
ToSqlWhere(newwhere);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (_table.AsTableImpl != null)
|
||||
if (_table.AsTableImpl != null && string.IsNullOrWhiteSpace(_tableRule?.Invoke(_table.DbName)) == true)
|
||||
{
|
||||
var oldTableRule = _tableRule;
|
||||
var names = _table.AsTableImpl.GetTableNamesBySqlWhere(newwhere.ToString(), _params, new SelectTableInfo { Table = _table }, _commonUtils);
|
||||
foreach (var name in names)
|
||||
{
|
||||
@ -1013,6 +1018,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
ToSqlExtension110(sb.Clear(), true);
|
||||
fetch(sb);
|
||||
}
|
||||
_tableRule = oldTableRule;
|
||||
return;
|
||||
}
|
||||
|
||||
@ -1036,8 +1042,9 @@ namespace FreeSql.Internal.CommonProvider
|
||||
ToSqlWhere(newwhere);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
if (_table.AsTableImpl != null)
|
||||
if (_table.AsTableImpl != null && string.IsNullOrWhiteSpace(_tableRule?.Invoke(_table.DbName)) == true)
|
||||
{
|
||||
var oldTableRule = _tableRule;
|
||||
var names = _table.AsTableImpl.GetTableNamesBySqlWhere(newwhere.ToString(), _params, new SelectTableInfo { Table = _table }, _commonUtils);
|
||||
foreach (var name in names)
|
||||
{
|
||||
@ -1045,6 +1052,7 @@ namespace FreeSql.Internal.CommonProvider
|
||||
ToSqlExtension110(sb.Clear(), true);
|
||||
await fetchAsync(sb);
|
||||
}
|
||||
_tableRule = oldTableRule;
|
||||
return;
|
||||
}
|
||||
|
||||
@ -1143,30 +1151,41 @@ namespace FreeSql.Internal.CommonProvider
|
||||
sb.Append(col.DbUpdateValue);
|
||||
else
|
||||
{
|
||||
var nulls = 0;
|
||||
var cwsb = new StringBuilder().Append(cw);
|
||||
foreach (var d in _source)
|
||||
var valsameIf = col.Attribute.MapType.IsNumberType() ||
|
||||
new[] { typeof(string), typeof(DateTime), typeof(DateTime?) }.Contains(col.Attribute.MapType) ||
|
||||
col.Attribute.MapType.NullableTypeOrThis().IsEnum;
|
||||
var ds = _source.Select(a => col.GetDbValue(a)).ToArray();
|
||||
if (valsameIf && ds.All(a => object.Equals(a, ds[0])))
|
||||
{
|
||||
cwsb.Append(" \r\nWHEN ");
|
||||
ToSqlWhen(cwsb, _tempPrimarys, d);
|
||||
cwsb.Append(" THEN ");
|
||||
var val = col.GetDbValue(d);
|
||||
|
||||
var val = ds.First();
|
||||
var colsql = _noneParameter ? _commonUtils.GetNoneParamaterSqlValue(_paramsSource, "u", col, col.Attribute.MapType, val) :
|
||||
_commonUtils.QuoteWriteParamterAdapter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"));
|
||||
cwsb.Append(_commonUtils.RewriteColumn(col, colsql));
|
||||
sb.Append(_commonUtils.RewriteColumn(col, colsql));
|
||||
if (_noneParameter == false)
|
||||
_commonUtils.AppendParamter(_paramsSource, null, col, col.Attribute.MapType, val);
|
||||
if (val == null || val == DBNull.Value) nulls++;
|
||||
}
|
||||
cwsb.Append(" END");
|
||||
if (nulls == _source.Count) sb.Append("NULL");
|
||||
else
|
||||
{
|
||||
var cwsb = new StringBuilder().Append(cw);
|
||||
foreach (var d in _source)
|
||||
{
|
||||
cwsb.Append(" \r\nWHEN ");
|
||||
ToSqlWhen(cwsb, _tempPrimarys, d);
|
||||
cwsb.Append(" THEN ");
|
||||
var val = col.GetDbValue(d);
|
||||
|
||||
var colsql = _noneParameter ? _commonUtils.GetNoneParamaterSqlValue(_paramsSource, "u", col, col.Attribute.MapType, val) :
|
||||
_commonUtils.QuoteWriteParamterAdapter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"));
|
||||
colsql = _commonUtils.RewriteColumn(col, colsql);
|
||||
cwsb.Append(colsql);
|
||||
if (_noneParameter == false)
|
||||
_commonUtils.AppendParamter(_paramsSource, null, col, col.Attribute.MapType, val);
|
||||
}
|
||||
cwsb.Append(" END");
|
||||
ToSqlCaseWhenEnd(cwsb, col);
|
||||
sb.Append(cwsb);
|
||||
cwsb.Clear();
|
||||
}
|
||||
cwsb.Clear();
|
||||
}
|
||||
++colidx;
|
||||
}
|
||||
|
@ -50,9 +50,9 @@ namespace FreeSql.Internal.ObjectPool
|
||||
{
|
||||
public IPolicy<T> Policy { get; protected set; }
|
||||
|
||||
private List<Object<T>> _allObjects = new List<Object<T>>();
|
||||
private object _allObjectsLock = new object();
|
||||
private ConcurrentStack<Object<T>> _freeObjects = new ConcurrentStack<Object<T>>();
|
||||
internal List<Object<T>> _allObjects = new List<Object<T>>();
|
||||
internal ConcurrentStack<Object<T>> _freeObjects = new ConcurrentStack<Object<T>>();
|
||||
|
||||
private ConcurrentQueue<GetSyncQueueInfo> _getSyncQueue = new ConcurrentQueue<GetSyncQueueInfo>();
|
||||
private ConcurrentQueue<TaskCompletionSource<Object<T>>> _getAsyncQueue = new ConcurrentQueue<TaskCompletionSource<Object<T>>>();
|
||||
@ -112,8 +112,8 @@ namespace FreeSql.Internal.ObjectPool
|
||||
try
|
||||
{
|
||||
var conn = GetFree(false);
|
||||
if (conn == null) throw new Exception(CoreStrings.Available_Failed_Get_Resource("CheckAvailable", this.Statistics));
|
||||
|
||||
if (conn == null) throw new Exception($"【{Policy.Name}】Failed to get resource {this.Statistics}");
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
@ -125,7 +125,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
{
|
||||
conn.ResetValue();
|
||||
}
|
||||
if (Policy.OnCheckAvailable(conn) == false) throw new Exception(CoreStrings.Available_Thrown_Exception("CheckAvailable"));
|
||||
if (Policy.OnCheckAvailable(conn) == false) throw new Exception("【{Policy.Name}】An exception needs to be thrown");
|
||||
break;
|
||||
}
|
||||
finally
|
||||
@ -177,11 +177,11 @@ namespace FreeSql.Internal.ObjectPool
|
||||
try
|
||||
{
|
||||
var conn = GetFree(false);
|
||||
if (conn == null) throw new Exception(CoreStrings.Available_Failed_Get_Resource("LiveCheckAvailable", this.Statistics));
|
||||
|
||||
if (conn == null) throw new Exception($"【{Policy.Name}】Failed to get resource {this.Statistics}");
|
||||
|
||||
try
|
||||
{
|
||||
if (Policy.OnCheckAvailable(conn) == false) throw new Exception(CoreStrings.Available_Thrown_Exception("LiveCheckAvailable"));
|
||||
if (Policy.OnCheckAvailable(conn) == false) throw new Exception("【{Policy.Name}】An exception needs to be thrown");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -281,10 +281,10 @@ namespace FreeSql.Internal.ObjectPool
|
||||
{
|
||||
|
||||
if (running == false)
|
||||
throw new ObjectDisposedException(CoreStrings.Policy_ObjectPool_Dispose(Policy.Name));
|
||||
throw new ObjectDisposedException($"【{Policy.Name}】The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079");
|
||||
|
||||
if (checkAvailable && UnavailableException != null)
|
||||
throw new Exception(CoreStrings.Policy_Status_NotAvailable(Policy.Name,UnavailableException?.Message), UnavailableException);
|
||||
throw new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException);
|
||||
|
||||
if ((_freeObjects.TryPop(out var obj) == false || obj == null) && _allObjects.Count < Policy.PoolSize)
|
||||
{
|
||||
@ -335,12 +335,13 @@ namespace FreeSql.Internal.ObjectPool
|
||||
if (obj == null) obj = queueItem.ReturnValue;
|
||||
if (obj == null) lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null;
|
||||
if (obj == null) obj = queueItem.ReturnValue;
|
||||
if (queueItem.Exception != null) throw queueItem.Exception;
|
||||
|
||||
if (obj == null)
|
||||
{
|
||||
Policy.OnGetTimeout();
|
||||
if (Policy.IsThrowGetTimeoutException)
|
||||
throw new TimeoutException(CoreStrings.ObjectPool_Get_Timeout(Policy.Name, "Get", timeout.Value.TotalSeconds));
|
||||
throw new TimeoutException($"【{Policy.Name}】ObjectPool.Get() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081");
|
||||
|
||||
return null;
|
||||
}
|
||||
@ -372,7 +373,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
if (obj == null)
|
||||
{
|
||||
if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1)
|
||||
throw new OutOfMemoryException(CoreStrings.ObjectPool_GetAsync_Queue_Long(Policy.Name, Policy.AsyncGetCapacity));
|
||||
throw new OutOfMemoryException($"【{Policy.Name}】ObjectPool.GetAsync() The queue is too long. Policy. AsyncGetCapacity = {Policy.AsyncGetCapacity}");
|
||||
|
||||
var tcs = new TaskCompletionSource<Object<T>>();
|
||||
|
||||
@ -392,7 +393,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
// Policy.GetTimeout();
|
||||
|
||||
// if (Policy.IsThrowGetTimeoutException)
|
||||
// throw new Exception($"ObjectPool.GetAsync 获取超时({timeout.Value.TotalSeconds}秒)。");
|
||||
// throw new TimeoutException($"【{Policy.Name}】ObjectPool.GetAsync() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081");
|
||||
|
||||
// return null;
|
||||
//}
|
||||
@ -444,16 +445,26 @@ namespace FreeSql.Internal.ObjectPool
|
||||
|
||||
if (queueItem.ReturnValue != null)
|
||||
{
|
||||
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
|
||||
obj.LastReturnTime = DateTime.Now;
|
||||
|
||||
try
|
||||
if (UnavailableException != null)
|
||||
{
|
||||
queueItem.Wait.Set();
|
||||
isReturn = true;
|
||||
queueItem.Exception = new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException);
|
||||
try
|
||||
{
|
||||
queueItem.Wait.Set();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
catch
|
||||
else
|
||||
{
|
||||
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
|
||||
obj.LastReturnTime = DateTime.Now;
|
||||
|
||||
try
|
||||
{
|
||||
queueItem.Wait.Set();
|
||||
isReturn = true;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
@ -464,10 +475,25 @@ namespace FreeSql.Internal.ObjectPool
|
||||
{
|
||||
if (_getAsyncQueue.TryDequeue(out var tcs) && tcs != null && tcs.Task.IsCanceled == false)
|
||||
{
|
||||
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
|
||||
obj.LastReturnTime = DateTime.Now;
|
||||
if (UnavailableException != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
tcs.TrySetException(new Exception($"【{Policy.Name}】Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
else
|
||||
{
|
||||
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
|
||||
obj.LastReturnTime = DateTime.Now;
|
||||
|
||||
try { isReturn = tcs.TrySetResult(obj); } catch { }
|
||||
try
|
||||
{
|
||||
isReturn = tcs.TrySetResult(obj);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -524,6 +550,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
internal Object<T> ReturnValue { get; set; }
|
||||
internal object Lock = new object();
|
||||
internal bool IsTimeout { get; set; } = false;
|
||||
internal Exception Exception { get; set; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
|
Reference in New Issue
Block a user