Skip to content

Commit

Permalink
自动分表分库要放在Valid验证和雪花Id填充之后,否则缺失分表所需时间字段
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jan 11, 2024
1 parent 3369a64 commit b7e3d9d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
24 changes: 15 additions & 9 deletions XCode/Entity/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,15 @@ public override Int32 Save()
/// <returns></returns>
public override Int32 SaveWithoutValid()
{
enableValid = false;
try { return Save(); }
finally { enableValid = true; }
_enableValid = false;
try
{
return Save();
}
finally
{
_enableValid = true;
}
}

/// <summary>异步保存。实现延迟保存,大事务保存。主要面向日志表和频繁更新的在线记录表</summary>
Expand All @@ -255,7 +261,7 @@ public override Boolean SaveAsync(Int32 msDelay = 0)
isnew = true;

// 提前执行Valid,让它提前准备好验证数据
if (enableValid)
if (_enableValid)
{
if (!Valid(isnew ? DataMethod.Insert : DataMethod.Update)) return false;
}
Expand Down Expand Up @@ -327,10 +333,7 @@ private TResult DoAction<TResult>(Func<TResult> func, DataMethod method)
}
}

// 自动分库分表
using var split = Meta.CreateShard((this as TEntity)!);

if (enableValid)
if (_enableValid)
{
var rt = Valid(method);

Expand All @@ -340,11 +343,14 @@ private TResult DoAction<TResult>(Func<TResult> func, DataMethod method)

AutoFillSnowIdPrimaryKey();

// 自动分库分表
using var split = Meta.CreateShard((this as TEntity)!);

return func();
}

[NonSerialized]
private Boolean enableValid = true;
private Boolean _enableValid = true;

/// <summary>验证并修补数据,通过抛出异常的方式提示验证失败。</summary>
/// <remarks>建议重写者调用基类的实现,因为基类自动生成雪花Id、填充创建更新信息以及验证字符串字段是否超长。</remarks>
Expand Down
8 changes: 5 additions & 3 deletions XCode/Shards/TimeShardPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ public virtual ShardModel Shard(Object value)
if (value is DateTime dt) return Shard(dt);
if (value is Int64 id)
{
if (!Factory.Snow.TryParse(id, out var time, out _, out _)) throw new XCodeException("雪花Id解析时间失败,无法用于分表");
if (!Factory.Snow.TryParse(id, out var time, out _, out _) || time.Year <= 1970)
throw new XCodeException("雪花Id解析时间失败,无法用于分表");

return Shard(time);
}
Expand All @@ -78,14 +79,15 @@ public virtual ShardModel Shard(IEntity entity)
if (fi.Type == typeof(DateTime))
{
var time = entity[fi.Name].ToDateTime();
if (time.Year <= 1) throw new XCodeException("实体对象时间字段为空,无法用于分表");
if (time.Year <= 1970) throw new XCodeException("实体对象时间字段为空,无法用于分表");

return Shard(time);
}
else if (fi.Type == typeof(Int64))
{
var id = entity[fi.Name].ToLong();
if (!Factory.Snow.TryParse(id, out var time, out _, out _)) throw new XCodeException("雪花Id解析时间失败,无法用于分表");
if (!Factory.Snow.TryParse(id, out var time, out _, out _) || time.Year <= 1970)
throw new XCodeException("雪花Id解析时间失败,无法用于分表");

return Shard(time);
}
Expand Down

0 comments on commit b7e3d9d

Please sign in to comment.