- 增加 IsVersion 对 byte[] 的支持;#548

This commit is contained in:
2881099 2020-11-19 20:21:32 +08:00
parent 60682936fa
commit d38be498a3
19 changed files with 104 additions and 28 deletions

View File

@ -502,5 +502,14 @@
<param name="that"></param>
<returns></returns>
</member>
<member name="M:Microsoft.Extensions.DependencyInjection.FreeSqlRepositoryDependencyInjection.AddFreeRepository(Microsoft.Extensions.DependencyInjection.IServiceCollection,System.Action{FreeSql.FluentDataFilter},System.Reflection.Assembly[])">
<summary>
批量注入 Repository可以参考代码自行调整
</summary>
<param name="services"></param>
<param name="globalDataFilter"></param>
<param name="assemblies"></param>
<returns></returns>
</member>
</members>
</doc>

View File

@ -1,4 +1,5 @@
using FreeSql.DataAnnotations;
using FreeSql.Internal;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@ -11,6 +12,54 @@ namespace FreeSql.Tests
{
public class UnitTest4
{
[Fact]
public void VersionByte()
{
var fsql = g.mysql;
fsql.Delete<ts_ver_byte>().Where("1=1").ExecuteAffrows();
var id = Guid.NewGuid();
Assert.Equal(1, fsql.Insert(new ts_ver_byte { id = id, title = "001" }).ExecuteAffrows());
var item = fsql.Select<ts_ver_byte>(id).First();
item.title = "002";
Assert.Equal(1, fsql.Update<ts_ver_byte>().SetSource(item).ExecuteAffrows());
item.title = "003";
Assert.Equal(1, fsql.Update<ts_ver_byte>().SetSource(item).ExecuteAffrows());
item.version = Utils.GuidToBytes(Guid.NewGuid());
item.title = "004";
Assert.Throws<DbUpdateVersionException>(() => fsql.Update<ts_ver_byte>().SetSource(item).ExecuteAffrows());
fsql.Delete<ts_ver_byte>().Where("1=1").ExecuteAffrows();
Assert.Equal(2, fsql.Insert(new[] { new ts_ver_byte { id = Guid.NewGuid(), title = "001" }, new ts_ver_byte { id = Guid.NewGuid(), title = "0011" } }).ExecuteAffrows());
var items = fsql.Select<ts_ver_byte>().OrderBy(a => a.title).ToList();
Assert.Equal(2, items.Count);
items[0].title = "002";
items[1].title = "0022";
Assert.Equal(2, fsql.Update<ts_ver_byte>().SetSource(items).ExecuteAffrows());
items[0].title = "003";
items[1].title = "0033";
Assert.Equal(2, fsql.Update<ts_ver_byte>().SetSource(items).ExecuteAffrows());
items[0].version = Utils.GuidToBytes(Guid.NewGuid());
items[0].title = "004";
items[1].title = "0044";
Assert.Throws<DbUpdateVersionException>(() => fsql.Update<ts_ver_byte>().SetSource(items).ExecuteAffrows());
items[0].version = Utils.GuidToBytes(Guid.NewGuid());
items[1].version = Utils.GuidToBytes(Guid.NewGuid());
items[0].title = "004";
items[1].title = "0044";
Assert.Throws<DbUpdateVersionException>(() => fsql.Update<ts_ver_byte>().SetSource(items).ExecuteAffrows());
}
class ts_ver_byte
{
public Guid id { get; set; }
public string title { get; set; }
[Column(IsVersion = true)]
public byte[] version { get; set; }
}
public record ts_iif(Guid id, string title);
[Fact]

View File

@ -179,6 +179,8 @@ namespace FreeSql.Internal.CommonProvider
}
if (val == null && col.Attribute.MapType == typeof(string) && col.Attribute.IsNullable == false)
col.SetValue(data, val = "");
if (val == null && col.Attribute.MapType == typeof(byte[]) && col.Attribute.IsVersion)
col.SetValue(data, val = Utils.GuidToBytes(Guid.NewGuid()));
}
}

View File

@ -37,6 +37,7 @@ namespace FreeSql.Internal.CommonProvider
public DbConnection _connection;
public int _commandTimeout = 0;
public Action<StringBuilder> _interceptSql;
public byte[] _updateVersionValue;
public UpdateProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere)
{
@ -75,6 +76,9 @@ namespace FreeSql.Internal.CommonProvider
_paramsSource.Clear();
IgnoreCanUpdate();
_whereGlobalFilter = _orm.GlobalFilter.GetFilters();
_batchProgress = null;
_interceptSql = null;
_updateVersionValue = null;
}
public IUpdate<T1> WithTransaction(DbTransaction transaction)
@ -122,9 +126,14 @@ namespace FreeSql.Internal.CommonProvider
if (affrows != _source.Count)
throw new DbUpdateVersionException($"记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{_source.Count},影响的行数{affrows}。", _table, sql, dbParms, affrows, _source.Select(a => (object)a));
foreach (var d in _source)
{
if (_table.VersionColumn.Attribute.MapType == typeof(byte[]))
_orm.SetEntityValueWithPropertyName(_table.Type, d, _table.VersionColumn.CsName, _updateVersionValue);
else
_orm.SetEntityIncrByWithPropertyName(_table.Type, d, _table.VersionColumn.CsName, 1);
}
}
}
#region values数量限制
internal List<T1>[] SplitSource(int valuesLimit, int parameterLimit)
@ -768,6 +777,12 @@ namespace FreeSql.Internal.CommonProvider
if (_table.VersionColumn != null)
{
var vcname = _commonUtils.QuoteSqlName(_table.VersionColumn.Attribute.Name);
if (_table.VersionColumn.Attribute.MapType == typeof(byte[]))
{
_updateVersionValue = Utils.GuidToBytes(Guid.NewGuid());
sb.Append(", ").Append(vcname).Append(" = ").Append(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, "uv", _table.VersionColumn, _table.VersionColumn.Attribute.MapType, _updateVersionValue));
}
else
sb.Append(", ").Append(vcname).Append(" = ").Append(_commonUtils.IsNull(vcname, 0)).Append(" + 1");
}

View File

@ -282,6 +282,7 @@ namespace FreeSql.Internal
break;
}
}
if (colattr.MapType == typeof(byte[]) && colattr.IsVersion == true) colattr.StringLength = 16;
if (colattr.MapType == typeof(byte[]) && colattr.StringLength != 0)
{
int strlen = colattr.StringLength;
@ -346,8 +347,8 @@ namespace FreeSql.Internal
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)
throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型,并且不可为 Nullable");
if (trytb.VersionColumn.Attribute.MapType.IsNullableType() || trytb.VersionColumn.Attribute.MapType.IsNumberType() == false && trytb.VersionColumn.Attribute.MapType != typeof(byte[]))
throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型 或者 byte[],并且不可为 Nullable");
}
var indexesDict = new Dictionary<string, IndexInfo>(StringComparer.CurrentCultureIgnoreCase);
@ -1742,18 +1743,18 @@ namespace FreeSql.Internal
act(info, value);
}
static BigInteger ToBigInteger(string that)
public static BigInteger ToBigInteger(string that)
{
if (string.IsNullOrEmpty(that)) return 0;
if (BigInteger.TryParse(that, System.Globalization.NumberStyles.Any, null, out var trybigint)) return trybigint;
return 0;
}
static string ToStringConcat(object obj)
public static string ToStringConcat(object obj)
{
if (obj == null) return null;
return string.Concat(obj);
}
static byte[] GuidToBytes(Guid guid)
public static byte[] GuidToBytes(Guid guid)
{
var bytes = new byte[16];
var guidN = guid.ToString("N");
@ -1761,12 +1762,12 @@ namespace FreeSql.Internal
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", System.Globalization.NumberStyles.HexNumber);
return bytes;
}
static Guid BytesToGuid(byte[] bytes)
public static Guid BytesToGuid(byte[] bytes)
{
if (bytes == null) return Guid.Empty;
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
static char StringToChar(string str)
public static char StringToChar(string str)
{
if (string.IsNullOrEmpty(str)) return default(char);
return str.ToCharArray(0, 1)[0];
@ -1793,8 +1794,8 @@ namespace FreeSql.Internal
static MethodInfo MethodTimeSpanTryParse = typeof(TimeSpan).GetMethod("TryParse", new[] { typeof(string), typeof(TimeSpan).MakeByRefType() });
static MethodInfo MethodDateTimeTryParse = typeof(DateTime).GetMethod("TryParse", new[] { typeof(string), typeof(DateTime).MakeByRefType() });
static MethodInfo MethodDateTimeOffsetTryParse = typeof(DateTimeOffset).GetMethod("TryParse", new[] { typeof(string), typeof(DateTimeOffset).MakeByRefType() });
static MethodInfo MethodToString = typeof(Utils).GetMethod("ToStringConcat", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(object) }, null);
static MethodInfo MethodBigIntegerParse = typeof(Utils).GetMethod("ToBigInteger", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(string) }, null);
static MethodInfo MethodToString = typeof(Utils).GetMethod("ToStringConcat", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(object) }, null);
static MethodInfo MethodBigIntegerParse = typeof(Utils).GetMethod("ToBigInteger", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
static PropertyInfo PropertyDateTimeOffsetDateTime = typeof(DateTimeOffset).GetProperty("DateTime", BindingFlags.Instance | BindingFlags.Public);
static PropertyInfo PropertyDateTimeTicks = typeof(DateTime).GetProperty("Ticks", BindingFlags.Instance | BindingFlags.Public);
static ConstructorInfo CtorDateTimeOffsetArgsTicks = typeof(DateTimeOffset). GetConstructor(new[] { typeof(long), typeof(TimeSpan) });
@ -1802,9 +1803,9 @@ namespace FreeSql.Internal
static MethodInfo MethodEncodingGetBytes = typeof(Encoding).GetMethod("GetBytes", new[] { typeof(string) });
static MethodInfo MethodEncodingGetString = typeof(Encoding).GetMethod("GetString", new[] { typeof(byte[]) });
static MethodInfo MethodStringToCharArray = typeof(string).GetMethod("ToCharArray", new Type[0]);
static MethodInfo MethodStringToChar = typeof(Utils).GetMethod("StringToChar", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(string) }, null);
static MethodInfo MethodGuidToBytes = typeof(Utils).GetMethod("GuidToBytes", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(Guid) }, null);
static MethodInfo MethodBytesToGuid = typeof(Utils).GetMethod("BytesToGuid", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(byte[]) }, null);
static MethodInfo MethodStringToChar = typeof(Utils).GetMethod("StringToChar", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
static MethodInfo MethodGuidToBytes = typeof(Utils).GetMethod("GuidToBytes", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(Guid) }, null);
static MethodInfo MethodBytesToGuid = typeof(Utils).GetMethod("BytesToGuid", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(byte[]) }, null);
public static ConcurrentBag<Func<LabelTarget, Expression, Type, Expression>> GetDataReaderValueBlockExpressionSwitchTypeFullName = new ConcurrentBag<Func<LabelTarget, Expression, Type, Expression>>();
public static ConcurrentBag<Func<LabelTarget, Expression, Expression, Type, Expression>> GetDataReaderValueBlockExpressionObjectToStringIfThenElse = new ConcurrentBag<Func<LabelTarget, Expression, Expression, Type, Expression>>();

View File

@ -41,7 +41,7 @@ namespace FreeSql.Dameng.Curd
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -41,7 +41,7 @@ namespace FreeSql.Firebird.Curd
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -125,7 +125,7 @@ namespace FreeSql.KingbaseES
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _insert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(_insert.InternalCommonUtils.QuoteSqlName(_insert.InternalTable.DbName)).Append(".").Append(field).Append(" + 1");

View File

@ -85,7 +85,7 @@ namespace FreeSql.MySql.Curd
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _mysqlInsert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(field).Append(" + 1");

View File

@ -41,7 +41,7 @@ namespace FreeSql.Odbc.Dameng
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -125,7 +125,7 @@ namespace FreeSql.Odbc.KingbaseES
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _pgsqlInsert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(_pgsqlInsert.InternalCommonUtils.QuoteSqlName(_pgsqlInsert.InternalTable.DbName)).Append(".").Append(field).Append(" + 1");

View File

@ -85,7 +85,7 @@ namespace FreeSql.Odbc.MySql
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _mysqlInsert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(field).Append(" + 1");

View File

@ -41,7 +41,7 @@ namespace FreeSql.Odbc.Oracle
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -125,7 +125,7 @@ namespace FreeSql.Odbc.PostgreSQL
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _pgsqlInsert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(_pgsqlInsert.InternalCommonUtils.QuoteSqlName(_pgsqlInsert.InternalTable.DbName)).Append(".").Append(field).Append(" + 1");

View File

@ -43,7 +43,7 @@ namespace FreeSql.Odbc.SqlServer
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -41,7 +41,7 @@ namespace FreeSql.Oracle.Curd
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -125,7 +125,7 @@ namespace FreeSql.PostgreSQL.Curd
if (colidx > 0) sb.Append(", \r\n");
if (col.Attribute.IsVersion == true)
if (col.Attribute.IsVersion == true && col.Attribute.MapType != typeof(byte[]))
{
var field = _pgsqlInsert.InternalCommonUtils.QuoteSqlName(col.Attribute.Name);
sb.Append(field).Append(" = ").Append(_pgsqlInsert.InternalCommonUtils.QuoteSqlName(_pgsqlInsert.InternalTable.DbName)).Append(".").Append(field).Append(" + 1");

View File

@ -41,7 +41,7 @@ namespace FreeSql.ShenTong.Curd
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");

View File

@ -43,7 +43,7 @@ namespace FreeSql.SqlServer.Curd
if (_doNothing == false && cols.Any())
sb.Append("WHEN MATCHED THEN \r\n")
.Append(" update set ").Append(string.Join(", ", cols.Select(a =>
a.Attribute.IsVersion ?
a.Attribute.IsVersion && a.Attribute.MapType != typeof(byte[]) ?
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t1.{_commonUtils.QuoteSqlName(a.Attribute.Name)} + 1" :
$"{_commonUtils.QuoteSqlName(a.Attribute.Name)} = t2.{a.Attribute.Name}"
))).Append(" \r\n");