From 441f0dbca31093263903ddc9cc1c815d9c6be6b0 Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Wed, 19 Oct 2022 22:31:09 +0800 Subject: [PATCH 1/3] [#209] --- .../MergeContexts/QueryableRewriteEngine.cs | 9 +++++++++ .../Sharding/ParseEngines/ParseEngine.cs | 15 --------------- 2 files changed, 9 insertions(+), 15 deletions(-) delete mode 100644 src/ShardingCore/Sharding/ParseEngines/ParseEngine.cs diff --git a/src/ShardingCore/Sharding/MergeContexts/QueryableRewriteEngine.cs b/src/ShardingCore/Sharding/MergeContexts/QueryableRewriteEngine.cs index cf848b6d..88ce737d 100644 --- a/src/ShardingCore/Sharding/MergeContexts/QueryableRewriteEngine.cs +++ b/src/ShardingCore/Sharding/MergeContexts/QueryableRewriteEngine.cs @@ -59,6 +59,15 @@ namespace ShardingCore.Sharding.MergeContexts var orders = orderByContext.PropertyOrders; var combineQueryable = mergeQueryCompilerContext.GetQueryCombineResult().GetCombineQueryable(); + + if (skip is < 0) + { + throw new ShardingCoreException($"queryable:{mergeQueryCompilerContext.GetQueryCombineResult().GetQueryCompilerContext().GetQueryExpression().ShardingPrint()} skip should >= 0"); + } + if (take is < 0) + { + throw new ShardingCoreException($"queryable:{mergeQueryCompilerContext.GetQueryCombineResult().GetQueryCompilerContext().GetQueryExpression().ShardingPrint()} take should >= 0"); + } //去除分页,获取前Take+Skip数量 var reWriteQueryable = combineQueryable; if (take.HasValue || skip.HasValue) diff --git a/src/ShardingCore/Sharding/ParseEngines/ParseEngine.cs b/src/ShardingCore/Sharding/ParseEngines/ParseEngine.cs deleted file mode 100644 index 0138bc5c..00000000 --- a/src/ShardingCore/Sharding/ParseEngines/ParseEngine.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -/* -* @Author: xjm -* @Description: -* @Date: DATE TIME -* @Email: 326308290@qq.com -*/ -namespace ShardingCore.Sharding.ParseEngines -{ - public class ParseEngine - { - - } -} \ No newline at end of file From 5eebc2aba249203c689384fe6c10fa6f80a8c2f2 Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Wed, 19 Oct 2022 23:13:20 +0800 Subject: [PATCH 2/3] [#208] --- samples/Sample.MySql/Startup.cs | 1 - samples/Sample.ShardingConsole/Program.cs | 1 - .../Bootstrappers/IShardingBootstrapper.cs | 2 +- .../Bootstrappers/ShardingBootstrapper.cs | 30 +-------------- .../ActivatorDbContextCreator.cs | 12 +++++- .../IShardingRuntimeContext.cs | 3 -- .../RuntimeContexts/ShardingRuntimeContext.cs | 38 ++----------------- .../Extensions/ShardingRuntimeExtension.cs | 7 +--- .../ParallelControl/DoOnlyOnce.cs | 2 +- .../ShardingExecutors/CustomerQueryScope.cs | 5 +-- .../DefaultShardingCompilerExecutor.cs | 1 - src/ShardingCore/ShardingCoreExtension.cs | 5 +-- ...dingAutoCreateOperatorVirtualTableRoute.cs | 32 +++++++++------- 13 files changed, 40 insertions(+), 99 deletions(-) diff --git a/samples/Sample.MySql/Startup.cs b/samples/Sample.MySql/Startup.cs index c60a7b3b..ea292331 100644 --- a/samples/Sample.MySql/Startup.cs +++ b/samples/Sample.MySql/Startup.cs @@ -179,7 +179,6 @@ namespace Sample.MySql { app.UseDeveloperExceptionPage(); } - app.ApplicationServices.UseAutoShardingCreate(); // app.ApplicationServices.UseAutoTryCompensateTable(); // app.ApplicationServices.UseAutoShardingCreate(); diff --git a/samples/Sample.ShardingConsole/Program.cs b/samples/Sample.ShardingConsole/Program.cs index e31aa330..8ebf8ef6 100644 --- a/samples/Sample.ShardingConsole/Program.cs +++ b/samples/Sample.ShardingConsole/Program.cs @@ -5,7 +5,6 @@ using Sample.ShardingConsole; using ShardingCore; using ShardingCore.Extensions; -ShardingProvider.ShardingRuntimeContext.UseAutoShardingCreate(); ShardingProvider.ShardingRuntimeContext.UseAutoTryCompensateTable(); var dbContextOptionsBuilder = new DbContextOptionsBuilder(); diff --git a/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs b/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs index 886cbb39..d27b2e78 100644 --- a/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs @@ -10,7 +10,7 @@ namespace ShardingCore.Bootstrappers /// 主要的分片初始化器,需要手动调用,如果你的分片路由存在定时执行的job譬如 /// 系统默认的时间分片的情况下那么需要调用IShardingRuntimeContext初始化的时候会调用 /// - public interface IShardingBootstrapper + internal interface IShardingBootstrapper { void AutoShardingCreate(); } diff --git a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs index 777073ed..8e82a374 100644 --- a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs @@ -25,21 +25,18 @@ namespace ShardingCore.Bootstrappers * @Date: Monday, 21 December 2020 09:10:07 * @Email: 326308290@qq.com */ - public class ShardingBootstrapper : IShardingBootstrapper + internal class ShardingBootstrapper : IShardingBootstrapper { private readonly IShardingProvider _shardingProvider; - private readonly IDbContextCreator _dbContextCreator; private readonly DoOnlyOnce _onlyOnce=new DoOnlyOnce(); - public ShardingBootstrapper(IShardingProvider shardingProvider,IDbContextCreator dbContextCreator) + public ShardingBootstrapper(IShardingProvider shardingProvider) { _shardingProvider = shardingProvider; - _dbContextCreator = dbContextCreator; } public void AutoShardingCreate() { if (!_onlyOnce.IsUnDo()) return; - CheckRequirement(); StartAutoShardingJob(); } @@ -51,29 +48,6 @@ namespace ShardingCore.Bootstrappers await jobRunnerService.StartAsync(); }, TaskCreationOptions.LongRunning); } - private void CheckRequirement() - { - try - { - using (var scope = _shardingProvider.CreateScope()) - { - using (var dbContext = _dbContextCreator.GetShellDbContext(scope.ServiceProvider)) - { - if (dbContext == null) - { - throw new ShardingCoreInvalidOperationException( - $"cant get shell db context,plz override {nameof(IDbContextCreator)}.{nameof(IDbContextCreator.GetShellDbContext)}"); - } - } - } - } - catch (Exception ex) - { - throw new ShardingCoreInvalidOperationException( - $"cant get shell db context,plz override {nameof(IDbContextCreator)}.{nameof(IDbContextCreator.GetShellDbContext)}", - ex); - } - } } } \ No newline at end of file diff --git a/src/ShardingCore/Core/DbContextCreator/ActivatorDbContextCreator.cs b/src/ShardingCore/Core/DbContextCreator/ActivatorDbContextCreator.cs index 67a322ff..c033f74b 100644 --- a/src/ShardingCore/Core/DbContextCreator/ActivatorDbContextCreator.cs +++ b/src/ShardingCore/Core/DbContextCreator/ActivatorDbContextCreator.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ShardingCore.Core.ServiceProviders; +using ShardingCore.Exceptions; using ShardingCore.Helpers; using ShardingCore.Sharding.Abstractions; @@ -46,7 +47,16 @@ namespace ShardingCore.Core.DbContextCreator public virtual DbContext GetShellDbContext(IShardingProvider shardingProvider) { - return shardingProvider.GetService(); + try + { + return shardingProvider.GetService(); + } + catch (Exception ex) + { + throw new ShardingCoreInvalidOperationException( + $"cant get shell db context,plz override {nameof(IDbContextCreator)}.{nameof(IDbContextCreator.GetShellDbContext)}", + ex); + } } } } diff --git a/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContext.cs b/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContext.cs index 14cda773..4b1662dd 100644 --- a/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContext.cs +++ b/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContext.cs @@ -56,11 +56,8 @@ namespace ShardingCore.Core.RuntimeContexts IShardingPageManager GetShardingPageManager(); IDataSourceInitializer GetDataSourceInitializer(); - void CheckRequirement(); - void GetOrCreateShardingRuntimeModel(DbContext dbContext); void Initialize(); - void AutoShardingCreate(); object GetService(Type serviceType); TService GetService(); object GetRequiredService(Type serviceType); diff --git a/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContext.cs b/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContext.cs index c37a3f43..75e32072 100644 --- a/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContext.cs +++ b/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContext.cs @@ -23,6 +23,7 @@ using ShardingCore.DynamicDataSources; using ShardingCore.Exceptions; using ShardingCore.Sharding.Abstractions; +using ShardingCore.Sharding.MergeEngines.ParallelControl; using ShardingCore.Sharding.ParallelTables; using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions; using ShardingCore.Sharding.ShardingComparision.Abstractions; @@ -67,10 +68,11 @@ namespace ShardingCore.Core.RuntimeContexts _serviceProvider = _serviceMap.BuildServiceProvider(); _serviceProvider.GetRequiredService().Initialize(); InitFieldValue(); + AutoShardingCreate(); } } - public void AutoShardingCreate() + private void AutoShardingCreate() { GetRequiredService().AutoShardingCreate(); } @@ -217,40 +219,6 @@ namespace ShardingCore.Core.RuntimeContexts return _dataSourceInitializer??=GetRequiredService(); } - public void CheckRequirement() - { - if (isCheckRequirement) - return; - - lock (CHECK_REQUIREMENT) - { - if (isCheckRequirement) - return; - isCheckRequirement = true; - - try - { - var shardingProvider = GetShardingProvider(); - using (var scope = shardingProvider.CreateScope()) - { - using (var dbContext = _dbContextCreator.GetShellDbContext(scope.ServiceProvider)) - { - if (dbContext == null) - { - throw new ShardingCoreInvalidOperationException( - $"cant get shell db context,plz override {nameof(IDbContextCreator)}.{nameof(IDbContextCreator.GetShellDbContext)}"); - } - } - } - } - catch (Exception ex) - { - throw new ShardingCoreInvalidOperationException( - $"cant get shell db context,plz override {nameof(IDbContextCreator)}.{nameof(IDbContextCreator.GetShellDbContext)}", - ex); - } - } - } public void GetOrCreateShardingRuntimeModel(DbContext dbContext) { diff --git a/src/ShardingCore/Extensions/ShardingRuntimeExtension.cs b/src/ShardingCore/Extensions/ShardingRuntimeExtension.cs index 1ffbdda8..a21c5ed6 100644 --- a/src/ShardingCore/Extensions/ShardingRuntimeExtension.cs +++ b/src/ShardingCore/Extensions/ShardingRuntimeExtension.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -10,11 +11,6 @@ namespace ShardingCore.Extensions public static class ShardingRuntimeExtension { - public static void UseAutoShardingCreate(this IShardingRuntimeContext shardingRuntimeContext) - { - shardingRuntimeContext.CheckRequirement(); - shardingRuntimeContext.AutoShardingCreate(); - } /// /// 自动尝试补偿表 /// @@ -22,7 +18,6 @@ namespace ShardingCore.Extensions /// public static void UseAutoTryCompensateTable(this IShardingRuntimeContext shardingRuntimeContext, int? parallelCount = null) { - shardingRuntimeContext.CheckRequirement(); var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); var dataSourceInitializer = shardingRuntimeContext.GetDataSourceInitializer(); var shardingConfigOptions = shardingRuntimeContext.GetShardingConfigOptions(); diff --git a/src/ShardingCore/Sharding/MergeEngines/ParallelControl/DoOnlyOnce.cs b/src/ShardingCore/Sharding/MergeEngines/ParallelControl/DoOnlyOnce.cs index fc7be647..03d8d68b 100644 --- a/src/ShardingCore/Sharding/MergeEngines/ParallelControl/DoOnlyOnce.cs +++ b/src/ShardingCore/Sharding/MergeEngines/ParallelControl/DoOnlyOnce.cs @@ -13,7 +13,7 @@ namespace ShardingCore.Sharding.MergeEngines.ParallelControl private const int Did = 1; private const int UnDo = 0; - private int Status = UnDo; + private int Status = UnDo; public bool IsUnDo() { diff --git a/src/ShardingCore/Sharding/ShardingExecutors/CustomerQueryScope.cs b/src/ShardingCore/Sharding/ShardingExecutors/CustomerQueryScope.cs index 5bac1d6f..5853d46a 100644 --- a/src/ShardingCore/Sharding/ShardingExecutors/CustomerQueryScope.cs +++ b/src/ShardingCore/Sharding/ShardingExecutors/CustomerQueryScope.cs @@ -3,9 +3,6 @@ using ShardingCore.Core.QueryRouteManagers; using ShardingCore.Core.QueryRouteManagers.Abstractions; using ShardingCore.Extensions; using ShardingCore.Sharding.Parsers.Abstractions; -using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions; -using ShardingCore.Sharding.ShardingExecutors; -using ShardingCore.Sharding.ShardingExecutors.Abstractions; /* * @Author: xjm @@ -13,7 +10,7 @@ using ShardingCore.Sharding.ShardingExecutors.Abstractions; * @Date: DATE TIME * @Email: 326308290@qq.com */ -namespace ShardingCore.ShardingExecutors +namespace ShardingCore.Sharding.ShardingExecutors { internal class CustomerQueryScope:IDisposable { diff --git a/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingCompilerExecutor.cs b/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingCompilerExecutor.cs index 59adaf86..e75cc7f4 100644 --- a/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingCompilerExecutor.cs +++ b/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingCompilerExecutor.cs @@ -10,7 +10,6 @@ using ShardingCore.Extensions; using ShardingCore.Sharding.Parsers.Abstractions; using ShardingCore.Sharding.ShardingExecutors.Abstractions; using ShardingCore.Sharding.Visitors.ShardingExtractParameters; -using ShardingCore.ShardingExecutors; namespace ShardingCore.Sharding.ShardingExecutors { diff --git a/src/ShardingCore/ShardingCoreExtension.cs b/src/ShardingCore/ShardingCoreExtension.cs index dd3b6f3b..d4278d7e 100644 --- a/src/ShardingCore/ShardingCoreExtension.cs +++ b/src/ShardingCore/ShardingCoreExtension.cs @@ -271,13 +271,12 @@ namespace ShardingCore /// - /// 启用定时任务自动创建表 + /// 当前接口可以直接移除掉,定时任务会在shardingcore初始化的时候自动调用 /// /// + [Obsolete("can remove this method,sharding core auto invoke.")] public static void UseAutoShardingCreate(this IServiceProvider serviceProvider) { - var shardingRuntimeContext = serviceProvider.GetRequiredService(); - shardingRuntimeContext.UseAutoShardingCreate(); } /// diff --git a/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs b/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs index feca356f..fd8417e7 100644 --- a/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs +++ b/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs @@ -81,6 +81,7 @@ namespace ShardingCore.VirtualRoutes.Abstractions /// public abstract bool AutoCreateTableByTime(); + /// /// 显示错误日志 /// @@ -140,21 +141,24 @@ namespace ShardingCore.VirtualRoutes.Abstractions logger.LogInformation($"auto create table data source names:[{string.Join(",", dataSources)}]"); - foreach (var dataSource in dataSources) + if (AutoCreateTableByTime()) { - try + foreach (var dataSource in dataSources) { - logger.LogInformation($"begin table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); - tableCreator.CreateTable(dataSource, typeof(TEntity), tail); - logger.LogInformation($"succeed table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); - } - catch (Exception e) - { - //ignore - logger.LogInformation($"warning table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); - if (DoLogError) - logger.LogError(e, $"{dataSource} {typeof(TEntity).Name}'s create table error "); - } + try + { + logger.LogInformation($"begin table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); + tableCreator.CreateTable(dataSource, typeof(TEntity), tail); + logger.LogInformation($"succeed table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); + } + catch (Exception e) + { + //ignore + logger.LogInformation($"warning table tail:[{tail}],entity:[{typeof(TEntity).Name}]"); + if (DoLogError) + logger.LogError(e, $"{dataSource} {typeof(TEntity).Name}'s create table error "); + } + } } return Task.CompletedTask; @@ -162,7 +166,7 @@ namespace ShardingCore.VirtualRoutes.Abstractions public bool AppendJob() { - return AutoCreateTableByTime(); + return true; } } } \ No newline at end of file From 9246b09b5a736df9860eb890f9c54bed2dda5598 Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Thu, 20 Oct 2022 13:18:55 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E9=92=88=E5=AF=B9commit=E7=9A=84=E6=8F=90=E4=BA=A4=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/WeatherForecastController.cs | 1 - .../ShardingRelationalTransaction.cs | 20 +-- .../IShardingDbContextExecutor.cs | 9 ++ .../Abstractions/IShardingTransaction.cs | 10 +- .../DataSourceDbContext.cs | 118 ++++++++++-------- .../IDataSourceDbContext.cs | 12 +- .../ShardingDbContextExecutor.cs | 33 ++++- 7 files changed, 136 insertions(+), 67 deletions(-) diff --git a/samples/Sample.MySql/Controllers/WeatherForecastController.cs b/samples/Sample.MySql/Controllers/WeatherForecastController.cs index 7ba7acc0..942e79b8 100644 --- a/samples/Sample.MySql/Controllers/WeatherForecastController.cs +++ b/samples/Sample.MySql/Controllers/WeatherForecastController.cs @@ -65,7 +65,6 @@ namespace Sample.MySql.Controllers // //一定要先在路由里面添加尾巴 // virtualTableRoute.Append("20220921"); // shardingTableCreator.CreateTable("ds0","20220921"); - return _defaultTableDbContext.Set(); } [HttpGet] diff --git a/src/ShardingCore/EFCores/RelationTransactions/ShardingRelationalTransaction.cs b/src/ShardingCore/EFCores/RelationTransactions/ShardingRelationalTransaction.cs index ca3a7f0d..bab0be75 100644 --- a/src/ShardingCore/EFCores/RelationTransactions/ShardingRelationalTransaction.cs +++ b/src/ShardingCore/EFCores/RelationTransactions/ShardingRelationalTransaction.cs @@ -92,13 +92,19 @@ namespace ShardingCore.EFCores await _shardingDbContext.CommitAsync(cancellationToken); _shardingDbContext.NotifyShardingTransaction(); } -// #if !NETCOREAPP3_0 -// public override void CreateSavepoint(string name) -// { -// AAA -// base.CreateSavepoint(name); -// } -// #endif +#if !NETCOREAPP3_0&&!NETSTANDARD2_0 + // public override void CreateSavepoint(string name) + // { + // base.CreateSavepoint(name); + // _shardingDbContext.CreateSavepoint(name); + // } + // + // public override async Task CreateSavepointAsync(string name, CancellationToken cancellationToken = new CancellationToken()) + // { + // await base.CreateSavepointAsync(name, cancellationToken); + // await _shardingDbContext.CreateSavepointAsync(name,cancellationToken); + // } +#endif #endif } } \ No newline at end of file diff --git a/src/ShardingCore/Sharding/Abstractions/IShardingDbContextExecutor.cs b/src/ShardingCore/Sharding/Abstractions/IShardingDbContextExecutor.cs index c4490175..e48c64cc 100644 --- a/src/ShardingCore/Sharding/Abstractions/IShardingDbContextExecutor.cs +++ b/src/ShardingCore/Sharding/Abstractions/IShardingDbContextExecutor.cs @@ -91,6 +91,15 @@ namespace ShardingCore.Sharding.Abstractions /// /// Task CommitAsync(CancellationToken cancellationToken = new CancellationToken()); + +#if !NETCOREAPP3_0&&!NETSTANDARD2_0 + // void CreateSavepoint(string name); + // Task CreateSavepointAsync(string name, CancellationToken cancellationToken = new CancellationToken()); + // void RollbackToSavepoint(string name); + // Task RollbackToSavepointAsync(string name,CancellationToken cancellationToken = default(CancellationToken)); + // void ReleaseSavepoint(string name); + // Task ReleaseSavepointAsync(string name, CancellationToken cancellationToken = default(CancellationToken)); +#endif #endif } } diff --git a/src/ShardingCore/Sharding/Abstractions/IShardingTransaction.cs b/src/ShardingCore/Sharding/Abstractions/IShardingTransaction.cs index eb6f18ae..5a7beedc 100644 --- a/src/ShardingCore/Sharding/Abstractions/IShardingTransaction.cs +++ b/src/ShardingCore/Sharding/Abstractions/IShardingTransaction.cs @@ -21,6 +21,14 @@ namespace ShardingCore.Sharding.Abstractions #if !NETCOREAPP2_0 Task RollbackAsync(CancellationToken cancellationToken = new CancellationToken()); Task CommitAsync(CancellationToken cancellationToken = new CancellationToken()); +#if !NETCOREAPP3_0 && !NETSTANDARD2_0 + // void CreateSavepoint(string name); + // Task CreateSavepointAsync(string name, CancellationToken cancellationToken = new CancellationToken()); + // void RollbackToSavepoint(string name); + // Task RollbackToSavepointAsync(string name,CancellationToken cancellationToken = default(CancellationToken)); + // void ReleaseSavepoint(string name); + // Task ReleaseSavepointAsync(string name, CancellationToken cancellationToken = default(CancellationToken)); +#endif #endif } -} +} \ No newline at end of file diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs index fbc1e945..a460063c 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs @@ -18,7 +18,6 @@ using ShardingCore.Core.RuntimeContexts; using ShardingCore.Exceptions; using ShardingCore.Extensions; using ShardingCore.Infrastructures; - using ShardingCore.Sharding.Abstractions; namespace ShardingCore.Sharding.ShardingDbContextExecutors @@ -32,11 +31,10 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors */ public class DataSourceDbContext : IDataSourceDbContext { - private static readonly IComparer _comparer = new NoShardingFirstComparer(); - private readonly ILogger _logger; public Type DbContextType { get; } + /// /// 当前是否是默认的dbcontext 也就是不分片的dbcontext /// @@ -82,6 +80,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors /// shell dbcontext最外面的壳 /// private readonly DbContext _shardingShellDbContext; + private readonly IShardingRuntimeContext _shardingRuntimeContext; /// @@ -117,8 +116,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors bool isDefault, DbContext shardingShellDbContext, IDbContextCreator dbContextCreator, - ActualConnectionStringManager actualConnectionStringManager, - ILogger logger) + ActualConnectionStringManager actualConnectionStringManager) { var shardingDbContext = (IShardingDbContext)shardingShellDbContext; DataSourceName = dataSourceName; @@ -126,11 +124,10 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors _shardingShellDbContext = shardingShellDbContext; _shardingRuntimeContext = shardingShellDbContext.GetShardingRuntimeContext(); DbContextType = shardingShellDbContext.GetType(); - _virtualDataSource =shardingDbContext + _virtualDataSource = shardingDbContext .GetVirtualDataSource(); _dbContextCreator = dbContextCreator; _actualConnectionStringManager = actualConnectionStringManager; - this._logger = logger; } /// @@ -155,8 +152,9 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors { //先创建dbcontext option builder var dbContextOptionBuilderCreator = _shardingRuntimeContext.GetDbContextOptionBuilderCreator(); - var dbContextOptionsBuilder = dbContextOptionBuilderCreator.CreateDbContextOptionBuilder().UseShardingOptions(_shardingRuntimeContext); - + var dbContextOptionsBuilder = dbContextOptionBuilderCreator.CreateDbContextOptionBuilder() + .UseShardingOptions(_shardingRuntimeContext); + if (IsDefault) { //如果是默认的需要使用shell的dbconnection为了保证可以使用事务 @@ -342,34 +340,17 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors { if (IsDefault) return; - try - { - CurrentDbContextTransaction?.Rollback(); - } - catch (Exception e) - { - _logger.LogError(e, "rollback error."); - } + CurrentDbContextTransaction?.Rollback(); } /// /// 提交数据 /// - /// 如果只有一个数据源那么就直接报错否则就忽略 - public void Commit(int dataSourceCount) + public void Commit() { if (IsDefault) return; - try - { - CurrentDbContextTransaction?.Commit(); - } - catch (Exception e) - { - _logger.LogError(e, "commit error."); - if (dataSourceCount == 1) - throw; - } + CurrentDbContextTransaction?.Commit(); } #if !NETCOREAPP2_0 public async Task RollbackAsync(CancellationToken cancellationToken = new CancellationToken()) @@ -377,35 +358,70 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors cancellationToken.ThrowIfCancellationRequested(); if (IsDefault) return; - try - { - if (CurrentDbContextTransaction != null) - await CurrentDbContextTransaction.RollbackAsync(cancellationToken); - } - catch (Exception e) - { - _logger.LogError(e, "rollback error."); - } + if (CurrentDbContextTransaction != null) + await CurrentDbContextTransaction.RollbackAsync(cancellationToken); } - public async Task CommitAsync(int dataSourceCount, CancellationToken cancellationToken = - new CancellationToken()) + public async Task CommitAsync(CancellationToken cancellationToken = + new CancellationToken()) { cancellationToken.ThrowIfCancellationRequested(); if (IsDefault) return; - try - { - if (CurrentDbContextTransaction != null) - await CurrentDbContextTransaction.CommitAsync(cancellationToken); - } - catch (Exception e) - { - _logger.LogError(e, "commit error."); - if (dataSourceCount == 1) - throw; - } + if (CurrentDbContextTransaction != null) + await CurrentDbContextTransaction.CommitAsync(cancellationToken); } +#if !NETCOREAPP3_0&&!NETSTANDARD2_0 + // public void CreateSavepoint(string name) + // { + // if (IsDefault) + // return; + // CurrentDbContextTransaction?.CreateSavepoint(name); + // } + // + // public async Task CreateSavepointAsync(string name, + // CancellationToken cancellationToken = new CancellationToken()) + // { + // cancellationToken.ThrowIfCancellationRequested(); + // if (IsDefault) + // return; + // if (CurrentDbContextTransaction != null) + // await CurrentDbContextTransaction.CreateSavepointAsync(name, cancellationToken); + // } + // + // public void RollbackToSavepoint(string name) + // { + // if (IsDefault) + // return; + // CurrentDbContextTransaction?.RollbackToSavepoint(name); + // } + // + // public async Task RollbackToSavepointAsync(string name, + // CancellationToken cancellationToken = default(CancellationToken)) + // { + // cancellationToken.ThrowIfCancellationRequested(); + // if (IsDefault) + // return; + // if (CurrentDbContextTransaction != null) + // await CurrentDbContextTransaction.RollbackToSavepointAsync(name, cancellationToken); + // } + // + // public void ReleaseSavepoint(string name) + // { + // if (IsDefault) + // return; + // CurrentDbContextTransaction?.ReleaseSavepoint(name); + // } + // + // public async Task ReleaseSavepointAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) + // { + // cancellationToken.ThrowIfCancellationRequested(); + // if (IsDefault) + // return; + // if (CurrentDbContextTransaction != null) + // await CurrentDbContextTransaction.ReleaseSavepointAsync(name, cancellationToken); + // } +#endif #endif public void Dispose() diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/IDataSourceDbContext.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/IDataSourceDbContext.cs index 370a946b..139966bd 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/IDataSourceDbContext.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/IDataSourceDbContext.cs @@ -45,10 +45,18 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors IDictionary GetCurrentContexts(); void Rollback(); - void Commit(int dataSourceCount); + void Commit(); #if !NETCOREAPP2_0 Task RollbackAsync(CancellationToken cancellationToken = new CancellationToken()); - Task CommitAsync(int dataSourceCount,CancellationToken cancellationToken = new CancellationToken()); + Task CommitAsync(CancellationToken cancellationToken = new CancellationToken()); +#if !NETCOREAPP3_0&&!NETSTANDARD2_0 + // void CreateSavepoint(string name); + // Task CreateSavepointAsync(string name, CancellationToken cancellationToken = new CancellationToken()); + // void RollbackToSavepoint(string name); + // Task RollbackToSavepointAsync(string name,CancellationToken cancellationToken = default(CancellationToken)); + // void ReleaseSavepoint(string name); + // Task ReleaseSavepointAsync(string name, CancellationToken cancellationToken = default(CancellationToken)); +#endif #endif } diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs index 27784205..3fb66d84 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs @@ -34,7 +34,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors /// public class ShardingDbContextExecutor : IShardingDbContextExecutor { - private readonly ILoggerFactory _loggerFactory; + private readonly ILogger _logger; private readonly DbContext _shardingDbContext; //private readonly ConcurrentDictionary> _dbContextCaches = new ConcurrentDictionary>(); @@ -78,7 +78,8 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors _routeTailFactory = _shardingRuntimeContext.GetRouteTailFactory(); var shardingReadWriteManager = _shardingRuntimeContext.GetShardingReadWriteManager(); var shardingProvider = _shardingRuntimeContext.GetShardingProvider(); - _loggerFactory=shardingProvider.GetService(); + var loggerFactory=shardingProvider.GetRequiredService(); + _logger=loggerFactory.CreateLogger(); _actualConnectionStringManager = new ActualConnectionStringManager(shardingReadWriteManager,_virtualDataSource); } @@ -86,7 +87,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors private IDataSourceDbContext GetDataSourceDbContext(string dataSourceName) { - return _dbContextCaches.GetOrAdd(dataSourceName, dsname => new DataSourceDbContext(dsname, _virtualDataSource.IsDefault(dsname), _shardingDbContext, _dbContextCreator, _actualConnectionStringManager,_loggerFactory.CreateLogger())); + return _dbContextCaches.GetOrAdd(dataSourceName, dsname => new DataSourceDbContext(dsname, _virtualDataSource.IsDefault(dsname), _shardingDbContext, _dbContextCreator, _actualConnectionStringManager)); } /// @@ -194,9 +195,20 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors public void Commit() { + int i = 0; foreach (var dbContextCache in _dbContextCaches) { - dbContextCache.Value.Commit(_dbContextCaches.Count); + try + { + dbContextCache.Value.Commit(); + } + catch (Exception e) + { + _logger.LogError(e, "commit error."); + if (i == 0) + throw; + } + i++; } AutoUseWriteConnectionString(); @@ -231,9 +243,20 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors public async Task CommitAsync(CancellationToken cancellationToken = new CancellationToken()) { + int i = 0; foreach (var dbContextCache in _dbContextCaches) { - await dbContextCache.Value.CommitAsync(_dbContextCaches.Count, cancellationToken); + try + { + await dbContextCache.Value.CommitAsync(cancellationToken); + } + catch (Exception e) + { + _logger.LogError(e, "commit error."); + if (i == 0) + throw; + } + i++; } AutoUseWriteConnectionString();