Skip to content

Commit

Permalink
自动分表策略,支持单一时间日期的分表,例如分表字段DataTime,记录日期,查询时仅指定某一天
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Sep 6, 2024
1 parent 125b494 commit 9d2bf5a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions XCode/Shards/TimeShardPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,13 @@ public virtual ShardModel[] Shards(Expression expression)

if (fi.Type == typeof(DateTime))
{
var qf = exps.FirstOrDefault(e => e.Action is "=");
if (qf != null)
{
var time = qf.Value.ToDateTime();
if (time.Year > 1) return GetModels(time, time.AddSeconds(1));
}

var sf = exps.FirstOrDefault(e => e.Action is ">" or ">=");
var ef = exps.FirstOrDefault(e => e.Action is "<" or "<=");
if (sf != null)
Expand Down
20 changes: 20 additions & 0 deletions XUnitTest.XCode/EntityTests/ShardTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -506,4 +506,24 @@ public void 跨月Shards()
Assert.Equal("Log2_202407", shards[0].TableName);
Assert.Equal("Log2_202408", shards[1].TableName);
}

[Fact]
public void 单日Shards()
{
var policy = new TimeShardPolicy(Log2._.CreateTime, Log2.Meta.Factory)
{
TablePolicy = "{0}_{1:yyyyMM}",
Step = TimeSpan.FromDays(31),
};

// 起止都是整数日期,末尾加1天
var start = "2024/7/25 00:00:00".ToDateTime();
var fi = policy.Field;
var where = fi.Equal(start);

var shards = policy.Shards(where);
Assert.NotNull(shards);
Assert.Equal(1, shards.Length);
Assert.Equal("Log2_202407", shards[0].TableName);
}
}

0 comments on commit 9d2bf5a

Please sign in to comment.