添加了很多单元测试

This commit is contained in:
xuejiaming 2021-11-26 23:11:09 +08:00
parent db1109b596
commit 9e287be7e3
55 changed files with 4020 additions and 128 deletions

View File

@ -29,6 +29,11 @@ namespace Sample.BulkConsole
return new OrderPaginationConfiguration();
}
public override void Configure(EntityMetadataTableBuilder<Order> builder)
{
}
public override bool AutoCreateTableByTime()
{
return true;

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sample.MySql.Domain.Entities;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.VirtualRoutes.Months;
namespace Sample.MySql.Shardings
@ -18,5 +19,10 @@ namespace Sample.MySql.Shardings
{
return true;
}
public override void Configure(EntityMetadataTableBuilder<SysUserLogByMonth> builder)
{
}
}
}

View File

@ -1,4 +1,5 @@
using Sample.MySql.Domain.Entities;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.VirtualRoutes.Mods;
namespace Sample.MySql.Shardings
@ -14,5 +15,10 @@ namespace Sample.MySql.Shardings
public SysUserModVirtualTableRoute() : base(2,3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
}
}
}

View File

@ -40,5 +40,10 @@ namespace Sample.SqlServer.Shardings
{
return new SysUserModPaginationConfiguration();
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
}
}
}

View File

@ -44,6 +44,11 @@ namespace Sample.SqlServer.Shardings
return list;
}
public override void Configure(EntityMetadataTableBuilder<SysUserSalary> builder)
{
}
protected string TimeFormatToTail(int time)
{
var dateOfMonth=DateTime.ParseExact($"{time}","yyyyMM",System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.AdjustToUniversal);

View File

@ -5,6 +5,7 @@ using System.Linq.Expressions;
using System.Threading.Tasks;
using Sample.SqlServer.Domain.Entities;
using ShardingCore.Core;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions;
@ -29,6 +30,11 @@ namespace Sample.SqlServer.Shardings
return new List<string>() {"", "1"};
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
}
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
{
var t = ShardingKeyToTail(shardingKey);

View File

@ -1,4 +1,5 @@
using Sample.SqlServer3x.Domain.Entities;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.VirtualRoutes.Mods;
namespace Sample.SqlServer3x.Shardings
@ -15,5 +16,9 @@ namespace Sample.SqlServer3x.Shardings
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
}
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Sample.SqlServerShardingTable.Entities;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions;
using ShardingCore.Exceptions;
@ -46,6 +47,11 @@ namespace Sample.SqlServerShardingTable.VirtualRoutes
};
}
public override void Configure(EntityMetadataTableBuilder<Order> builder)
{
}
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
{
//因为hash路由仅支持等于所以仅仅只需要写等于的情况

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Samples.AutoByDate.SqlServer.Domain.Entities;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.VirtualRoutes.Days;
namespace Samples.AutoByDate.SqlServer.Shardings
@ -24,5 +25,10 @@ namespace Samples.AutoByDate.SqlServer.Shardings
{
return true;
}
public override void Configure(EntityMetadataTableBuilder<SysUserLogByDay> builder)
{
}
}
}

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Threading.Tasks;
using Samples.AutoByDate.SqlServer.Domain.Entities;
using Samples.AutoByDate.SqlServer.Domain.Maps;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.VirtualRoutes.Weeks;
namespace Samples.AutoByDate.SqlServer.Shardings
@ -19,5 +20,10 @@ namespace Samples.AutoByDate.SqlServer.Shardings
{
return true;
}
public override void Configure(EntityMetadataTableBuilder<TestLogByWeek> builder)
{
}
}
}

View File

@ -76,9 +76,6 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions
/// 配置分表信息
/// </summary>
/// <param name="builder"></param>
public virtual void Configure(EntityMetadataTableBuilder<T> builder)
{
}
public abstract void Configure(EntityMetadataTableBuilder<T> builder);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogMonthLong
{
public string Id { get; set; }
public string Body { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogNoSharding
{
public string Id { get; set; }
public string Body { get; set; }
public DateTime CreationTime { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogWeekTimeLong
{
public string Id { get; set; }
public string Body { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test.Domain.Entities
{
public class LogYearDateTime
{
public Guid Id { get; set; }
public string LogBody { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogMonthLongMap:IEntityTypeConfiguration<LogMonthLong>
{
public void Configure(EntityTypeBuilder<LogMonthLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogMonthLong));
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogNoShardingMap:IEntityTypeConfiguration<LogNoSharding>
{
public void Configure(EntityTypeBuilder<LogNoSharding> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(256);
builder.ToTable(nameof(LogNoSharding));
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogWeekTimeLongMap : IEntityTypeConfiguration<LogWeekTimeLong>
{
public void Configure(EntityTypeBuilder<LogWeekTimeLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekTimeLong));
}
}
}

View File

@ -0,0 +1,22 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test.Domain.Entities;
namespace ShardingCore.Test.Domain.Maps
{
public class LogYearDateTimeMap : IEntityTypeConfiguration<LogYearDateTime>
{
public void Configure(EntityTypeBuilder<LogYearDateTime> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogYearDateTime));
}
}
}

View File

@ -27,6 +27,10 @@ namespace ShardingCore.Test
modelBuilder.ApplyConfiguration(new OrderMap());
modelBuilder.ApplyConfiguration(new LogDayMap());
modelBuilder.ApplyConfiguration(new LogWeekDateTimeMap());
modelBuilder.ApplyConfiguration(new LogWeekTimeLongMap());
modelBuilder.ApplyConfiguration(new LogYearDateTimeMap());
modelBuilder.ApplyConfiguration(new LogNoShardingMap());
modelBuilder.ApplyConfiguration(new LogMonthLongMap());
}
public IRouteTail RouteTail { get; set; }

View File

@ -13,6 +13,7 @@ using ShardingCore.Core.VirtualDatabase.VirtualTables;
using ShardingCore.Exceptions;
using ShardingCore.Extensions;
using ShardingCore.Extensions.ShardingPageExtensions;
using ShardingCore.Helpers;
using ShardingCore.Sharding;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
using ShardingCore.Sharding.ShardingComparision.Abstractions;
@ -41,9 +42,9 @@ namespace ShardingCore.Test
private readonly IShardingTableCreator<ShardingDefaultDbContext> _shardingTableCreator;
private readonly IShardingReadWriteManager _shardingReadWriteManager;
public ShardingTest(ShardingDefaultDbContext virtualDbContext,IShardingRouteManager shardingRouteManager, IConfiguration configuration,
public ShardingTest(ShardingDefaultDbContext virtualDbContext, IShardingRouteManager shardingRouteManager, IConfiguration configuration,
IEntityMetadataManager<ShardingDefaultDbContext> entityMetadataManager,
IShardingComparer<ShardingDefaultDbContext> shardingComparer,IVirtualDataSource<ShardingDefaultDbContext> virtualDataSource,
IShardingComparer<ShardingDefaultDbContext> shardingComparer, IVirtualDataSource<ShardingDefaultDbContext> virtualDataSource,
IVirtualTableManager<ShardingDefaultDbContext> virtualTableManager,
IShardingTableCreator<ShardingDefaultDbContext> shardingTableCreator, IShardingReadWriteManager shardingReadWriteManager)
{
@ -62,14 +63,14 @@ namespace ShardingCore.Test
[Fact]
public async Task GenericTest()
{
var a = new DefaultPhysicDataSource("aaa","aaa",true);
var b = new DefaultPhysicDataSource("aaa","aaa1",false);
Assert.Equal(a,b);
var x = new EntityMetadata(typeof(LogDay),"aa",typeof(ShardingDefaultDbContext),new List<PropertyInfo>());
var y = new EntityMetadata(typeof(LogDay),"aa1",typeof(ShardingDefaultDbContext),new List<PropertyInfo>());
var a = new DefaultPhysicDataSource("aaa", "aaa", true);
var b = new DefaultPhysicDataSource("aaa", "aaa1", false);
Assert.Equal(a, b);
var x = new EntityMetadata(typeof(LogDay), "aa", typeof(ShardingDefaultDbContext), new List<PropertyInfo>());
var y = new EntityMetadata(typeof(LogDay), "aa1", typeof(ShardingDefaultDbContext), new List<PropertyInfo>());
Assert.Equal(x, y);
var dateTime = new DateTime(2021,1,1);
var logDays = Enumerable.Range(0,100).Select(o=>new LogDay(){Id = Guid.NewGuid(),LogLevel = "info",LogBody = o.ToString(),LogTime = dateTime.AddDays(o)}).ToList();
var dateTime = new DateTime(2021, 1, 1);
var logDays = Enumerable.Range(0, 100).Select(o => new LogDay() { Id = Guid.NewGuid(), LogLevel = "info", LogBody = o.ToString(), LogTime = dateTime.AddDays(o) }).ToList();
var bulkShardingTableEnumerable = _virtualDbContext.BulkShardingTableEnumerable(logDays);
Assert.Equal(100, bulkShardingTableEnumerable.Count);
var bulkShardingEnumerable = _virtualDbContext.BulkShardingEnumerable(logDays);
@ -80,7 +81,7 @@ namespace ShardingCore.Test
}
_virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300").ShardingPrint();
var contains=await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300").Select(o => o.Id).ContainsAsync("300");
var contains = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300").Select(o => o.Id).ContainsAsync("300");
Assert.True(contains);
try
@ -89,22 +90,22 @@ namespace ShardingCore.Test
}
catch (Exception e)
{
Assert.Equal(typeof(ShardingCoreInvalidOperationException),e.GetType());
Assert.Equal(typeof(ShardingCoreInvalidOperationException), e.GetType());
}
var queryable=new List<string>().Select(o => new SequenceClass { Id = "123", T = o }).AsQueryable();
var queryable = new List<string>().Select(o => new SequenceClass { Id = "123", T = o }).AsQueryable();
var sourceType = queryable.GetType().GetSequenceType();
Assert.Equal(typeof(SequenceClass),sourceType);
Assert.Equal(typeof(SequenceClass), sourceType);
try
{
_shardingTableCreator.CreateTable<Order>("A", "202105");
}
catch (Exception e)
{
Assert.Equal(typeof(ShardingCoreException),e.GetType());
Assert.Equal(typeof(ShardingCoreException), e.GetType());
}
var orderMetadata=_entityMetadataManager.TryGet<Order>();
var orderMetadata = _entityMetadataManager.TryGet<Order>();
Assert.NotNull(orderMetadata);
var isKey1 = orderMetadata.ShardingDataSourceFieldIsKey();
Assert.False(isKey1);
@ -122,28 +123,33 @@ namespace ShardingCore.Test
}
catch (Exception e)
{
Assert.Equal(typeof(ShardingCoreParallelQueryTimeOutException),e.GetType());
Assert.Equal(typeof(ShardingCoreParallelQueryTimeOutException), e.GetType());
}
await _virtualDbContext.AddRangeAsync(logDays);
var bulkShardingExpression = _virtualDbContext.BulkShardingExpression<ShardingDefaultDbContext,Order>(o=>new[]{"A","B"}.Contains(o.Area));
Assert.Equal(2, bulkShardingExpression.Count);
Assert.True(bulkShardingExpression.ContainsKey("A"));
Assert.True(bulkShardingExpression.ContainsKey("B"));
var bulkShardingExpression = _virtualDbContext.BulkShardingExpression<ShardingDefaultDbContext, Order>(o => new[] { "A", "B" }.Contains(o.Area));
Assert.Equal(2, bulkShardingExpression.Count);
Assert.True(bulkShardingExpression.ContainsKey("A"));
Assert.True(bulkShardingExpression.ContainsKey("B"));
var bulkShardingTableExpression = _virtualDbContext.BulkShardingTableExpression<ShardingDefaultDbContext, SysUserMod>(o => o.Id == Guid.NewGuid().ToString());
Assert.Equal(1, bulkShardingTableExpression.Count());
var noShardingExpression = _virtualDbContext.BulkShardingExpression<ShardingDefaultDbContext, LogNoSharding>(o => o.Id == "123");
Assert.Equal(1, noShardingExpression.Count());
var bulkShardingTableExpression = _virtualDbContext.BulkShardingTableExpression<ShardingDefaultDbContext,SysUserMod>(o=>o.Id==Guid.NewGuid().ToString());
Assert.Equal(1, bulkShardingTableExpression.Count());
var isShardingDbContext = _virtualDbContext.IsShardingDbContext();
Assert.True(isShardingDbContext);
var isShardingTableDbContext = _virtualDbContext.IsShardingTableDbContext();
Assert.True(isShardingTableDbContext);
var shardingDbContext = _virtualDbContext.GetType().IsShardingDbContext();
Assert.True(shardingDbContext);
var shardingTableDbContext = _virtualDbContext.GetType().IsShardingTableDbContext();
Assert.True(shardingTableDbContext);
var virtualTable = _virtualTableManager.GetVirtualTable<SysUserMod>();
Assert.NotNull(virtualTable);
Assert.True(isShardingDbContext);
var isShardingTableDbContext = _virtualDbContext.IsShardingTableDbContext();
Assert.True(isShardingTableDbContext);
var shardingDbContext = _virtualDbContext.GetType().IsShardingDbContext();
Assert.True(shardingDbContext);
var shardingTableDbContext = _virtualDbContext.GetType().IsShardingTableDbContext();
Assert.True(shardingTableDbContext);
var virtualTable = _virtualTableManager.GetVirtualTable<SysUserMod>();
Assert.NotNull(virtualTable);
}
public class SequenceClass
@ -179,7 +185,7 @@ namespace ShardingCore.Test
var y = new Guid("3425D899-291D-921B-DDE4-49FFE37AE493");
//asc y<x c# compare guid
var compare0 = x.CompareTo(y);
Assert.True(compare0>0);
Assert.True(compare0 > 0);
//asc x<y db compare uniqueidentifier
var compare1 = _shardingComparer.Compare(x, y, true);
Assert.True(compare1 < 0);
@ -289,7 +295,7 @@ namespace ShardingCore.Test
Name = u.Name
}).ToListAsync();
var list2 = list.OrderBy(o=>o.Age).Select(o=>o.Age).Distinct().ToList();
var list2 = list.OrderBy(o => o.Age).Select(o => o.Age).Distinct().ToList();
Assert.Equal(24000, list.Count());
Assert.Equal(24, list.Count(o => o.Name == "name_200"));
@ -333,7 +339,7 @@ namespace ShardingCore.Test
[Fact]
public async Task ToList_Id_In_Test()
{
var ids = new[] {"1", "2", "3", "4"};
var ids = new[] { "1", "2", "3", "4" };
var sysUserMods = await _virtualDbContext.Set<SysUserMod>().Where(o => new List<string> { "1", "2", "3", "4" }.Contains(o.Id)).ToListAsync();
foreach (var id in ids)
{
@ -346,7 +352,7 @@ namespace ShardingCore.Test
[Fact]
public async Task ToList_Id_Eq_Test()
{
var id= 3;
var id = 3;
var mods = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == id.ToString()).ToListAsync();
Assert.Single(mods);
var mods1 = await _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "4").ToListAsync();
@ -494,14 +500,14 @@ namespace ShardingCore.Test
public async Task Max_Join_Test()
{
var queryable = (from u in _virtualDbContext.Set<SysUserMod>().Where(o => o.Id == "300")
join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId
select new
{
Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth,
Name = u.Name
});
join salary in _virtualDbContext.Set<SysUserSalary>()
on u.Id equals salary.UserId
select new
{
Salary = salary.Salary,
DateOfMonth = salary.DateOfMonth,
Name = u.Name
});
var maxSalary = await queryable.MaxAsync(o => o.Salary);
Assert.Equal(1390000, maxSalary);
}
@ -535,25 +541,25 @@ namespace ShardingCore.Test
[Fact]
public async Task Group_Test()
{
var ids = new[] {"200", "300"};
var dateOfMonths = new[] {202111, 202110};
var ids = new[] { "200", "300" };
var dateOfMonths = new[] { 202111, 202110 };
var group = await (from u in _virtualDbContext.Set<SysUserSalary>()
.Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth))
group u by new
{
UId = u.UserId
}
group u by new
{
UId = u.UserId
}
into g
select new
{
GroupUserId = g.Key.UId,
Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary)
}).ToListAsync();
select new
{
GroupUserId = g.Key.UId,
Count = g.Count(),
TotalSalary = g.Sum(o => o.Salary),
AvgSalary = g.Average(o => o.Salary),
AvgSalaryDecimal = g.Average(o => o.SalaryDecimal),
MinSalary = g.Min(o => o.Salary),
MaxSalary = g.Max(o => o.Salary)
}).ToListAsync();
Assert.Equal(2, group.Count);
Assert.Equal(2, group[0].Count);
Assert.Equal(2260000, group[0].TotalSalary);
@ -568,43 +574,43 @@ namespace ShardingCore.Test
{
var asyncCount = await _virtualDbContext.Set<Order>().CountAsync();
Assert.Equal(320, asyncCount);
var syncCount = _virtualDbContext.Set<Order>().Count();
var syncCount = _virtualDbContext.Set<Order>().Count();
Assert.Equal(320, syncCount);
var countA =await _virtualDbContext.Set<Order>().CountAsync(o=>o.Area=="A");
var countB =await _virtualDbContext.Set<Order>().CountAsync(o=>o.Area=="B");
var countC =await _virtualDbContext.Set<Order>().CountAsync(o=>o.Area=="C");
Assert.Equal(320, countA+ countB+ countC);
var countA = await _virtualDbContext.Set<Order>().CountAsync(o => o.Area == "A");
var countB = await _virtualDbContext.Set<Order>().CountAsync(o => o.Area == "B");
var countC = await _virtualDbContext.Set<Order>().CountAsync(o => o.Area == "C");
Assert.Equal(320, countA + countB + countC);
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var fourCount = await _virtualDbContext.Set<Order>().Where(o=>o.CreateTime>=fourBegin&&o.CreateTime<fiveBegin).CountAsync();
Assert.Equal(30,fourCount);
var fourCount = await _virtualDbContext.Set<Order>().Where(o => o.CreateTime >= fourBegin && o.CreateTime < fiveBegin).CountAsync();
Assert.Equal(30, fourCount);
}
[Fact]
public async Task OrderFirstTest()
{
var threeMonth = new DateTime(2021,3,1);
var order = await _virtualDbContext.Set<Order>().FirstOrDefaultAsync(o=>o.CreateTime== threeMonth);//µÚ59Ìõ 1ÔÂ31Ìì2ÔÂ28Ìì
var threeMonth = new DateTime(2021, 3, 1);
var order = await _virtualDbContext.Set<Order>().FirstOrDefaultAsync(o => o.CreateTime == threeMonth);//µÚ59Ìõ 1ÔÂ31Ìì2ÔÂ28Ìì
Assert.NotNull(order);
Assert.Equal(59,order.Money);
Assert.Equal("C",order.Area);
Assert.Equal(59, order.Money);
Assert.Equal("C", order.Area);
}
[Fact]
public async Task OrderOrderTest()
{
var orders = await _virtualDbContext.Set<Order>().OrderBy(o => o.CreateTime).ToListAsync();
Assert.Equal(320,orders.Count);
Assert.Equal(320, orders.Count);
var i = 0;
foreach (var order in orders)
{
Assert.Equal(i,order.Money);
Assert.Equal(i, order.Money);
i++;
}
var threeMonth = new DateTime(2021, 3, 1);
var orderPage = await _virtualDbContext.Set<Order>().Where(o=>o.CreateTime > threeMonth).OrderByDescending(o => o.CreateTime).ToShardingPageAsync(1,20);
var orderPage = await _virtualDbContext.Set<Order>().Where(o => o.CreateTime > threeMonth).OrderByDescending(o => o.CreateTime).ToShardingPageAsync(1, 20);
Assert.Equal(20, orderPage.Data.Count);
Assert.Equal(260,orderPage.Total);
Assert.Equal(260, orderPage.Total);
var j = 319;
@ -615,7 +621,7 @@ namespace ShardingCore.Test
}
var orderPage1 = await _virtualDbContext.Set<Order>().Where(o => o.CreateTime > threeMonth).OrderBy(o=>o.CreateTime).ToShardingPageAsync(1, 20);
var orderPage1 = await _virtualDbContext.Set<Order>().Where(o => o.CreateTime > threeMonth).OrderBy(o => o.CreateTime).ToShardingPageAsync(1, 20);
Assert.Equal(20, orderPage1.Data.Count);
Assert.Equal(260, orderPage1.Total);
@ -632,7 +638,7 @@ namespace ShardingCore.Test
public async Task LogDayCountTest()
{
var countAsync = await _virtualDbContext.Set<LogDay>().CountAsync();
Assert.Equal(3000,countAsync);
Assert.Equal(3000, countAsync);
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var fourCount = await _virtualDbContext.Set<LogDay>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync();
@ -656,14 +662,14 @@ namespace ShardingCore.Test
{
var virtualTable = _virtualTableManager.GetVirtualTable(typeof(LogDay));
var virtualTableName = virtualTable.GetVirtualTableName();
Assert.Equal(nameof(LogDay),virtualTableName);
Assert.Equal(nameof(LogDay), virtualTableName);
var table = _virtualTableManager.GetVirtualTable(virtualTableName);
var tryGetVirtualTable = _virtualTableManager.TryGetVirtualTable(typeof(LogDay));
Assert.NotNull(tryGetVirtualTable);
var tryGetVirtualTable1 = _virtualTableManager.TryGetVirtualTable(virtualTableName);
Assert.NotNull(tryGetVirtualTable1);
var all = virtualTable.GetAllPhysicTables().All(o=>string.IsNullOrWhiteSpace(o.TableSeparator));
var all = virtualTable.GetAllPhysicTables().All(o => string.IsNullOrWhiteSpace(o.TableSeparator));
Assert.True(all);
var entityMetadata = _entityMetadataManager.TryGet<LogDay>();
Assert.NotNull(entityMetadata);
@ -681,15 +687,15 @@ namespace ShardingCore.Test
{
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var page= await _virtualDbContext.Set<LogDay>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o=>o.LogTime)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(300, page.Total);
var page = await _virtualDbContext.Set<LogDay>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(300, page.Total);
var page1 = await _virtualDbContext.Set<LogDay>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(300, page1.Total);
var page1 = await _virtualDbContext.Set<LogDay>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(300, page1.Total);
}
[Fact]
@ -705,49 +711,50 @@ namespace ShardingCore.Test
{
_shardingRouteManager.Current.TryCreateOrAddMustDataSource<Order>("C");
var sum = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync();
Assert.Equal(0,sum);
.Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync();
Assert.Equal(0, sum);
var sum1 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (long?)o.Money).SumAsync();
Assert.Equal(0,sum1);
.Where(o => o.CreateTime == fiveBegin).Select(o => (long?)o.Money).SumAsync();
Assert.Equal(0, sum1);
var sum2 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (int)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (int)o.Money).SumAsync();
Assert.Equal(0, sum2);
var sum3 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (int?)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (int?)o.Money).SumAsync();
Assert.Equal(0, sum3);
var sum4 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (decimal)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (decimal)o.Money).SumAsync();
Assert.Equal(0, sum4);
var sum5 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (decimal?)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (decimal?)o.Money).SumAsync();
Assert.Equal(0, sum5);
var sum6 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (double)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (double)o.Money).SumAsync();
Assert.Equal(0, sum6);
var sum7 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (double?)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (double?)o.Money).SumAsync();
Assert.Equal(0, sum7);
var sum8 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (float)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (float)o.Money).SumAsync();
Assert.Equal(0, sum8);
var sum9 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => (float?)o.Money).SumAsync();
.Where(o => o.CreateTime == fiveBegin).Select(o => (float?)o.Money).SumAsync();
Assert.Equal(0, sum9);
}
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintDataSource<Order>("C");
var sum = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync();
Assert.Equal(0,sum);
.Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync();
Assert.Equal(0, sum);
}
var max = await _virtualDbContext.Set<Order>().MaxAsync(o => o.Money);
var all= await _virtualDbContext.Set<Order>().AllAsync(o=>o.Money<=321);
Assert.Equal(319, max);
var all = await _virtualDbContext.Set<Order>().AllAsync(o => o.Money <= 321);
Assert.True(all);
var longCount=await _virtualDbContext.Set<Order>().LongCountAsync();
Assert.Equal(320,longCount);
var longCount = await _virtualDbContext.Set<Order>().LongCountAsync();
Assert.Equal(320, longCount);
}
[Fact]
@ -756,11 +763,11 @@ namespace ShardingCore.Test
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var moneyMax = await _virtualDbContext.Set<Order>()
var moneyMax = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).MaxAsync();
Assert.Equal(120, moneyMax);
var moneyMax1 = await _virtualDbContext.Set<Order>()
var moneyMax1 = await _virtualDbContext.Set<Order>()
.Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).MaxAsync();
Assert.Equal(120, moneyMax1);
var moneyMax2 = await _virtualDbContext.Set<Order>()
@ -858,17 +865,17 @@ namespace ShardingCore.Test
[Fact]
public async Task Order_Entity()
{
var x=await _virtualDbContext.Set<Order>().OrderBy(o => o.Money).LastOrDefaultAsync();
var x = await _virtualDbContext.Set<Order>().OrderBy(o => o.Money).LastOrDefaultAsync();
Assert.NotNull(x);
Assert.Equal(319,x.Money);
Assert.Equal(319, x.Money);
var x1 = await _virtualDbContext.Set<Order>().OrderBy(o => o.Money).LastAsync();
Assert.Equal(x,x1);
Assert.Equal(x, x1);
var y = await _virtualDbContext.Set<Order>().OrderBy(o => o.Money).FirstOrDefaultAsync();
Assert.NotNull(y);
Assert.Equal(0, y.Money);
var y1 = await _virtualDbContext.Set<Order>().OrderBy(o => o.Money).FirstAsync();
Assert.Equal(y, y1);
var z=await _virtualDbContext.Set<Order>().SingleOrDefaultAsync(o => o.Money == 13);
var z = await _virtualDbContext.Set<Order>().SingleOrDefaultAsync(o => o.Money == 13);
var z1 = await _virtualDbContext.Set<Order>().SingleAsync(o => o.Money == 13);
Assert.Equal(z, z1);
}
@ -878,7 +885,7 @@ namespace ShardingCore.Test
{
//切换到只读数据库只读数据库又只配置了A数据源读取B数据源
_virtualDbContext.ReadWriteSeparationReadOnly();
var list = await _virtualDbContext.Set<Order>().Where(o=>o.Money==1).ToListAsync();
var list = await _virtualDbContext.Set<Order>().Where(o => o.Money == 1).ToListAsync();
Assert.Equal(2, list.Count);
_virtualDbContext.ReadWriteSeparationWriteOnly();
@ -966,6 +973,271 @@ namespace ShardingCore.Test
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public async Task LogWeekTimeLongCountTest()
{
var countAsync = await _virtualDbContext.Set<LogWeekTimeLong>().CountAsync();
Assert.Equal(300, countAsync);
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var fourCount = await _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogWeekTimeLong>("20210419_25");
var countAsync1 = await _virtualDbContext.Set<LogWeekTimeLong>().CountAsync();
Assert.Equal(7, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogWeekTimeLong>("20210419_25", "20210426_02");
var countAsync2 = await _virtualDbContext.Set<LogWeekTimeLong>().CountAsync();
Assert.Equal(14, countAsync2);
}
}
[Fact]
public async Task LogWeekDateLongShardingPage()
{
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var page = await _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = await _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public async Task LogYearTimeLongCountTest()
{
var countAsync = await _virtualDbContext.Set<LogYearDateTime>().CountAsync();
Assert.Equal(600, countAsync);
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var fourCount = await _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogYearDateTime>("2020");
var countAsync1 = await _virtualDbContext.Set<LogYearDateTime>().CountAsync();
Assert.Equal(366, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogYearDateTime>("2021");
var countAsync2 = await _virtualDbContext.Set<LogYearDateTime>().CountAsync();
Assert.Equal(234, countAsync2);
}
}
[Fact]
public async Task LogYearDateLongShardingPage()
{
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var page = await _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = await _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public async Task LogMonthTimeLongCountTest()
{
var countAsync = await _virtualDbContext.Set<LogMonthLong>().CountAsync();
Assert.Equal(300, countAsync);
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var fourCount = await _virtualDbContext.Set<LogMonthLong>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogMonthLong>("202104");
var countAsync1 = await _virtualDbContext.Set<LogMonthLong>().CountAsync();
Assert.Equal(30, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogMonthLong>("202104", "202105");
var countAsync2 = await _virtualDbContext.Set<LogMonthLong>().CountAsync();
Assert.Equal(61, countAsync2);
}
}
[Fact]
public async Task LogMonthDateLongShardingPage()
{
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var page = await _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = await _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPageAsync(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public async Task CrudTest()
{
var logNoSharding = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoShardings = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
var logNoSharding1 = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoSharding1s = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
using (var tran = await _virtualDbContext.Database.BeginTransactionAsync())
{
try
{
await _virtualDbContext.AddAsync(logNoSharding);
await _virtualDbContext.AddRangeAsync(logNoShardings);
await _virtualDbContext.Set<LogNoSharding>().AddAsync(logNoSharding1);
await _virtualDbContext.Set<LogNoSharding>().AddRangeAsync(logNoSharding1s);
await _virtualDbContext.SaveChangesAsync();
await tran.CommitAsync();
}
catch (Exception e)
{
await tran.RollbackAsync();
}
}
logNoSharding.Body = DateTime.Now.ToString("yyyyMMdd");
_virtualDbContext.Update(logNoSharding);
logNoShardings.ForEach(o=>o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.UpdateRange(logNoShardings);
logNoSharding1.Body = DateTime.Now.ToString("yyyyMMdd");
_virtualDbContext.Set<LogNoSharding>().Update(logNoSharding1);
logNoSharding1s.ForEach(o=>o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.Set<LogNoSharding>().UpdateRange(logNoSharding1s);
await _virtualDbContext.SaveChangesAsync();
_virtualDbContext.Remove(logNoSharding);
_virtualDbContext.RemoveRange(logNoShardings);
_virtualDbContext.Set<LogNoSharding>().Remove(logNoSharding1);
logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.Set<LogNoSharding>().RemoveRange(logNoSharding1s);
await _virtualDbContext.SaveChangesAsync();
}
[Fact]
public async Task CrudTest1()
{
var logNoSharding = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoShardings = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
using (var tran = await _virtualDbContext.Database.BeginTransactionAsync())
{
try
{
await _virtualDbContext.AddAsync((object)logNoSharding);
await _virtualDbContext.AddRangeAsync(logNoShardings.Select(o=>(object)o).ToArray());
await _virtualDbContext.SaveChangesAsync();
await tran.CommitAsync();
}
catch (Exception e)
{
await tran.RollbackAsync();
}
}
logNoSharding.Body = DateTime.Now.ToString("yyyyMMdd");
_virtualDbContext.Update((object)logNoSharding);
logNoShardings.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.UpdateRange(logNoShardings.Select(o => (object)o).ToArray());
await _virtualDbContext.SaveChangesAsync();
_virtualDbContext.Remove((object)logNoSharding);
_virtualDbContext.RemoveRange(logNoShardings.Select(o => (object)o).ToArray());
await _virtualDbContext.SaveChangesAsync();
}
// [Fact]
// public async Task Group_API_Test()
// {

View File

@ -2,6 +2,8 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.QueryRouteManagers.Abstractions;
@ -11,6 +13,7 @@ using ShardingCore.Core.VirtualDatabase.VirtualTables;
using ShardingCore.Exceptions;
using ShardingCore.Extensions;
using ShardingCore.Extensions.ShardingPageExtensions;
using ShardingCore.Helpers;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
using ShardingCore.Sharding.ShardingComparision.Abstractions;
using ShardingCore.TableCreator;
@ -891,6 +894,297 @@ namespace ShardingCore.Test
Assert.Null(areaB);
}
}
[Fact]
public void LogWeekDateTimeCountTest()
{
var countAsync = _virtualDbContext.Set<LogWeekDateTime>().Count();
Assert.Equal(300, countAsync);
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var fourCount = _virtualDbContext.Set<LogWeekDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogWeekDateTime>("20210419_25");
var countAsync1 = _virtualDbContext.Set<LogWeekDateTime>().Count();
Assert.Equal(7, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogWeekDateTime>("20210419_25", "20210426_02");
var countAsync2 = _virtualDbContext.Set<LogWeekDateTime>().Count();
Assert.Equal(14, countAsync2);
}
}
[Fact]
public void LogWeekDateTimeShardingPage()
{
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var page = _virtualDbContext.Set<LogWeekDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPage(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = _virtualDbContext.Set<LogWeekDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPage(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public void LogWeekTimeLongCountTest()
{
var countAsync = _virtualDbContext.Set<LogWeekTimeLong>().Count();
Assert.Equal(300, countAsync);
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var fourCount = _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogWeekTimeLong>("20210419_25");
var countAsync1 = _virtualDbContext.Set<LogWeekTimeLong>().Count();
Assert.Equal(7, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogWeekTimeLong>("20210419_25", "20210426_02");
var countAsync2 = _virtualDbContext.Set<LogWeekTimeLong>().Count();
Assert.Equal(14, countAsync2);
}
}
[Fact]
public void LogWeekDateLongShardingPage()
{
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var page = _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPage(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPage(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public void LogYearTimeLongCountTest()
{
var countAsync = _virtualDbContext.Set<LogYearDateTime>().Count();
Assert.Equal(600, countAsync);
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var fourCount = _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogYearDateTime>("2020");
var countAsync1 = _virtualDbContext.Set<LogYearDateTime>().Count();
Assert.Equal(366, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogYearDateTime>("2021");
var countAsync2 = _virtualDbContext.Set<LogYearDateTime>().Count();
Assert.Equal(234, countAsync2);
}
}
[Fact]
public void LogYearDateLongShardingPage()
{
var fourBegin = new DateTime(2021, 4, 1).Date;
var fiveBegin = new DateTime(2021, 5, 1).Date;
var page = _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPage(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = _virtualDbContext.Set<LogYearDateTime>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPage(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public void LogMonthTimeLongCountTest()
{
var countAsync = _virtualDbContext.Set<LogMonthLong>().Count();
Assert.Equal(300, countAsync);
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var fourCount = _virtualDbContext.Set<LogMonthLong>().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count();
Assert.Equal(30, fourCount);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddMustTail<LogMonthLong>("202104");
var countAsync1 = _virtualDbContext.Set<LogMonthLong>().Count();
Assert.Equal(30, countAsync1);
}
Assert.Null(_shardingRouteManager.Current);
using (_shardingRouteManager.CreateScope())
{
_shardingRouteManager.Current.TryCreateOrAddHintTail<LogMonthLong>("202104", "202105");
var countAsync2 = _virtualDbContext.Set<LogMonthLong>().Count();
Assert.Equal(61, countAsync2);
}
}
[Fact]
public void LogMonthDateLongShardingPage()
{
var fourBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 4, 1).Date);
var fiveBegin = ShardingCoreHelper.ConvertDateTimeToLong(new DateTime(2021, 5, 1).Date);
var page = _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime)
.ToShardingPage(2, 10);
Assert.Equal(10, page.Data.Count);
Assert.Equal(31, page.Total);
var page1 = _virtualDbContext.Set<LogWeekTimeLong>().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin)
.ToShardingPage(2, 10);
Assert.Equal(10, page1.Data.Count);
Assert.Equal(31, page1.Total);
}
[Fact]
public void CrudTest()
{
var logNoSharding = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoShardings = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
var logNoSharding1 = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoSharding1s = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
using (var tran = _virtualDbContext.Database.BeginTransaction())
{
try
{
_virtualDbContext.Add(logNoSharding);
_virtualDbContext.AddRange(logNoShardings);
_virtualDbContext.Set<LogNoSharding>().Add(logNoSharding1);
_virtualDbContext.Set<LogNoSharding>().AddRange(logNoSharding1s);
_virtualDbContext.SaveChanges();
tran.Commit();
}
catch (Exception e)
{
tran.Rollback();
}
}
logNoSharding.Body = DateTime.Now.ToString("yyyyMMdd");
_virtualDbContext.Update(logNoSharding);
logNoShardings.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.UpdateRange(logNoShardings);
logNoSharding1.Body = DateTime.Now.ToString("yyyyMMdd");
_virtualDbContext.Set<LogNoSharding>().Update(logNoSharding1);
logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.Set<LogNoSharding>().UpdateRange(logNoSharding1s);
_virtualDbContext.SaveChanges();
_virtualDbContext.Remove(logNoSharding);
_virtualDbContext.RemoveRange(logNoShardings);
_virtualDbContext.Set<LogNoSharding>().Remove(logNoSharding1);
logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd"));
_virtualDbContext.Set<LogNoSharding>().RemoveRange(logNoSharding1s);
_virtualDbContext.SaveChanges();
}
[Fact]
public void CrudTest1()
{
var logNoSharding = new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
};
var logNoShardings = new List<LogNoSharding>()
{
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
},
new LogNoSharding()
{
Id = Guid.NewGuid().ToString("n"),
Body = DateTime.Now.ToString("yyyyMMddHHmmss"),
CreationTime = DateTime.Now
}
};
using (var tran = _virtualDbContext.Database.BeginTransaction())
{
try
{
_virtualDbContext.Add((object)logNoSharding);
_virtualDbContext.AddRange(logNoShardings.Select(o => (object)o).ToArray());
_virtualDbContext.SaveChanges();
tran.Commit();
}
catch (Exception e)
{
tran.Rollback();
}
}
}
// [Fact]
// public void Group_API_Test()
// {

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.Test.Domain.Maps;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test.Shardings
{
public class LogMonthLongvirtualRoute:AbstractSimpleShardingMonthKeyLongVirtualTableRoute<LogMonthLong>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogMonthLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Weeks;
namespace ShardingCore.Test.Shardings
{
public class LogWeekTimeLongVirtualTableRoute : AbstractSimpleShardingWeekKeyLongVirtualTableRoute<LogWeekTimeLong>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogWeekTimeLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Years;
namespace ShardingCore.Test.Shardings
{
public class LogYearDateTimeVirtualRoute:AbstractSimpleShardingYearKeyDateTimeVirtualTableRoute<LogYearDateTime>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2020, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogYearDateTime> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
@ -20,6 +21,11 @@ namespace ShardingCore.Test.Shardings
return allTails;
}
public override void Configure(EntityMetadataTableBuilder<Order> builder)
{
}
public override IPaginationConfiguration<Order> CreatePaginationConfiguration()
{
return new OrderCreateTimePaginationConfiguration();

View File

@ -7,6 +7,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ShardingCore.Bootstrapers;
using ShardingCore.Helpers;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.Test.Domain.Entities;
using ShardingCore.Test.Shardings;
@ -36,13 +37,10 @@ namespace ShardingCore.Test
o.UseSqlServer(conn).UseLoggerFactory(efLogger))
.Begin(o =>
{
#if EFCORE6Test
#if DEBUG
o.CreateShardingTableOnStart = true;
o.EnsureCreatedWithOutShardingTable = true;
#endif
#if !EFCORE6Test
o.CreateShardingTableOnStart = false;
o.EnsureCreatedWithOutShardingTable = false;
#endif
o.AutoTrackEntity = true;
})
@ -68,6 +66,9 @@ namespace ShardingCore.Test
op.AddShardingTableRoute<OrderCreateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogDayVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekDateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekTimeLongVirtualTableRoute>();
op.AddShardingTableRoute<LogYearDateTimeVirtualRoute>();
op.AddShardingTableRoute<LogMonthLongvirtualRoute>();
}).AddReadWriteSeparation(sp =>
{
return new Dictionary<string, ISet<string>>()
@ -196,6 +197,44 @@ namespace ShardingCore.Test
});
begin2 = begin2.AddDays(1);
}
List<LogWeekTimeLong> logWeekLongs = new List<LogWeekTimeLong>(300);
var begin3 = new DateTime(2021,1,1);
for (int i = 0; i < 300; i++)
{
logWeekLongs.Add(new LogWeekTimeLong()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin3)
});
begin3 = begin3.AddDays(1);
}
List<LogYearDateTime> logYears = new List<LogYearDateTime>(600);
var begin4 = new DateTime(2020,1,1);
for (int i = 0; i < 600; i++)
{
logYears.Add(new LogYearDateTime()
{
Id = Guid.NewGuid(),
LogBody = $"body_{i}",
LogTime = begin4
});
begin4 = begin4.AddDays(1);
}
List<LogMonthLong> logMonthLongs = new List<LogMonthLong>(300);
var begin5 = new DateTime(2021, 1, 1);
for (int i = 0; i < 300; i++)
{
logMonthLongs.Add(new LogMonthLong()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin5)
});
begin5 = begin5.AddDays(1);
}
using (var tran = virtualDbContext.Database.BeginTransaction())
{
@ -204,6 +243,9 @@ namespace ShardingCore.Test
await virtualDbContext.AddRangeAsync(orders);
await virtualDbContext.AddRangeAsync(logDays);
await virtualDbContext.AddRangeAsync(logWeeks);
await virtualDbContext.AddRangeAsync(logWeekLongs);
await virtualDbContext.AddRangeAsync(logYears);
await virtualDbContext.AddRangeAsync(logMonthLongs);
await virtualDbContext.SaveChangesAsync();
tran.Commit();

View File

@ -0,0 +1,12 @@
using System;
namespace ShardingCore.Test2x.Domain.Entities
{
public class LogDay
{
public Guid Id { get; set; }
public string LogLevel { get; set; }
public string LogBody { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System;
namespace ShardingCore.Test2x.Domain.Entities
{
public class LogWeekDateTime
{
public string Id { get; set; }
public string Body { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,10 @@
namespace ShardingCore.Test2x.Domain.Entities
{
public class LogWeekTimeLong
{
public string Id { get; set; }
public string Body { get; set; }
public long LogTime { get; set; }
}
}

View File

@ -0,0 +1,11 @@
using System;
namespace ShardingCore.Test2x.Domain.Entities
{
public class LogYearDateTime
{
public Guid Id { get; set; }
public string LogBody { get; set; }
public DateTime LogTime { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using ShardingCore.Core;
namespace ShardingCore.Test2x.Domain.Entities
{
public class Order:IShardingDataSource,IShardingTable
{
public Guid Id { get; set; }
[ShardingDataSourceKey]
public string Area { get; set; }
public long Money { get; set; }
[ShardingTableKey]
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,26 @@
namespace ShardingCore.Test2x.Domain.Entities
{
/*
* @Author: xjm
* @Description:
* @Date: Thursday, 14 January 2021 15:36:43
* @Email: 326308290@qq.com
*/
public class SysUserMod
{
/// <summary>
/// 用户Id用于分表
/// </summary>
public string Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
public int Age { get; set; }
public int AgeGroup { get; set; }
}
}

View File

@ -0,0 +1,39 @@
namespace ShardingCore.Test2x.Domain.Entities
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:43:22
* @Email: 326308290@qq.com
*/
public class SysUserSalary
{
public string Id { get; set; }
public string UserId { get; set; }
/// <summary>
/// 每月的金额
/// </summary>
public int DateOfMonth { get; set; }
/// <summary>
/// 工资
/// </summary>
public int Salary { get; set; }
/// <summary>
/// 工资
/// </summary>
public long SalaryLong { get; set; }
/// <summary>
/// 工资
/// </summary>
public decimal SalaryDecimal { get; set; }
/// <summary>
/// 工资
/// </summary>
public double SalaryDouble { get; set; }
/// <summary>
/// 工资
/// </summary>
public float SalaryFloat { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
public class LogDayMap:IEntityTypeConfiguration<LogDay>
{
public void Configure(EntityTypeBuilder<LogDay> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogLevel).IsRequired().IsUnicode(false).HasMaxLength(32);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogDay));
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
public class LogWeekDateTimeMap:IEntityTypeConfiguration<LogWeekDateTime>
{
public void Configure(EntityTypeBuilder<LogWeekDateTime> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekDateTime));
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
public class LogWeekTimeLongMap : IEntityTypeConfiguration<LogWeekTimeLong>
{
public void Configure(EntityTypeBuilder<LogWeekTimeLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekTimeLong));
}
}
}

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
public class LogYearDateTimeMap : IEntityTypeConfiguration<LogYearDateTime>
{
public void Configure(EntityTypeBuilder<LogYearDateTime> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256);
builder.ToTable(nameof(LogYearDateTime));
}
}
}

View File

@ -0,0 +1,16 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
public class OrderMap:IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Area).IsRequired().IsUnicode(false).HasMaxLength(20);
builder.ToTable(nameof(Order));
}
}
}

View File

@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
/*
* @Author: xjm
* @Description:
* @Date: Thursday, 14 January 2021 15:37:33
* @Email: 326308290@qq.com
*/
public class SysUserModMap:IEntityTypeConfiguration<SysUserMod>
{
public void Configure(EntityTypeBuilder<SysUserMod> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().HasMaxLength(128);
builder.Property(o => o.Name).HasMaxLength(128);
builder.ToTable(nameof(SysUserMod));
}
}
}

View File

@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Domain.Maps
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:42:35
* @Email: 326308290@qq.com
*/
public class SysUserSalaryMap:IEntityTypeConfiguration<SysUserSalary>
{
public void Configure(EntityTypeBuilder<SysUserSalary> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().HasMaxLength(128);
builder.Property(o => o.UserId).IsRequired().HasMaxLength(128);
builder.ToTable(nameof(SysUserSalary));
}
}
}

View File

@ -3,9 +3,6 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<DefineConstants>TRACE;DEBUG;EFCORE2Test;</DefineConstants>
<AssemblyName>ShardingCore.Test</AssemblyName>
<RootNamespace>ShardingCore.Test</RootNamespace>
</PropertyGroup>
<ItemGroup>
@ -19,11 +16,6 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Include="..\ShardingCore.Test\**\*.cs" />
<Compile Remove="..\ShardingCore.Test\obj\**" />
<Compile Remove="..\ShardingCore.Test\bin\**" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src2x\ShardingCore.2x\ShardingCore.2x.csproj" />
</ItemGroup>

View File

@ -0,0 +1,36 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.Sharding;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Test2x.Domain.Maps;
namespace ShardingCore.Test2x
{
/*
* @Author: xjm
* @Description:
* @Date: 2021/8/15 10:21:03
* @Ver: 1.0
* @Email: 326308290@qq.com
*/
public class ShardingDefaultDbContext:AbstractShardingDbContext, IShardingTableDbContext
{
public ShardingDefaultDbContext(DbContextOptions<ShardingDefaultDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new SysUserModMap());
modelBuilder.ApplyConfiguration(new SysUserSalaryMap());
modelBuilder.ApplyConfiguration(new OrderMap());
modelBuilder.ApplyConfiguration(new LogDayMap());
modelBuilder.ApplyConfiguration(new LogWeekDateTimeMap());
modelBuilder.ApplyConfiguration(new LogWeekTimeLongMap());
modelBuilder.ApplyConfiguration(new LogYearDateTimeMap());
}
public IRouteTail RouteTail { get; set; }
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
using System;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.Test2x.Shardings.PaginationConfigs;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test2x.Shardings
{
public class LogDayVirtualTableRoute:AbstractSimpleShardingDayKeyDateTimeVirtualTableRoute<LogDay>
{
protected override bool EnableHintRoute => true;
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogDay> builder)
{
builder.ShardingProperty(o => o.LogTime);
builder.TableSeparator(string.Empty);
}
public override IPaginationConfiguration<LogDay> CreatePaginationConfiguration()
{
return new LogDayPaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Weeks;
namespace ShardingCore.Test2x.Shardings
{
public class LogWeekDateTimeVirtualTableRoute:AbstractSimpleShardingWeekKeyDateTimeVirtualTableRoute<LogWeekDateTime>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogWeekDateTime> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Weeks;
namespace ShardingCore.Test2x.Shardings
{
public class LogWeekTimeLongVirtualTableRoute : AbstractSimpleShardingWeekKeyLongVirtualTableRoute<LogWeekTimeLong>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogWeekTimeLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Years;
namespace ShardingCore.Test2x.Shardings
{
public class LogYearDateTimeVirtualRoute:AbstractSimpleShardingYearKeyDateTimeVirtualTableRoute<LogYearDateTime>
{
protected override bool EnableHintRoute => true;
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2020, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogYearDateTime> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Shardings
{
public class OrderAreaShardingVirtualDataSourceRoute:AbstractShardingOperatorVirtualDataSourceRoute<Order,string>
{
protected override bool EnableHintRoute =>true;
private readonly List<string> _dataSources = new List<string>()
{
"A", "B", "C"
};
protected override string ConvertToShardingKey(object shardingKey)
{
return shardingKey?.ToString() ?? string.Empty;
}
//我们设置区域就是数据库
public override string ShardingKeyToDataSourceName(object shardingKey)
{
return ConvertToShardingKey(shardingKey);
}
public override List<string> GetAllDataSourceNames()
{
return _dataSources;
}
public override bool AddDataSourceName(string dataSourceName)
{
if (_dataSources.Any(o => o == dataSourceName))
return false;
_dataSources.Add(dataSourceName);
return true;
}
protected override Expression<Func<string, bool>> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
{
var t = ShardingKeyToDataSourceName(shardingKey);
switch (shardingOperator)
{
case ShardingOperatorEnum.Equal: return tail => tail == t;
default:
{
return tail => true;
}
}
}
}
}

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Months;
namespace ShardingCore.Test2x.Shardings
{
public class OrderCreateTimeVirtualTableRoute:AbstractSimpleShardingMonthKeyDateTimeVirtualTableRoute<Order>
{
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override List<string> GetAllTails()
{
var allTails = base.GetAllTails();
allTails.Add("202112");
return allTails;
}
public override void Configure(EntityMetadataTableBuilder<Order> builder)
{
}
public override IPaginationConfiguration<Order> CreatePaginationConfiguration()
{
return new OrderCreateTimePaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
}
public class OrderCreateTimePaginationConfiguration : IPaginationConfiguration<Order>
{
public void Configure(PaginationBuilder<Order> builder)
{
builder.PaginationSequence(o => o.CreateTime)
.UseQueryMatch(PaginationMatchEnum.Owner | PaginationMatchEnum.Named | PaginationMatchEnum.PrimaryMatch)
.UseAppendIfOrderNone().UseRouteComparer(Comparer<string>.Default);
}
}
}

View File

@ -0,0 +1,15 @@
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Shardings.PaginationConfigs
{
public class LogDayPaginationConfiguration: IPaginationConfiguration<LogDay>
{
public void Configure(PaginationBuilder<LogDay> builder)
{
builder.PaginationSequence(o => o.LogTime)
.UseQueryMatch(PaginationMatchEnum.Named | PaginationMatchEnum.Owner |
PaginationMatchEnum.PrimaryMatch);
}
}
}

View File

@ -0,0 +1,27 @@
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Mods;
namespace ShardingCore.Test2x.Shardings
{
/*
* @Author: xjm
* @Description:
* @Date: Thursday, 14 January 2021 15:39:27
* @Email: 326308290@qq.com
*/
public class SysUserModVirtualTableRoute : AbstractSimpleShardingModKeyStringVirtualTableRoute<SysUserMod>
{
protected override bool EnableHintRoute => true;
public SysUserModVirtualTableRoute() : base(2,3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserMod> builder)
{
builder.ShardingProperty(o => o.Id);
builder.TableSeparator("_");
}
}
}

View File

@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions;
using ShardingCore.Test2x.Domain.Entities;
namespace ShardingCore.Test2x.Shardings
{
/*
* @Author: xjm
* @Description:
* @Date: Monday, 01 February 2021 15:54:55
* @Email: 326308290@qq.com
*/
public class SysUserSalaryVirtualTableRoute:AbstractShardingOperatorVirtualTableRoute<SysUserSalary,int>
{
protected override int ConvertToShardingKey(object shardingKey)
{
return Convert.ToInt32(shardingKey);
}
public override string ShardingKeyToTail(object shardingKey)
{
var time = ConvertToShardingKey(shardingKey);
return TimeFormatToTail(time);
}
public override List<string> GetAllTails()
{
var beginTime = new DateTime(2020, 1, 1);
var endTime = new DateTime(2021, 12, 1);
var list = new List<string>(24);
var tempTime = beginTime;
while (tempTime <= endTime)
{
list.Add($"{tempTime:yyyyMM}");
tempTime = tempTime.AddMonths(1);
}
return list;
}
protected string TimeFormatToTail(int time)
{
var dateOfMonth=DateTime.ParseExact($"{time}","yyyyMM",System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.AdjustToUniversal);
return $"{dateOfMonth:yyyyMM}";
}
protected override Expression<Func<string, bool>> GetRouteToFilter(int shardingKey, ShardingOperatorEnum shardingOperator)
{
var t = TimeFormatToTail(shardingKey);
switch (shardingOperator)
{
case ShardingOperatorEnum.GreaterThan:
case ShardingOperatorEnum.GreaterThanOrEqual:
return tail => String.Compare(tail, t, StringComparison.Ordinal) >= 0;
case ShardingOperatorEnum.LessThan:
return tail => String.Compare(tail, t, StringComparison.Ordinal) < 0;
case ShardingOperatorEnum.LessThanOrEqual:
return tail => String.Compare(tail, t, StringComparison.Ordinal) <= 0;
case ShardingOperatorEnum.Equal: return tail => tail == t;
default:
{
#if DEBUG
Console.WriteLine($"shardingOperator is not equal scan all table tail");
#endif
return tail => true;
}
}
}
public override void Configure(EntityMetadataTableBuilder<SysUserSalary> builder)
{
builder.ShardingProperty(o => o.DateOfMonth);
}
}
}

View File

@ -0,0 +1,238 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ShardingCore.Bootstrapers;
using ShardingCore.Helpers;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.Test2x.Shardings;
namespace ShardingCore.Test2x
{
/*
* @Author: xjm
* @Description:
* @Date: Friday, 15 January 2021 15:37:46
* @Email: 326308290@qq.com
*/
public class Startup
{
public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
{
builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
});
// 支持的形式:
// ConfigureServices(IServiceCollection services)
// ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
// ConfigureServices(HostBuilderContext hostBuilderContext, IServiceCollection services)
public void ConfigureServices(IServiceCollection services, HostBuilderContext hostBuilderContext)
{
services.AddShardingDbContext<ShardingDefaultDbContext>((conn, o) =>
o.UseSqlServer(conn).UseLoggerFactory(efLogger))
.Begin(o =>
{
o.CreateShardingTableOnStart = true;
o.EnsureCreatedWithOutShardingTable = true;
o.AutoTrackEntity = true;
})
.AddShardingTransaction((connection, builder) =>
builder.UseSqlServer(connection).UseLoggerFactory(efLogger))
.AddDefaultDataSource("A", "Data Source=localhost;Initial Catalog=ShardingCoreDBA;Integrated Security=True;")
.AddShardingDataSource(sp =>
{
return new Dictionary<string, string>()
{
{ "B", "Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;" },
{ "C", "Data Source=localhost;Initial Catalog=ShardingCoreDBC;Integrated Security=True;" },
};
})
.AddShardingDataSourceRoute(o =>
{
o.AddShardingDatabaseRoute<OrderAreaShardingVirtualDataSourceRoute>();
})
.AddShardingTableRoute(op =>
{
op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
op.AddShardingTableRoute<OrderCreateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogDayVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekDateTimeVirtualTableRoute>();
op.AddShardingTableRoute<LogWeekTimeLongVirtualTableRoute>();
op.AddShardingTableRoute<LogYearDateTimeVirtualRoute>();
}).AddReadWriteSeparation(sp =>
{
return new Dictionary<string, ISet<string>>()
{
{
"A", new HashSet<string>()
{
"Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;"
}
}
};
},ReadStrategyEnum.Loop,readConnStringGetStrategy:ReadConnStringGetStrategyEnum.LatestEveryTime).End();
// services.AddShardingDbContext<ShardingDefaultDbContext, DefaultDbContext>(o => o.UseMySql(hostBuilderContext.Configuration.GetSection("MySql")["ConnectionString"],new MySqlServerVersion("5.7.15"))
// ,op =>
// {
// op.EnsureCreatedWithOutShardingTable = true;
// op.CreateShardingTableOnStart = true;
// op.UseShardingOptionsBuilder((connection, builder) => builder.UseMySql(connection,new MySqlServerVersion("5.7.15")).UseLoggerFactory(efLogger),
// (conStr,builder)=> builder.UseMySql(conStr,new MySqlServerVersion("5.7.15")).UseLoggerFactory(efLogger));
// op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
// op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
// });
}
// 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法
public void Configure(IServiceProvider serviceProvider)
{
var shardingBootstrapper = serviceProvider.GetService<IShardingBootstrapper>();
shardingBootstrapper.Start();
// 有一些测试数据要初始化可以放在这里
InitData(serviceProvider).GetAwaiter().GetResult();
}
/// <summary>
/// 添加种子数据
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
private async Task InitData(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var virtualDbContext = scope.ServiceProvider.GetService<ShardingDefaultDbContext>();
if (!await virtualDbContext.Set<SysUserMod>().AnyAsync())
{
var ids = Enumerable.Range(1, 1000);
var userMods = new List<SysUserMod>();
var userSalaries = new List<SysUserSalary>();
var beginTime = new DateTime(2020, 1, 1);
var endTime = new DateTime(2021, 12, 1);
foreach (var id in ids)
{
userMods.Add(new SysUserMod()
{
Id = id.ToString(),
Age = id,
Name = $"name_{id}",
AgeGroup = Math.Abs(id % 10)
});
var tempTime = beginTime;
var i = 0;
while (tempTime <= endTime)
{
var dateOfMonth = $@"{tempTime:yyyyMM}";
userSalaries.Add(new SysUserSalary()
{
Id = $@"{id}{dateOfMonth}",
UserId = id.ToString(),
DateOfMonth = int.Parse(dateOfMonth),
Salary = 700000 + id * 100 * i,
SalaryLong = 700000 + id * 100 * i,
SalaryDecimal = (700000 + id * 100 * i) / 100m,
SalaryDouble = (700000 + id * 100 * i) / 100d,
SalaryFloat = (700000 + id * 100 * i) / 100f
});
tempTime = tempTime.AddMonths(1);
i++;
}
}
var areas = new List<string>(){"A","B","C"};
List<Order> orders = new List<Order>(360);
var begin = new DateTime(2021, 1, 1);
for (int i = 0; i < 320; i++)
{
orders.Add(new Order()
{
Id = Guid.NewGuid(),
Area = areas[i%3],
CreateTime = begin,
Money = i
});
begin = begin.AddDays(1);
}
List<LogDay> logDays = new List<LogDay>(3600);
var levels = new List<string>(){"info","warning","error"};
var begin1 = new DateTime(2021, 1, 1);
for (int i = 0; i < 300; i++)
{
var ltime = begin1;
for (int j = 0; j < 10; j++)
{
logDays.Add(new LogDay()
{
Id = Guid.NewGuid(),
LogLevel = levels[j%3],
LogBody = $"{i}_{j}",
LogTime = ltime.AddHours(1)
});
ltime = ltime.AddHours(1);
}
begin1 = begin1.AddDays(1);
}
List<LogWeekDateTime> logWeeks = new List<LogWeekDateTime>(300);
var begin2 = new DateTime(2021,1,1);
for (int i = 0; i < 300; i++)
{
logWeeks.Add(new LogWeekDateTime()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = begin2
});
begin2 = begin2.AddDays(1);
}
List<LogWeekTimeLong> logWeekLongs = new List<LogWeekTimeLong>(300);
var begin3 = new DateTime(2021,1,1);
for (int i = 0; i < 300; i++)
{
logWeekLongs.Add(new LogWeekTimeLong()
{
Id = Guid.NewGuid().ToString("n"),
Body = $"body_{i}",
LogTime = ShardingCoreHelper.ConvertDateTimeToLong(begin3)
});
begin3 = begin3.AddDays(1);
}
List<LogYearDateTime> logYears = new List<LogYearDateTime>(600);
var begin4 = new DateTime(2020,1,1);
for (int i = 0; i < 600; i++)
{
logYears.Add(new LogYearDateTime()
{
Id = Guid.NewGuid(),
LogBody = $"body_{i}",
LogTime = begin4
});
begin4 = begin4.AddDays(1);
}
using (var tran = virtualDbContext.Database.BeginTransaction())
{
await virtualDbContext.AddRangeAsync(userMods);
await virtualDbContext.AddRangeAsync(userSalaries);
await virtualDbContext.AddRangeAsync(orders);
await virtualDbContext.AddRangeAsync(logDays);
await virtualDbContext.AddRangeAsync(logWeeks);
await virtualDbContext.AddRangeAsync(logWeekLongs);
await virtualDbContext.AddRangeAsync(logYears);
await virtualDbContext.SaveChangesAsync();
tran.Commit();
}
}
}
}
}
}