[#72]修复自动建表bug,并且添加单元测试发布x.3.1.55

This commit is contained in:
xuejiaming 2021-11-29 08:38:33 +08:00
parent 647c1d4678
commit ada3b5f124
96 changed files with 8289 additions and 33 deletions

View File

@ -1,9 +1,9 @@
:start :start
::定义版本 ::定义版本
set EFCORE2=2.3.1.54 set EFCORE2=2.3.1.55
set EFCORE3=3.3.1.54 set EFCORE3=3.3.1.55
set EFCORE5=5.3.1.54 set EFCORE5=5.3.1.55
set EFCORE6=6.3.1.54 set EFCORE6=6.3.1.55
::删除所有bin与obj下的文件 ::删除所有bin与obj下的文件
@echo off @echo off

View File

@ -164,6 +164,7 @@ namespace ShardingCore.Bootstrapers
{ {
try try
{ {
//添加物理表 //添加物理表
virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail)); virtualTable.AddPhysicTable(new DefaultPhysicTable(virtualTable, tail));
_tableCreator.CreateTable(dataSourceName, entityMetadata.EntityType, tail); _tableCreator.CreateTable(dataSourceName, entityMetadata.EntityType, tail);

View File

@ -3,14 +3,14 @@ using System.Collections.Generic;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails; using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails;
using ShardingCore.Extensions; using ShardingCore.Extensions;
namespace ShardingCore.Sharding.ShardingDbContextExecutors
{
/* /*
* @Author: xjm * @Author: xjm
* @Description: * @Description:
* @Date: Sunday, 28 November 2021 21:47:38 * @Date: Sunday, 28 November 2021 21:47:38
* @Email: 326308290@qq.com * @Email: 326308290@qq.com
*/ */
namespace ShardingCore.Sharding.ShardingDbContextExecutors
{
public class NoShardingFirstComparer:IComparer<string> public class NoShardingFirstComparer:IComparer<string>
{ {
private readonly string _defaultTail; private readonly string _defaultTail;

View File

@ -3,6 +3,8 @@ using ShardingCore.VirtualRoutes.Abstractions;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq.Expressions; using System.Linq.Expressions;
using ShardingCore.Core.PhysicTables;
using ShardingCore.Core.VirtualTables;
namespace ShardingCore.VirtualRoutes.Days namespace ShardingCore.VirtualRoutes.Days
{ {
@ -20,7 +22,8 @@ namespace ShardingCore.VirtualRoutes.Days
/// <returns></returns> /// <returns></returns>
public abstract DateTime GetBeginTime(); public abstract DateTime GetBeginTime();
/// <summary> /// <summary>
/// return all tails in database /// 这个方法会在程序启动的时候被调用,后续整个生命周期将不会被调用,仅用来告诉框架启动的时候有多少张TEntity对象的后缀表,
/// 然后会在启动的时候添加到 <see cref="IVirtualTable{TEntity}.AddPhysicTable(IPhysicTable physicTable)"/>
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public override List<string> GetAllTails() public override List<string> GetAllTails()

View File

@ -164,7 +164,7 @@ namespace ShardingCore.Test
{ {
dics.Add(tail, null); dics.Add(tail, null);
} }
Assert.Equal(",a,b", string.Join(",", dics.Keys)); Assert.Equal($"{emptyTailIdentity},{aTailIdentity},{bTailIdentity}", string.Join(",", dics.Keys));
} }
} }

View File

@ -4,6 +4,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Helpers;
using ShardingCore.Test.Domain.Entities; using ShardingCore.Test.Domain.Entities;
using ShardingCore.VirtualRoutes.Days; using ShardingCore.VirtualRoutes.Days;
@ -27,5 +28,25 @@ namespace ShardingCore.Test.Shardings
{ {
return new DateTime(2021, 1, 1); return new DateTime(2021, 1, 1);
} }
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var currentTimeStampLong = ShardingCoreHelper.ConvertDateTimeToLong(currentTimeStamp);
var tail = TimeFormatToTail(currentTimeStampLong);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
} }
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations; using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test.Domain.Entities; using ShardingCore.Test.Domain.Entities;
@ -32,5 +33,24 @@ namespace ShardingCore.Test.Shardings
{ {
return true; return true;
} }
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
} }
} }

View File

@ -37,11 +37,8 @@ namespace ShardingCore.Test
o.UseSqlServer(conn).UseLoggerFactory(efLogger)) o.UseSqlServer(conn).UseLoggerFactory(efLogger))
.Begin(o => .Begin(o =>
{ {
#if DEBUG
o.CreateShardingTableOnStart = true; o.CreateShardingTableOnStart = true;
o.EnsureCreatedWithOutShardingTable = true; o.EnsureCreatedWithOutShardingTable = true;
#endif
o.AutoTrackEntity = true; o.AutoTrackEntity = true;
}) })
.AddShardingTransaction((connection, builder) => .AddShardingTransaction((connection, builder) =>

View File

@ -10,6 +10,7 @@ using ShardingCore.Core.QueryRouteManagers.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources; using ShardingCore.Core.VirtualDatabase.VirtualDataSources;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.PhysicDataSources; using ShardingCore.Core.VirtualDatabase.VirtualDataSources.PhysicDataSources;
using ShardingCore.Core.VirtualDatabase.VirtualTables; using ShardingCore.Core.VirtualDatabase.VirtualTables;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails;
using ShardingCore.Exceptions; using ShardingCore.Exceptions;
using ShardingCore.Extensions; using ShardingCore.Extensions;
using ShardingCore.Extensions.ShardingPageExtensions; using ShardingCore.Extensions.ShardingPageExtensions;
@ -17,6 +18,7 @@ using ShardingCore.Helpers;
using ShardingCore.Sharding; using ShardingCore.Sharding;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions; using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
using ShardingCore.Sharding.ShardingComparision.Abstractions; using ShardingCore.Sharding.ShardingComparision.Abstractions;
using ShardingCore.Sharding.ShardingDbContextExecutors;
using ShardingCore.TableCreator; using ShardingCore.TableCreator;
using ShardingCore.Test2x.Domain.Entities; using ShardingCore.Test2x.Domain.Entities;
using Xunit; using Xunit;
@ -150,6 +152,21 @@ namespace ShardingCore.Test2x
var virtualTable = _virtualTableManager.GetVirtualTable<SysUserMod>(); var virtualTable = _virtualTableManager.GetVirtualTable<SysUserMod>();
Assert.NotNull(virtualTable); Assert.NotNull(virtualTable);
var emptyTailIdentity = new SingleQueryRouteTail(string.Empty).GetRouteTailIdentity();
var aTailIdentity = new SingleQueryRouteTail("a").GetRouteTailIdentity();
var bTailIdentity = new SingleQueryRouteTail("b").GetRouteTailIdentity();
var dics = new SortedDictionary<string, string>(new NoShardingFirstComparer());
var dicTails = new List<string>() { emptyTailIdentity, aTailIdentity, bTailIdentity };
for (int i = 0; i < 10; i++)
{
dics.Clear();
var reOrderList = dicTails.OrderBy(o => Guid.NewGuid()).ToList();
foreach (var tail in reOrderList)
{
dics.Add(tail, null);
}
Assert.Equal($"{emptyTailIdentity},{aTailIdentity},{bTailIdentity}", string.Join(",", dics.Keys));
}
} }
public class SequenceClass public class SequenceClass

View File

@ -1,5 +1,7 @@
using System; using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Helpers;
using ShardingCore.Test2x.Domain.Entities; using ShardingCore.Test2x.Domain.Entities;
using ShardingCore.VirtualRoutes.Days; using ShardingCore.VirtualRoutes.Days;
@ -23,5 +25,24 @@ namespace ShardingCore.Test2x.Shardings
{ {
return new DateTime(2021, 1, 1); return new DateTime(2021, 1, 1);
} }
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021, 11, 20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var currentTimeStampLong = ShardingCoreHelper.ConvertDateTimeToLong(currentTimeStamp);
var tail = TimeFormatToTail(currentTimeStampLong);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
} }
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations; using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test2x.Domain.Entities; using ShardingCore.Test2x.Domain.Entities;
@ -32,5 +33,23 @@ namespace ShardingCore.Test2x.Shardings
{ {
return true; return true;
} }
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021, 11, 20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
} }
} }

View File

@ -37,11 +37,6 @@ namespace ShardingCore.Test2x
o.UseSqlServer(conn).UseLoggerFactory(efLogger)) o.UseSqlServer(conn).UseLoggerFactory(efLogger))
.Begin(o => .Begin(o =>
{ {
#if DEBUG
//o.CreateShardingTableOnStart = true;
//o.EnsureCreatedWithOutShardingTable = true;
#endif
o.AutoTrackEntity = true; o.AutoTrackEntity = true;
}) })
.AddShardingTransaction((connection, builder) => .AddShardingTransaction((connection, builder) =>

View File

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test3x.Domain.Entities
{
public class LogDayLong
{
public Guid Id { get; set; }
public string LogLevel { get; set; }
public string LogBody { get; set; }
public long LogTime { get; set; }
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test3x.Domain.Entities
{
public class SysUserModInt
{
/// <summary>
/// 用户Id用于分表
/// </summary>
public int Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
public int Age { get; set; }
public int AgeGroup { get; set; }
}
}

View File

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

View File

@ -0,0 +1,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.Test3x.Domain.Entities;
namespace ShardingCore.Test3x.Domain.Maps
{
public class LogDayLongMap:IEntityTypeConfiguration<LogDayLong>
{
public void Configure(EntityTypeBuilder<LogDayLong> 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(LogDayLong));
}
}
}

View File

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

View File

@ -0,0 +1,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.Test3x.Domain.Entities;
namespace ShardingCore.Test3x.Domain.Maps
{
public class LogMonthLongMap:IEntityTypeConfiguration<LogMonthLong>
{
public void Configure(EntityTypeBuilder<LogMonthLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogMonthLong));
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,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.Test3x.Domain.Entities;
namespace ShardingCore.Test3x.Domain.Maps
{
public class LogWeekTimeLongMap : IEntityTypeConfiguration<LogWeekTimeLong>
{
public void Configure(EntityTypeBuilder<LogWeekTimeLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekTimeLong));
}
}
}

View File

@ -0,0 +1,22 @@

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

View File

@ -0,0 +1,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.Test3x.Domain.Entities;
namespace ShardingCore.Test3x.Domain.Maps
{
public class LogYearLongMap:IEntityTypeConfiguration<LogYearLong>
{
public void Configure(EntityTypeBuilder<LogYearLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.LogBody).HasMaxLength(128);
builder.ToTable(nameof(LogYearLong));
}
}
}

View File

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

View File

@ -0,0 +1,23 @@
using 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.Test3x.Domain.Entities;
namespace ShardingCore.Test3x.Domain.Maps
{
public class SysUserModIntMap:IEntityTypeConfiguration<SysUserModInt>
{
public void Configure(EntityTypeBuilder<SysUserModInt> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).ValueGeneratedNever();
builder.Property(o => o.Name).HasMaxLength(128);
builder.ToTable(nameof(SysUserModInt));
}
}
}

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Helpers;
using ShardingCore.Test3x.Domain.Entities;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test3x.Shardings
{
public class LogDayLongVirtualRoute:AbstractSimpleShardingDayKeyLongVirtualTableRoute<LogDayLong>
{
protected override bool EnableHintRoute => true;
public override void Configure(EntityMetadataTableBuilder<LogDayLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var currentTimeStampLong = ShardingCoreHelper.ConvertDateTimeToLong(currentTimeStamp);
var tail = TimeFormatToTail(currentTimeStampLong);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test3x.Domain.Entities;
using ShardingCore.Test3x.Shardings.PaginationConfigs;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test3x.Shardings
{
public class LogDayVirtualTableRoute:AbstractSimpleShardingDayKeyDateTimeVirtualTableRoute<LogDay>
{
protected override bool EnableHintRoute => true;
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogDay> builder)
{
builder.ShardingProperty(o => o.LogTime);
builder.TableSeparator(string.Empty);
}
public override IPaginationConfiguration<LogDay> CreatePaginationConfiguration()
{
return new LogDayPaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test3x.Domain.Entities;
using ShardingCore.VirtualRoutes.Mods;
namespace ShardingCore.Test3x.Shardings
{
public class SysUserModIntVirtualRoute:AbstractSimpleShardingModKeyIntVirtualTableRoute<SysUserModInt>
{
protected override bool EnableHintRoute => true;
public SysUserModIntVirtualRoute() : base(2, 3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserModInt> builder)
{
builder.ShardingProperty(o => o.Id);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test5x.Domain.Entities
{
public class LogDayLong
{
public Guid Id { get; set; }
public string LogLevel { get; set; }
public string LogBody { get; set; }
public long LogTime { get; set; }
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShardingCore.Test5x.Domain.Entities
{
public class SysUserModInt
{
/// <summary>
/// 用户Id用于分表
/// </summary>
public int Id { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
public int Age { get; set; }
public int AgeGroup { get; set; }
}
}

View File

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

View File

@ -0,0 +1,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.Test5x.Domain.Entities;
namespace ShardingCore.Test5x.Domain.Maps
{
public class LogDayLongMap:IEntityTypeConfiguration<LogDayLong>
{
public void Configure(EntityTypeBuilder<LogDayLong> 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(LogDayLong));
}
}
}

View File

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

View File

@ -0,0 +1,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.Test5x.Domain.Entities;
namespace ShardingCore.Test5x.Domain.Maps
{
public class LogMonthLongMap:IEntityTypeConfiguration<LogMonthLong>
{
public void Configure(EntityTypeBuilder<LogMonthLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogMonthLong));
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,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.Test5x.Domain.Entities;
namespace ShardingCore.Test5x.Domain.Maps
{
public class LogWeekTimeLongMap : IEntityTypeConfiguration<LogWeekTimeLong>
{
public void Configure(EntityTypeBuilder<LogWeekTimeLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.Body).HasMaxLength(128);
builder.ToTable(nameof(LogWeekTimeLong));
}
}
}

View File

@ -0,0 +1,22 @@

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

View File

@ -0,0 +1,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.Test5x.Domain.Entities;
namespace ShardingCore.Test5x.Domain.Maps
{
public class LogYearLongMap:IEntityTypeConfiguration<LogYearLong>
{
public void Configure(EntityTypeBuilder<LogYearLong> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).IsRequired().IsUnicode(false).HasMaxLength(50);
builder.Property(o => o.LogBody).HasMaxLength(128);
builder.ToTable(nameof(LogYearLong));
}
}
}

View File

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

View File

@ -0,0 +1,23 @@
using 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.Test5x.Domain.Entities;
namespace ShardingCore.Test5x.Domain.Maps
{
public class SysUserModIntMap:IEntityTypeConfiguration<SysUserModInt>
{
public void Configure(EntityTypeBuilder<SysUserModInt> builder)
{
builder.HasKey(o => o.Id);
builder.Property(o => o.Id).ValueGeneratedNever();
builder.Property(o => o.Name).HasMaxLength(128);
builder.ToTable(nameof(SysUserModInt));
}
}
}

View File

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

View File

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

View File

@ -4,9 +4,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net5.0</TargetFramework>
<LangVersion>9.0</LangVersion> <LangVersion>9.0</LangVersion>
<DefineConstants>TRACE;DEBUG;EFCORE5Test;</DefineConstants>
<AssemblyName>ShardingCore.Test</AssemblyName>
<RootNamespace>ShardingCore.Test</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -22,12 +19,6 @@
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Include="..\ShardingCore.Test\**\*.cs" />
<Compile Remove="..\ShardingCore.Test\obj\**" />
<Compile Remove="..\ShardingCore.Test\bin\**" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src5x\ShardingCore.5x\ShardingCore.5x.csproj" /> <ProjectReference Include="..\..\src5x\ShardingCore.5x\ShardingCore.5x.csproj" />
</ItemGroup> </ItemGroup>

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Helpers;
using ShardingCore.Test5x.Domain.Entities;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test5x.Shardings
{
public class LogDayLongVirtualRoute:AbstractSimpleShardingDayKeyLongVirtualTableRoute<LogDayLong>
{
protected override bool EnableHintRoute => true;
public override void Configure(EntityMetadataTableBuilder<LogDayLong> builder)
{
builder.ShardingProperty(o => o.LogTime);
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var currentTimeStampLong = ShardingCoreHelper.ConvertDateTimeToLong(currentTimeStamp);
var tail = TimeFormatToTail(currentTimeStampLong);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Sharding.PaginationConfigurations;
using ShardingCore.Test5x.Domain.Entities;
using ShardingCore.Test5x.Shardings.PaginationConfigs;
using ShardingCore.VirtualRoutes.Days;
namespace ShardingCore.Test5x.Shardings
{
public class LogDayVirtualTableRoute:AbstractSimpleShardingDayKeyDateTimeVirtualTableRoute<LogDay>
{
protected override bool EnableHintRoute => true;
public override DateTime GetBeginTime()
{
return new DateTime(2021, 1, 1);
}
public override void Configure(EntityMetadataTableBuilder<LogDay> builder)
{
builder.ShardingProperty(o => o.LogTime);
builder.TableSeparator(string.Empty);
}
public override IPaginationConfiguration<LogDay> CreatePaginationConfiguration()
{
return new LogDayPaginationConfiguration();
}
public override bool AutoCreateTableByTime()
{
return true;
}
public override List<string> GetAllTails()
{
var beginTime = GetBeginTime().Date;
var tails = new List<string>();
//提前创建表
var nowTimeStamp = new DateTime(2021,11,20).Date;
if (beginTime > nowTimeStamp)
throw new ArgumentException("begin time error");
var currentTimeStamp = beginTime;
while (currentTimeStamp <= nowTimeStamp)
{
var tail = ShardingKeyToTail(currentTimeStamp);
tails.Add(tail);
currentTimeStamp = currentTimeStamp.AddDays(1);
}
return tails;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Test5x.Domain.Entities;
using ShardingCore.VirtualRoutes.Mods;
namespace ShardingCore.Test5x.Shardings
{
public class SysUserModIntVirtualRoute:AbstractSimpleShardingModKeyIntVirtualTableRoute<SysUserModInt>
{
protected override bool EnableHintRoute => true;
public SysUserModIntVirtualRoute() : base(2, 3)
{
}
public override void Configure(EntityMetadataTableBuilder<SysUserModInt> builder)
{
builder.ShardingProperty(o => o.Id);
}
}
}

View File

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

View File

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

View File

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