From 9e287be7e36120912956177a95bdcc430109fcab Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Fri, 26 Nov 2021 23:11:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E5=BE=88=E5=A4=9A?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Sample.BulkConsole/OrderVirtualRoute.cs | 5 + .../Shardings/SysUserLogByMonthRoute.cs | 6 + .../Shardings/SysUserModVirtualTableRoute.cs | 6 + .../Shardings/SysUserModVirtualTableRoute.cs | 5 + .../SysUserSalaryVirtualTableRoute.cs | 5 + .../Sample.SqlServer/Shardings/TestVRoute.cs | 6 + .../Shardings/SysUserModVirtualTableRoute.cs | 5 + .../OrderHashRangeVirtualTableRoute.cs | 6 + .../SysUserLogByDayVirtualTableRoute.cs | 6 + .../Shardings/TestLogWeekVirtualRoute.cs | 6 + .../Abstractions/AbstractVirtualTableRoute.cs | 5 +- .../Domain/Entities/LogMonthLong.cs | 15 + .../Domain/Entities/LogNoSharding.cs | 15 + .../Domain/Entities/LogWeekTimeLong.cs | 16 + .../Domain/Entities/LogYearDateTime.cs | 15 + .../Domain/Maps/LogMonthLongMap.cs | 23 + .../Domain/Maps/LogNoShardingMap.cs | 22 + .../Domain/Maps/LogWeekTimeLongMap.cs | 22 + .../Domain/Maps/LogYearDateTimeMap.cs | 22 + .../ShardingDefaultDbContext.cs | 4 + test/ShardingCore.Test/ShardingTest.cs | 494 ++++++-- test/ShardingCore.Test/ShardingTestSync.cs | 294 +++++ .../Shardings/LogMonthLongvirtualRoute.cs | 32 + .../LogWeekTimeLongVirtualTableRoute.cs | 31 + .../Shardings/LogYearDateTimeVirtualRoute.cs | 30 + .../OrderCreateTimeVirtualTableRoute.cs | 6 + test/ShardingCore.Test/Startup.cs | 52 +- .../Domain/Entities/LogDay.cs | 12 + .../Domain/Entities/LogWeekDateTime.cs | 12 + .../Domain/Entities/LogWeekTimeLong.cs | 10 + .../Domain/Entities/LogYearDateTime.cs | 11 + .../Domain/Entities/Order.cs | 15 + .../Domain/Entities/SysUserMod.cs | 26 + .../Domain/Entities/SysUserSalary.cs | 39 + .../Domain/Maps/LogDayMap.cs | 17 + .../Domain/Maps/LogWeekDateTimeMap.cs | 17 + .../Domain/Maps/LogWeekTimeLongMap.cs | 17 + .../Domain/Maps/LogYearDateTimeMap.cs | 16 + .../Domain/Maps/OrderMap.cs | 16 + .../Domain/Maps/SysUserModMap.cs | 23 + .../Domain/Maps/SysUserSalaryMap.cs | 23 + .../ShardingCore.Test2x.csproj | 8 - .../ShardingDefaultDbContext.cs | 36 + test/ShardingCore.Test2x/ShardingTest.cs | 1077 +++++++++++++++++ test/ShardingCore.Test2x/ShardingTestSync.cs | 1039 ++++++++++++++++ .../Shardings/LogDayVirtualTableRoute.cs | 36 + .../LogWeekDateTimeVirtualTableRoute.cs | 27 + .../LogWeekTimeLongVirtualTableRoute.cs | 27 + .../Shardings/LogYearDateTimeVirtualRoute.cs | 26 + ...OrderAreaShardingVirtualDataSourceRoute.cs | 56 + .../OrderCreateTimeVirtualTableRoute.cs | 48 + .../LogDayPaginationConfiguration.cs | 15 + .../Shardings/SysUserModVirtualTableRoute.cs | 27 + .../SysUserSalaryVirtualTableRoute.cs | 80 ++ test/ShardingCore.Test2x/Startup.cs | 238 ++++ 55 files changed, 4020 insertions(+), 128 deletions(-) create mode 100644 test/ShardingCore.Test/Domain/Entities/LogMonthLong.cs create mode 100644 test/ShardingCore.Test/Domain/Entities/LogNoSharding.cs create mode 100644 test/ShardingCore.Test/Domain/Entities/LogWeekTimeLong.cs create mode 100644 test/ShardingCore.Test/Domain/Entities/LogYearDateTime.cs create mode 100644 test/ShardingCore.Test/Domain/Maps/LogMonthLongMap.cs create mode 100644 test/ShardingCore.Test/Domain/Maps/LogNoShardingMap.cs create mode 100644 test/ShardingCore.Test/Domain/Maps/LogWeekTimeLongMap.cs create mode 100644 test/ShardingCore.Test/Domain/Maps/LogYearDateTimeMap.cs create mode 100644 test/ShardingCore.Test/Shardings/LogMonthLongvirtualRoute.cs create mode 100644 test/ShardingCore.Test/Shardings/LogWeekTimeLongVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test/Shardings/LogYearDateTimeVirtualRoute.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/LogDay.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/LogWeekDateTime.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/LogWeekTimeLong.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/LogYearDateTime.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/Order.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/SysUserMod.cs create mode 100644 test/ShardingCore.Test2x/Domain/Entities/SysUserSalary.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/LogDayMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/LogWeekDateTimeMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/LogWeekTimeLongMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/LogYearDateTimeMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/OrderMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/SysUserModMap.cs create mode 100644 test/ShardingCore.Test2x/Domain/Maps/SysUserSalaryMap.cs create mode 100644 test/ShardingCore.Test2x/ShardingDefaultDbContext.cs create mode 100644 test/ShardingCore.Test2x/ShardingTest.cs create mode 100644 test/ShardingCore.Test2x/ShardingTestSync.cs create mode 100644 test/ShardingCore.Test2x/Shardings/LogDayVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/LogWeekDateTimeVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/LogWeekTimeLongVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/LogYearDateTimeVirtualRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/OrderAreaShardingVirtualDataSourceRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/OrderCreateTimeVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/PaginationConfigs/LogDayPaginationConfiguration.cs create mode 100644 test/ShardingCore.Test2x/Shardings/SysUserModVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Shardings/SysUserSalaryVirtualTableRoute.cs create mode 100644 test/ShardingCore.Test2x/Startup.cs diff --git a/samples/Sample.BulkConsole/OrderVirtualRoute.cs b/samples/Sample.BulkConsole/OrderVirtualRoute.cs index ffc677ea..81a1562a 100644 --- a/samples/Sample.BulkConsole/OrderVirtualRoute.cs +++ b/samples/Sample.BulkConsole/OrderVirtualRoute.cs @@ -29,6 +29,11 @@ namespace Sample.BulkConsole return new OrderPaginationConfiguration(); } + public override void Configure(EntityMetadataTableBuilder builder) + { + + } + public override bool AutoCreateTableByTime() { return true; diff --git a/samples/Sample.MySql/Shardings/SysUserLogByMonthRoute.cs b/samples/Sample.MySql/Shardings/SysUserLogByMonthRoute.cs index 6c6eaafb..3696f7d5 100644 --- a/samples/Sample.MySql/Shardings/SysUserLogByMonthRoute.cs +++ b/samples/Sample.MySql/Shardings/SysUserLogByMonthRoute.cs @@ -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 builder) + { + + } } } diff --git a/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs b/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs index e9802f31..ceac49f2 100644 --- a/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs +++ b/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs @@ -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 builder) + { + + } } } \ No newline at end of file diff --git a/samples/Sample.SqlServer/Shardings/SysUserModVirtualTableRoute.cs b/samples/Sample.SqlServer/Shardings/SysUserModVirtualTableRoute.cs index b9a18d09..3bf6f491 100644 --- a/samples/Sample.SqlServer/Shardings/SysUserModVirtualTableRoute.cs +++ b/samples/Sample.SqlServer/Shardings/SysUserModVirtualTableRoute.cs @@ -40,5 +40,10 @@ namespace Sample.SqlServer.Shardings { return new SysUserModPaginationConfiguration(); } + + public override void Configure(EntityMetadataTableBuilder builder) + { + + } } } \ No newline at end of file diff --git a/samples/Sample.SqlServer/Shardings/SysUserSalaryVirtualTableRoute.cs b/samples/Sample.SqlServer/Shardings/SysUserSalaryVirtualTableRoute.cs index bf6341b5..e228da9a 100644 --- a/samples/Sample.SqlServer/Shardings/SysUserSalaryVirtualTableRoute.cs +++ b/samples/Sample.SqlServer/Shardings/SysUserSalaryVirtualTableRoute.cs @@ -44,6 +44,11 @@ namespace Sample.SqlServer.Shardings return list; } + public override void Configure(EntityMetadataTableBuilder builder) + { + + } + protected string TimeFormatToTail(int time) { var dateOfMonth=DateTime.ParseExact($"{time}","yyyyMM",System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.AdjustToUniversal); diff --git a/samples/Sample.SqlServer/Shardings/TestVRoute.cs b/samples/Sample.SqlServer/Shardings/TestVRoute.cs index 84d013d8..ab85f3ec 100644 --- a/samples/Sample.SqlServer/Shardings/TestVRoute.cs +++ b/samples/Sample.SqlServer/Shardings/TestVRoute.cs @@ -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() {"", "1"}; } + public override void Configure(EntityMetadataTableBuilder builder) + { + + } + protected override Expression> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator) { var t = ShardingKeyToTail(shardingKey); diff --git a/samples/Sample.SqlServer3x/Shardings/SysUserModVirtualTableRoute.cs b/samples/Sample.SqlServer3x/Shardings/SysUserModVirtualTableRoute.cs index 39588207..b8cb5f48 100644 --- a/samples/Sample.SqlServer3x/Shardings/SysUserModVirtualTableRoute.cs +++ b/samples/Sample.SqlServer3x/Shardings/SysUserModVirtualTableRoute.cs @@ -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 builder) + { + + } } } \ No newline at end of file diff --git a/samples/Sample.SqlServerShardingTable/VirtualRoutes/OrderHashRangeVirtualTableRoute.cs b/samples/Sample.SqlServerShardingTable/VirtualRoutes/OrderHashRangeVirtualTableRoute.cs index e940d7a2..5b30d087 100644 --- a/samples/Sample.SqlServerShardingTable/VirtualRoutes/OrderHashRangeVirtualTableRoute.cs +++ b/samples/Sample.SqlServerShardingTable/VirtualRoutes/OrderHashRangeVirtualTableRoute.cs @@ -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 builder) + { + + } + protected override Expression> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator) { //因为hash路由仅支持等于所以仅仅只需要写等于的情况 diff --git a/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualTableRoute.cs b/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualTableRoute.cs index 215fac7d..0fdf3b24 100644 --- a/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualTableRoute.cs +++ b/samples/Samples.AutoByDate.SqlServer/Shardings/SysUserLogByDayVirtualTableRoute.cs @@ -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 builder) + { + + } } } \ No newline at end of file diff --git a/samples/Samples.AutoByDate.SqlServer/Shardings/TestLogWeekVirtualRoute.cs b/samples/Samples.AutoByDate.SqlServer/Shardings/TestLogWeekVirtualRoute.cs index a4793f0e..c83422ac 100644 --- a/samples/Samples.AutoByDate.SqlServer/Shardings/TestLogWeekVirtualRoute.cs +++ b/samples/Samples.AutoByDate.SqlServer/Shardings/TestLogWeekVirtualRoute.cs @@ -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 builder) + { + + } } } diff --git a/src/ShardingCore/Core/VirtualRoutes/TableRoutes/Abstractions/AbstractVirtualTableRoute.cs b/src/ShardingCore/Core/VirtualRoutes/TableRoutes/Abstractions/AbstractVirtualTableRoute.cs index 51979a96..b18fbc13 100644 --- a/src/ShardingCore/Core/VirtualRoutes/TableRoutes/Abstractions/AbstractVirtualTableRoute.cs +++ b/src/ShardingCore/Core/VirtualRoutes/TableRoutes/Abstractions/AbstractVirtualTableRoute.cs @@ -76,9 +76,6 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions /// 配置分表信息 /// /// - public virtual void Configure(EntityMetadataTableBuilder builder) - { - - } + public abstract void Configure(EntityMetadataTableBuilder builder); } } \ No newline at end of file diff --git a/test/ShardingCore.Test/Domain/Entities/LogMonthLong.cs b/test/ShardingCore.Test/Domain/Entities/LogMonthLong.cs new file mode 100644 index 00000000..043ad7e2 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Entities/LogMonthLong.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test/Domain/Entities/LogNoSharding.cs b/test/ShardingCore.Test/Domain/Entities/LogNoSharding.cs new file mode 100644 index 00000000..56cf6fd9 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Entities/LogNoSharding.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test/Domain/Entities/LogWeekTimeLong.cs b/test/ShardingCore.Test/Domain/Entities/LogWeekTimeLong.cs new file mode 100644 index 00000000..014f0886 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Entities/LogWeekTimeLong.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test/Domain/Entities/LogYearDateTime.cs b/test/ShardingCore.Test/Domain/Entities/LogYearDateTime.cs new file mode 100644 index 00000000..4d420d9f --- /dev/null +++ b/test/ShardingCore.Test/Domain/Entities/LogYearDateTime.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test/Domain/Maps/LogMonthLongMap.cs b/test/ShardingCore.Test/Domain/Maps/LogMonthLongMap.cs new file mode 100644 index 00000000..40c20d46 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Maps/LogMonthLongMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test/Domain/Maps/LogNoShardingMap.cs b/test/ShardingCore.Test/Domain/Maps/LogNoShardingMap.cs new file mode 100644 index 00000000..691d9db4 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Maps/LogNoShardingMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test/Domain/Maps/LogWeekTimeLongMap.cs b/test/ShardingCore.Test/Domain/Maps/LogWeekTimeLongMap.cs new file mode 100644 index 00000000..b04b108a --- /dev/null +++ b/test/ShardingCore.Test/Domain/Maps/LogWeekTimeLongMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test/Domain/Maps/LogYearDateTimeMap.cs b/test/ShardingCore.Test/Domain/Maps/LogYearDateTimeMap.cs new file mode 100644 index 00000000..5a1283b7 --- /dev/null +++ b/test/ShardingCore.Test/Domain/Maps/LogYearDateTimeMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(o => o.Id); + builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256); + builder.ToTable(nameof(LogYearDateTime)); + } + } +} diff --git a/test/ShardingCore.Test/ShardingDefaultDbContext.cs b/test/ShardingCore.Test/ShardingDefaultDbContext.cs index fb3c4cb2..36d487ba 100644 --- a/test/ShardingCore.Test/ShardingDefaultDbContext.cs +++ b/test/ShardingCore.Test/ShardingDefaultDbContext.cs @@ -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; } diff --git a/test/ShardingCore.Test/ShardingTest.cs b/test/ShardingCore.Test/ShardingTest.cs index 38a164a2..475d4711 100644 --- a/test/ShardingCore.Test/ShardingTest.cs +++ b/test/ShardingCore.Test/ShardingTest.cs @@ -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 _shardingTableCreator; private readonly IShardingReadWriteManager _shardingReadWriteManager; - public ShardingTest(ShardingDefaultDbContext virtualDbContext,IShardingRouteManager shardingRouteManager, IConfiguration configuration, + public ShardingTest(ShardingDefaultDbContext virtualDbContext, IShardingRouteManager shardingRouteManager, IConfiguration configuration, IEntityMetadataManager entityMetadataManager, - IShardingComparer shardingComparer,IVirtualDataSource virtualDataSource, + IShardingComparer shardingComparer, IVirtualDataSource virtualDataSource, IVirtualTableManager virtualTableManager, IShardingTableCreator 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()); - var y = new EntityMetadata(typeof(LogDay),"aa1",typeof(ShardingDefaultDbContext),new List()); + 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()); + var y = new EntityMetadata(typeof(LogDay), "aa1", typeof(ShardingDefaultDbContext), new List()); 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().Where(o => o.Id == "300").ShardingPrint(); - var contains=await _virtualDbContext.Set().Where(o => o.Id == "300").Select(o => o.Id).ContainsAsync("300"); + var contains = await _virtualDbContext.Set().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().Select(o => new SequenceClass { Id = "123", T = o }).AsQueryable(); + var queryable = new List().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("A", "202105"); } catch (Exception e) { - Assert.Equal(typeof(ShardingCoreException),e.GetType()); + Assert.Equal(typeof(ShardingCoreException), e.GetType()); } - var orderMetadata=_entityMetadataManager.TryGet(); + var orderMetadata = _entityMetadataManager.TryGet(); 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(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(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(o => o.Id == Guid.NewGuid().ToString()); + Assert.Equal(1, bulkShardingTableExpression.Count()); + + var noShardingExpression = _virtualDbContext.BulkShardingExpression(o => o.Id == "123"); + Assert.Equal(1, noShardingExpression.Count()); - var bulkShardingTableExpression = _virtualDbContext.BulkShardingTableExpression(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(); - 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(); + Assert.NotNull(virtualTable); + } public class SequenceClass @@ -179,7 +185,7 @@ namespace ShardingCore.Test var y = new Guid("3425D899-291D-921B-DDE4-49FFE37AE493"); //asc y0); + Assert.True(compare0 > 0); //asc xo.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().Where(o => new List { "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().Where(o => o.Id == id.ToString()).ToListAsync(); Assert.Single(mods); var mods1 = await _virtualDbContext.Set().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().Where(o => o.Id == "300") - join salary in _virtualDbContext.Set() - on u.Id equals salary.UserId - select new - { - Salary = salary.Salary, - DateOfMonth = salary.DateOfMonth, - Name = u.Name - }); + join salary in _virtualDbContext.Set() + 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() .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().CountAsync(); Assert.Equal(320, asyncCount); - var syncCount = _virtualDbContext.Set().Count(); + var syncCount = _virtualDbContext.Set().Count(); Assert.Equal(320, syncCount); - var countA =await _virtualDbContext.Set().CountAsync(o=>o.Area=="A"); - var countB =await _virtualDbContext.Set().CountAsync(o=>o.Area=="B"); - var countC =await _virtualDbContext.Set().CountAsync(o=>o.Area=="C"); - Assert.Equal(320, countA+ countB+ countC); + var countA = await _virtualDbContext.Set().CountAsync(o => o.Area == "A"); + var countB = await _virtualDbContext.Set().CountAsync(o => o.Area == "B"); + var countC = await _virtualDbContext.Set().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().Where(o=>o.CreateTime>=fourBegin&&o.CreateTime().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().FirstOrDefaultAsync(o=>o.CreateTime== threeMonth);//59 131228 + var threeMonth = new DateTime(2021, 3, 1); + var order = await _virtualDbContext.Set().FirstOrDefaultAsync(o => o.CreateTime == threeMonth);//59 131228 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().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().Where(o=>o.CreateTime > threeMonth).OrderByDescending(o => o.CreateTime).ToShardingPageAsync(1,20); + var orderPage = await _virtualDbContext.Set().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().Where(o => o.CreateTime > threeMonth).OrderBy(o=>o.CreateTime).ToShardingPageAsync(1, 20); + var orderPage1 = await _virtualDbContext.Set().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().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().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(); 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().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().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().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().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("C"); var sum = await _virtualDbContext.Set() - .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() - .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() - .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() - .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() - .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() - .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() - .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() - .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() - .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() - .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("C"); var sum = await _virtualDbContext.Set() - .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().MaxAsync(o => o.Money); - var all= await _virtualDbContext.Set().AllAsync(o=>o.Money<=321); + Assert.Equal(319, max); + var all = await _virtualDbContext.Set().AllAsync(o => o.Money <= 321); Assert.True(all); - var longCount=await _virtualDbContext.Set().LongCountAsync(); - Assert.Equal(320,longCount); + var longCount = await _virtualDbContext.Set().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() + + var moneyMax = await _virtualDbContext.Set() .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).MaxAsync(); Assert.Equal(120, moneyMax); - var moneyMax1 = await _virtualDbContext.Set() + var moneyMax1 = await _virtualDbContext.Set() .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).MaxAsync(); Assert.Equal(120, moneyMax1); var moneyMax2 = await _virtualDbContext.Set() @@ -858,17 +865,17 @@ namespace ShardingCore.Test [Fact] public async Task Order_Entity() { - var x=await _virtualDbContext.Set().OrderBy(o => o.Money).LastOrDefaultAsync(); + var x = await _virtualDbContext.Set().OrderBy(o => o.Money).LastOrDefaultAsync(); Assert.NotNull(x); - Assert.Equal(319,x.Money); + Assert.Equal(319, x.Money); var x1 = await _virtualDbContext.Set().OrderBy(o => o.Money).LastAsync(); - Assert.Equal(x,x1); + Assert.Equal(x, x1); var y = await _virtualDbContext.Set().OrderBy(o => o.Money).FirstOrDefaultAsync(); Assert.NotNull(y); Assert.Equal(0, y.Money); var y1 = await _virtualDbContext.Set().OrderBy(o => o.Money).FirstAsync(); Assert.Equal(y, y1); - var z=await _virtualDbContext.Set().SingleOrDefaultAsync(o => o.Money == 13); + var z = await _virtualDbContext.Set().SingleOrDefaultAsync(o => o.Money == 13); var z1 = await _virtualDbContext.Set().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().Where(o=>o.Money==1).ToListAsync(); + var list = await _virtualDbContext.Set().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = await _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("2020"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(366, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("2021"); + var countAsync2 = await _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("202104"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(30, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("202104", "202105"); + var countAsync2 = await _virtualDbContext.Set().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().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().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() + { + 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() + { + 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().AddAsync(logNoSharding1); + + await _virtualDbContext.Set().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().Update(logNoSharding1); + + logNoSharding1s.ForEach(o=>o.Body = DateTime.Now.ToString("yyyyMMdd")); + _virtualDbContext.Set().UpdateRange(logNoSharding1s); + await _virtualDbContext.SaveChangesAsync(); + + + _virtualDbContext.Remove(logNoSharding); + + _virtualDbContext.RemoveRange(logNoShardings); + + _virtualDbContext.Set().Remove(logNoSharding1); + + logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd")); + _virtualDbContext.Set().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() + { + 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() // { diff --git a/test/ShardingCore.Test/ShardingTestSync.cs b/test/ShardingCore.Test/ShardingTestSync.cs index bb187959..03587ad3 100644 --- a/test/ShardingCore.Test/ShardingTestSync.cs +++ b/test/ShardingCore.Test/ShardingTestSync.cs @@ -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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("2020"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(366, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("2021"); + var countAsync2 = _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("202104"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(30, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("202104", "202105"); + var countAsync2 = _virtualDbContext.Set().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().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().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() + { + 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() + { + 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().Add(logNoSharding1); + + _virtualDbContext.Set().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().Update(logNoSharding1); + + logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd")); + _virtualDbContext.Set().UpdateRange(logNoSharding1s); + _virtualDbContext.SaveChanges(); + + + _virtualDbContext.Remove(logNoSharding); + + _virtualDbContext.RemoveRange(logNoShardings); + + _virtualDbContext.Set().Remove(logNoSharding1); + + logNoSharding1s.ForEach(o => o.Body = DateTime.Now.ToString("yyyyMMdd")); + _virtualDbContext.Set().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() + { + 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() // { diff --git a/test/ShardingCore.Test/Shardings/LogMonthLongvirtualRoute.cs b/test/ShardingCore.Test/Shardings/LogMonthLongvirtualRoute.cs new file mode 100644 index 00000000..3e254a16 --- /dev/null +++ b/test/ShardingCore.Test/Shardings/LogMonthLongvirtualRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test/Shardings/LogWeekTimeLongVirtualTableRoute.cs b/test/ShardingCore.Test/Shardings/LogWeekTimeLongVirtualTableRoute.cs new file mode 100644 index 00000000..71551f00 --- /dev/null +++ b/test/ShardingCore.Test/Shardings/LogWeekTimeLongVirtualTableRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test/Shardings/LogYearDateTimeVirtualRoute.cs b/test/ShardingCore.Test/Shardings/LogYearDateTimeVirtualRoute.cs new file mode 100644 index 00000000..d9ffe6b4 --- /dev/null +++ b/test/ShardingCore.Test/Shardings/LogYearDateTimeVirtualRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test/Shardings/OrderCreateTimeVirtualTableRoute.cs b/test/ShardingCore.Test/Shardings/OrderCreateTimeVirtualTableRoute.cs index e3327c18..e72645e2 100644 --- a/test/ShardingCore.Test/Shardings/OrderCreateTimeVirtualTableRoute.cs +++ b/test/ShardingCore.Test/Shardings/OrderCreateTimeVirtualTableRoute.cs @@ -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 builder) + { + + } + public override IPaginationConfiguration CreatePaginationConfiguration() { return new OrderCreateTimePaginationConfiguration(); diff --git a/test/ShardingCore.Test/Startup.cs b/test/ShardingCore.Test/Startup.cs index 5a40ac38..faaae4c1 100644 --- a/test/ShardingCore.Test/Startup.cs +++ b/test/ShardingCore.Test/Startup.cs @@ -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(); op.AddShardingTableRoute(); op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); }).AddReadWriteSeparation(sp => { return new Dictionary>() @@ -196,6 +197,44 @@ namespace ShardingCore.Test }); begin2 = begin2.AddDays(1); } + List logWeekLongs = new List(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 logYears = new List(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 logMonthLongs = new List(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(); diff --git a/test/ShardingCore.Test2x/Domain/Entities/LogDay.cs b/test/ShardingCore.Test2x/Domain/Entities/LogDay.cs new file mode 100644 index 00000000..7fdeb499 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/LogDay.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Entities/LogWeekDateTime.cs b/test/ShardingCore.Test2x/Domain/Entities/LogWeekDateTime.cs new file mode 100644 index 00000000..abf1e73f --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/LogWeekDateTime.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Entities/LogWeekTimeLong.cs b/test/ShardingCore.Test2x/Domain/Entities/LogWeekTimeLong.cs new file mode 100644 index 00000000..3e0daf52 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/LogWeekTimeLong.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Entities/LogYearDateTime.cs b/test/ShardingCore.Test2x/Domain/Entities/LogYearDateTime.cs new file mode 100644 index 00000000..5f8e0b87 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/LogYearDateTime.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Entities/Order.cs b/test/ShardingCore.Test2x/Domain/Entities/Order.cs new file mode 100644 index 00000000..c9b3042a --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/Order.cs @@ -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; } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Entities/SysUserMod.cs b/test/ShardingCore.Test2x/Domain/Entities/SysUserMod.cs new file mode 100644 index 00000000..1981beb4 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/SysUserMod.cs @@ -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 + { + /// + /// 用户Id用于分表 + /// + public string Id { get; set; } + /// + /// 用户名称 + /// + public string Name { get; set; } + /// + /// 用户姓名 + /// + public int Age { get; set; } + public int AgeGroup { get; set; } + + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/Domain/Entities/SysUserSalary.cs b/test/ShardingCore.Test2x/Domain/Entities/SysUserSalary.cs new file mode 100644 index 00000000..f68d1c75 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Entities/SysUserSalary.cs @@ -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; } + /// + /// 每月的金额 + /// + public int DateOfMonth { get; set; } + /// + /// 工资 + /// + public int Salary { get; set; } + /// + /// 工资 + /// + public long SalaryLong { get; set; } + + /// + /// 工资 + /// + public decimal SalaryDecimal { get; set; } + /// + /// 工资 + /// + public double SalaryDouble { get; set; } + /// + /// 工资 + /// + public float SalaryFloat { get; set; } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/Domain/Maps/LogDayMap.cs b/test/ShardingCore.Test2x/Domain/Maps/LogDayMap.cs new file mode 100644 index 00000000..c17af52c --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/LogDayMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Maps/LogWeekDateTimeMap.cs b/test/ShardingCore.Test2x/Domain/Maps/LogWeekDateTimeMap.cs new file mode 100644 index 00000000..82c70e81 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/LogWeekDateTimeMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Maps/LogWeekTimeLongMap.cs b/test/ShardingCore.Test2x/Domain/Maps/LogWeekTimeLongMap.cs new file mode 100644 index 00000000..a9601564 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/LogWeekTimeLongMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Maps/LogYearDateTimeMap.cs b/test/ShardingCore.Test2x/Domain/Maps/LogYearDateTimeMap.cs new file mode 100644 index 00000000..827785fe --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/LogYearDateTimeMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(o => o.Id); + builder.Property(o => o.LogBody).IsRequired().HasMaxLength(256); + builder.ToTable(nameof(LogYearDateTime)); + } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Maps/OrderMap.cs b/test/ShardingCore.Test2x/Domain/Maps/OrderMap.cs new file mode 100644 index 00000000..63d5e80f --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/OrderMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(o => o.Id); + builder.Property(o => o.Area).IsRequired().IsUnicode(false).HasMaxLength(20); + builder.ToTable(nameof(Order)); + } + } +} diff --git a/test/ShardingCore.Test2x/Domain/Maps/SysUserModMap.cs b/test/ShardingCore.Test2x/Domain/Maps/SysUserModMap.cs new file mode 100644 index 00000000..2f416d42 --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/SysUserModMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/Domain/Maps/SysUserSalaryMap.cs b/test/ShardingCore.Test2x/Domain/Maps/SysUserSalaryMap.cs new file mode 100644 index 00000000..6ed0f5ea --- /dev/null +++ b/test/ShardingCore.Test2x/Domain/Maps/SysUserSalaryMap.cs @@ -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 + { + public void Configure(EntityTypeBuilder 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)); + } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/ShardingCore.Test2x.csproj b/test/ShardingCore.Test2x/ShardingCore.Test2x.csproj index 4af61bc1..2d08df18 100644 --- a/test/ShardingCore.Test2x/ShardingCore.Test2x.csproj +++ b/test/ShardingCore.Test2x/ShardingCore.Test2x.csproj @@ -3,9 +3,6 @@ net5.0 9.0 - TRACE;DEBUG;EFCORE2Test; - ShardingCore.Test - ShardingCore.Test @@ -19,11 +16,6 @@ runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - diff --git a/test/ShardingCore.Test2x/ShardingDefaultDbContext.cs b/test/ShardingCore.Test2x/ShardingDefaultDbContext.cs new file mode 100644 index 00000000..aed62b50 --- /dev/null +++ b/test/ShardingCore.Test2x/ShardingDefaultDbContext.cs @@ -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 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; } + } +} diff --git a/test/ShardingCore.Test2x/ShardingTest.cs b/test/ShardingCore.Test2x/ShardingTest.cs new file mode 100644 index 00000000..219b8254 --- /dev/null +++ b/test/ShardingCore.Test2x/ShardingTest.cs @@ -0,0 +1,1077 @@ +using System; +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; +using ShardingCore.Core.VirtualDatabase.VirtualDataSources; +using ShardingCore.Core.VirtualDatabase.VirtualDataSources.PhysicDataSources; +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; +using ShardingCore.TableCreator; +using ShardingCore.Test2x.Domain.Entities; +using Xunit; + +namespace ShardingCore.Test2x +{ + /* + * @Author: xjm + * @Description: + * @Date: Friday, 15 January 2021 17:22:10 + * @Email: 326308290@qq.com + */ + public class ShardingTest + { + private readonly ShardingDefaultDbContext _virtualDbContext; + private readonly IShardingRouteManager _shardingRouteManager; + private readonly ActualConnectionStringManager _connectionStringManager; + private readonly IConfiguration _configuration; + private readonly IEntityMetadataManager _entityMetadataManager; + private readonly IShardingComparer _shardingComparer; + private readonly IVirtualDataSource _virtualDataSource; + private readonly IVirtualTableManager _virtualTableManager; + private readonly IShardingTableCreator _shardingTableCreator; + private readonly IShardingReadWriteManager _shardingReadWriteManager; + + public ShardingTest(ShardingDefaultDbContext virtualDbContext,IShardingRouteManager shardingRouteManager, IConfiguration configuration, + IEntityMetadataManager entityMetadataManager, + IShardingComparer shardingComparer,IVirtualDataSource virtualDataSource, + IVirtualTableManager virtualTableManager, + IShardingTableCreator shardingTableCreator, IShardingReadWriteManager shardingReadWriteManager) + { + _virtualDbContext = virtualDbContext; + _shardingRouteManager = shardingRouteManager; + _connectionStringManager = new ActualConnectionStringManager(); + _configuration = configuration; + this._entityMetadataManager = entityMetadataManager; + _shardingComparer = shardingComparer; + _virtualDataSource = virtualDataSource; + _virtualTableManager = virtualTableManager; + _shardingTableCreator = shardingTableCreator; + _shardingReadWriteManager = shardingReadWriteManager; + } + + [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()); + var y = new EntityMetadata(typeof(LogDay),"aa1",typeof(ShardingDefaultDbContext),new List()); + 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 bulkShardingTableEnumerable = _virtualDbContext.BulkShardingTableEnumerable(logDays); + Assert.Equal(100, bulkShardingTableEnumerable.Count); + var bulkShardingEnumerable = _virtualDbContext.BulkShardingEnumerable(logDays); + Assert.Equal(1, bulkShardingEnumerable.Count); + foreach (var (key, value) in bulkShardingEnumerable) + { + Assert.Equal(100, value.Count); + } + + _virtualDbContext.Set().Where(o => o.Id == "300").ShardingPrint(); + var contains=await _virtualDbContext.Set().Where(o => o.Id == "300").Select(o => o.Id).ContainsAsync("300"); + Assert.True(contains); + + try + { + var x1 = _virtualDataSource.GetPhysicDataSource("abc"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreInvalidOperationException),e.GetType()); + } + + var queryable=new List().Select(o => new SequenceClass { Id = "123", T = o }).AsQueryable(); + var sourceType = queryable.GetType().GetSequenceType(); + Assert.Equal(typeof(SequenceClass),sourceType); + try + { + _shardingTableCreator.CreateTable("A", "202105"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreException),e.GetType()); + } + + var orderMetadata=_entityMetadataManager.TryGet(); + Assert.NotNull(orderMetadata); + var isKey1 = orderMetadata.ShardingDataSourceFieldIsKey(); + Assert.False(isKey1); + var isKey2 = orderMetadata.ShardingTableFieldIsKey(); + Assert.False(isKey2); + var userModMetadata = _entityMetadataManager.TryGet(); + Assert.NotNull(userModMetadata); + var isKey3 = userModMetadata.ShardingDataSourceFieldIsKey(); + Assert.False(isKey3); + var isKey4 = userModMetadata.ShardingTableFieldIsKey(); + Assert.True(isKey4); + try + { + throw new ShardingCoreParallelQueryTimeOutException("test"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreParallelQueryTimeOutException),e.GetType()); + } + + await _virtualDbContext.AddRangeAsync(logDays); + var bulkShardingExpression = _virtualDbContext.BulkShardingExpression(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(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(); + Assert.NotNull(virtualTable); + } + + public class SequenceClass + { + public string Id { get; set; } + public string T { get; set; } + } + [Fact] + public void TestEntityMetadataManager() + { + var objMetadata0 = _entityMetadataManager.TryGet(typeof(object)); + Assert.Null(objMetadata0); + var objMetadata1 = _entityMetadataManager.TryGet(); + Assert.Null(objMetadata1); + + var objMetadata2 = _entityMetadataManager.TryGet(typeof(SysUserMod)); + Assert.NotNull(objMetadata2); + var objMetadata3 = _entityMetadataManager.TryGet(); + Assert.NotNull(objMetadata3); + var sysUserModIsShardingTable0 = _entityMetadataManager.IsShardingTable(typeof(SysUserMod)); + Assert.True(sysUserModIsShardingTable0); + var sysUserModIsShardingTable1 = _entityMetadataManager.IsShardingTable(); + Assert.True(sysUserModIsShardingTable1); + var sysUserModIsShardingDataSource0 = _entityMetadataManager.IsShardingDataSource(typeof(SysUserMod)); + Assert.False(sysUserModIsShardingDataSource0); + var sysUserModIsShardingDataSource1 = _entityMetadataManager.IsShardingDataSource(); + Assert.False(sysUserModIsShardingDataSource1); + } + [Fact] + public void TestShardingComparer() + { + var x = new Guid("7CDE28F8-D548-B96D-1C61-39FFE37AE492"); + var y = new Guid("3425D899-291D-921B-DDE4-49FFE37AE493"); + //asc y0); + //asc x().Where(o=>o.Id=="339"); + // var routeResults1 = _tableRouteRuleEngineFactory.Route(queryable1); + // Assert.Equal(1,routeResults1.Count()); + // Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count()); + // Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail); + // Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName); + // var ids = new[] {"339", "124","142"}; + // var queryable2= _virtualDbContext.Set().Where(o=>ids.Contains(o.Id)); + // var routeResult2s = _tableRouteRuleEngineFactory.Route(queryable2); + // Assert.Equal(2,routeResult2s.Count()); + // Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count()); + // Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count()); + // Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail))); + //} + [Fact] + public async Task ToList_All_Route_Test() + { + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("00"); + + var mod00s = await _virtualDbContext.Set().ToListAsync(); + Assert.Equal(333, mod00s.Count); + } + var mods = await _virtualDbContext.Set().ToListAsync(); + Assert.Equal(1000, mods.Count); + + var modOrders1 = await _virtualDbContext.Set().OrderBy(o => o.Age).ToListAsync(); + int ascAge = 1; + foreach (var sysUserMod in modOrders1) + { + Assert.Equal(ascAge, sysUserMod.Age); + ascAge++; + } + + + var modOrders2 = await _virtualDbContext.Set().OrderByDescending(o => o.Age).ToListAsync(); + int descAge = 1000; + foreach (var sysUserMod in modOrders2) + { + Assert.Equal(descAge, sysUserMod.Age); + descAge--; + } + } + [Fact] + public async Task ToList_All_Test() + { + + var mods = await _virtualDbContext.Set().ToListAsync(); + Assert.Equal(1000, mods.Count); + + var modOrders1 = await _virtualDbContext.Set().OrderBy(o => o.Age).ToListAsync(); + int ascAge = 1; + foreach (var sysUserMod in modOrders1) + { + Assert.Equal(ascAge, sysUserMod.Age); + ascAge++; + } + + var modOrders2 = await _virtualDbContext.Set().OrderByDescending(o => o.Age).ToListAsync(); + int descAge = 1000; + foreach (var sysUserMod in modOrders2) + { + Assert.Equal(descAge, sysUserMod.Age); + descAge--; + } + + + + var pageResult = await _virtualDbContext.Set().Skip(10).Take(10).OrderByDescending(o => o.Age).ToListAsync(); + Assert.Equal(10, pageResult.Count); + int pageDescAge = 990; + foreach (var sysUserMod in pageResult) + { + Assert.Equal(pageDescAge, sysUserMod.Age); + pageDescAge--; + } + } + + [Fact] + public async Task ToList_Join_Test() + { + var list = await (from u in _virtualDbContext.Set() + join salary in _virtualDbContext.Set() + on u.Id equals salary.UserId + select new + { + u.Id, + u.Age, + Salary = salary.Salary, + DateOfMonth = salary.DateOfMonth, + Name = u.Name + }).ToListAsync(); + + 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")); + + + var queryable = (from u in _virtualDbContext.Set().Where(o => o.Id == "300") + join salary in _virtualDbContext.Set() + on u.Id equals salary.UserId + select new + { + Salary = salary.Salary, + DateOfMonth = salary.DateOfMonth, + Name = u.Name + }); + var list1 = await queryable.ToListAsync(); + Assert.Equal(24, list1.Count()); + Assert.DoesNotContain(list1, o => o.Name != "name_300"); + } + + [Fact] + public async Task ToList_OrderBy_Asc_Desc_Test() + { + var modascs = await _virtualDbContext.Set().OrderBy(o => o.Age).ToListAsync(); + Assert.Equal(1000, modascs.Count); + var i = 1; + foreach (var age in modascs) + { + Assert.Equal(i, age.Age); + i++; + } + + var moddescs = await _virtualDbContext.Set().OrderByDescending(o => o.Age).ToListAsync(); + Assert.Equal(1000, moddescs.Count); + var j = 1000; + foreach (var age in moddescs) + { + Assert.Equal(j, age.Age); + j--; + } + } + + [Fact] + public async Task ToList_Id_In_Test() + { + var ids = new[] {"1", "2", "3", "4"}; + var sysUserMods = await _virtualDbContext.Set().Where(o => new List { "1", "2", "3", "4" }.Contains(o.Id)).ToListAsync(); + foreach (var id in ids) + { + Assert.Contains(sysUserMods, o => o.Id == id); + } + + Assert.DoesNotContain(sysUserMods, o => o.Age > 4); + } + + [Fact] + public async Task ToList_Id_Eq_Test() + { + var id= 3; + var mods = await _virtualDbContext.Set().Where(o => o.Id == id.ToString()).ToListAsync(); + Assert.Single(mods); + var mods1 = await _virtualDbContext.Set().Where(o => o.Id == "4").ToListAsync(); + Assert.Single(mods1); + Assert.Equal("3", mods[0].Id); + } + + [Fact] + public async Task ToList_Id_Not_Eq_Test() + { + var mods = await _virtualDbContext.Set().Where(o => o.Id != "3").ToListAsync(); + Assert.Equal(999, mods.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + } + + [Fact] + public async Task ToList_Id_Not_Eq_Skip_Test() + { + var mods = await _virtualDbContext.Set().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToListAsync(); + Assert.Equal(997, mods.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + Assert.Equal(4, mods[0].Age); + Assert.Equal(5, mods[1].Age); + + var modsDesc = await _virtualDbContext.Set().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToListAsync(); + Assert.Equal(986, modsDesc.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + Assert.Equal(987, modsDesc[0].Age); + Assert.Equal(986, modsDesc[1].Age); + } + + [Fact] + public async Task ToList_Name_Eq_Test() + { + var mods = await _virtualDbContext.Set().Where(o => o.Name == "name_3").ToListAsync(); + Assert.Single(mods); + Assert.Equal("3", mods[0].Id); + } + + [Fact] + public async Task ToList_Id_Eq_Not_In_Db_Test() + { + var mods = await _virtualDbContext.Set().Where(o => o.Id == "1001").ToListAsync(); + Assert.Empty(mods); + } + + [Fact] + public async Task ToList_Name_Eq_Not_In_Db_Test() + { + var mods = await _virtualDbContext.Set().Where(o => o.Name == "name_1001").ToListAsync(); + Assert.Empty(mods); + } + + [Fact] + public async Task FirstOrDefault_Order_By_Id_Test() + { + var sysUserModAge = await _virtualDbContext.Set().OrderBy(o => o.Age).FirstOrDefaultAsync(); + Assert.True(sysUserModAge != null && sysUserModAge.Id == "1"); + var sysUserModAgeDesc = await _virtualDbContext.Set().OrderByDescending(o => o.Age).FirstOrDefaultAsync(); + Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000"); + var sysUserMod = await _virtualDbContext.Set().OrderBy(o => o.Id).FirstOrDefaultAsync(); + Assert.True(sysUserMod != null && sysUserMod.Id == "1"); + + var sysUserModDesc = await _virtualDbContext.Set().OrderByDescending(o => o.Id).FirstOrDefaultAsync(); + Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999"); + + } + + [Fact] + public async Task FirstOrDefault2() + { + var sysUserMod = await _virtualDbContext.Set().Where(o => o.Id == "1").FirstOrDefaultAsync(); + Assert.NotNull(sysUserMod); + var userMod = _virtualDbContext.Set().Find("1"); + Assert.Equal(sysUserMod, userMod); + Assert.True(sysUserMod.Id == "1"); + var user198 = await _virtualDbContext.Set().FirstOrDefaultAsync(o => o.Id == "198"); + Assert.True(user198.Id == "198"); + var userId198 = await _virtualDbContext.Set().Where(o => o.Id == "198").Select(o => o.Id).FirstOrDefaultAsync(); + Assert.Equal(userId198, "198"); + } + + [Fact] + public async Task FirstOrDefault3() + { + var sysUserMod = await _virtualDbContext.Set().Where(o => o.Name == "name_2").FirstOrDefaultAsync(); + Assert.NotNull(sysUserMod); + Assert.Equal("2", sysUserMod.Id); + + } + + [Fact] + public async Task FirstOrDefault4() + { + var sysUserMod = await _virtualDbContext.Set().Where(o => o.Id != "1").FirstOrDefaultAsync(); + Assert.NotNull(sysUserMod); + Assert.True(sysUserMod.Id != "1"); + } + + [Fact] + public async Task FirstOrDefault5() + { + var sysUserMod = await _virtualDbContext.Set().Where(o => o.Name == "name_1001").FirstOrDefaultAsync(); + Assert.Null(sysUserMod); + } + + [Fact] + public async Task Count_Test() + { + var a = await _virtualDbContext.Set().Where(o => o.Name == "name_1000").CountAsync(); + Assert.Equal(1, a); + var b = await _virtualDbContext.Set().Where(o => o.Name != "name_1000").CountAsync(); + Assert.Equal(999, b); + } + + [Fact] + public async Task Sum_Test() + { + var a = await _virtualDbContext.Set().SumAsync(o => o.Age); + var expected = 0; + for (int i = 1; i <= 1000; i++) + { + expected += i; + } + + Assert.Equal(expected, a); + var b = await _virtualDbContext.Set().Where(o => o.Name != "name_1000").SumAsync(o => o.Age); + Assert.Equal(expected - 1000, b); + } + + [Fact] + public async Task Max_Test() + { + var a = await _virtualDbContext.Set().MaxAsync(o => o.Age); + Assert.Equal(1000, a); + var b = await _virtualDbContext.Set().Where(o => o.Name != "name_1000").MaxAsync(o => o.Age); + Assert.Equal(999, b); + var c = await _virtualDbContext.Set().Where(o => o.Age < 500).MaxAsync(o => o.Age); + Assert.Equal(499, c); + var e = await _virtualDbContext.Set().Where(o => o.Age <= 500).MaxAsync(o => o.Age); + Assert.Equal(500, e); + } + + [Fact] + public async Task Max_Join_Test() + { + var queryable = (from u in _virtualDbContext.Set().Where(o => o.Id == "300") + join salary in _virtualDbContext.Set() + 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); + } + + [Fact] + public async Task Min_Test() + { + var a = await _virtualDbContext.Set().MinAsync(o => o.Age); + Assert.Equal(1, a); + var b = await _virtualDbContext.Set().Where(o => o.Name != "name_1").MinAsync(o => o.Age); + Assert.Equal(2, b); + var c = await _virtualDbContext.Set().Where(o => o.Age > 500).MinAsync(o => o.Age); + Assert.Equal(501, c); + var e = await _virtualDbContext.Set().Where(o => o.Age >= 500).MinAsync(o => o.Age); + Assert.Equal(500, e); + } + + [Fact] + public async Task Any_Test() + { + var a = await _virtualDbContext.Set().AnyAsync(o => o.Age == 100); + Assert.True(a); + var b = await _virtualDbContext.Set().Where(o => o.Name != "name_1").AnyAsync(o => o.Age == 1); + Assert.False(b); + var c = await _virtualDbContext.Set().Where(o => o.Age > 500).AnyAsync(o => o.Age <= 500); + Assert.False(c); + var e = await _virtualDbContext.Set().Where(o => o.Age >= 500).AnyAsync(o => o.Age <= 500); + Assert.True(e); + } + + [Fact] + public async Task Group_Test() + { + var ids = new[] {"200", "300"}; + var dateOfMonths = new[] {202111, 202110}; + var group = await (from u in _virtualDbContext.Set() + .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) + 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(); + Assert.Equal(2, group.Count); + Assert.Equal(2, group[0].Count); + Assert.Equal(2260000, group[0].TotalSalary); + Assert.Equal(1130000, group[0].AvgSalary); + Assert.Equal(11300, group[0].AvgSalaryDecimal); + Assert.Equal(1120000, group[0].MinSalary); + Assert.Equal(1140000, group[0].MaxSalary); + } + + [Fact] + public async Task OrderCountTest() + { + var asyncCount = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(320, asyncCount); + var syncCount = _virtualDbContext.Set().Count(); + Assert.Equal(320, syncCount); + + var countA =await _virtualDbContext.Set().CountAsync(o=>o.Area=="A"); + var countB =await _virtualDbContext.Set().CountAsync(o=>o.Area=="B"); + var countC =await _virtualDbContext.Set().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().Where(o=>o.CreateTime>=fourBegin&&o.CreateTime().FirstOrDefaultAsync(o=>o.CreateTime== threeMonth);//59 131228 + Assert.NotNull(order); + Assert.Equal(59,order.Money); + Assert.Equal("C",order.Area); + } + [Fact] + public async Task OrderOrderTest() + { + var orders = await _virtualDbContext.Set().OrderBy(o => o.CreateTime).ToListAsync(); + Assert.Equal(320,orders.Count); + var i = 0; + foreach (var order in orders) + { + Assert.Equal(i,order.Money); + i++; + } + + var threeMonth = new DateTime(2021, 3, 1); + var orderPage = await _virtualDbContext.Set().Where(o=>o.CreateTime > threeMonth).OrderByDescending(o => o.CreateTime).ToShardingPageAsync(1,20); + Assert.Equal(20, orderPage.Data.Count); + Assert.Equal(260,orderPage.Total); + + + var j = 319; + foreach (var order in orderPage.Data) + { + Assert.Equal(j, order.Money); + j--; + } + + + var orderPage1 = await _virtualDbContext.Set().Where(o => o.CreateTime > threeMonth).OrderBy(o=>o.CreateTime).ToShardingPageAsync(1, 20); + Assert.Equal(20, orderPage1.Data.Count); + Assert.Equal(260, orderPage1.Total); + + + var j1 = 60; + foreach (var order in orderPage1.Data) + { + Assert.Equal(j1, order.Money); + j1++; + } + } + + [Fact] + public async Task LogDayCountTest() + { + var countAsync = await _virtualDbContext.Set().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(300, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210102"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(10, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210103", "20210104"); + var countAsync2 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(20, countAsync2); + } + } + [Fact] + public void LogDayTableSeparatorTest() + { + var virtualTable = _virtualTableManager.GetVirtualTable(typeof(LogDay)); + var virtualTableName = virtualTable.GetVirtualTableName(); + 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)); + Assert.True(all); + var entityMetadata = _entityMetadataManager.TryGet(); + Assert.NotNull(entityMetadata); + var isShardingTable = entityMetadata.IsShardingTable(); + Assert.True(isShardingTable); + var isShardingDataSource = entityMetadata.IsShardingDataSource(); + Assert.False(isShardingDataSource); + var emptySeparator = string.IsNullOrWhiteSpace(entityMetadata.TableSeparator); + Assert.True(emptySeparator); + Assert.Null(entityMetadata.AutoCreateDataSourceTable); + } + + [Fact] + public async Task LogDayShardingPage() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var page= await _virtualDbContext.Set().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().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin) + .ToShardingPageAsync(2, 10); + Assert.Equal(10, page1.Data.Count); + Assert.Equal(300, page1.Total); + } + + [Fact] + public async Task Order_Average() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var moneyAverage = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).AverageAsync(); + Assert.Equal(105, moneyAverage); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + var sum = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync(); + Assert.Equal(0,sum); + var sum1 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (long?)o.Money).SumAsync(); + Assert.Equal(0,sum1); + var sum2 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (int)o.Money).SumAsync(); + Assert.Equal(0, sum2); + var sum3 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (int?)o.Money).SumAsync(); + Assert.Equal(0, sum3); + var sum4 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (decimal)o.Money).SumAsync(); + Assert.Equal(0, sum4); + var sum5 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (decimal?)o.Money).SumAsync(); + Assert.Equal(0, sum5); + var sum6 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (double)o.Money).SumAsync(); + Assert.Equal(0, sum6); + var sum7 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (double?)o.Money).SumAsync(); + Assert.Equal(0, sum7); + var sum8 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (float)o.Money).SumAsync(); + Assert.Equal(0, sum8); + var sum9 = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (float?)o.Money).SumAsync(); + Assert.Equal(0, sum9); + } + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintDataSource("C"); + var sum = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).SumAsync(); + Assert.Equal(0,sum); + } + + var max = await _virtualDbContext.Set().MaxAsync(o => o.Money); + Assert.Equal(319,max); + var all= await _virtualDbContext.Set().AllAsync(o=>o.Money<=321); + Assert.True(all); + var longCount=await _virtualDbContext.Set().LongCountAsync(); + Assert.Equal(320,longCount); + } + + [Fact] + public async Task Order_Max() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + + + var moneyMax = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).MaxAsync(); + Assert.Equal(120, moneyMax); + var moneyMax1 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax1); + var moneyMax2 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax2); + var moneyMax3 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int?)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax3); + var moneyMax4 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax4); + var moneyMax5 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double?)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax5); + var moneyMax6 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax6); + var moneyMax7 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float?)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax7); + var moneyMax8 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax8); + var moneyMax9 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal?)o.Money).MaxAsync(); + Assert.Equal(120, moneyMax9); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + try + { + var max = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).MaxAsync(); + } + catch (Exception e) + { + Assert.True(e.Message.Contains("contains")); + } + } + } + [Fact] + public async Task Order_Min() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + + + var moneyMin = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).MinAsync(); + Assert.Equal(90, moneyMin); + var moneyMin1 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).MinAsync(); + Assert.Equal(90, moneyMin1); + var moneyMin2 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int)o.Money).MinAsync(); + Assert.Equal(90, moneyMin2); + var moneyMin3 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int?)o.Money).MinAsync(); + Assert.Equal(90, moneyMin3); + var moneyMin4 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float)o.Money).MinAsync(); + Assert.Equal(90, moneyMin4); + var moneyMin5 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float?)o.Money).MinAsync(); + Assert.Equal(90, moneyMin5); + var moneyMin6 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double)o.Money).MinAsync(); + Assert.Equal(90, moneyMin6); + var moneyMin7 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double?)o.Money).MinAsync(); + Assert.Equal(90, moneyMin7); + var moneyMin8 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal)o.Money).MinAsync(); + Assert.Equal(90, moneyMin8); + var moneyMin9 = await _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal?)o.Money).MinAsync(); + Assert.Equal(90, moneyMin9); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + try + { + var max = await _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).MinAsync(); + } + catch (InvalidOperationException e) + { + Assert.True(e.Message.Contains("contains")); + } + } + } + + [Fact] + public async Task Order_Entity() + { + var x=await _virtualDbContext.Set().OrderBy(o => o.Money).LastOrDefaultAsync(); + Assert.NotNull(x); + Assert.Equal(319,x.Money); + var x1 = await _virtualDbContext.Set().OrderBy(o => o.Money).LastAsync(); + Assert.Equal(x,x1); + var y = await _virtualDbContext.Set().OrderBy(o => o.Money).FirstOrDefaultAsync(); + Assert.NotNull(y); + Assert.Equal(0, y.Money); + var y1 = await _virtualDbContext.Set().OrderBy(o => o.Money).FirstAsync(); + Assert.Equal(y, y1); + var z=await _virtualDbContext.Set().SingleOrDefaultAsync(o => o.Money == 13); + var z1 = await _virtualDbContext.Set().SingleAsync(o => o.Money == 13); + Assert.Equal(z, z1); + } + + [Fact] + public async Task OrderReadWrite() + { + //лֻݿ⣬ֻݿֻAԴȡBԴ + _virtualDbContext.ReadWriteSeparationReadOnly(); + var list = await _virtualDbContext.Set().Where(o=>o.Money==1).ToListAsync(); + Assert.Equal(2, list.Count); + + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = await _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefaultAsync(); + Assert.Null(areaB); + } + _virtualDbContext.ReadWriteSeparationReadOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = await _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefaultAsync(); + Assert.NotNull(areaB); + } + + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingReadWriteManager.CreateScope()) + { + _shardingReadWriteManager.GetCurrent().SetReadWriteSeparation(100, true); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = await _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefaultAsync(); + Assert.NotNull(areaB); + } + } + using (_shardingReadWriteManager.CreateScope()) + { + _shardingReadWriteManager.GetCurrent().SetReadWriteSeparation(100, true); + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = await _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefaultAsync(); + Assert.Null(areaB); + } + } + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = await _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefaultAsync(); + Assert.Null(areaB); + } + } + + + [Fact] + public async Task LogWeekDateTimeCountTest() + { + var countAsync = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(300, countAsync); + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var fourCount = await _virtualDbContext.Set().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(14, countAsync2); + } + } + + [Fact] + public async Task LogWeekDateTimeShardingPage() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var page = await _virtualDbContext.Set().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().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 LogWeekTimeLongCountTest() + { + var countAsync = await _virtualDbContext.Set().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = await _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).CountAsync(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("2020"); + var countAsync1 = await _virtualDbContext.Set().CountAsync(); + Assert.Equal(366, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail( "2021"); + var countAsync2 = await _virtualDbContext.Set().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().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().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 Group_API_Test() + // { + // var ids = new[] {"200", "300"}; + // var dateOfMonths = new[] {202111, 202110}; + // var group = await _virtualDbContext.Set() + // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) + // .ShardingGroupByAsync(g => new {UId = g.UserId}, g => 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) + // }); + // Assert.Equal(2, group.Count); + // Assert.Equal(2, group[0].Count); + // Assert.Equal(2260000, group[0].TotalSalary); + // Assert.Equal(1130000, group[0].AvgSalary); + // Assert.Equal(11300, group[0].AvgSalaryDecimal); + // Assert.Equal(1120000, group[0].MinSalary); + // Assert.Equal(1140000, group[0].MaxSalary); + // } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/ShardingTestSync.cs b/test/ShardingCore.Test2x/ShardingTestSync.cs new file mode 100644 index 00000000..650cf872 --- /dev/null +++ b/test/ShardingCore.Test2x/ShardingTestSync.cs @@ -0,0 +1,1039 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Microsoft.Extensions.Configuration; +using ShardingCore.Core.EntityMetadatas; +using ShardingCore.Core.QueryRouteManagers.Abstractions; +using ShardingCore.Core.VirtualDatabase.VirtualDataSources; +using ShardingCore.Core.VirtualDatabase.VirtualDataSources.PhysicDataSources; +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; +using ShardingCore.Test2x.Domain.Entities; +using Xunit; + +namespace ShardingCore.Test2x +{ + + + public class ShardingTestSync + { + private readonly ShardingDefaultDbContext _virtualDbContext; + private readonly IShardingRouteManager _shardingRouteManager; + private readonly IConfiguration _configuration; + private readonly IEntityMetadataManager _entityMetadataManager; + private readonly IShardingComparer _shardingComparer; + private readonly IVirtualDataSource _virtualDataSource; + private readonly IVirtualTableManager _virtualTableManager; + private readonly IShardingTableCreator _shardingTableCreator; + private readonly IShardingReadWriteManager _shardingReadWriteManager; + + public ShardingTestSync(ShardingDefaultDbContext virtualDbContext, IShardingRouteManager shardingRouteManager, IConfiguration configuration, + IEntityMetadataManager entityMetadataManager, + IShardingComparer shardingComparer, IVirtualDataSource virtualDataSource, + IVirtualTableManager virtualTableManager, + IShardingTableCreator shardingTableCreator, IShardingReadWriteManager shardingReadWriteManager) + { + _virtualDbContext = virtualDbContext; + _shardingRouteManager = shardingRouteManager; + _configuration = configuration; + this._entityMetadataManager = entityMetadataManager; + _shardingComparer = shardingComparer; + _virtualDataSource = virtualDataSource; + _virtualTableManager = virtualTableManager; + _shardingTableCreator = shardingTableCreator; + _shardingReadWriteManager = shardingReadWriteManager; + } + + [Fact] + public void 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()); + var y = new EntityMetadata(typeof(LogDay), "aa1", typeof(ShardingDefaultDbContext), new List()); + 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 bulkShardingTableEnumerable = _virtualDbContext.BulkShardingTableEnumerable(logDays); + Assert.Equal(100, bulkShardingTableEnumerable.Count); + var bulkShardingEnumerable = _virtualDbContext.BulkShardingEnumerable(logDays); + Assert.Equal(1, bulkShardingEnumerable.Count); + foreach (var (key, value) in bulkShardingEnumerable) + { + Assert.Equal(100, value.Count); + } + + _virtualDbContext.Set().Where(o => o.Id == "300").ShardingPrint(); + var contains = _virtualDbContext.Set().Where(o => o.Id == "300").Select(o => o.Id).Contains("300"); + Assert.True(contains); + + try + { + var x1 = _virtualDataSource.GetPhysicDataSource("abc"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreInvalidOperationException), e.GetType()); + } + + var queryable = new List().Select(o => new SequenceClass { Id = "123", T = o }).AsQueryable(); + var sourceType = queryable.GetType().GetSequenceType(); + Assert.Equal(typeof(SequenceClass), sourceType); + try + { + _shardingTableCreator.CreateTable("A", "202105"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreException), e.GetType()); + } + + var orderMetadata = _entityMetadataManager.TryGet(); + Assert.NotNull(orderMetadata); + var isKey1 = orderMetadata.ShardingDataSourceFieldIsKey(); + Assert.False(isKey1); + var isKey2 = orderMetadata.ShardingTableFieldIsKey(); + Assert.False(isKey2); + var userModMetadata = _entityMetadataManager.TryGet(); + Assert.NotNull(userModMetadata); + var isKey3 = userModMetadata.ShardingDataSourceFieldIsKey(); + Assert.False(isKey3); + var isKey4 = userModMetadata.ShardingTableFieldIsKey(); + Assert.True(isKey4); + try + { + throw new ShardingCoreParallelQueryTimeOutException("test"); + } + catch (Exception e) + { + Assert.Equal(typeof(ShardingCoreParallelQueryTimeOutException), e.GetType()); + } + + _virtualDbContext.AddRange(logDays); + var bulkShardingExpression = _virtualDbContext.BulkShardingExpression(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(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(); + Assert.NotNull(virtualTable); + + } + + public class SequenceClass + { + public string Id { get; set; } + public string T { get; set; } + } + [Fact] + public void TestEntityMetadataManager() + { + var objMetadata0 = _entityMetadataManager.TryGet(typeof(object)); + Assert.Null(objMetadata0); + var objMetadata1 = _entityMetadataManager.TryGet(); + Assert.Null(objMetadata1); + + var objMetadata2 = _entityMetadataManager.TryGet(typeof(SysUserMod)); + Assert.NotNull(objMetadata2); + var objMetadata3 = _entityMetadataManager.TryGet(); + Assert.NotNull(objMetadata3); + var sysUserModIsShardingTable0 = _entityMetadataManager.IsShardingTable(typeof(SysUserMod)); + Assert.True(sysUserModIsShardingTable0); + var sysUserModIsShardingTable1 = _entityMetadataManager.IsShardingTable(); + Assert.True(sysUserModIsShardingTable1); + var sysUserModIsShardingDataSource0 = _entityMetadataManager.IsShardingDataSource(typeof(SysUserMod)); + Assert.False(sysUserModIsShardingDataSource0); + var sysUserModIsShardingDataSource1 = _entityMetadataManager.IsShardingDataSource(); + Assert.False(sysUserModIsShardingDataSource1); + } + [Fact] + public void TestShardingComparer() + { + var x = new Guid("7CDE28F8-D548-B96D-1C61-39FFE37AE492"); + var y = new Guid("3425D899-291D-921B-DDE4-49FFE37AE493"); + //asc y 0); + //asc x().Where(o=>o.Id=="339"); + // var routeResults1 = _tableRouteRuleEngineFactory.Route(queryable1); + // Assert.Equal(1,routeResults1.Count()); + // Assert.Equal(1,routeResults1.FirstOrDefault().ReplaceTables.Count()); + // Assert.Equal("0",routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().Tail); + // Assert.Equal(nameof(SysUserMod),routeResults1.FirstOrDefault().ReplaceTables.FirstOrDefault().OriginalName); + // var ids = new[] {"339", "124","142"}; + // var queryable2= _virtualDbContext.Set().Where(o=>ids.Contains(o.Id)); + // var routeResult2s = _tableRouteRuleEngineFactory.Route(queryable2); + // Assert.Equal(2,routeResult2s.Count()); + // Assert.Equal(1,routeResult2s.FirstOrDefault().ReplaceTables.Count()); + // Assert.Equal(2,routeResult2s.SelectMany(o=>o.ReplaceTables).Count()); + // Assert.Equal(true,routeResult2s.SelectMany(o=>o.ReplaceTables).All(o=>new[]{"0","1"}.Contains(o.Tail))); + //} + [Fact] + public void ToList_All_Route_Test() + { + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("00"); + + var mod00s = _virtualDbContext.Set().ToList(); + Assert.Equal(333, mod00s.Count); + } + var mods = _virtualDbContext.Set().ToList(); + Assert.Equal(1000, mods.Count); + + var modOrders1 = _virtualDbContext.Set().OrderBy(o => o.Age).ToList(); + int ascAge = 1; + foreach (var sysUserMod in modOrders1) + { + Assert.Equal(ascAge, sysUserMod.Age); + ascAge++; + } + + + var modOrders2 = _virtualDbContext.Set().OrderByDescending(o => o.Age).ToList(); + int descAge = 1000; + foreach (var sysUserMod in modOrders2) + { + Assert.Equal(descAge, sysUserMod.Age); + descAge--; + } + } + [Fact] + public void ToList_All_Test() + { + + var mods = _virtualDbContext.Set().ToList(); + Assert.Equal(1000, mods.Count); + + var modOrders1 = _virtualDbContext.Set().OrderBy(o => o.Age).ToList(); + int ascAge = 1; + foreach (var sysUserMod in modOrders1) + { + Assert.Equal(ascAge, sysUserMod.Age); + ascAge++; + } + + var modOrders2 = _virtualDbContext.Set().OrderByDescending(o => o.Age).ToList(); + int descAge = 1000; + foreach (var sysUserMod in modOrders2) + { + Assert.Equal(descAge, sysUserMod.Age); + descAge--; + } + + + + var pageResult = _virtualDbContext.Set().Skip(10).Take(10).OrderByDescending(o => o.Age).ToList(); + Assert.Equal(10, pageResult.Count); + int pageDescAge = 990; + foreach (var sysUserMod in pageResult) + { + Assert.Equal(pageDescAge, sysUserMod.Age); + pageDescAge--; + } + } + + [Fact] + public void ToList_Join_Test() + { + var list = (from u in _virtualDbContext.Set() + join salary in _virtualDbContext.Set() + on u.Id equals salary.UserId + select new + { + u.Id, + u.Age, + Salary = salary.Salary, + DateOfMonth = salary.DateOfMonth, + Name = u.Name + }).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")); + + + var queryable = (from u in _virtualDbContext.Set().Where(o => o.Id == "300") + join salary in _virtualDbContext.Set() + on u.Id equals salary.UserId + select new + { + Salary = salary.Salary, + DateOfMonth = salary.DateOfMonth, + Name = u.Name + }); + var list1 = queryable.ToList(); + Assert.Equal(24, list1.Count()); + Assert.DoesNotContain(list1, o => o.Name != "name_300"); + } + + [Fact] + public void ToList_OrderBy_Asc_Desc_Test() + { + var modascs = _virtualDbContext.Set().OrderBy(o => o.Age).ToList(); + Assert.Equal(1000, modascs.Count); + var i = 1; + foreach (var age in modascs) + { + Assert.Equal(i, age.Age); + i++; + } + + var moddescs = _virtualDbContext.Set().OrderByDescending(o => o.Age).ToList(); + Assert.Equal(1000, moddescs.Count); + var j = 1000; + foreach (var age in moddescs) + { + Assert.Equal(j, age.Age); + j--; + } + } + + [Fact] + public void ToList_Id_In_Test() + { + var ids = new[] { "1", "2", "3", "4" }; + var sysUserMods = _virtualDbContext.Set().Where(o => new List { "1", "2", "3", "4" }.Contains(o.Id)).ToList(); + foreach (var id in ids) + { + Assert.Contains(sysUserMods, o => o.Id == id); + } + + Assert.DoesNotContain(sysUserMods, o => o.Age > 4); + } + + [Fact] + public void ToList_Id_Eq_Test() + { + var id = 3; + var mods = _virtualDbContext.Set().Where(o => o.Id == id.ToString()).ToList(); + Assert.Single(mods); + var mods1 = _virtualDbContext.Set().Where(o => o.Id == "4").ToList(); + Assert.Single(mods1); + Assert.Equal("3", mods[0].Id); + } + + [Fact] + public void ToList_Id_Not_Eq_Test() + { + var mods = _virtualDbContext.Set().Where(o => o.Id != "3").ToList(); + Assert.Equal(999, mods.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + } + + [Fact] + public void ToList_Id_Not_Eq_Skip_Test() + { + var mods = _virtualDbContext.Set().Where(o => o.Id != "3").OrderBy(o => o.Age).Skip(2).ToList(); + Assert.Equal(997, mods.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + Assert.Equal(4, mods[0].Age); + Assert.Equal(5, mods[1].Age); + + var modsDesc = _virtualDbContext.Set().Where(o => o.Id != "3").OrderByDescending(o => o.Age).Skip(13).ToList(); + Assert.Equal(986, modsDesc.Count); + Assert.DoesNotContain(mods, o => o.Id == "3"); + Assert.Equal(987, modsDesc[0].Age); + Assert.Equal(986, modsDesc[1].Age); + } + + [Fact] + public void ToList_Name_Eq_Test() + { + var mods = _virtualDbContext.Set().Where(o => o.Name == "name_3").ToList(); + Assert.Single(mods); + Assert.Equal("3", mods[0].Id); + } + + [Fact] + public void ToList_Id_Eq_Not_In_Db_Test() + { + var mods = _virtualDbContext.Set().Where(o => o.Id == "1001").ToList(); + Assert.Empty(mods); + } + + [Fact] + public void ToList_Name_Eq_Not_In_Db_Test() + { + var mods = _virtualDbContext.Set().Where(o => o.Name == "name_1001").ToList(); + Assert.Empty(mods); + } + + [Fact] + public void FirstOrDefault_Order_By_Id_Test() + { + var sysUserModAge = _virtualDbContext.Set().OrderBy(o => o.Age).FirstOrDefault(); + Assert.True(sysUserModAge != null && sysUserModAge.Id == "1"); + var sysUserModAgeDesc = _virtualDbContext.Set().OrderByDescending(o => o.Age).FirstOrDefault(); + Assert.True(sysUserModAgeDesc != null && sysUserModAgeDesc.Id == "1000"); + var sysUserMod = _virtualDbContext.Set().OrderBy(o => o.Id).FirstOrDefault(); + Assert.True(sysUserMod != null && sysUserMod.Id == "1"); + + var sysUserModDesc = _virtualDbContext.Set().OrderByDescending(o => o.Id).FirstOrDefault(); + Assert.True(sysUserModDesc != null && sysUserModDesc.Id == "999"); + + } + + [Fact] + public void FirstOrDefault2() + { + var sysUserMod = _virtualDbContext.Set().Where(o => o.Id == "1").FirstOrDefault(); + Assert.NotNull(sysUserMod); + var userMod = _virtualDbContext.Set().Find("1"); + Assert.Equal(sysUserMod, userMod); + Assert.True(sysUserMod.Id == "1"); + var user198 = _virtualDbContext.Set().FirstOrDefault(o => o.Id == "198"); + Assert.True(user198.Id == "198"); + var userId198 = _virtualDbContext.Set().Where(o => o.Id == "198").Select(o => o.Id).FirstOrDefault(); + Assert.Equal(userId198, "198"); + } + + [Fact] + public void FirstOrDefault3() + { + var sysUserMod = _virtualDbContext.Set().Where(o => o.Name == "name_2").FirstOrDefault(); + Assert.NotNull(sysUserMod); + Assert.Equal("2", sysUserMod.Id); + + } + + [Fact] + public void FirstOrDefault4() + { + var sysUserMod = _virtualDbContext.Set().Where(o => o.Id != "1").FirstOrDefault(); + Assert.NotNull(sysUserMod); + Assert.True(sysUserMod.Id != "1"); + } + + [Fact] + public void FirstOrDefault5() + { + var sysUserMod = _virtualDbContext.Set().Where(o => o.Name == "name_1001").FirstOrDefault(); + Assert.Null(sysUserMod); + } + + [Fact] + public void Count_Test() + { + var a = _virtualDbContext.Set().Where(o => o.Name == "name_1000").Count(); + Assert.Equal(1, a); + var b = _virtualDbContext.Set().Where(o => o.Name != "name_1000").Count(); + Assert.Equal(999, b); + } + + [Fact] + public void Sum_Test() + { + var a = _virtualDbContext.Set().Sum(o => o.Age); + var expected = 0; + for (int i = 1; i <= 1000; i++) + { + expected += i; + } + + Assert.Equal(expected, a); + var b = _virtualDbContext.Set().Where(o => o.Name != "name_1000").Sum(o => o.Age); + Assert.Equal(expected - 1000, b); + } + + [Fact] + public void Max_Test() + { + var a = _virtualDbContext.Set().Max(o => o.Age); + Assert.Equal(1000, a); + var b = _virtualDbContext.Set().Where(o => o.Name != "name_1000").Max(o => o.Age); + Assert.Equal(999, b); + var c = _virtualDbContext.Set().Where(o => o.Age < 500).Max(o => o.Age); + Assert.Equal(499, c); + var e = _virtualDbContext.Set().Where(o => o.Age <= 500).Max(o => o.Age); + Assert.Equal(500, e); + } + + [Fact] + public void Max_Join_Test() + { + var queryable = (from u in _virtualDbContext.Set().Where(o => o.Id == "300") + join salary in _virtualDbContext.Set() + on u.Id equals salary.UserId + select new + { + Salary = salary.Salary, + DateOfMonth = salary.DateOfMonth, + Name = u.Name + }); + var maxSalary = queryable.Max(o => o.Salary); + Assert.Equal(1390000, maxSalary); + } + + [Fact] + public void Min_Test() + { + var a = _virtualDbContext.Set().Min(o => o.Age); + Assert.Equal(1, a); + var b = _virtualDbContext.Set().Where(o => o.Name != "name_1").Min(o => o.Age); + Assert.Equal(2, b); + var c = _virtualDbContext.Set().Where(o => o.Age > 500).Min(o => o.Age); + Assert.Equal(501, c); + var e = _virtualDbContext.Set().Where(o => o.Age >= 500).Min(o => o.Age); + Assert.Equal(500, e); + } + + [Fact] + public void Any_Test() + { + var a = _virtualDbContext.Set().Any(o => o.Age == 100); + Assert.True(a); + var b = _virtualDbContext.Set().Where(o => o.Name != "name_1").Any(o => o.Age == 1); + Assert.False(b); + var c = _virtualDbContext.Set().Where(o => o.Age > 500).Any(o => o.Age <= 500); + Assert.False(c); + var e = _virtualDbContext.Set().Where(o => o.Age >= 500).Any(o => o.Age <= 500); + Assert.True(e); + } + + [Fact] + public void Group_Test() + { + var ids = new[] { "200", "300" }; + var dateOfMonths = new[] { 202111, 202110 }; + var group = (from u in _virtualDbContext.Set() + .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) + 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) + }).ToList(); + Assert.Equal(2, group.Count); + Assert.Equal(2, group[0].Count); + Assert.Equal(2260000, group[0].TotalSalary); + Assert.Equal(1130000, group[0].AvgSalary); + Assert.Equal(11300, group[0].AvgSalaryDecimal); + Assert.Equal(1120000, group[0].MinSalary); + Assert.Equal(1140000, group[0].MaxSalary); + } + + [Fact] + public void OrderCountTest() + { + var asyncCount = _virtualDbContext.Set().Count(); + Assert.Equal(320, asyncCount); + var syncCount = _virtualDbContext.Set().Count(); + Assert.Equal(320, syncCount); + + var countA = _virtualDbContext.Set().Count(o => o.Area == "A"); + var countB = _virtualDbContext.Set().Count(o => o.Area == "B"); + var countC = _virtualDbContext.Set().Count(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 = _virtualDbContext.Set().Where(o => o.CreateTime >= fourBegin && o.CreateTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + } + [Fact] + public void OrderFirstTest() + { + var threeMonth = new DateTime(2021, 3, 1); + var order = _virtualDbContext.Set().FirstOrDefault(o => o.CreateTime == threeMonth);//第59条 1月31天2月28天 + Assert.NotNull(order); + Assert.Equal(59, order.Money); + Assert.Equal("C", order.Area); + } + [Fact] + public void OrderOrderTest() + { + var orders = _virtualDbContext.Set().OrderBy(o => o.CreateTime).ToList(); + Assert.Equal(320, orders.Count); + var i = 0; + foreach (var order in orders) + { + Assert.Equal(i, order.Money); + i++; + } + + var threeMonth = new DateTime(2021, 3, 1); + var orderPage = _virtualDbContext.Set().Where(o => o.CreateTime > threeMonth).OrderByDescending(o => o.CreateTime).ToShardingPage(1, 20); + Assert.Equal(20, orderPage.Data.Count); + Assert.Equal(260, orderPage.Total); + + var j = 319; + foreach (var order in orderPage.Data) + { + Assert.Equal(j, order.Money); + j--; + } + } + + [Fact] + public void LogDayCountTest() + { + var countAsync = _virtualDbContext.Set().Count(); + Assert.Equal(3000, countAsync); + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var fourCount = _virtualDbContext.Set().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(300, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210102"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(10, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210103", "20210104"); + var countAsync2 = _virtualDbContext.Set().Count(); + Assert.Equal(20, countAsync2); + } + } + [Fact] + public void LogDayTableSeparatorTest() + { + var virtualTable = _virtualTableManager.GetVirtualTable(typeof(LogDay)); + var virtualTableName = virtualTable.GetVirtualTableName(); + 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)); + Assert.True(all); + var entityMetadata = _entityMetadataManager.TryGet(); + Assert.NotNull(entityMetadata); + var isShardingTable = entityMetadata.IsShardingTable(); + Assert.True(isShardingTable); + var isShardingDataSource = entityMetadata.IsShardingDataSource(); + Assert.False(isShardingDataSource); + var emptySeparator = string.IsNullOrWhiteSpace(entityMetadata.TableSeparator); + Assert.True(emptySeparator); + Assert.Null(entityMetadata.AutoCreateDataSourceTable); + } + + [Fact] + public void LogDayShardingPage() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var page = _virtualDbContext.Set().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin).OrderBy(o => o.LogTime) + .ToShardingPage(2, 10); + Assert.Equal(10, page.Data.Count); + Assert.Equal(300, page.Total); + + var page1 = _virtualDbContext.Set().Where(o => o.LogTime >= fourBegin && o.LogTime <= fiveBegin) + .ToShardingPage(2, 10); + Assert.Equal(10, page1.Data.Count); + Assert.Equal(300, page1.Total); + + } + + [Fact] + public void Order_Average() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var moneyAverage = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).Average(); + Assert.Equal(105, moneyAverage); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + var sum = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).Sum(); + Assert.Equal(0, sum); + var sum1 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (long?)o.Money).Sum(); + Assert.Equal(0, sum1); + var sum2 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (int)o.Money).Sum(); + Assert.Equal(0, sum2); + var sum3 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (int?)o.Money).Sum(); + Assert.Equal(0, sum3); + var sum4 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (decimal)o.Money).Sum(); + Assert.Equal(0, sum4); + var sum5 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (decimal?)o.Money).Sum(); + Assert.Equal(0, sum5); + var sum6 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (double)o.Money).Sum(); + Assert.Equal(0, sum6); + var sum7 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (double?)o.Money).Sum(); + Assert.Equal(0, sum7); + var sum8 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (float)o.Money).Sum(); + Assert.Equal(0, sum8); + var sum9 = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => (float?)o.Money).Sum(); + Assert.Equal(0, sum9); + } + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintDataSource("C"); + var sum = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).Sum(); + Assert.Equal(0, sum); + } + + var all = _virtualDbContext.Set().All(o => o.Money <= 321); + Assert.True(all); + var longCount = _virtualDbContext.Set().LongCount(); + Assert.Equal(320, longCount); + } + + [Fact] + public void Order_Max() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var moneyMax = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).Max(); + Assert.Equal(120, moneyMax); + var moneyMax1 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).Max(); + Assert.Equal(120, moneyMax1); + var moneyMax2 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int)o.Money).Max(); + Assert.Equal(120, moneyMax2); + var moneyMax3 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int?)o.Money).Max(); + Assert.Equal(120, moneyMax3); + var moneyMax4 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double)o.Money).Max(); + Assert.Equal(120, moneyMax4); + var moneyMax5 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double?)o.Money).Max(); + Assert.Equal(120, moneyMax5); + var moneyMax6 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float)o.Money).Max(); + Assert.Equal(120, moneyMax6); + var moneyMax7 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float?)o.Money).Max(); + Assert.Equal(120, moneyMax7); + var moneyMax8 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal)o.Money).Max(); + Assert.Equal(120, moneyMax8); + var moneyMax9 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal?)o.Money).Max(); + Assert.Equal(120, moneyMax9); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + try + { + var max = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).Max(); + } + catch (Exception e) + { + Assert.Equal(typeof(InvalidOperationException),e.InnerException.GetType()); + Assert.True(e.InnerException.Message.Contains("contains")); + } + } + } + [Fact] + public void Order_Min() + { + var fourBegin = new DateTime(2021, 4, 1).Date; + var fiveBegin = new DateTime(2021, 5, 1).Date; + var moneyMin = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => o.Money).Min(); + Assert.Equal(90, moneyMin); + var moneyMin1 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (long?)o.Money).Min(); + Assert.Equal(90, moneyMin1); + var moneyMin2 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int)o.Money).Min(); + Assert.Equal(90, moneyMin2); + var moneyMin3 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (int?)o.Money).Min(); + Assert.Equal(90, moneyMin3); + var moneyMin4 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float)o.Money).Min(); + Assert.Equal(90, moneyMin4); + var moneyMin5 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (float?)o.Money).Min(); + Assert.Equal(90, moneyMin5); + var moneyMin6 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double)o.Money).Min(); + Assert.Equal(90, moneyMin6); + var moneyMin7 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (double?)o.Money).Min(); + Assert.Equal(90, moneyMin7); + var moneyMin8 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal)o.Money).Min(); + Assert.Equal(90, moneyMin8); + var moneyMin9 = _virtualDbContext.Set() + .Where(o => o.CreateTime >= fourBegin && o.CreateTime <= fiveBegin).Select(o => (decimal?)o.Money).Min(); + Assert.Equal(90, moneyMin9); + + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("C"); + try + { + var max = _virtualDbContext.Set() + .Where(o => o.CreateTime == fiveBegin).Select(o => o.Money).Min(); + } + catch (Exception e) + { + Assert.Equal(typeof(InvalidOperationException), e.InnerException.GetType()); + Assert.True(e.InnerException.Message.Contains("contains")); + } + } + } + + [Fact] + public void Order_Entity() + { + var x = _virtualDbContext.Set().OrderBy(o => o.Money).LastOrDefault(); + Assert.NotNull(x); + Assert.Equal(319, x.Money); + var x1 = _virtualDbContext.Set().OrderBy(o => o.Money).Last(); + Assert.Equal(x, x1); + var y = _virtualDbContext.Set().OrderBy(o => o.Money).FirstOrDefault(); + Assert.NotNull(y); + Assert.Equal(0, y.Money); + var y1 = _virtualDbContext.Set().OrderBy(o => o.Money).First(); + Assert.Equal(y, y1); + var z = _virtualDbContext.Set().SingleOrDefault(o => o.Money == 13); + var z1 = _virtualDbContext.Set().Single(o => o.Money == 13); + Assert.Equal(z, z1); + } + [Fact] + public void OrderReadWrite() + { + //切换到只读数据库,只读数据库又只配置了A数据源读取B数据源 + _virtualDbContext.ReadWriteSeparationReadOnly(); + var list = _virtualDbContext.Set().Where(o => o.Money == 1).ToList(); + Assert.Equal(2, list.Count); + + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefault(); + Assert.Null(areaB); + } + _virtualDbContext.ReadWriteSeparationReadOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefault(); + Assert.NotNull(areaB); + } + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingReadWriteManager.CreateScope()) + { + _shardingReadWriteManager.GetCurrent().SetReadWriteSeparation(100, true); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefault(); + Assert.NotNull(areaB); + } + } + using (_shardingReadWriteManager.CreateScope()) + { + _shardingReadWriteManager.GetCurrent().SetReadWriteSeparation(100, true); + _virtualDbContext.ReadWriteSeparationWriteOnly(); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefault(); + Assert.Null(areaB); + } + } + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustDataSource("A"); + var areaB = _virtualDbContext.Set().Where(o => o.Area == "B").FirstOrDefault(); + Assert.Null(areaB); + } + } + [Fact] + public void LogWeekDateTimeCountTest() + { + var countAsync = _virtualDbContext.Set().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("20210419_25"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(7, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("20210419_25", "20210426_02"); + var countAsync2 = _virtualDbContext.Set().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().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().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().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().Where(o => o.LogTime >= fourBegin && o.LogTime < fiveBegin).Count(); + Assert.Equal(30, fourCount); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddMustTail("2020"); + var countAsync1 = _virtualDbContext.Set().Count(); + Assert.Equal(366, countAsync1); + } + Assert.Null(_shardingRouteManager.Current); + using (_shardingRouteManager.CreateScope()) + { + _shardingRouteManager.Current.TryCreateOrAddHintTail("2021"); + var countAsync2 = _virtualDbContext.Set().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().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().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 Group_API_Test() + // { + // var ids = new[] {"200", "300"}; + // var dateOfMonths = new[] {202111, 202110}; + // var group = _virtualDbContext.Set() + // .Where(o => ids.Contains(o.UserId) && dateOfMonths.Contains(o.DateOfMonth)) + // .ShardingGroupBy(g => new {UId = g.UserId}, g => 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) + // }); + // Assert.Equal(2, group.Count); + // Assert.Equal(2, group[0].Count); + // Assert.Equal(2260000, group[0].TotalSalary); + // Assert.Equal(1130000, group[0].AvgSalary); + // Assert.Equal(11300, group[0].AvgSalaryDecimal); + // Assert.Equal(1120000, group[0].MinSalary); + // Assert.Equal(1140000, group[0].MaxSalary); + // } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/LogDayVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/LogDayVirtualTableRoute.cs new file mode 100644 index 00000000..540770ed --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/LogDayVirtualTableRoute.cs @@ -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 + { + protected override bool EnableHintRoute => true; + + public override DateTime GetBeginTime() + { + return new DateTime(2021, 1, 1); + } + + + public override void Configure(EntityMetadataTableBuilder builder) + { + builder.ShardingProperty(o => o.LogTime); + builder.TableSeparator(string.Empty); + } + + public override IPaginationConfiguration CreatePaginationConfiguration() + { + return new LogDayPaginationConfiguration(); + } + + public override bool AutoCreateTableByTime() + { + return true; + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/LogWeekDateTimeVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/LogWeekDateTimeVirtualTableRoute.cs new file mode 100644 index 00000000..a630caf0 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/LogWeekDateTimeVirtualTableRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/LogWeekTimeLongVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/LogWeekTimeLongVirtualTableRoute.cs new file mode 100644 index 00000000..226b9fb5 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/LogWeekTimeLongVirtualTableRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/LogYearDateTimeVirtualRoute.cs b/test/ShardingCore.Test2x/Shardings/LogYearDateTimeVirtualRoute.cs new file mode 100644 index 00000000..a77b526e --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/LogYearDateTimeVirtualRoute.cs @@ -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 + { + 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 builder) + { + builder.ShardingProperty(o => o.LogTime); + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/OrderAreaShardingVirtualDataSourceRoute.cs b/test/ShardingCore.Test2x/Shardings/OrderAreaShardingVirtualDataSourceRoute.cs new file mode 100644 index 00000000..011a8534 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/OrderAreaShardingVirtualDataSourceRoute.cs @@ -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 + { + protected override bool EnableHintRoute =>true; + + private readonly List _dataSources = new List() + { + "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 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> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator) + { + + var t = ShardingKeyToDataSourceName(shardingKey); + switch (shardingOperator) + { + case ShardingOperatorEnum.Equal: return tail => tail == t; + default: + { + return tail => true; + } + } + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/OrderCreateTimeVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/OrderCreateTimeVirtualTableRoute.cs new file mode 100644 index 00000000..6af65945 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/OrderCreateTimeVirtualTableRoute.cs @@ -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 + { + public override DateTime GetBeginTime() + { + return new DateTime(2021, 1, 1); + } + + public override List GetAllTails() + { + var allTails = base.GetAllTails(); + allTails.Add("202112"); + return allTails; + } + + public override void Configure(EntityMetadataTableBuilder builder) + { + + } + + public override IPaginationConfiguration CreatePaginationConfiguration() + { + return new OrderCreateTimePaginationConfiguration(); + } + public override bool AutoCreateTableByTime() + { + return true; + } + } + + public class OrderCreateTimePaginationConfiguration : IPaginationConfiguration + { + public void Configure(PaginationBuilder builder) + { + builder.PaginationSequence(o => o.CreateTime) + .UseQueryMatch(PaginationMatchEnum.Owner | PaginationMatchEnum.Named | PaginationMatchEnum.PrimaryMatch) + .UseAppendIfOrderNone().UseRouteComparer(Comparer.Default); + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/PaginationConfigs/LogDayPaginationConfiguration.cs b/test/ShardingCore.Test2x/Shardings/PaginationConfigs/LogDayPaginationConfiguration.cs new file mode 100644 index 00000000..81dde835 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/PaginationConfigs/LogDayPaginationConfiguration.cs @@ -0,0 +1,15 @@ +using ShardingCore.Sharding.PaginationConfigurations; +using ShardingCore.Test2x.Domain.Entities; + +namespace ShardingCore.Test2x.Shardings.PaginationConfigs +{ + public class LogDayPaginationConfiguration: IPaginationConfiguration + { + public void Configure(PaginationBuilder builder) + { + builder.PaginationSequence(o => o.LogTime) + .UseQueryMatch(PaginationMatchEnum.Named | PaginationMatchEnum.Owner | + PaginationMatchEnum.PrimaryMatch); + } + } +} diff --git a/test/ShardingCore.Test2x/Shardings/SysUserModVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/SysUserModVirtualTableRoute.cs new file mode 100644 index 00000000..5b16baa3 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/SysUserModVirtualTableRoute.cs @@ -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 + { + protected override bool EnableHintRoute => true; + + public SysUserModVirtualTableRoute() : base(2,3) + { + } + + public override void Configure(EntityMetadataTableBuilder builder) + { + builder.ShardingProperty(o => o.Id); + builder.TableSeparator("_"); + } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/Shardings/SysUserSalaryVirtualTableRoute.cs b/test/ShardingCore.Test2x/Shardings/SysUserSalaryVirtualTableRoute.cs new file mode 100644 index 00000000..1f21b844 --- /dev/null +++ b/test/ShardingCore.Test2x/Shardings/SysUserSalaryVirtualTableRoute.cs @@ -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 + { + 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 GetAllTails() + { + var beginTime = new DateTime(2020, 1, 1); + var endTime = new DateTime(2021, 12, 1); + var list = new List(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> 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 builder) + { + builder.ShardingProperty(o => o.DateOfMonth); + } + } +} \ No newline at end of file diff --git a/test/ShardingCore.Test2x/Startup.cs b/test/ShardingCore.Test2x/Startup.cs new file mode 100644 index 00000000..474f54b7 --- /dev/null +++ b/test/ShardingCore.Test2x/Startup.cs @@ -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((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() + { + { "B", "Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;" }, + { "C", "Data Source=localhost;Initial Catalog=ShardingCoreDBC;Integrated Security=True;" }, + }; + }) + .AddShardingDataSourceRoute(o => + { + o.AddShardingDatabaseRoute(); + }) + .AddShardingTableRoute(op => + { + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + op.AddShardingTableRoute(); + }).AddReadWriteSeparation(sp => + { + return new Dictionary>() + { + { + "A", new HashSet() + { + "Data Source=localhost;Initial Catalog=ShardingCoreDBB;Integrated Security=True;" + } + } + }; + },ReadStrategyEnum.Loop,readConnStringGetStrategy:ReadConnStringGetStrategyEnum.LatestEveryTime).End(); + // services.AddShardingDbContext(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(); + // op.AddShardingTableRoute(); + // }); + } + + // 可以添加要用到的方法参数,会自动从注册的服务中获取服务实例,类似于 asp.net core 里 Configure 方法 + public void Configure(IServiceProvider serviceProvider) + { + var shardingBootstrapper = serviceProvider.GetService(); + shardingBootstrapper.Start(); + // 有一些测试数据要初始化可以放在这里 + InitData(serviceProvider).GetAwaiter().GetResult(); + } + + /// + /// 添加种子数据 + /// + /// + /// + private async Task InitData(IServiceProvider serviceProvider) + { + using (var scope = serviceProvider.CreateScope()) + { + var virtualDbContext = scope.ServiceProvider.GetService(); + if (!await virtualDbContext.Set().AnyAsync()) + { + var ids = Enumerable.Range(1, 1000); + var userMods = new List(); + var userSalaries = new List(); + 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(){"A","B","C"}; + List orders = new List(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 logDays = new List(3600); + + var levels = new List(){"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 logWeeks = new List(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 logWeekLongs = new List(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 logYears = new List(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(); + } + } + } + } + } +} \ No newline at end of file