diff --git a/Examples/base_entity/Program.cs b/Examples/base_entity/Program.cs index 95dfcc5a..949cbac3 100644 --- a/Examples/base_entity/Program.cs +++ b/Examples/base_entity/Program.cs @@ -39,6 +39,7 @@ namespace base_entity .UseNoneCommandParameter(true) .UseConnectionString(FreeSql.DataType.Sqlite, "data source=test.db;max pool size=5") //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2") + .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=3") .Build(); BaseEntity.Initialization(fsql); #endregion diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs index 7a8e141d..a4a29bea 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs @@ -36,6 +36,7 @@ namespace FreeSql.Tests.MySqlConnector public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -458,7 +459,10 @@ namespace FreeSql.Tests.MySqlConnector public float testFieldFloat { get; set; } public decimal testFieldDecimal { get; set; } public TimeSpan testFieldTimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } public string testFieldString { get; set; } public Guid testFieldGuid { get; set; } @@ -476,7 +480,10 @@ namespace FreeSql.Tests.MySqlConnector public float? testFieldFloatNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } public MygisPoint testFieldPoint { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs index 3fe86a01..6ad6d8e6 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs @@ -36,6 +36,7 @@ namespace FreeSql.Tests.MySql public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -464,7 +465,10 @@ namespace FreeSql.Tests.MySql public float testFieldFloat { get; set; } public decimal testFieldDecimal { get; set; } public TimeSpan testFieldTimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } public string testFieldString { get; set; } public Guid testFieldGuid { get; set; } @@ -482,7 +486,10 @@ namespace FreeSql.Tests.MySql public float? testFieldFloatNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } public MygisPoint testFieldPoint { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs index 4cfd7adc..ca92ea08 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs @@ -36,6 +36,7 @@ namespace FreeSql.Tests.Oracle public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -222,8 +223,12 @@ namespace FreeSql.Tests.Oracle public float Float { get; set; } public decimal Decimal { get; set; } public TimeSpan TimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime DateTime { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } public string String { get; set; } public Guid Guid { get; set; } @@ -241,8 +246,12 @@ namespace FreeSql.Tests.Oracle public float? FloatNullable { get; set; } public decimal? DecimalNullable { get; set; } public TimeSpan? TimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? DateTimeNullable { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } public TableAllTypeEnumType1 Enum1 { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs index d91dc319..f16ed691 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs @@ -43,6 +43,7 @@ namespace FreeSql.Tests.PostgreSQL public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -367,7 +368,10 @@ namespace FreeSql.Tests.PostgreSQL public float testFieldFloat { get; set; } public decimal testFieldDecimal { get; set; } public TimeSpan testFieldTimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } public string testFieldString { get; set; } public Guid testFieldGuid { get; set; } @@ -397,7 +401,10 @@ namespace FreeSql.Tests.PostgreSQL public float? testFieldFloatNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } public NpgsqlPoint? testFieldNpgsqlPointNullable { get; set; } public NpgsqlLine? testFieldNpgsqlLineNullable { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs index 179d32e3..722b421c 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs @@ -37,6 +37,7 @@ namespace FreeSql.Tests.SqlServer public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -159,7 +160,7 @@ namespace FreeSql.Tests.SqlServer var sqlTestUpdate = g.sqlserver.Update().SetSource(item3NP).NoneParameter().ToSql(); var item3 = insert.AppendData(item2).ExecuteInserted(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); + var newitem2 = select.Where(a => a.Id == item3NP[0].Id).ToOne(); var items = select.ToList(); } @@ -344,8 +345,12 @@ namespace FreeSql.Tests.SqlServer public float testFieldFloat { get; set; } public decimal testFieldDecimal { get; set; } public TimeSpan testFieldTimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime testFieldDateTime { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTimeOffset testFieldDateTimeOffset { get; set; } + public byte[] testFieldBytes { get; set; } public string testFieldString { get; set; } public Guid testFieldGuid { get; set; } @@ -363,8 +368,12 @@ namespace FreeSql.Tests.SqlServer public float? testFieldFloatNullable { get; set; } public decimal? testFieldDecimalNullable { get; set; } public TimeSpan? testFieldTimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? testFieldDateTimeNullable { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; } + public Guid? testFieldGuidNullable { get; set; } public TableAllTypeEnumType1 testFieldEnum1 { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs index 48281579..f3195f9b 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs @@ -36,6 +36,7 @@ namespace FreeSql.Tests.Sqlite public string 标题 { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime 创建时间 { get; set; } } @@ -262,8 +263,12 @@ namespace FreeSql.Tests.Sqlite public float Float { get; set; } public decimal Decimal { get; set; } public TimeSpan TimeSpan { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime DateTime { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } public string String { get; set; } public Guid Guid { get; set; } @@ -281,8 +286,12 @@ namespace FreeSql.Tests.Sqlite public float? FloatNullable { get; set; } public decimal? DecimalNullable { get; set; } public TimeSpan? TimeSpanNullable { get; set; } + + [Column(ServerTime = DateTimeKind.Local)] public DateTime? DateTimeNullable { get; set; } + [Column(ServerTime = DateTimeKind.Local)] public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } public TableAllTypeEnumType1 Enum1 { get; set; } diff --git a/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs b/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs index 894723ad..b6080caf 100644 --- a/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs +++ b/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs @@ -670,10 +670,10 @@ namespace FreeSql.Tests .From((a, b) => a.InnerJoin(aa => aa.TemplatesId == b.Id2)) .GroupBy((a, b) => b.Code) - .ToSql(a => new + .ToSql(a => new NewsArticleDto { - a.Key, - sss = a.Sum(a.Value.Item1.OptionsEntity04) + ArticleTitle = a.Key, + ChannelId = a.Sum(a.Value.Item1.OptionsEntity04) }); var testgrpsql2 = g.sqlite.Select() diff --git a/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs b/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs index 64a43bb4..cf9195e2 100644 --- a/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs +++ b/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs @@ -183,9 +183,44 @@ namespace FreeSql.Tests public string varchar_notnull { get; set; } } + public class TestIgnoreDefaultValue { + public Guid Id { get; set; } + + [Column(IsIgnore = true)] + public double? quantity { get; set; } = 100f; + + public DateTime ct1 { get; set; } + public DateTime? ct2 { get; set; } + } + [Fact] public void Test02() { + var serverTime = g.pgsql.Select().Limit(1).First(a => DateTime.UtcNow); + var timeOffset = DateTime.UtcNow.Subtract(serverTime); //鍑忓幓鏁版嵁搴撴椂闂 + + g.pgsql.Aop.AuditValue += new EventHandler((_, e) => + { + if (e.Column.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime)) + { + if (e.Value == null || (DateTime)e.Value == default(DateTime)) + { + e.Value = DateTime.Now.Subtract(timeOffset); + return; + } + } + }); + + + g.pgsql.Delete().Where("1=1").ExecuteAffrows(); + g.pgsql.GetRepository().Insert(new TestIgnoreDefaultValue[] + { + new TestIgnoreDefaultValue(), + new TestIgnoreDefaultValue(), + new TestIgnoreDefaultValue() + }); + var testttt = g.pgsql.Select().Limit(10).ToList(); + var slsksd = g.mysql.Update().SetSource(new UserLike { Id = Guid.NewGuid(), CreateUserId = 1000, SubjectId = Guid.NewGuid() }) .UpdateColumns(a => new { diff --git a/FreeSql/DataAnnotations/ColumnAttribute.cs b/FreeSql/DataAnnotations/ColumnAttribute.cs index 0c9944e1..71216b91 100644 --- a/FreeSql/DataAnnotations/ColumnAttribute.cs +++ b/FreeSql/DataAnnotations/ColumnAttribute.cs @@ -43,11 +43,6 @@ namespace FreeSql.DataAnnotations /// public bool IsVersion { get => _IsVersion ?? false; set => _IsVersion = value; } - /// - /// 鏁版嵁搴撻粯璁ゅ - /// - public object DbDefautValue { get; internal set; } - /// /// 绫诲瀷鏄犲皠锛岄櫎浜嗗彲鍋氬熀鏈殑绫诲瀷鏄犲皠澶栵紝鐗瑰埆浠嬬粛鐨勫姛鑳斤細 /// 1銆佸皢 enum 灞炴ф槧灏勬垚 typeof(string) @@ -76,5 +71,18 @@ namespace FreeSql.DataAnnotations /// 璇ュ瓧娈垫槸鍚﹀彲浠ユ洿鏂帮紝榛樿鍊紅rue锛屾寚瀹氫负false鏇存柊鏃惰瀛楁浼氳蹇界暐 /// public bool CanUpdate { get => _CanUpdate ?? true; set => _CanUpdate = value; } + + internal DateTimeKind? _ServerTime; + /// + /// 鏍囪灞炴т负鏁版嵁搴撴湇鍔″櫒鏃堕棿(utc/local)锛屽湪鎻掑叆鐨勬椂鍊欎娇鐢ㄧ被浼 getdate() 鎵ц + /// + public DateTimeKind ServerTime + { + get => _ServerTime ?? DateTimeKind.Local; + set + { + _ServerTime = value == DateTimeKind.Unspecified ? DateTimeKind.Local : value; + } + } } } diff --git a/FreeSql/DataAnnotations/ColumnFluent.cs b/FreeSql/DataAnnotations/ColumnFluent.cs index 3cebe19c..f98d6ffc 100644 --- a/FreeSql/DataAnnotations/ColumnFluent.cs +++ b/FreeSql/DataAnnotations/ColumnFluent.cs @@ -124,5 +124,16 @@ namespace FreeSql.DataAnnotations _column.CanUpdate = value; return this; } + + /// + /// 鏍囪灞炴т负鏁版嵁搴撴湇鍔″櫒鏃堕棿(utc/local)锛屽湪鎻掑叆鐨勬椂鍊欎娇鐢ㄧ被浼 getdate() 鎵ц + /// + /// + /// + public ColumnFluent ServerTime(DateTimeKind value) + { + _column.ServerTime = value; + return this; + } } } diff --git a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs index 9a2604b7..e94e9eb8 100644 --- a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs +++ b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs @@ -39,7 +39,7 @@ public static partial class FreeSqlGlobalExtensions }); public static bool IsIntegerType(this Type that) => that == null ? false : (dicIsNumberType.Value.TryGetValue(that, out var tryval) ? tryval : false); public static bool IsNumberType(this Type that) => that == null ? false : dicIsNumberType.Value.ContainsKey(that); - public static bool IsNullableType(this Type that) => that?.FullName.StartsWith("System.Nullable`1[") == true; + public static bool IsNullableType(this Type that) => that.IsArray == false && that?.FullName.StartsWith("System.Nullable`1[") == true; public static bool IsAnonymousType(this Type that) => that?.FullName.StartsWith("<>f__AnonymousType") == true; public static bool IsArrayOrList(this Type that) => that == null ? false : (that.IsArray || typeof(IList).IsAssignableFrom(that)); public static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GetGenericArguments().First() : that; diff --git a/FreeSql/FreeSql.xml b/FreeSql/FreeSql.xml index 996523e3..768d92dd 100644 --- a/FreeSql/FreeSql.xml +++ b/FreeSql/FreeSql.xml @@ -45,11 +45,6 @@ 璁剧疆琛岄攣锛堜箰瑙傞攣锛夌増鏈彿锛屾瘡娆℃洿鏂扮疮鍔犵増鏈彿锛岃嫢鏇存柊鏁翠釜瀹炰綋鏃朵細闄勫甫褰撳墠鐨勭増鏈彿鍒ゆ柇锛堜慨鏀瑰け璐ユ椂鎶涘嚭寮傚父锛 - - - 鏁版嵁搴撻粯璁ゅ - - 绫诲瀷鏄犲皠锛岄櫎浜嗗彲鍋氬熀鏈殑绫诲瀷鏄犲皠澶栵紝鐗瑰埆浠嬬粛鐨勫姛鑳斤細 @@ -78,6 +73,11 @@ 璇ュ瓧娈垫槸鍚﹀彲浠ユ洿鏂帮紝榛樿鍊紅rue锛屾寚瀹氫负false鏇存柊鏃惰瀛楁浼氳蹇界暐 + + + 鏍囪灞炴т负鏁版嵁搴撴湇鍔″櫒鏃堕棿(utc/local)锛屽湪鎻掑叆鐨勬椂鍊欎娇鐢ㄧ被浼 getdate() 鎵ц + + 鏁版嵁搴撳垪鍚 @@ -152,6 +152,13 @@ + + + 鏍囪灞炴т负鏁版嵁搴撴湇鍔″櫒鏃堕棿(utc/local)锛屽湪鎻掑叆鐨勬椂鍊欎娇鐢ㄧ被浼 getdate() 鎵ц + + + + 鑷畾涔夎〃杈惧紡鍑芥暟瑙f瀽 diff --git a/FreeSql/Internal/CommonExpression.cs b/FreeSql/Internal/CommonExpression.cs index e2f715d3..b31fc599 100644 --- a/FreeSql/Internal/CommonExpression.cs +++ b/FreeSql/Internal/CommonExpression.cs @@ -110,7 +110,7 @@ namespace FreeSql.Internal parent.Consturctor = initExp.NewExpression.Type.GetConstructors()[0]; parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - if (initExp.NewExpression.Type != _tables.FirstOrDefault()?.Table.Type) + if (_tables != null && _tables.Any() && initExp.NewExpression.Type != _tables.FirstOrDefault().Table.Type) { //dto 鏄犲皠 var dtoProps = initExp.NewExpression.Type.GetPropertiesDictIgnoreCase().Values; diff --git a/FreeSql/Internal/CommonProvider/InsertProvider.cs b/FreeSql/Internal/CommonProvider/InsertProvider.cs index 0bd497c1..83b63483 100644 --- a/FreeSql/Internal/CommonProvider/InsertProvider.cs +++ b/FreeSql/Internal/CommonProvider/InsertProvider.cs @@ -445,13 +445,18 @@ namespace FreeSql.Internal.CommonProvider if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name)) continue; if (colidx2 > 0) sb.Append(", "); - object val = col.GetMapValue(d); - if (_noneParameter) - sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + if (string.IsNullOrEmpty(col.DbInsertValue) == false) + sb.Append(col.DbInsertValue); else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); - _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + object val = col.GetMapValue(d); + if (_noneParameter) + sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); + _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + } } ++colidx2; } diff --git a/FreeSql/Internal/CommonUtils.cs b/FreeSql/Internal/CommonUtils.cs index 1adbebfa..9b0e17bc 100644 --- a/FreeSql/Internal/CommonUtils.cs +++ b/FreeSql/Internal/CommonUtils.cs @@ -34,6 +34,8 @@ namespace FreeSql.Internal public abstract string StringConcat(string[] objs, Type[] types); public abstract string Mod(string left, string right, Type leftType, Type rightType); public abstract string Div(string left, string right, Type leftType, Type rightType); + public abstract string Now { get; } + public abstract string NowUtc { get; } public abstract string QuoteWriteParamter(Type type, string paramterName); public abstract string QuoteReadColumn(Type type, string columnName); @@ -126,7 +128,7 @@ namespace FreeSql.Internal if (trycol._Position != null) attr._Position = trycol.Position; if (trycol._CanInsert != null) attr._CanInsert = trycol.CanInsert; if (trycol._CanUpdate != null) attr._CanUpdate = trycol.CanUpdate; - if (trycol.DbDefautValue != null) attr.DbDefautValue = trycol.DbDefautValue; + if (trycol._ServerTime != null) attr._ServerTime = trycol._ServerTime; } var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); foreach (var tryattrobj in attrs) @@ -145,7 +147,7 @@ namespace FreeSql.Internal if (tryattr._Position != null) attr._Position = tryattr.Position; if (tryattr._CanInsert != null) attr._CanInsert = tryattr.CanInsert; if (tryattr._CanUpdate != null) attr._CanUpdate = tryattr.CanUpdate; - if (tryattr.DbDefautValue != null) attr.DbDefautValue = tryattr.DbDefautValue; + if (tryattr._ServerTime != null) attr._ServerTime = tryattr.ServerTime; } ColumnAttribute ret = null; if (!string.IsNullOrEmpty(attr.Name)) ret = attr; @@ -160,7 +162,7 @@ namespace FreeSql.Internal if (attr._Position != null) ret = attr; if (attr._CanInsert != null) ret = attr; if (attr._CanUpdate != null) ret = attr; - if (attr.DbDefautValue != null) ret = attr; + if (attr._ServerTime != null) ret = attr; if (ret != null && ret.MapType == null) ret.MapType = proto.PropertyType; return ret; } @@ -343,8 +345,16 @@ namespace FreeSql.Internal /// Dict锛歬ey=灞炴у悕锛寁alue=娉ㄩ噴 public static Dictionary GetProperyCommentBySummary(Type type) { - var xmlPath = type.Assembly.Location.Replace(".dll", ".xml").Replace(".exe", ".xml"); - if (File.Exists(xmlPath) == false) return null; + var regex = new Regex(@"\.(dll|exe)", RegexOptions.IgnoreCase); + var xmlPath = regex.Replace(type.Assembly.Location, ".xml"); + if (File.Exists(xmlPath) == false) + { + if (string.IsNullOrEmpty(type.Assembly.CodeBase)) return null; + xmlPath = regex.Replace(type.Assembly.CodeBase, ".xml"); + if (xmlPath.StartsWith("file:///") && Uri.TryCreate(xmlPath, UriKind.Absolute, out var tryuri)) + xmlPath = tryuri.LocalPath; + if (File.Exists(xmlPath) == false) return null; + } var dic = new Dictionary(); var sReader = new StringReader(File.ReadAllText(xmlPath)); diff --git a/FreeSql/Internal/Model/ColumnInfo.cs b/FreeSql/Internal/Model/ColumnInfo.cs index 84780850..05dc24a2 100644 --- a/FreeSql/Internal/Model/ColumnInfo.cs +++ b/FreeSql/Internal/Model/ColumnInfo.cs @@ -14,6 +14,8 @@ namespace FreeSql.Internal.Model public ColumnAttribute Attribute { get; set; } public string Comment { get; internal set; } public string DbTypeText { get; internal set; } + public string DbDefaultValue { get; internal set; } + public string DbInsertValue { get; internal set; } public int DbSize { get; internal set; } public byte DbPrecision { get; internal set; } public byte DbScale { get; internal set; } diff --git a/FreeSql/Internal/UtilsExpressionTree.cs b/FreeSql/Internal/UtilsExpressionTree.cs index 5904d7fa..69cb6087 100644 --- a/FreeSql/Internal/UtilsExpressionTree.cs +++ b/FreeSql/Internal/UtilsExpressionTree.cs @@ -151,26 +151,48 @@ namespace FreeSql.Internal trytb.ColumnsByCsIgnore.Add(p.Name, col); continue; } - if (entityDefault != null) colattr.DbDefautValue = trytb.Properties[p.Name].GetValue(entityDefault, null); + 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(colattr.DbDefautValue, enumValues.GetValue(a))) + if (object.Equals(defaultValue, enumValues.GetValue(a))) { isEqualsEnumValue = true; break; } if (isEqualsEnumValue == false && enumValues.Length > 0) - colattr.DbDefautValue = enumValues.GetValue(0); + defaultValue = enumValues.GetValue(0); } - if (colattr.DbDefautValue != null && p.PropertyType != colattr.MapType) colattr.DbDefautValue = Utils.GetDataReaderValue(colattr.MapType, colattr.DbDefautValue); - if (colattr.DbDefautValue == null) colattr.DbDefautValue = tp?.defaultValue; - if (colattr.IsNullable == false && colattr.DbDefautValue == null) + 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; - colattr.DbDefautValue = citype.CreateInstanceGetDefaultValue(); + defaultValue = citype.CreateInstanceGetDefaultValue(); + } + try + { + col.DbDefaultValue = common.GetNoneParamaterSqlValue(new List(), colattr.MapType, defaultValue); + } + 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 (colattr._ServerTime != null && new[] { typeof(DateTime), typeof(DateTimeOffset) }.Contains(colattr.MapType.NullableTypeOrThis())) + { + col.DbDefaultValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc; + col.DbInsertValue = colattr.ServerTime == DateTimeKind.Local ? common.Now : common.NowUtc; } trytb.Columns.Add(colattr.Name, col); @@ -1584,7 +1606,11 @@ namespace FreeSql.Internal Expression.Block( new[] { arrNewExp, arrExp, arrLenExp, arrXExp, arrReadValExp }, Expression.Assign(arrExp, Expression.TypeAs(valueExp, typeof(Array))), - Expression.Assign(arrLenExp, Expression.Call(arrExp, MethodArrayGetLength, Expression.Constant(0))), + Expression.IfThenElse( + Expression.Equal(arrExp, Expression.Constant(null)), + Expression.Assign(arrLenExp, Expression.Constant(0)), + Expression.Assign(arrLenExp, Expression.Call(arrExp, MethodArrayGetLength, Expression.Constant(0))) + ), Expression.Assign(arrXExp, Expression.Constant(0)), Expression.Assign(arrNewExp, Expression.NewArrayBounds(elementType, arrLenExp)), Expression.Loop( diff --git a/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs b/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs index 34dae9ea..03426dee 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs @@ -149,8 +149,7 @@ namespace FreeSql.MySql sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); sb.Append(","); @@ -237,26 +236,31 @@ where a.table_schema in ({0}) and a.table_name in ({1})", tboldname ?? tbname); tbcol.Attribute.IsIdentity != tbstructcol.is_identity || isCommentChanged) { + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable && tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL;\r\n"); sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(")"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) { //淇敼鍒楀悕 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" CHANGE COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } continue; } //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsNullable == false && tbcol.Attribute.IsIdentity == false) sbalter.Append(" DEFAULT ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)); + if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sbalter.Append(" DEFAULT ").Append(tbcol.DbDefaultValue); if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } var dsuksql = _commonUtils.FormatSql(@" @@ -301,8 +305,7 @@ where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRI sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); sb.Append(","); @@ -331,10 +334,11 @@ where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRI //insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; } if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"ifnull({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + if (tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); diff --git a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs index 9f1bf803..36477266 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs @@ -175,8 +175,8 @@ namespace FreeSql.MySql { switch (exp.Member.Name) { - case "Now": return "now()"; - case "UtcNow": return "utc_timestamp()"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "curdate()"; case "MinValue": return "cast('0001/1/1 0:00:00' as datetime)"; case "MaxValue": return "cast('9999/12/31 23:59:59' as datetime)"; diff --git a/Providers/FreeSql.Provider.MySql/MySqlUtils.cs b/Providers/FreeSql.Provider.MySql/MySqlUtils.cs index e76342d8..15d4dec4 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlUtils.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlUtils.cs @@ -88,6 +88,8 @@ namespace FreeSql.MySql public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} div {right}"; + public override string Now => "now()"; + public override string NowUtc => "utc_timestamp()"; public override string QuoteWriteParamter(Type type, string paramterName) { diff --git a/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs b/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs index 1fe7e253..d4e9f674 100644 --- a/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs +++ b/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs @@ -96,6 +96,8 @@ namespace FreeSql.MySql public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} div {right}"; + public override string Now => "now()"; + public override string NowUtc => "utc_timestamp()"; public override string QuoteWriteParamter(Type type, string paramterName) { diff --git a/Providers/FreeSql.Provider.Odbc/Default/OdbcUtils.cs b/Providers/FreeSql.Provider.Odbc/Default/OdbcUtils.cs index c589bcdb..001c8bed 100644 --- a/Providers/FreeSql.Provider.Odbc/Default/OdbcUtils.cs +++ b/Providers/FreeSql.Provider.Odbc/Default/OdbcUtils.cs @@ -60,6 +60,8 @@ namespace FreeSql.Odbc.Default public override string StringConcat(string[] objs, Type[] types) => Adapter.ConcatSql(objs, types); public override string Mod(string left, string right, Type leftType, Type rightType) => Adapter.Mod(left, right, leftType, rightType); public override string Div(string left, string right, Type leftType, Type rightType) => Adapter.Div(left, right, leftType, rightType); + public override string Now => Adapter.LambdaDateTime_Now; + public override string NowUtc => Adapter.LambdaDateTime_UtcNow; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => Adapter.FieldSql(type, columnName); diff --git a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlCodeFirst.cs b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlCodeFirst.cs index 557692e9..b4a17d8d 100644 --- a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlCodeFirst.cs +++ b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlCodeFirst.cs @@ -138,8 +138,7 @@ namespace FreeSql.Odbc.MySql sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); sb.Append(","); @@ -226,26 +225,31 @@ where a.table_schema in ({0}) and a.table_name in ({1})", tboldname ?? tbname); tbcol.Attribute.IsIdentity != tbstructcol.is_identity || isCommentChanged) { + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable && tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL;\r\n"); sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(")"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) { //淇敼鍒楀悕 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" CHANGE COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } continue; } //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsNullable == false && tbcol.Attribute.IsIdentity == false) sbalter.Append(" DEFAULT ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)); + if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sbalter.Append(" DEFAULT ").Append(tbcol.DbDefaultValue); if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" AUTO_INCREMENT"); + if (tbcol.Attribute.IsIdentity == true) sbalter.Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); sbalter.Append(";\r\n"); } var dsuksql = _commonUtils.FormatSql(@" @@ -290,8 +294,7 @@ where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRI sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); sb.Append(","); @@ -320,10 +323,11 @@ where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRI //insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; } if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"ifnull({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + if (tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); diff --git a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs index 9c1df930..7388e72a 100644 --- a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlExpression.cs @@ -175,8 +175,8 @@ namespace FreeSql.Odbc.MySql { switch (exp.Member.Name) { - case "Now": return "now()"; - case "UtcNow": return "utc_timestamp()"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "curdate()"; case "MinValue": return "cast('0001/1/1 0:00:00' as datetime)"; case "MaxValue": return "cast('9999/12/31 23:59:59' as datetime)"; diff --git a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlUtils.cs b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlUtils.cs index dc53f35a..7222f2e2 100644 --- a/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlUtils.cs +++ b/Providers/FreeSql.Provider.Odbc/MySql/OdbcMySqlUtils.cs @@ -59,6 +59,8 @@ namespace FreeSql.Odbc.MySql public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} div {right}"; + public override string Now => "now()"; + public override string NowUtc => "utc_timestamp()"; public override string QuoteWriteParamter(Type type, string paramterName) { diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsert.cs b/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsert.cs index a5b9be8e..7e584c90 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsert.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/Curd/OdbcOracleInsert.cs @@ -62,13 +62,18 @@ namespace FreeSql.Odbc.Oracle if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name)) continue; if (colidx2 > 0) sb.Append(", "); - object val = col.GetMapValue(d); - if (_noneParameter) - sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + if (string.IsNullOrEmpty(col.DbInsertValue) == false) + sb.Append(col.DbInsertValue); else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); - _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + object val = col.GetMapValue(d); + if (_noneParameter) + sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); + _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + } } ++colidx2; } diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleCodeFirst.cs b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleCodeFirst.cs index a7fc5be4..844364ad 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleCodeFirst.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleCodeFirst.cs @@ -218,7 +218,7 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname); if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) { if (tbcol.Attribute.IsNullable == false) - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue.Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "" : "NOT").Append(" NULL';\r\n"); } if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) @@ -240,7 +240,7 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD (").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); if (tbcol.Attribute.IsNullable == false) { - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append("';\r\n"); + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(tbcol.DbDefaultValue.Replace("'", "''")).Append("';\r\n"); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" NOT NULL';\r\n"); } if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); @@ -253,8 +253,7 @@ select nvl(freesql_long_2_varchar(a.index_name, c.table_name, c.column_position), c.column_name), a.index_name, case when c.descend = 'DESC' then 1 else 0 end, -case when a.uniqueness = 'UNIQUE' then 1 else 0 end, -c.column_position +case when a.uniqueness = 'UNIQUE' then 1 else 0 end from all_indexes a, all_ind_columns c where a.index_name = c.index_name @@ -334,10 +333,10 @@ and not exists(select 1 from all_constraints where constraint_name = a.index_nam insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; } if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"nvl({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"nvl({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue.Replace("'", "''")).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n"); diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs index 9bc4e84e..da39f52d 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleExpression.cs @@ -175,8 +175,8 @@ namespace FreeSql.Odbc.Oracle { switch (exp.Member.Name) { - case "Now": return "systimestamp"; - case "UtcNow": return "sys_extract_utc(systimestamp)"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "trunc(systimestamp)"; case "MinValue": return "to_timestamp('0001-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS.FF6')"; case "MaxValue": return "to_timestamp('9999-12-31 23:59:59','YYYY-MM-DD HH24:MI:SS.FF6')"; diff --git a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleUtils.cs b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleUtils.cs index 8827a089..e851589e 100644 --- a/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleUtils.cs +++ b/Providers/FreeSql.Provider.Odbc/Oracle/OdbcOracleUtils.cs @@ -87,6 +87,8 @@ namespace FreeSql.Odbc.Oracle public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"mod({left}, {right})"; public override string Div(string left, string right, Type leftType, Type rightType) => $"trunc({left} / {right})"; + public override string Now => "systimestamp"; + public override string NowUtc => "sys_extract_utc(systimestamp)"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLCodeFirst.cs b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLCodeFirst.cs index 2b5c557e..5686919c 100644 --- a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLCodeFirst.cs +++ b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLCodeFirst.cs @@ -236,7 +236,11 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname); if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) { if (tbcol.Attribute.IsNullable != true || tbcol.Attribute.IsNullable == true && tbcol.Attribute.IsPrimary == false) + { + if (tbcol.Attribute.IsNullable == false) + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL;\r\n"); sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "DROP" : "SET").Append(" NOT NULL;\r\n"); + } } if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); @@ -249,7 +253,7 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname); } //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); - sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0};\r\n", tbcol.Attribute.DbDefautValue)); + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(tbcol.DbDefaultValue).Append(";\r\n"); if (tbcol.Attribute.IsNullable == false) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" SET NOT NULL;\r\n"); if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); @@ -338,10 +342,10 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"coalesce({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"coalesce({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); diff --git a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs index 86463249..b9a0b56e 100644 --- a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLExpression.cs @@ -265,8 +265,8 @@ namespace FreeSql.Odbc.PostgreSQL { switch (exp.Member.Name) { - case "Now": return "current_timestamp"; - case "UtcNow": return "(current_timestamp at time zone 'UTC')"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "current_date"; case "MinValue": return "'0001/1/1 0:00:00'::timestamp"; case "MaxValue": return "'9999/12/31 23:59:59'::timestamp"; diff --git a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLUtils.cs b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLUtils.cs index c9bcbc21..365f9eab 100644 --- a/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLUtils.cs +++ b/Providers/FreeSql.Provider.Odbc/PostgreSQL/OdbcPostgreSQLUtils.cs @@ -113,6 +113,8 @@ namespace FreeSql.Odbc.PostgreSQL public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} / {right}"; + public override string Now => "current_timestamp"; + public override string NowUtc => "(current_timestamp at time zone 'UTC')"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerCodeFirst.cs b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerCodeFirst.cs index 6403f544..87d5f2bb 100644 --- a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerCodeFirst.cs +++ b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerCodeFirst.cs @@ -179,8 +179,7 @@ ELSE var pkidx = 0; foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (tbcol.Attribute.IsPrimary == true) { @@ -288,11 +287,7 @@ use " + database, tboldname ?? tbname); //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)"); - if (tbcol.Attribute.IsNullable == false && tbcol.Attribute.IsIdentity == false) - { - var addcoldbdefault = tbcol.Attribute.DbDefautValue; - if (addcoldbdefault != null) sbalter.Append(_commonUtils.FormatSql(" default({0})", addcoldbdefault)); - } + if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sbalter.Append(" default(").Append(GetTransferDbDefaultValue(tbcol)).Append(")"); sbalter.Append(";\r\n"); if (string.IsNullOrEmpty(tbcol.Comment) == false) AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); } @@ -354,8 +349,7 @@ use " + database, tboldname ?? tbname); var pkidx2 = 0; foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (tbcol.Attribute.IsPrimary == true) { @@ -396,10 +390,11 @@ use " + database, tboldname ?? tbname); if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"isnull({insertvalue},{_commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol))})"; + insertvalue = $"isnull({insertvalue},{GetTransferDbDefaultValue(tbcol)})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol)); + if (tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + insertvalue = GetTransferDbDefaultValue(tbcol); sb.Append(insertvalue.Replace("'", "''")).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n"); @@ -438,16 +433,15 @@ use " + database, tboldname ?? tbname); } } } - object GetTransferDbDefaultValue(ColumnInfo col) + string GetTransferDbDefaultValue(ColumnInfo col) { - var ddv = col.Attribute.DbDefautValue; - if (ddv == null) return ddv; - if (ddv is DateTime || ddv is DateTime?) + var ddv = col.DbDefaultValue; + if (string.IsNullOrEmpty(ddv) || ddv == "NULL") return ddv; + if (col.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime) && DateTime.TryParse(ddv, out var trydt)) { - var dt = (DateTime)ddv; - if (col.Attribute.DbType.Contains("SMALLDATETIME") && dt < new DateTime(1900, 1, 1)) ddv = new DateTime(1900, 1, 1); - else if (col.Attribute.DbType.Contains("DATETIME") && dt < new DateTime(1753, 1, 1)) ddv = new DateTime(1753, 1, 1); - else if (col.Attribute.DbType.Contains("DATE") && dt < new DateTime(0001, 1, 1)) ddv = new DateTime(0001, 1, 1); + if (col.Attribute.DbType.Contains("SMALLDATETIME") && trydt < new DateTime(1900, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1900, 1, 1)); + else if (col.Attribute.DbType.Contains("DATETIME") && trydt < new DateTime(1753, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1753, 1, 1)); + else if (col.Attribute.DbType.Contains("DATE") && trydt < new DateTime(0001, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(0001, 1, 1)); } return ddv; } diff --git a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs index 5a73fde2..41e40119 100644 --- a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs +++ b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerExpression.cs @@ -179,8 +179,8 @@ namespace FreeSql.Odbc.SqlServer { switch (exp.Member.Name) { - case "Now": return "getdate()"; - case "UtcNow": return "getutcdate()"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "convert(char(10),getdate(),120)"; case "MinValue": return "'1753/1/1 0:00:00'"; case "MaxValue": return "'9999/12/31 23:59:59'"; diff --git a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerUtils.cs b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerUtils.cs index 02f18715..bdd06913 100644 --- a/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerUtils.cs +++ b/Providers/FreeSql.Provider.Odbc/SqlServer/OdbcSqlServerUtils.cs @@ -74,6 +74,8 @@ namespace FreeSql.Odbc.SqlServer } public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} / {right}"; + public override string Now => "getdate()"; + public override string NowUtc => "getutcdate()"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs index 259c103b..afda477c 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs @@ -64,13 +64,18 @@ namespace FreeSql.Oracle.Curd if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name)) continue; if (colidx2 > 0) sb.Append(", "); - object val = col.GetMapValue(d); - if (_noneParameter) - sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + if (string.IsNullOrEmpty(col.DbInsertValue) == false) + sb.Append(col.DbInsertValue); else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); - _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + object val = col.GetMapValue(d); + if (_noneParameter) + sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); + _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col, col.Attribute.MapType, val); + } } ++colidx2; } diff --git a/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs b/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs index ee4f2097..52bb15f6 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs @@ -219,7 +219,7 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname); if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) { if (tbcol.Attribute.IsNullable == false) - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue.Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "" : "NOT").Append(" NULL';\r\n"); } if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) @@ -241,7 +241,7 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD (").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); if (tbcol.Attribute.IsNullable == false) { - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append("';\r\n"); + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(tbcol.DbDefaultValue.Replace("'", "''")).Append("';\r\n"); sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" NOT NULL';\r\n"); } if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); @@ -334,10 +334,10 @@ and not exists(select 1 from all_constraints where constraint_name = a.index_nam insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; } if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"nvl({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"nvl({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue.Replace("'", "''")).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n"); diff --git a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs index 20a1011f..7dbc44e7 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs @@ -175,8 +175,8 @@ namespace FreeSql.Oracle { switch (exp.Member.Name) { - case "Now": return "systimestamp"; - case "UtcNow": return "sys_extract_utc(systimestamp)"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "trunc(systimestamp)"; case "MinValue": return "to_timestamp('0001-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS.FF6')"; case "MaxValue": return "to_timestamp('9999-12-31 23:59:59','YYYY-MM-DD HH24:MI:SS.FF6')"; diff --git a/Providers/FreeSql.Provider.Oracle/OracleUtils.cs b/Providers/FreeSql.Provider.Oracle/OracleUtils.cs index 11c46adc..570c4c0f 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleUtils.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleUtils.cs @@ -82,6 +82,8 @@ namespace FreeSql.Oracle public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"mod({left}, {right})"; public override string Div(string left, string right, Type leftType, Type rightType) => $"trunc({left} / {right})"; + public override string Now => "systimestamp"; + public override string NowUtc => "sys_extract_utc(systimestamp)"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs index fa57fdf1..f8bfab2f 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs @@ -274,7 +274,11 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname); if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) { if (tbcol.Attribute.IsNullable != true || tbcol.Attribute.IsNullable == true && tbcol.Attribute.IsPrimary == false) + { + if (tbcol.Attribute.IsNullable == false) + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL;\r\n"); sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "DROP" : "SET").Append(" NOT NULL;\r\n"); + } } if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); @@ -287,7 +291,7 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname); } //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); - sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0};\r\n", tbcol.Attribute.DbDefautValue)); + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(tbcol.DbDefaultValue).Append(";\r\n"); if (tbcol.Attribute.IsNullable == false) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" SET NOT NULL;\r\n"); if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); @@ -376,10 +380,10 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"coalesce({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"coalesce({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs index 3ea73ae2..7996dca4 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs @@ -295,8 +295,8 @@ namespace FreeSql.PostgreSQL { switch (exp.Member.Name) { - case "Now": return "current_timestamp"; - case "UtcNow": return "(current_timestamp at time zone 'UTC')"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "current_date"; case "MinValue": return "'0001/1/1 0:00:00'::timestamp"; case "MaxValue": return "'9999/12/31 23:59:59'::timestamp"; diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs index ce2213a7..a0c015f1 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs @@ -139,6 +139,8 @@ namespace FreeSql.PostgreSQL public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} / {right}"; + public override string Now => "current_timestamp"; + public override string NowUtc => "(current_timestamp at time zone 'UTC')"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs index 44747d23..127acd83 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs @@ -182,8 +182,7 @@ ELSE var pkidx = 0; foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (tbcol.Attribute.IsPrimary == true) { @@ -291,11 +290,7 @@ use " + database, tboldname ?? tbname); //娣诲姞鍒 sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)"); - if (tbcol.Attribute.IsNullable == false && tbcol.Attribute.IsIdentity == false) - { - var addcoldbdefault = tbcol.Attribute.DbDefautValue; - if (addcoldbdefault != null) sbalter.Append(_commonUtils.FormatSql(" default({0})", addcoldbdefault)); - } + if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sbalter.Append(" default(").Append(GetTransferDbDefaultValue(tbcol)).Append(")"); sbalter.Append(";\r\n"); if (string.IsNullOrEmpty(tbcol.Comment) == false) AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); } @@ -357,8 +352,7 @@ use " + database, tboldname ?? tbname); var pkidx2 = 0; foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); if (tbcol.Attribute.IsPrimary == true) { @@ -399,10 +393,11 @@ use " + database, tboldname ?? tbname); if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"isnull({insertvalue},{_commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol))})"; + insertvalue = $"isnull({insertvalue},{GetTransferDbDefaultValue(tbcol)})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol)); + if (tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) + insertvalue = GetTransferDbDefaultValue(tbcol); sb.Append(insertvalue.Replace("'", "''")).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n"); @@ -441,16 +436,15 @@ use " + database, tboldname ?? tbname); } } } - object GetTransferDbDefaultValue(ColumnInfo col) + string GetTransferDbDefaultValue(ColumnInfo col) { - var ddv = col.Attribute.DbDefautValue; - if (ddv == null) return ddv; - if (ddv is DateTime || ddv is DateTime?) + var ddv = col.DbDefaultValue; + if (string.IsNullOrEmpty(ddv) || ddv == "NULL") return ddv; + if (col.Attribute.MapType.NullableTypeOrThis() == typeof(DateTime) && DateTime.TryParse(ddv, out var trydt)) { - var dt = (DateTime)ddv; - if (col.Attribute.DbType.Contains("SMALLDATETIME") && dt < new DateTime(1900, 1, 1)) ddv = new DateTime(1900, 1, 1); - else if (col.Attribute.DbType.Contains("DATETIME") && dt < new DateTime(1753, 1, 1)) ddv = new DateTime(1753, 1, 1); - else if (col.Attribute.DbType.Contains("DATE") && dt < new DateTime(0001, 1, 1)) ddv = new DateTime(0001, 1, 1); + if (col.Attribute.DbType.Contains("SMALLDATETIME") && trydt < new DateTime(1900, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1900, 1, 1)); + else if (col.Attribute.DbType.Contains("DATETIME") && trydt < new DateTime(1753, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(1753, 1, 1)); + else if (col.Attribute.DbType.Contains("DATE") && trydt < new DateTime(0001, 1, 1)) ddv = _commonUtils.FormatSql("{0}", new DateTime(0001, 1, 1)); } return ddv; } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs index 5768d9c1..d8f61bc3 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs @@ -179,8 +179,8 @@ namespace FreeSql.SqlServer { switch (exp.Member.Name) { - case "Now": return "getdate()"; - case "UtcNow": return "getutcdate()"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "convert(char(10),getdate(),120)"; case "MinValue": return "'1753/1/1 0:00:00'"; case "MaxValue": return "'9999/12/31 23:59:59'"; diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs index 56659c60..bf66c1b1 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs @@ -85,6 +85,8 @@ namespace FreeSql.SqlServer } public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} / {right}"; + public override string Now => "getdate()"; + public override string NowUtc => "getutcdate()"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName; diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs b/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs index 1c665dc7..d2e14193 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs @@ -117,8 +117,7 @@ namespace FreeSql.Sqlite sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) { isIndent = true; @@ -244,8 +243,7 @@ namespace FreeSql.Sqlite sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); foreach (var tbcol in tb.ColumnsByPosition) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) { isIndent = true; @@ -278,10 +276,10 @@ namespace FreeSql.Sqlite insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; } if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + insertvalue = $"ifnull({insertvalue},{tbcol.DbDefaultValue})"; } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + insertvalue = tbcol.DbDefaultValue; sb.Append(insertvalue).Append(", "); } sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs index 9bc01183..68f8cea6 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs @@ -175,8 +175,8 @@ namespace FreeSql.Sqlite { switch (exp.Member.Name) { - case "Now": return "datetime(current_timestamp,'localtime')"; - case "UtcNow": return "current_timestamp"; + case "Now": return _common.Now; + case "UtcNow": return _common.NowUtc; case "Today": return "date(current_timestamp,'localtime')"; case "MinValue": return "datetime('0001-01-01 00:00:00.000')"; case "MaxValue": return "datetime('9999-12-31 23:59:59.999')"; diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs b/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs index 498ef244..fd7a88f8 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs @@ -85,6 +85,8 @@ namespace FreeSql.Sqlite public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; public override string Div(string left, string right, Type leftType, Type rightType) => $"{left} / {right}"; + public override string Now => "datetime(current_timestamp,'localtime')"; + public override string NowUtc => "current_timestamp"; public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; public override string QuoteReadColumn(Type type, string columnName) => columnName;