mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-20 04:48:16 +08:00
Merge branch 'master' into daily
This commit is contained in:
@ -45,7 +45,7 @@ namespace FreeSql.DataAnnotations
|
||||
{
|
||||
if (string.IsNullOrEmpty(AsTable) == false)
|
||||
{
|
||||
var atm = Regex.Match(AsTable, @"([\w_\d]+)\s*=\s*(\d\d\d\d)\s*\-\s*(\d\d?)\s*\-\s*(\d\d?)\s*( [\d:]+)?\((\d+)\s*(year|month|day|hour)\)", RegexOptions.IgnoreCase);
|
||||
var atm = Regex.Match(AsTable, @"([\w_\d]+)\s*=\s*(\d\d\d\d)\s*\-\s*(\d\d?)\s*\-\s*(\d\d?)\s*( [\d:]+)?\(([\d,]+)\s*(year|month|day|hour)\)", RegexOptions.IgnoreCase);
|
||||
if (atm.Success == false)
|
||||
throw new Exception(CoreStrings.AsTable_PropertyName_FormatError(AsTable));
|
||||
|
||||
@ -65,11 +65,12 @@ namespace FreeSql.DataAnnotations
|
||||
else if (hhmmss.Length == 2) beginTime = $"{beginTime} {hhmmss[0]}:{hhmmss[1]}:0";
|
||||
else if (hhmmss.Length == 3) beginTime = $"{beginTime} {hhmmss[0]}:{hhmmss[1]}:{hhmmss[2]}";
|
||||
}
|
||||
int.TryParse(atm.Groups[6].Value, out var atm6);
|
||||
var intervals = atm.Groups[6].Value.Split(',').Select(a => int.TryParse(a, out var atm6) ? atm6 : 0).Where(a => a > 0).ToArray();
|
||||
string atm7 = atm.Groups[7].Value.ToLower();
|
||||
tb.AsTableImpl = new DateTimeAsTableImpl(Name, DateTime.Parse(beginTime), dt =>
|
||||
tb.AsTableImpl = new DateTimeAsTableImpl(Name, DateTime.Parse(beginTime), (dt, idx) =>
|
||||
{
|
||||
switch (atm7)
|
||||
var atm6 = idx >= 0 && idx < intervals.Length ? intervals[idx] : intervals.Last();
|
||||
switch (atm7)
|
||||
{
|
||||
case "year": return dt.AddYears(atm6);
|
||||
case "month": return dt.AddMonths(atm6);
|
||||
@ -85,23 +86,24 @@ namespace FreeSql.DataAnnotations
|
||||
public interface IAsTable
|
||||
{
|
||||
string[] AllTables { get; }
|
||||
string GetTableNameByColumnValue(object columnValue, bool autoExpand = false);
|
||||
IAsTable SetTableName(int index, string tableName);
|
||||
string GetTableNameByColumnValue(object columnValue, bool autoExpand = false);
|
||||
string[] GetTableNamesByColumnValueRange(object columnValue1, object columnValue2);
|
||||
string[] GetTableNamesBySqlWhere(string sqlWhere, List<DbParameter> dbParams, SelectTableInfo tb, CommonUtils commonUtils);
|
||||
}
|
||||
class DateTimeAsTableImpl : IAsTable
|
||||
class DateTimeAsTableImpl : IAsTable
|
||||
{
|
||||
readonly object _lock = new object();
|
||||
readonly List<string> _allTables = new List<string>();
|
||||
readonly List<DateTime> _allTablesTime = new List<DateTime>();
|
||||
readonly DateTime _beginTime;
|
||||
DateTime _lastTime;
|
||||
Func<DateTime, DateTime> _nextTimeFunc;
|
||||
Func<DateTime, int, DateTime> _nextTimeFunc;
|
||||
string _tableName;
|
||||
Match _tableNameFormat;
|
||||
static Regex _regTableNameFormat = new Regex(@"\{([^\\}]+)\}");
|
||||
|
||||
public DateTimeAsTableImpl(string tableName, DateTime beginTime, Func<DateTime, DateTime> nextTimeFunc)
|
||||
public DateTimeAsTableImpl(string tableName, DateTime beginTime, Func<DateTime, int, DateTime> nextTimeFunc)
|
||||
{
|
||||
if (nextTimeFunc == null) throw new ArgumentException(CoreStrings.Cannot_Be_NULL_Name("nextTimeFunc"));
|
||||
//beginTime = beginTime.Date; //日期部分作为开始
|
||||
@ -116,7 +118,8 @@ namespace FreeSql.DataAnnotations
|
||||
int GetTimestamp(DateTime dt) => (int)dt.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
|
||||
void ExpandTable(DateTime beginTime, DateTime endTime)
|
||||
{
|
||||
if (beginTime > endTime) endTime = _nextTimeFunc(beginTime);
|
||||
var index = 0;
|
||||
if (beginTime > endTime) endTime = _nextTimeFunc(beginTime, -1);
|
||||
lock (_lock)
|
||||
{
|
||||
while (beginTime <= endTime)
|
||||
@ -127,7 +130,7 @@ namespace FreeSql.DataAnnotations
|
||||
_allTables.Insert(0, name);
|
||||
_allTablesTime.Insert(0, beginTime);
|
||||
_lastTime = beginTime;
|
||||
beginTime = _nextTimeFunc(beginTime);
|
||||
beginTime = _nextTimeFunc(beginTime, index++);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -153,7 +156,7 @@ namespace FreeSql.DataAnnotations
|
||||
{
|
||||
var dt = ParseColumnValue(columnValue);
|
||||
if (dt < _beginTime) throw new Exception(CoreStrings.SubTableFieldValue_CannotLessThen(dt.ToString("yyyy-MM-dd HH:mm:ss"), _beginTime.ToString("yyyy-MM-dd HH:mm:ss")));
|
||||
var tmpTime = _nextTimeFunc(_lastTime);
|
||||
var tmpTime = _nextTimeFunc(_lastTime, -1);
|
||||
if (dt >= tmpTime && autoExpand)
|
||||
{
|
||||
// 自动建表
|
||||
@ -375,5 +378,13 @@ namespace FreeSql.DataAnnotations
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public IAsTable SetTableName(int index, string tableName)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_allTables[index] = tableName;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -45,8 +45,20 @@ namespace FreeSql.DataAnnotations
|
||||
_table.DisableSyncStructure = value;
|
||||
return this;
|
||||
}
|
||||
/// <summary>
|
||||
/// 格式:属性名=开始时间(递增)<para></para>
|
||||
/// 按年分表:[Table(Name = "log_{yyyy}", AsTable = "create_time=2022-1-1(1 year)")]<para></para>
|
||||
/// 按月分表:[Table(Name = "log_{yyyyMM}", AsTable = "create_time=2022-5-1(1 month)")]<para></para>
|
||||
/// 按日分表:[Table(Name = "log_{yyyyMMdd}", AsTable = "create_time=2022-5-1(5 day)")]<para></para>
|
||||
/// 按时分表:[Table(Name = "log_{yyyyMMddHH}", AsTable = "create_time=2022-5-1(6 hour)")]<para></para>
|
||||
/// </summary>
|
||||
public TableFluent AsTable(string value)
|
||||
{
|
||||
_table.AsTable = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColumnFluent Property(string proto)
|
||||
public ColumnFluent Property(string proto)
|
||||
{
|
||||
if (_properties.TryGetValue(proto, out var tryProto) == false) throw new KeyNotFoundException(CoreStrings.NotFound_PropertyName(proto));
|
||||
var col = _table._columns.GetOrAdd(tryProto.Name, name => new ColumnAttribute { });
|
||||
@ -125,9 +137,21 @@ namespace FreeSql.DataAnnotations
|
||||
{
|
||||
_table.DisableSyncStructure = value;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 格式:属性名=开始时间(递增)<para></para>
|
||||
/// 按年分表:[Table(Name = "log_{yyyy}", AsTable = "create_time=2022-1-1(1 year)")]<para></para>
|
||||
/// 按月分表:[Table(Name = "log_{yyyyMM}", AsTable = "create_time=2022-5-1(1 month)")]<para></para>
|
||||
/// 按日分表:[Table(Name = "log_{yyyyMMdd}", AsTable = "create_time=2022-5-1(5 day)")]<para></para>
|
||||
/// 按时分表:[Table(Name = "log_{yyyyMMddHH}", AsTable = "create_time=2022-5-1(6 hour)")]<para></para>
|
||||
/// </summary>
|
||||
public TableFluent<T> AsTable(string value)
|
||||
{
|
||||
_table.AsTable = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ColumnFluent Property<TProto>(Expression<Func<T, TProto>> column)
|
||||
public ColumnFluent Property<TProto>(Expression<Func<T, TProto>> column)
|
||||
{
|
||||
var exp = column?.Body;
|
||||
if (exp?.NodeType == ExpressionType.Convert) exp = (exp as UnaryExpression)?.Operand;
|
||||
|
@ -17,12 +17,12 @@
|
||||
<SignAssembly>true</SignAssembly>
|
||||
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
|
||||
<DelaySign>false</DelaySign>
|
||||
<Version>3.2.806-preview20231120</Version>
|
||||
<Version>3.2.806-preview20231124</Version>
|
||||
<PackageReadmeFile>readme.md</PackageReadmeFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="../readme.md" Pack="true" PackagePath="\"/>
|
||||
<None Include="../readme.md" Pack="true" PackagePath="\" />
|
||||
<None Include="../logo.png" Pack="true" PackagePath="\" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
@ -478,6 +478,15 @@
|
||||
禁用 CodeFirst 同步结构迁移
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent.AsTable(System.String)">
|
||||
<summary>
|
||||
格式:属性名=开始时间(递增)<para></para>
|
||||
按年分表:[Table(Name = "log_{yyyy}", AsTable = "create_time=2022-1-1(1 year)")]<para></para>
|
||||
按月分表:[Table(Name = "log_{yyyyMM}", AsTable = "create_time=2022-5-1(1 month)")]<para></para>
|
||||
按日分表:[Table(Name = "log_{yyyyMMdd}", AsTable = "create_time=2022-5-1(5 day)")]<para></para>
|
||||
按时分表:[Table(Name = "log_{yyyyMMddHH}", AsTable = "create_time=2022-5-1(6 hour)")]<para></para>
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent.Navigate(System.String,System.String,System.Type)">
|
||||
<summary>
|
||||
导航关系Fluent,与 NavigateAttribute 对应
|
||||
@ -511,6 +520,15 @@
|
||||
禁用 CodeFirst 同步结构迁移
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent`1.AsTable(System.String)">
|
||||
<summary>
|
||||
格式:属性名=开始时间(递增)<para></para>
|
||||
按年分表:[Table(Name = "log_{yyyy}", AsTable = "create_time=2022-1-1(1 year)")]<para></para>
|
||||
按月分表:[Table(Name = "log_{yyyyMM}", AsTable = "create_time=2022-5-1(1 month)")]<para></para>
|
||||
按日分表:[Table(Name = "log_{yyyyMMdd}", AsTable = "create_time=2022-5-1(5 day)")]<para></para>
|
||||
按时分表:[Table(Name = "log_{yyyyMMddHH}", AsTable = "create_time=2022-5-1(6 hour)")]<para></para>
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent`1.Navigate``1(System.Linq.Expressions.Expression{System.Func{`0,``0}},System.String,System.Type)">
|
||||
<summary>
|
||||
导航关系Fluent,与 NavigateAttribute 对应
|
||||
@ -1086,6 +1104,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
|
||||
@ -5769,6 +5863,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>
|
||||
@ -6285,115 +6401,3 @@
|
||||
</member>
|
||||
</members>
|
||||
</doc>
|
||||
`0})">
|
||||
<summary>
|
||||
插入数据,传入实体集合
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<param name="source"></param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.InsertOrUpdate``1">
|
||||
<summary>
|
||||
插入或更新数据,此功能依赖数据库特性(低版本可能不支持),参考如下:<para></para>
|
||||
MySql 5.6+: on duplicate key update<para></para>
|
||||
PostgreSQL 9.4+: on conflict do update<para></para>
|
||||
SqlServer 2008+: merge into<para></para>
|
||||
Oracle 11+: merge into<para></para>
|
||||
Sqlite: replace into<para></para>
|
||||
达梦: merge into<para></para>
|
||||
人大金仓:on conflict do update<para></para>
|
||||
神通:merge into<para></para>
|
||||
MsAccess:不支持<para></para>
|
||||
注意区别:FreeSql.Repository 仓储也有 InsertOrUpdate 方法(不依赖数据库特性)
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Update``1">
|
||||
<summary>
|
||||
修改数据
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Update``1(System.Object)">
|
||||
<summary>
|
||||
修改数据,传入动态条件,如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Select``1">
|
||||
<summary>
|
||||
查询数据
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Select``1(System.Object)">
|
||||
<summary>
|
||||
查询数据,传入动态条件,如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Delete``1">
|
||||
<summary>
|
||||
删除数据
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Delete``1(System.Object)">
|
||||
<summary>
|
||||
删除数据,传入动态条件,如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1}
|
||||
</summary>
|
||||
<typeparam name="T1"></typeparam>
|
||||
<param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Transaction(System.Action)">
|
||||
<summary>
|
||||
开启事务(不支持异步)<para></para>
|
||||
v1.5.0 关闭了线程事务超时自动提交的机制
|
||||
</summary>
|
||||
<param name="handler">事务体 () => {}</param>
|
||||
</member>
|
||||
<member name="M:IFreeSql.Transaction(System.Data.IsolationLevel,System.Action)">
|
||||
<summary>
|
||||
开启事务(不支持异步)<para></para>
|
||||
v1.5.0 关闭了线程事务超时自动提交的机制
|
||||
</summary>
|
||||
<param name="isolationLevel"></param>
|
||||
<param name="handler">事务体 () => {}</param>
|
||||
</member>
|
||||
<member name="P:IFreeSql.Ado">
|
||||
<summary>
|
||||
数据库访问对象
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:IFreeSql.Aop">
|
||||
<summary>
|
||||
所有拦截方法都在这里
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:IFreeSql.CodeFirst">
|
||||
<summary>
|
||||
CodeFirst 模式开发相关方法
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:IFreeSql.DbFirst">
|
||||
<summary>
|
||||
DbFirst 模式开发相关方法
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:IFreeSql.GlobalFilter">
|
||||
<summary>
|
||||
全局过滤设置,可默认附加为 Select/Update/Delete 条件
|
||||
</summary>
|
||||
</member>
|
||||
</members>
|
||||
</doc>
|
||||
|
@ -26,7 +26,7 @@ namespace FreeSql.Internal.Model
|
||||
public bool DisableSyncStructure { get; set; }
|
||||
public string Comment { get; set; }
|
||||
public bool IsRereadSql { get; internal set; }
|
||||
public bool IsDictionaryType { get; internal set; }
|
||||
public bool IsDictionaryType { get; set; }
|
||||
|
||||
public IAsTable AsTableImpl { get; internal set; }
|
||||
public ColumnInfo AsTableColumn { get; internal set; }
|
||||
|
@ -352,7 +352,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
}
|
||||
catch
|
||||
{
|
||||
Return(obj);
|
||||
Return(obj, true);
|
||||
throw;
|
||||
}
|
||||
|
||||
@ -404,7 +404,7 @@ namespace FreeSql.Internal.ObjectPool
|
||||
}
|
||||
catch
|
||||
{
|
||||
Return(obj);
|
||||
Return(obj, true);
|
||||
throw;
|
||||
}
|
||||
|
||||
|
@ -112,477 +112,22 @@ namespace FreeSql.Internal
|
||||
continue;
|
||||
}
|
||||
if (tp == null && colattr != null) colattr.IsIgnore = true; //无法匹配的属性,认定是导航属性,且自动过滤
|
||||
var colattrIsNullable = colattr?._IsNullable;
|
||||
var colattrIsNull = colattr == null;
|
||||
if (colattr == null)
|
||||
colattr = new ColumnAttribute
|
||||
{
|
||||
Name = p.Name,
|
||||
DbType = tp.dbtypeFull,
|
||||
IsNullable = tp.isnullable ?? true,
|
||||
MapType = p.PropertyType
|
||||
};
|
||||
if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable;
|
||||
if (string.IsNullOrEmpty(colattr.DbType)) colattr.DbType = tp?.dbtypeFull ?? "varchar(255)";
|
||||
if (colattr.DbType.StartsWith("set(") || colattr.DbType.StartsWith("enum("))
|
||||
{
|
||||
var leftBt = colattr.DbType.IndexOf('(');
|
||||
colattr.DbType = colattr.DbType.Substring(0, leftBt).ToUpper() + colattr.DbType.Substring(leftBt);
|
||||
}
|
||||
else if (common._orm.Ado.DataType != DataType.ClickHouse)
|
||||
colattr.DbType = colattr.DbType.ToUpper();
|
||||
|
||||
if (colattrIsNull == false && colattrIsNullable == true) colattr.DbType = colattr.DbType.Replace("NOT NULL", "");
|
||||
if (colattrIsNull == false && colattrIsNullable == false && colattr.DbType.Contains("NOT NULL") == false) colattr.DbType = Regex.Replace(colattr.DbType, @"\bNULL\b", "").Trim() + " NOT NULL";
|
||||
if (colattr._IsNullable == null && tp != null && tp.isnullable == null) colattr.IsNullable = tp.dbtypeFull.Contains("NOT NULL") == false;
|
||||
if (colattr.DbType?.Contains("NOT NULL") == true) colattr.IsNullable = false;
|
||||
if (string.IsNullOrEmpty(colattr.Name)) colattr.Name = p.Name;
|
||||
if (common.CodeFirst.IsSyncStructureToLower) colattr.Name = colattr.Name.ToLower();
|
||||
if (common.CodeFirst.IsSyncStructureToUpper) colattr.Name = colattr.Name.ToUpper();
|
||||
var col = ColumnAttributeToInfo(trytb, entityDefault, p.Name, p.PropertyType, setMethod == null, ref colattr, tp, common);
|
||||
if (col == null) continue;
|
||||
|
||||
if ((colattr.IsNullable != true || colattr.IsIdentity == true || colattr.IsPrimary == true) && colattr.DbType.Contains("NOT NULL") == false && common._orm.Ado.DataType != DataType.ClickHouse)
|
||||
{
|
||||
colattr.IsNullable = false;
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, @"\bNULL\b", "").Trim() + " NOT NULL";
|
||||
}
|
||||
if (colattr.IsNullable == true && colattr.DbType.Contains("NOT NULL")) colattr.DbType = colattr.DbType.Replace("NOT NULL", "");
|
||||
else if (colattr.IsNullable == true && !colattr.DbType.Contains("Nullable") && common._orm.Ado.DataType == DataType.ClickHouse) colattr.DbType = $"Nullable({colattr.DbType})";
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, @"\([^\)]+\)", m =>
|
||||
{
|
||||
var tmpLt = Regex.Replace(m.Groups[0].Value, @"\s", "");
|
||||
if (tmpLt.Contains("CHAR")) tmpLt = tmpLt.Replace("CHAR", " CHAR");
|
||||
if (tmpLt.Contains("BYTE")) tmpLt = tmpLt.Replace("BYTE", " BYTE");
|
||||
return tmpLt;
|
||||
});
|
||||
if (colattr.IsIdentity == true && colattr.MapType.IsNumberType() == false)
|
||||
colattr.IsIdentity = false;
|
||||
if (setMethod == null) colattr.IsIgnore = true;
|
||||
if (propsComment != null && propsComment.TryGetValue(p.Name, out var trycomment))
|
||||
col.Comment = trycomment;
|
||||
if (string.IsNullOrEmpty(col.Comment) && propsCommentByDescAttr != null && propsCommentByDescAttr.TryGetValue(p.Name, out trycomment))
|
||||
col.Comment = trycomment;
|
||||
|
||||
var col = new ColumnInfo
|
||||
{
|
||||
Table = trytb,
|
||||
CsName = p.Name,
|
||||
CsType = p.PropertyType,
|
||||
Attribute = colattr
|
||||
};
|
||||
if (propsComment != null && propsComment.TryGetValue(p.Name, out var trycomment))
|
||||
col.Comment = trycomment;
|
||||
if (string.IsNullOrEmpty(col.Comment) && propsCommentByDescAttr != null && propsCommentByDescAttr.TryGetValue(p.Name, out trycomment))
|
||||
col.Comment = trycomment;
|
||||
|
||||
if (colattr.IsIgnore)
|
||||
{
|
||||
trytb.ColumnsByCsIgnore.Add(p.Name, col);
|
||||
continue;
|
||||
}
|
||||
object defaultValue = null;
|
||||
if (entityDefault != null) defaultValue = trytb.Properties[p.Name].GetValue(entityDefault, null);
|
||||
if (p.PropertyType.IsEnum)
|
||||
{
|
||||
var isEqualsEnumValue = false;
|
||||
var enumValues = Enum.GetValues(p.PropertyType);
|
||||
for (var a = 0; a < enumValues.Length; a++)
|
||||
if (object.Equals(defaultValue, enumValues.GetValue(a)))
|
||||
{
|
||||
isEqualsEnumValue = true;
|
||||
break;
|
||||
}
|
||||
if (isEqualsEnumValue == false && enumValues.Length > 0)
|
||||
defaultValue = enumValues.GetValue(0);
|
||||
}
|
||||
if (defaultValue != null && p.PropertyType != colattr.MapType) defaultValue = Utils.GetDataReaderValue(colattr.MapType, defaultValue);
|
||||
if (defaultValue == null) defaultValue = tp?.defaultValue;
|
||||
if (colattr.IsNullable == false && defaultValue == null)
|
||||
{
|
||||
var citype = colattr.MapType.IsNullableType() ? colattr.MapType.GetGenericArguments().FirstOrDefault() : colattr.MapType;
|
||||
defaultValue = citype.CreateInstanceGetDefaultValue();
|
||||
}
|
||||
try
|
||||
{
|
||||
var initParms = new List<DbParameter>();
|
||||
col.DbDefaultValue = common.GetNoneParamaterSqlValue(initParms, "init", col, colattr.MapType, defaultValue);
|
||||
if (initParms.Any()) col.DbDefaultValue = "NULL";
|
||||
}
|
||||
catch
|
||||
{
|
||||
col.DbDefaultValue = "NULL";
|
||||
}
|
||||
//if (defaultValue != null && colattr.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
//{
|
||||
// var dt = (DateTime)defaultValue;
|
||||
// if (Math.Abs(dt.Subtract(DateTime.Now).TotalSeconds) < 60)
|
||||
// col.DbDefaultValue = common.Now;
|
||||
// else if (Math.Abs(dt.Subtract(DateTime.UtcNow).TotalSeconds) < 60)
|
||||
// col.DbDefaultValue = common.NowUtc;
|
||||
//}
|
||||
|
||||
if (common._orm.Ado.DataType == DataType.GBase)
|
||||
{
|
||||
if (colattr.IsIdentity == true)
|
||||
{
|
||||
var colType = col.CsType.NullableTypeOrThis();
|
||||
if (colType == typeof(int) || colType == typeof(uint))
|
||||
colattr.DbType = "SERIAL";
|
||||
else if (colType == typeof(long) || colType == typeof(ulong))
|
||||
colattr.DbType = "SERIAL8";
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
{
|
||||
if (colattr._Precision == null)
|
||||
{
|
||||
colattr.DbType = "DATETIME YEAR TO FRACTION(3)";
|
||||
colattr.Precision = 3;
|
||||
col.DbPrecision = 3;
|
||||
}
|
||||
else if (colattr._Precision == 0)
|
||||
{
|
||||
colattr.DbType = "DATETIME YEAR TO SECOND";
|
||||
}
|
||||
else if (colattr._Precision > 0)
|
||||
{
|
||||
colattr.DbType = $"DATETIME YEAR TO FRACTION({colattr.Precision})";
|
||||
col.DbPrecision = (byte)colattr.Precision;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (colattr.ServerTime != DateTimeKind.Unspecified && new[] { typeof(DateTime), typeof(DateTimeOffset) }.Contains(colattr.MapType.NullableTypeOrThis()))
|
||||
{
|
||||
var commonNow = common.Now;
|
||||
var commonNowUtc = common.NowUtc;
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql: //处理毫秒
|
||||
case DataType.CustomMySql:
|
||||
var timeLength = 0;
|
||||
var mTimeLength = Regex.Match(colattr.DbType, @"(DATETIME|TIMESTAMP)\s*\((\d+)\)");
|
||||
if (mTimeLength.Success) timeLength = int.Parse(mTimeLength.Groups[2].Value);
|
||||
if (timeLength > 0 && timeLength < 7)
|
||||
{
|
||||
commonNow = $"{commonNow.TrimEnd('(', ')')}({timeLength})";
|
||||
commonNowUtc = $"{commonNowUtc.TrimEnd('(', ')')}({timeLength})";
|
||||
}
|
||||
//https://github.com/dotnetcore/FreeSql/issues/1604 mysql 不支持默认值 utc_timestamp DDL
|
||||
if (colattr.ServerTime == DateTimeKind.Local)
|
||||
col.DbDefaultValue = commonNow;
|
||||
break;
|
||||
default:
|
||||
col.DbDefaultValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
break;
|
||||
}
|
||||
col.DbInsertValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
col.DbUpdateValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
}
|
||||
if (string.IsNullOrEmpty(colattr.InsertValueSql) == false)
|
||||
{
|
||||
col.DbDefaultValue = colattr.InsertValueSql;
|
||||
col.DbInsertValue = colattr.InsertValueSql;
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(string) && colattr.StringLength != 0)
|
||||
{
|
||||
int strlen = colattr.StringLength;
|
||||
var charPatten = @"(CHARACTER|CHAR2|CHAR)\s*(\([^\)]*\))?";
|
||||
var strNotNull = colattr.IsNullable == false ? " NOT NULL" : "";
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql:
|
||||
case DataType.CustomMySql:
|
||||
if (strlen == -2) colattr.DbType = $"LONGTEXT{strNotNull}";
|
||||
else if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.SqlServer:
|
||||
case DataType.OdbcSqlServer:
|
||||
case DataType.CustomSqlServer:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1(MAX)");
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.PostgreSQL:
|
||||
case DataType.OdbcPostgreSQL:
|
||||
case DataType.CustomPostgreSQL:
|
||||
case DataType.KingbaseES:
|
||||
case DataType.OdbcKingbaseES:
|
||||
case DataType.ShenTong:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Oracle:
|
||||
case DataType.CustomOracle:
|
||||
if (strlen < 0) colattr.DbType = $"NCLOB{strNotNull}"; //v1.3.2+ https://github.com/dotnetcore/FreeSql/issues/259
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Dameng:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.OdbcOracle:
|
||||
case DataType.OdbcDameng:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1(4000)"); //ODBC 不支持 NCLOB
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Sqlite:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.MsAccess:
|
||||
charPatten = @"(CHAR|CHAR2|CHARACTER|TEXT)\s*(\([^\)]*\))?";
|
||||
if (strlen < 0) colattr.DbType = $"LONGTEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Firebird:
|
||||
charPatten = @"(CHAR|CHAR2|CHARACTER|TEXT)\s*(\([^\)]*\))?";
|
||||
if (strlen < 0) colattr.DbType = $"BLOB SUB_TYPE 1{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.GBase:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colattr.MapType == typeof(string) && colattr.IsVersion == true) colattr.StringLength = 40;
|
||||
if (colattr.MapType == typeof(byte[]) && colattr.IsVersion == true) colattr.StringLength = 16; // 8=sqlserver timestamp, 16=GuidToBytes
|
||||
if (colattr.MapType == typeof(byte[]) && colattr.StringLength != 0)
|
||||
{
|
||||
int strlen = colattr.StringLength;
|
||||
var bytePatten = @"(VARBINARY|BINARY|BYTEA)\s*(\([^\)]*\))?";
|
||||
var strNotNull = colattr.IsNullable == false ? " NOT NULL" : "";
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql:
|
||||
case DataType.CustomMySql:
|
||||
if (strlen == -2) colattr.DbType = $"LONGBLOB{strNotNull}";
|
||||
else if (strlen < 0) colattr.DbType = $"BLOB{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.SqlServer:
|
||||
case DataType.OdbcSqlServer:
|
||||
case DataType.CustomSqlServer:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1(MAX)");
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.PostgreSQL:
|
||||
case DataType.OdbcPostgreSQL:
|
||||
case DataType.CustomPostgreSQL:
|
||||
case DataType.KingbaseES:
|
||||
case DataType.OdbcKingbaseES:
|
||||
case DataType.ShenTong: //驱动引发的异常:“System.Data.OscarClient.OscarException”(位于 System.Data.OscarClient.dll 中)
|
||||
colattr.DbType = $"BYTEA{strNotNull}"; //变长二进制串
|
||||
break;
|
||||
case DataType.Oracle:
|
||||
case DataType.CustomOracle:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.Dameng:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.OdbcOracle:
|
||||
case DataType.OdbcDameng:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.Sqlite:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.MsAccess:
|
||||
if (strlen < 0) colattr.DbType = $"BLOB{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Firebird:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.GBase:
|
||||
colattr.DbType = $"BYTE{strNotNull}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(decimal) && (colattr.Precision > 0 || colattr.Scale > 0))
|
||||
{
|
||||
if (colattr.Precision <= 0) colattr.Precision = 10;
|
||||
if (colattr.Scale <= 0) colattr.Scale = 0;
|
||||
var decimalPatten = @"(DECIMAL|NUMERIC|NUMBER)\s*(\([^\)]*\))?";
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, decimalPatten, $"$1({colattr.Precision},{colattr.Scale})");
|
||||
}
|
||||
|
||||
if (trytb.Columns.ContainsKey(colattr.Name)) throw new Exception(CoreStrings.Duplicate_ColumnAttribute(colattr.Name));
|
||||
if (trytb.ColumnsByCs.ContainsKey(p.Name)) throw new Exception(CoreStrings.Duplicate_PropertyName(p.Name));
|
||||
|
||||
trytb.Columns.Add(colattr.Name, col);
|
||||
trytb.Columns.Add(colattr.Name, col);
|
||||
trytb.ColumnsByCs.Add(p.Name, col);
|
||||
columnsList.Add(col);
|
||||
}
|
||||
trytb.VersionColumn = trytb.Columns.Values.Where(a => a.Attribute.IsVersion == true).LastOrDefault();
|
||||
if (trytb.VersionColumn != null)
|
||||
{
|
||||
if (trytb.VersionColumn.Attribute.MapType.IsNullableType() ||
|
||||
trytb.VersionColumn.Attribute.MapType.IsNumberType() == false && !new[] { typeof(byte[]), typeof(string) }.Contains(trytb.VersionColumn.Attribute.MapType))
|
||||
throw new Exception(CoreStrings.Properties_AsRowLock_Must_Numeric_Byte(trytb.VersionColumn.CsName));
|
||||
}
|
||||
tbattr?.ParseAsTable(trytb);
|
||||
|
||||
var indexesDict = new Dictionary<string, IndexInfo>(StringComparer.CurrentCultureIgnoreCase);
|
||||
//从数据库查找主键、自增、索引
|
||||
if (common.CodeFirst.IsConfigEntityFromDbFirst)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (common._orm.DbFirst != null)
|
||||
{
|
||||
if (common.dbTables == null)
|
||||
lock (common.dbTablesLock)
|
||||
if (common.dbTables == null)
|
||||
common.dbTables = common._orm.DbFirst.GetTablesByDatabase();
|
||||
|
||||
var finddbtbs = common.dbTables.Where(a => string.Compare(a.Name, trytb.CsName, true) == 0 || string.Compare(a.Name, trytb.DbName, true) == 0);
|
||||
foreach (var dbtb in finddbtbs)
|
||||
{
|
||||
foreach (var dbident in dbtb.Identitys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsIdentity = true;
|
||||
}
|
||||
foreach (var dbpk in dbtb.Primarys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var dbidx in dbtb.IndexesDict)
|
||||
{
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var dbcol in dbidx.Value.Columns)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbcol.Column.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbcol.Column.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis())
|
||||
indexColumns.Add(new IndexColumnInfo
|
||||
{
|
||||
Column = trycol,
|
||||
IsDesc = dbcol.IsDesc
|
||||
});
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
if (indexesDict.ContainsKey(dbidx.Key)) indexesDict.Remove(dbidx.Key);
|
||||
indexesDict.Add(dbidx.Key, new IndexInfo
|
||||
{
|
||||
Name = dbidx.Key,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = dbidx.Value.IsUnique,
|
||||
IndexMethod = IndexMethod.B_Tree
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
//索引和唯一键
|
||||
var indexes = common.GetEntityIndexAttribute(trytb.Type);
|
||||
foreach (var index in indexes)
|
||||
{
|
||||
var val = index.Fields?.Trim(' ', '\t', ',');
|
||||
if (string.IsNullOrEmpty(val)) continue;
|
||||
var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray();
|
||||
if (arr.Any() == false) continue;
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var field in arr)
|
||||
{
|
||||
var idxcol = new IndexColumnInfo();
|
||||
if (field.EndsWith(" DESC", StringComparison.CurrentCultureIgnoreCase)) idxcol.IsDesc = true;
|
||||
var colname = Regex.Replace(field, " (DESC|ASC)", "", RegexOptions.IgnoreCase);
|
||||
if (trytb.ColumnsByCs.TryGetValue(colname, out var trycol) || trytb.Columns.TryGetValue(colname, out trycol))
|
||||
{
|
||||
idxcol.Column = trycol;
|
||||
indexColumns.Add(idxcol);
|
||||
}
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
var indexName = common.CodeFirst.IsSyncStructureToLower ? index.Name.ToLower() : (common.CodeFirst.IsSyncStructureToUpper ? index.Name.ToUpper() : index.Name);
|
||||
if (indexesDict.ContainsKey(indexName)) indexesDict.Remove(indexName);
|
||||
indexesDict.Add(indexName, new IndexInfo
|
||||
{
|
||||
Name = indexName,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = index.IsUnique,
|
||||
IndexMethod = index.IndexMethod
|
||||
});
|
||||
}
|
||||
trytb.Indexes = indexesDict.Values.ToArray();
|
||||
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, "id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault();
|
||||
if (identcol != null) trytb.Primarys = new[] { identcol };
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
col.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
{
|
||||
col.Attribute.IsNullable = false;
|
||||
col.Attribute.DbType = col.Attribute.DbType.Replace("NOT NULL", "").Replace(" NULL", "").Trim();
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.Sqlite:
|
||||
col.Attribute.DbType += " NOT NULL"; //sqlite 主键也可以插入 null
|
||||
break;
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Columns.Values)
|
||||
{
|
||||
if (col.Attribute.IsPrimary == false && col.Attribute.IsIdentity) col.Attribute.CanUpdate = false;
|
||||
var ltp = @"\(([^\)]+)\)";
|
||||
col.DbTypeText = Regex.Replace(col.Attribute.DbType.Replace("NOT NULL", "").Replace(" NULL", "").Trim(), ltp, "");
|
||||
var m = Regex.Match(col.Attribute.DbType, ltp);
|
||||
if (m.Success == false) continue;
|
||||
var sizeStr = m.Groups[1].Value.Trim();
|
||||
if (sizeStr.EndsWith(" BYTE") || sizeStr.EndsWith(" CHAR")) sizeStr = sizeStr.Remove(sizeStr.Length - 5); //ORACLE
|
||||
if (string.Compare(sizeStr, "max", true) == 0)
|
||||
{
|
||||
col.DbSize = -1;
|
||||
continue;
|
||||
}
|
||||
var sizeArr = sizeStr.Split(',');
|
||||
if (int.TryParse(sizeArr[0].Trim(), out var size) == false) continue;
|
||||
if (col.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
{
|
||||
col.DbScale = (byte)size;
|
||||
if (col.Attribute.Scale <= 0) col.Attribute.Scale = col.DbScale;
|
||||
continue;
|
||||
}
|
||||
if (sizeArr.Length == 1)
|
||||
{
|
||||
col.DbSize = size;
|
||||
if (col.Attribute.StringLength <= 0) col.Attribute.StringLength = col.DbSize;
|
||||
continue;
|
||||
}
|
||||
if (byte.TryParse(sizeArr[1], out var scale) == false) continue;
|
||||
col.DbPrecision = (byte)size;
|
||||
col.DbScale = scale;
|
||||
if (col.Attribute.Precision <= 0)
|
||||
{
|
||||
col.Attribute.Precision = col.DbPrecision;
|
||||
col.Attribute.Scale = col.DbScale;
|
||||
}
|
||||
}
|
||||
trytb.IsRereadSql = trytb.Columns.Where(a => string.IsNullOrWhiteSpace(a.Value.Attribute.RereadSql) == false).Any();
|
||||
trytb.ColumnsByPosition = columnsList.Where(a => a.Attribute.Position > 0).OrderBy(a => a.Attribute.Position)
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position == 0))
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position < 0).OrderBy(a => a.Attribute.Position)).ToArray();
|
||||
trytb.ColumnsByCanUpdateDbUpdateValue = columnsList.Where(a => a.Attribute.CanUpdate == true && string.IsNullOrEmpty(a.DbUpdateValue) == false).ToArray();
|
||||
AuditTableInfo(trytb, tbattr, indexes, columnsList, common);
|
||||
tbc.AddOrUpdate(entity, trytb, (oldkey, oldval) => trytb);
|
||||
|
||||
#region 查找导航属性的关系、virtual 属性延时加载,动态产生新的重写类
|
||||
@ -635,6 +180,475 @@ namespace FreeSql.Internal
|
||||
|
||||
return tbc.TryGetValue(entity, out var trytb2) ? trytb2 : trytb;
|
||||
}
|
||||
public static ColumnInfo ColumnAttributeToInfo(TableInfo trytb, object entityDefault, string csName, Type mapType, bool isIgnore, ref ColumnAttribute colattr, DbInfoResult tp, CommonUtils common)
|
||||
{
|
||||
var colattrIsNullable = colattr?._IsNullable;
|
||||
var colattrIsNull = colattr == null;
|
||||
if (colattr == null)
|
||||
colattr = new ColumnAttribute
|
||||
{
|
||||
Name = csName,
|
||||
DbType = tp.dbtypeFull,
|
||||
IsNullable = tp.isnullable ?? true,
|
||||
MapType = mapType
|
||||
};
|
||||
if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable;
|
||||
if (string.IsNullOrEmpty(colattr.DbType)) colattr.DbType = tp?.dbtypeFull ?? "varchar(255)";
|
||||
if (colattr.DbType.StartsWith("set(") || colattr.DbType.StartsWith("enum("))
|
||||
{
|
||||
var leftBt = colattr.DbType.IndexOf('(');
|
||||
colattr.DbType = colattr.DbType.Substring(0, leftBt).ToUpper() + colattr.DbType.Substring(leftBt);
|
||||
}
|
||||
else if (common._orm.Ado.DataType != DataType.ClickHouse)
|
||||
colattr.DbType = colattr.DbType.ToUpper();
|
||||
|
||||
if (colattrIsNull == false && colattrIsNullable == true) colattr.DbType = colattr.DbType.Replace("NOT NULL", "");
|
||||
if (colattrIsNull == false && colattrIsNullable == false && colattr.DbType.Contains("NOT NULL") == false) colattr.DbType = Regex.Replace(colattr.DbType, @"\bNULL\b", "").Trim() + " NOT NULL";
|
||||
if (colattr._IsNullable == null && tp != null && tp.isnullable == null) colattr.IsNullable = tp.dbtypeFull.Contains("NOT NULL") == false;
|
||||
if (colattr.DbType?.Contains("NOT NULL") == true) colattr.IsNullable = false;
|
||||
if (string.IsNullOrEmpty(colattr.Name)) colattr.Name = csName;
|
||||
if (common.CodeFirst.IsSyncStructureToLower) colattr.Name = colattr.Name.ToLower();
|
||||
if (common.CodeFirst.IsSyncStructureToUpper) colattr.Name = colattr.Name.ToUpper();
|
||||
|
||||
if ((colattr.IsNullable != true || colattr.IsIdentity == true || colattr.IsPrimary == true) && colattr.DbType.Contains("NOT NULL") == false && common._orm.Ado.DataType != DataType.ClickHouse)
|
||||
{
|
||||
colattr.IsNullable = false;
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, @"\bNULL\b", "").Trim() + " NOT NULL";
|
||||
}
|
||||
if (colattr.IsNullable == true && colattr.DbType.Contains("NOT NULL")) colattr.DbType = colattr.DbType.Replace("NOT NULL", "");
|
||||
else if (colattr.IsNullable == true && !colattr.DbType.Contains("Nullable") && common._orm.Ado.DataType == DataType.ClickHouse) colattr.DbType = $"Nullable({colattr.DbType})";
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, @"\([^\)]+\)", m =>
|
||||
{
|
||||
var tmpLt = Regex.Replace(m.Groups[0].Value, @"\s", "");
|
||||
if (tmpLt.Contains("CHAR")) tmpLt = tmpLt.Replace("CHAR", " CHAR");
|
||||
if (tmpLt.Contains("BYTE")) tmpLt = tmpLt.Replace("BYTE", " BYTE");
|
||||
return tmpLt;
|
||||
});
|
||||
if (colattr.IsIdentity == true && colattr.MapType.IsNumberType() == false)
|
||||
colattr.IsIdentity = false;
|
||||
if (isIgnore) colattr.IsIgnore = true;
|
||||
|
||||
var col = new ColumnInfo
|
||||
{
|
||||
Table = trytb,
|
||||
CsName = csName,
|
||||
CsType = mapType,
|
||||
Attribute = colattr
|
||||
};
|
||||
|
||||
if (colattr.IsIgnore)
|
||||
{
|
||||
trytb.ColumnsByCsIgnore.Add(csName, col);
|
||||
return null;
|
||||
}
|
||||
object defaultValue = null;
|
||||
if (entityDefault != null) defaultValue = trytb.Properties[csName].GetValue(entityDefault, null);
|
||||
if (defaultValue != null && mapType.IsEnum)
|
||||
{
|
||||
var isEqualsEnumValue = false;
|
||||
var enumValues = Enum.GetValues(mapType);
|
||||
for (var a = 0; a < enumValues.Length; a++)
|
||||
if (object.Equals(defaultValue, enumValues.GetValue(a)))
|
||||
{
|
||||
isEqualsEnumValue = true;
|
||||
break;
|
||||
}
|
||||
if (isEqualsEnumValue == false && enumValues.Length > 0)
|
||||
defaultValue = enumValues.GetValue(0);
|
||||
}
|
||||
if (defaultValue != null && mapType != colattr.MapType) defaultValue = Utils.GetDataReaderValue(colattr.MapType, defaultValue);
|
||||
if (defaultValue == null) defaultValue = tp?.defaultValue;
|
||||
if (colattr.IsNullable == false && defaultValue == null)
|
||||
{
|
||||
var citype = colattr.MapType.IsNullableType() ? colattr.MapType.GetGenericArguments().FirstOrDefault() : colattr.MapType;
|
||||
defaultValue = citype.CreateInstanceGetDefaultValue();
|
||||
}
|
||||
try
|
||||
{
|
||||
var initParms = new List<DbParameter>();
|
||||
col.DbDefaultValue = common.GetNoneParamaterSqlValue(initParms, "init", col, colattr.MapType, defaultValue);
|
||||
if (initParms.Any()) col.DbDefaultValue = "NULL";
|
||||
}
|
||||
catch
|
||||
{
|
||||
col.DbDefaultValue = "NULL";
|
||||
}
|
||||
//if (defaultValue != null && colattr.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
//{
|
||||
// var dt = (DateTime)defaultValue;
|
||||
// if (Math.Abs(dt.Subtract(DateTime.Now).TotalSeconds) < 60)
|
||||
// col.DbDefaultValue = common.Now;
|
||||
// else if (Math.Abs(dt.Subtract(DateTime.UtcNow).TotalSeconds) < 60)
|
||||
// col.DbDefaultValue = common.NowUtc;
|
||||
//}
|
||||
|
||||
if (common._orm.Ado.DataType == DataType.GBase)
|
||||
{
|
||||
if (colattr.IsIdentity == true)
|
||||
{
|
||||
var colType = col.CsType.NullableTypeOrThis();
|
||||
if (colType == typeof(int) || colType == typeof(uint))
|
||||
colattr.DbType = "SERIAL";
|
||||
else if (colType == typeof(long) || colType == typeof(ulong))
|
||||
colattr.DbType = "SERIAL8";
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
{
|
||||
if (colattr._Precision == null)
|
||||
{
|
||||
colattr.DbType = "DATETIME YEAR TO FRACTION(3)";
|
||||
colattr.Precision = 3;
|
||||
col.DbPrecision = 3;
|
||||
}
|
||||
else if (colattr._Precision == 0)
|
||||
{
|
||||
colattr.DbType = "DATETIME YEAR TO SECOND";
|
||||
}
|
||||
else if (colattr._Precision > 0)
|
||||
{
|
||||
colattr.DbType = $"DATETIME YEAR TO FRACTION({colattr.Precision})";
|
||||
col.DbPrecision = (byte)colattr.Precision;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (colattr.ServerTime != DateTimeKind.Unspecified && new[] { typeof(DateTime), typeof(DateTimeOffset) }.Contains(colattr.MapType.NullableTypeOrThis()))
|
||||
{
|
||||
var commonNow = common.Now;
|
||||
var commonNowUtc = common.NowUtc;
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql: //处理毫秒
|
||||
case DataType.CustomMySql:
|
||||
var timeLength = 0;
|
||||
var mTimeLength = Regex.Match(colattr.DbType, @"(DATETIME|TIMESTAMP)\s*\((\d+)\)");
|
||||
if (mTimeLength.Success) timeLength = int.Parse(mTimeLength.Groups[2].Value);
|
||||
if (timeLength > 0 && timeLength < 7)
|
||||
{
|
||||
commonNow = $"{commonNow.TrimEnd('(', ')')}({timeLength})";
|
||||
commonNowUtc = $"{commonNowUtc.TrimEnd('(', ')')}({timeLength})";
|
||||
}
|
||||
//https://github.com/dotnetcore/FreeSql/issues/1604 mysql 不支持默认值 utc_timestamp DDL
|
||||
if (colattr.ServerTime == DateTimeKind.Local)
|
||||
col.DbDefaultValue = commonNow;
|
||||
break;
|
||||
default:
|
||||
col.DbDefaultValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
break;
|
||||
}
|
||||
col.DbInsertValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
col.DbUpdateValue = colattr.ServerTime == DateTimeKind.Local ? commonNow : commonNowUtc;
|
||||
}
|
||||
if (string.IsNullOrEmpty(colattr.InsertValueSql) == false)
|
||||
{
|
||||
col.DbDefaultValue = colattr.InsertValueSql;
|
||||
col.DbInsertValue = colattr.InsertValueSql;
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(string) && colattr.StringLength != 0)
|
||||
{
|
||||
int strlen = colattr.StringLength;
|
||||
var charPatten = @"(CHARACTER|CHAR2|CHAR)\s*(\([^\)]*\))?";
|
||||
var strNotNull = colattr.IsNullable == false ? " NOT NULL" : "";
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql:
|
||||
case DataType.CustomMySql:
|
||||
if (strlen == -2) colattr.DbType = $"LONGTEXT{strNotNull}";
|
||||
else if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.SqlServer:
|
||||
case DataType.OdbcSqlServer:
|
||||
case DataType.CustomSqlServer:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1(MAX)");
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.PostgreSQL:
|
||||
case DataType.OdbcPostgreSQL:
|
||||
case DataType.CustomPostgreSQL:
|
||||
case DataType.KingbaseES:
|
||||
case DataType.OdbcKingbaseES:
|
||||
case DataType.ShenTong:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Oracle:
|
||||
case DataType.CustomOracle:
|
||||
if (strlen < 0) colattr.DbType = $"NCLOB{strNotNull}"; //v1.3.2+ https://github.com/dotnetcore/FreeSql/issues/259
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Dameng:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.OdbcOracle:
|
||||
case DataType.OdbcDameng:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1(4000)"); //ODBC 不支持 NCLOB
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Sqlite:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.MsAccess:
|
||||
charPatten = @"(CHAR|CHAR2|CHARACTER|TEXT)\s*(\([^\)]*\))?";
|
||||
if (strlen < 0) colattr.DbType = $"LONGTEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Firebird:
|
||||
charPatten = @"(CHAR|CHAR2|CHARACTER|TEXT)\s*(\([^\)]*\))?";
|
||||
if (strlen < 0) colattr.DbType = $"BLOB SUB_TYPE 1{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.GBase:
|
||||
if (strlen < 0) colattr.DbType = $"TEXT{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, charPatten, $"$1({strlen})");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colattr.MapType == typeof(string) && colattr.IsVersion == true) colattr.StringLength = 40;
|
||||
if (colattr.MapType == typeof(byte[]) && colattr.IsVersion == true) colattr.StringLength = 16; // 8=sqlserver timestamp, 16=GuidToBytes
|
||||
if (colattr.MapType == typeof(byte[]) && colattr.StringLength != 0)
|
||||
{
|
||||
int strlen = colattr.StringLength;
|
||||
var bytePatten = @"(VARBINARY|BINARY|BYTEA)\s*(\([^\)]*\))?";
|
||||
var strNotNull = colattr.IsNullable == false ? " NOT NULL" : "";
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.MySql:
|
||||
case DataType.OdbcMySql:
|
||||
case DataType.CustomMySql:
|
||||
if (strlen == -2) colattr.DbType = $"LONGBLOB{strNotNull}";
|
||||
else if (strlen < 0) colattr.DbType = $"BLOB{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.SqlServer:
|
||||
case DataType.OdbcSqlServer:
|
||||
case DataType.CustomSqlServer:
|
||||
if (strlen < 0) colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1(MAX)");
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.PostgreSQL:
|
||||
case DataType.OdbcPostgreSQL:
|
||||
case DataType.CustomPostgreSQL:
|
||||
case DataType.KingbaseES:
|
||||
case DataType.OdbcKingbaseES:
|
||||
case DataType.ShenTong: //驱动引发的异常:“System.Data.OscarClient.OscarException”(位于 System.Data.OscarClient.dll 中)
|
||||
colattr.DbType = $"BYTEA{strNotNull}"; //变长二进制串
|
||||
break;
|
||||
case DataType.Oracle:
|
||||
case DataType.CustomOracle:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.Dameng:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.OdbcOracle:
|
||||
case DataType.OdbcDameng:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.Sqlite:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.MsAccess:
|
||||
if (strlen < 0) colattr.DbType = $"BLOB{strNotNull}";
|
||||
else colattr.DbType = Regex.Replace(colattr.DbType, bytePatten, $"$1({strlen})");
|
||||
break;
|
||||
case DataType.Firebird:
|
||||
colattr.DbType = $"BLOB{strNotNull}";
|
||||
break;
|
||||
case DataType.GBase:
|
||||
colattr.DbType = $"BYTE{strNotNull}";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (colattr.MapType.NullableTypeOrThis() == typeof(decimal) && (colattr.Precision > 0 || colattr.Scale > 0))
|
||||
{
|
||||
if (colattr.Precision <= 0) colattr.Precision = 10;
|
||||
if (colattr.Scale <= 0) colattr.Scale = 0;
|
||||
var decimalPatten = @"(DECIMAL|NUMERIC|NUMBER)\s*(\([^\)]*\))?";
|
||||
colattr.DbType = Regex.Replace(colattr.DbType, decimalPatten, $"$1({colattr.Precision},{colattr.Scale})");
|
||||
}
|
||||
|
||||
if (trytb.Columns.ContainsKey(colattr.Name)) throw new Exception(CoreStrings.Duplicate_ColumnAttribute(colattr.Name));
|
||||
if (trytb.ColumnsByCs.ContainsKey(csName)) throw new Exception(CoreStrings.Duplicate_PropertyName(csName));
|
||||
|
||||
return col;
|
||||
}
|
||||
public static void AuditTableInfo(TableInfo trytb, TableAttribute tbattr, IEnumerable<IndexAttribute> indexes, List<ColumnInfo> columnsList, CommonUtils common)
|
||||
{
|
||||
trytb.VersionColumn = trytb.Columns.Values.Where(a => a.Attribute.IsVersion == true).LastOrDefault();
|
||||
if (trytb.VersionColumn != null)
|
||||
{
|
||||
if (trytb.VersionColumn.Attribute.MapType.IsNullableType() ||
|
||||
trytb.VersionColumn.Attribute.MapType.IsNumberType() == false && !new[] { typeof(byte[]), typeof(string) }.Contains(trytb.VersionColumn.Attribute.MapType))
|
||||
throw new Exception(CoreStrings.Properties_AsRowLock_Must_Numeric_Byte(trytb.VersionColumn.CsName));
|
||||
}
|
||||
tbattr?.ParseAsTable(trytb);
|
||||
|
||||
var indexesDict = new Dictionary<string, IndexInfo>(StringComparer.CurrentCultureIgnoreCase);
|
||||
//从数据库查找主键、自增、索引
|
||||
if (common.CodeFirst.IsConfigEntityFromDbFirst)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (common._orm.DbFirst != null)
|
||||
{
|
||||
if (common.dbTables == null)
|
||||
lock (common.dbTablesLock)
|
||||
if (common.dbTables == null)
|
||||
common.dbTables = common._orm.DbFirst.GetTablesByDatabase();
|
||||
|
||||
var finddbtbs = common.dbTables.Where(a => string.Compare(a.Name, trytb.CsName, true) == 0 || string.Compare(a.Name, trytb.DbName, true) == 0);
|
||||
foreach (var dbtb in finddbtbs)
|
||||
{
|
||||
foreach (var dbident in dbtb.Identitys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsIdentity = true;
|
||||
}
|
||||
foreach (var dbpk in dbtb.Primarys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var dbidx in dbtb.IndexesDict)
|
||||
{
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var dbcol in dbidx.Value.Columns)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbcol.Column.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbcol.Column.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis())
|
||||
indexColumns.Add(new IndexColumnInfo
|
||||
{
|
||||
Column = trycol,
|
||||
IsDesc = dbcol.IsDesc
|
||||
});
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
if (indexesDict.ContainsKey(dbidx.Key)) indexesDict.Remove(dbidx.Key);
|
||||
indexesDict.Add(dbidx.Key, new IndexInfo
|
||||
{
|
||||
Name = dbidx.Key,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = dbidx.Value.IsUnique,
|
||||
IndexMethod = IndexMethod.B_Tree
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
//索引和唯一键
|
||||
foreach (var index in indexes)
|
||||
{
|
||||
var val = index.Fields?.Trim(' ', '\t', ',');
|
||||
if (string.IsNullOrEmpty(val)) continue;
|
||||
var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray();
|
||||
if (arr.Any() == false) continue;
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var field in arr)
|
||||
{
|
||||
var idxcol = new IndexColumnInfo();
|
||||
if (field.EndsWith(" DESC", StringComparison.CurrentCultureIgnoreCase)) idxcol.IsDesc = true;
|
||||
var colname = Regex.Replace(field, " (DESC|ASC)", "", RegexOptions.IgnoreCase);
|
||||
if (trytb.ColumnsByCs.TryGetValue(colname, out var trycol) || trytb.Columns.TryGetValue(colname, out trycol))
|
||||
{
|
||||
idxcol.Column = trycol;
|
||||
indexColumns.Add(idxcol);
|
||||
}
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
var indexName = common.CodeFirst.IsSyncStructureToLower ? index.Name.ToLower() : (common.CodeFirst.IsSyncStructureToUpper ? index.Name.ToUpper() : index.Name);
|
||||
if (indexesDict.ContainsKey(indexName)) indexesDict.Remove(indexName);
|
||||
indexesDict.Add(indexName, new IndexInfo
|
||||
{
|
||||
Name = indexName,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = index.IsUnique,
|
||||
IndexMethod = index.IndexMethod
|
||||
});
|
||||
}
|
||||
trytb.Indexes = indexesDict.Values.ToArray();
|
||||
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, "id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault();
|
||||
if (identcol != null) trytb.Primarys = new[] { identcol };
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute._IsPrimary == null && string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
col.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
{
|
||||
col.Attribute.IsNullable = false;
|
||||
col.Attribute.DbType = col.Attribute.DbType.Replace("NOT NULL", "").Replace(" NULL", "").Trim();
|
||||
switch (common._orm.Ado.DataType)
|
||||
{
|
||||
case DataType.Sqlite:
|
||||
col.Attribute.DbType += " NOT NULL"; //sqlite 主键也可以插入 null
|
||||
break;
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Columns.Values)
|
||||
{
|
||||
if (col.Attribute.IsPrimary == false && col.Attribute.IsIdentity) col.Attribute.CanUpdate = false;
|
||||
var ltp = @"\(([^\)]+)\)";
|
||||
col.DbTypeText = Regex.Replace(col.Attribute.DbType.Replace("NOT NULL", "").Replace(" NULL", "").Trim(), ltp, "");
|
||||
var m = Regex.Match(col.Attribute.DbType, ltp);
|
||||
if (m.Success == false) continue;
|
||||
var sizeStr = m.Groups[1].Value.Trim();
|
||||
if (sizeStr.EndsWith(" BYTE") || sizeStr.EndsWith(" CHAR")) sizeStr = sizeStr.Remove(sizeStr.Length - 5); //ORACLE
|
||||
if (string.Compare(sizeStr, "max", true) == 0)
|
||||
{
|
||||
col.DbSize = -1;
|
||||
continue;
|
||||
}
|
||||
var sizeArr = sizeStr.Split(',');
|
||||
if (int.TryParse(sizeArr[0].Trim(), out var size) == false) continue;
|
||||
if (col.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime))
|
||||
{
|
||||
col.DbScale = (byte)size;
|
||||
if (col.Attribute.Scale <= 0) col.Attribute.Scale = col.DbScale;
|
||||
continue;
|
||||
}
|
||||
if (sizeArr.Length == 1)
|
||||
{
|
||||
col.DbSize = size;
|
||||
if (col.Attribute.StringLength <= 0) col.Attribute.StringLength = col.DbSize;
|
||||
continue;
|
||||
}
|
||||
if (byte.TryParse(sizeArr[1], out var scale) == false) continue;
|
||||
col.DbPrecision = (byte)size;
|
||||
col.DbScale = scale;
|
||||
if (col.Attribute.Precision <= 0)
|
||||
{
|
||||
col.Attribute.Precision = col.DbPrecision;
|
||||
col.Attribute.Scale = col.DbScale;
|
||||
}
|
||||
}
|
||||
trytb.IsRereadSql = trytb.Columns.Where(a => string.IsNullOrWhiteSpace(a.Value.Attribute.RereadSql) == false).Any();
|
||||
trytb.ColumnsByPosition = columnsList.Where(a => a.Attribute.Position > 0).OrderBy(a => a.Attribute.Position)
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position == 0))
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position < 0).OrderBy(a => a.Attribute.Position)).ToArray();
|
||||
trytb.ColumnsByCanUpdateDbUpdateValue = columnsList.Where(a => a.Attribute.CanUpdate == true && string.IsNullOrEmpty(a.DbUpdateValue) == false).ToArray();
|
||||
}
|
||||
public static void AddTableRef(CommonUtils common, TableInfo trytb, PropertyInfo pnv, bool isLazy, NativeTuple<PropertyInfo, bool, bool, MethodInfo, MethodInfo> vp, StringBuilder cscode)
|
||||
{
|
||||
var getMethod = vp?.Item4;
|
||||
|
Reference in New Issue
Block a user