Skip to content

Commit

Permalink
add support DbCommandCreated event for CommandExecuter
Browse files Browse the repository at this point in the history
fix #89
  • Loading branch information
Ahoo-Wang committed Aug 13, 2019
1 parent 1ba4f72 commit 3878859
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 20 deletions.
7 changes: 7 additions & 0 deletions SmartSql.sln
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmartSql.Cache.Sync", "src\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmartSql.DataConnector", "src\SmartSql.DataConnector\SmartSql.DataConnector.csproj", "{B6C8A252-B5D8-479B-8518-21AB79B65670}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmartSql.Oracle", "src\SmartSql.Oracle\SmartSql.Oracle.csproj", "{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -198,6 +200,10 @@ Global
{B6C8A252-B5D8-479B-8518-21AB79B65670}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6C8A252-B5D8-479B-8518-21AB79B65670}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6C8A252-B5D8-479B-8518-21AB79B65670}.Release|Any CPU.Build.0 = Release|Any CPU
{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -235,6 +241,7 @@ Global
{9FC40FC1-8FEC-4048-A78B-AA392F87DCA2} = {903A0C86-20AC-4E4A-A33F-25706FA0E20A}
{1F4EA4D3-D710-480E-9561-69DE388EAFE2} = {9E0B56FD-1AEC-414A-9630-555FA06B287F}
{B6C8A252-B5D8-479B-8518-21AB79B65670} = {903A0C86-20AC-4E4A-A33F-25706FA0E20A}
{F27F1F16-F219-43FF-BEBE-6BDF9FC89A9E} = {FB71A21B-B0FD-4F40-985D-4BB7756D33BF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6942F9AB-D574-4C16-8CF7-0D10B637237B}
Expand Down
2 changes: 1 addition & 1 deletion build/version.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<VersionMajor>4</VersionMajor>
<VersionMinor>1</VersionMinor>
<VersionPatch>18</VersionPatch>
<VersionPatch>19</VersionPatch>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
</PropertyGroup>
</Project>
15 changes: 15 additions & 0 deletions src/SmartSql.Oracle/SmartSql.Oracle.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\SmartSql\SmartSql.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.18.3" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions src/SmartSql.Oracle/SmartSqlBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Microsoft.Extensions.Logging;
using Oracle.ManagedDataAccess.Client;
using SmartSql.Command;
using SmartSql.Exceptions;

namespace SmartSql
{
public static class SmartSqlBuilderExtensions
{
public static SmartSqlBuilder UseOracleCommandExecuter(this SmartSqlBuilder smartSqlBuilder)
{
return UseOracleCommandExecuter(smartSqlBuilder, smartSqlBuilder.LoggerFactory);
}
public static SmartSqlBuilder UseOracleCommandExecuter(this SmartSqlBuilder smartSqlBuilder,
ILoggerFactory loggerFactory)
{
var cmdExe = new CommandExecuter(loggerFactory.CreateLogger<CommandExecuter>());
cmdExe.DbCommandCreated += OnDbCommandCreated;
return smartSqlBuilder;
}

private static void OnDbCommandCreated(object cmdExe, DbCommandCreatedEventArgs eventArgs)
{
var oracleCommand = eventArgs.DbCommand as OracleCommand;
if (oracleCommand == null)
{
throw new SmartSqlException("The ADO.NET Driver is not [Oracle.ManagedDataAccess.Core].");
}

oracleCommand.BindByName = true;
oracleCommand.InitialLONGFetchSize = -1;
}
}
}
1 change: 1 addition & 0 deletions src/SmartSql.Test.Unit/SmartSql.Test.Unit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
<ProjectReference Include="..\SmartSql.DyRepository\SmartSql.DyRepository.csproj" />
<ProjectReference Include="..\SmartSql.InvokeSync\SmartSql.InvokeSync.csproj" />
<ProjectReference Include="..\SmartSql.Options\SmartSql.Options.csproj" />
<ProjectReference Include="..\SmartSql.Oracle\SmartSql.Oracle.csproj" />
<ProjectReference Include="..\SmartSql.ScriptTag\SmartSql.ScriptTag.csproj" />
<ProjectReference Include="..\SmartSql.Test\SmartSql.Test.csproj" />
<ProjectReference Include="..\SmartSql.TypeHandler.PostgreSql\SmartSql.TypeHandler.PostgreSql.csproj" />
Expand Down
3 changes: 2 additions & 1 deletion src/SmartSql.Test.Unit/SmartSqlMapConfig.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
<Settings IgnoreParameterCase="false" ParameterPrefix="$" IsCacheEnabled="true" EnablePropertyChangedTrack="true" IgnoreDbNull="true"/>
<Properties>
<Property Name="Redis" Value="localhost"/>
<Property Name="DbProvider" Value="SqlServer"/>
<Property Name="ConnectionString" Value="Data Source=.;Initial Catalog=SmartSqlTestDB;Integrated Security=True"/>
<Property Name="JsonTypeHandler`" Value="SmartSql.TypeHandler.JsonTypeHandler`1,SmartSql.TypeHandler"/>
<Property Name="JsonTypeHandler" Value="SmartSql.TypeHandler.JsonTypeHandler,SmartSql.TypeHandler"/>
<Property Name="ScriptBuilder" Value="SmartSql.ScriptTag.ScriptBuilder,SmartSql.ScriptTag"/>
<Property Name="RedisCacheProvider" Value="SmartSql.Cache.Redis.RedisCacheProvider,SmartSql.Cache.Redis"/>
</Properties>
<Database>
<DbProvider Name="SqlServer"/>
<DbProvider Name="${DbProvider}"/>
<Write Name="WriteDB" ConnectionString="${ConnectionString}"/>
<Read Name="ReadDb-1" ConnectionString="${ConnectionString}" Weight="100"/>
<Read Name="ReadDb-2" ConnectionString="${ConnectionString}" Weight="100"/>
Expand Down
56 changes: 41 additions & 15 deletions src/SmartSql/Command/CommandExecuter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,52 @@

namespace SmartSql.Command
{
public class DbCommandCreatedEventArgs : EventArgs
{
public DbCommand DbCommand { get; set; }
}

public delegate void DbCommandCreatedEventHandler(object sender, DbCommandCreatedEventArgs eventArgs);

public class CommandExecuter : ICommandExecuter
{
private readonly ILogger<CommandExecuter> _logger;

public event DbCommandCreatedEventHandler DbCommandCreated;

public CommandExecuter(ILogger<CommandExecuter> logger)
{
_logger = logger;
}

private static readonly DiagnosticListener _diagnosticListener = SmartSqlDiagnosticListenerExtensions.Instance;

private DbCommand CreateCmd(ExecutionContext executionContext)
{
var dbSession = executionContext.DbSession;
var dbCmd = dbSession.Connection.CreateCommand();
dbCmd.CommandType = executionContext.Request.CommandType;
dbCmd.Transaction = dbSession.Transaction;
dbCmd.CommandText = executionContext.Request.RealSql;

if (executionContext.Request.CommandTimeout.HasValue)
{
dbCmd.CommandTimeout = executionContext.Request.CommandTimeout.Value;
}

foreach (var dbParam in executionContext.Request.Parameters.DbParameters.Values)
{
dbCmd.Parameters.Add(dbParam);
}

DbCommandCreated?.Invoke(this, new DbCommandCreatedEventArgs
{
DbCommand = dbCmd
});

return dbCmd;
}

private TResult ExecuteWrap<TResult>(Func<TResult> executeImpl, ExecutionContext executionContext
, [CallerMemberName] string operation = "")
{
Expand All @@ -51,6 +70,7 @@ private TResult ExecuteWrap<TResult>(Func<TResult> executeImpl, ExecutionContext
{
stopwatch = Stopwatch.StartNew();
}

operationId = _diagnosticListener.WriteCommandExecuterExecuteBefore(executionContext, operation);
var result = executeImpl();
_diagnosticListener.WriteCommandExecuterExecuteAfter(operationId, executionContext, operation);
Expand Down Expand Up @@ -83,7 +103,6 @@ public DataTable GetDateTable(ExecutionContext executionContext)
dataAdapter.Fill(dataTable);
return dataTable;
}, executionContext);

}

public DataSet GetDateSet(ExecutionContext executionContext)
Expand All @@ -98,8 +117,8 @@ public DataSet GetDateSet(ExecutionContext executionContext)
dataAdapter.Fill(dataSet);
return dataSet;
}, executionContext);

}

public int ExecuteNonQuery(ExecutionContext executionContext)
{
return ExecuteWrap(() =>
Expand All @@ -108,8 +127,8 @@ public int ExecuteNonQuery(ExecutionContext executionContext)
DbCommand dbCmd = CreateCmd(executionContext);
return dbCmd.ExecuteNonQuery();
}, executionContext);

}

public DataReaderWrapper ExecuteReader(ExecutionContext executionContext)
{
return ExecuteWrap(() =>
Expand All @@ -119,7 +138,6 @@ public DataReaderWrapper ExecuteReader(ExecutionContext executionContext)
var dbReader = dbCmd.ExecuteReader();
return new DataReaderWrapper(dbReader);
}, executionContext);

}

public object ExecuteScalar(ExecutionContext executionContext)
Expand All @@ -130,9 +148,10 @@ public object ExecuteScalar(ExecutionContext executionContext)
DbCommand dbCmd = CreateCmd(executionContext);
return dbCmd.ExecuteScalar();
}, executionContext);

}
private async Task<TResult> ExecuteWrapAsync<TResult>(Func<Task<TResult>> executeImplAsync, ExecutionContext executionContext

private async Task<TResult> ExecuteWrapAsync<TResult>(Func<Task<TResult>> executeImplAsync,
ExecutionContext executionContext
, [CallerMemberName] string operation = "")
{
Stopwatch stopwatch = null;
Expand All @@ -143,6 +162,7 @@ private async Task<TResult> ExecuteWrapAsync<TResult>(Func<Task<TResult>> execut
{
stopwatch = Stopwatch.StartNew();
}

operationId = _diagnosticListener.WriteCommandExecuterExecuteBefore(executionContext, operation);
var result = await executeImplAsync();
_diagnosticListener.WriteCommandExecuterExecuteAfter(operationId, executionContext, operation);
Expand All @@ -162,17 +182,19 @@ private async Task<TResult> ExecuteWrapAsync<TResult>(Func<Task<TResult>> execut
}
}
}

public async Task<object> ExecuteScalarAsync(ExecutionContext executionContext)
{
return await ExecuteWrapAsync(async () =>
{
await executionContext.DbSession.OpenAsync();
DbCommand dbCmd = CreateCmd(executionContext);
return await dbCmd.ExecuteScalarAsync();
}, executionContext);
{
await executionContext.DbSession.OpenAsync();
DbCommand dbCmd = CreateCmd(executionContext);
return await dbCmd.ExecuteScalarAsync();
}, executionContext);
}

public async Task<object> ExecuteScalarAsync(ExecutionContext executionContext, CancellationToken cancellationToken)
public async Task<object> ExecuteScalarAsync(ExecutionContext executionContext,
CancellationToken cancellationToken)
{
return await ExecuteWrapAsync(async () =>
{
Expand Down Expand Up @@ -209,6 +231,7 @@ public async Task<DataSet> GetDateSetAsync(ExecutionContext executionContext)
return dataSet;
}, executionContext);
}

public async Task<DataReaderWrapper> ExecuteReaderAsync(ExecutionContext executionContext)
{
return await ExecuteWrapAsync(async () =>
Expand All @@ -220,7 +243,8 @@ public async Task<DataReaderWrapper> ExecuteReaderAsync(ExecutionContext executi
}, executionContext);
}

public async Task<DataReaderWrapper> ExecuteReaderAsync(ExecutionContext executionContext, CancellationToken cancellationToken)
public async Task<DataReaderWrapper> ExecuteReaderAsync(ExecutionContext executionContext,
CancellationToken cancellationToken)
{
return await ExecuteWrapAsync(async () =>
{
Expand All @@ -230,6 +254,7 @@ public async Task<DataReaderWrapper> ExecuteReaderAsync(ExecutionContext executi
return new DataReaderWrapper(dbReader);
}, executionContext);
}

public async Task<int> ExecuteNonQueryAsync(ExecutionContext executionContext)
{
return await ExecuteWrapAsync(async () =>
Expand All @@ -240,7 +265,8 @@ public async Task<int> ExecuteNonQueryAsync(ExecutionContext executionContext)
}, executionContext);
}

public async Task<int> ExecuteNonQueryAsync(ExecutionContext executionContext, CancellationToken cancellationToken)
public async Task<int> ExecuteNonQueryAsync(ExecutionContext executionContext,
CancellationToken cancellationToken)
{
return await ExecuteWrapAsync(async () =>
{
Expand All @@ -250,4 +276,4 @@ public async Task<int> ExecuteNonQueryAsync(ExecutionContext executionContext, C
}, executionContext);
}
}
}
}
2 changes: 2 additions & 0 deletions src/SmartSql/Configuration/SmartSqlConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using SmartSql.Cache;
using SmartSql.IdGenerator;
using Microsoft.Extensions.Logging.Abstractions;
using SmartSql.Command;
using SmartSql.Filters;

namespace SmartSql.Configuration
Expand All @@ -36,6 +37,7 @@ public class SmartSqlConfig
public IDbSessionStore SessionStore { get; set; }
public IDbSessionFactory DbSessionFactory { get; set; }
public ICacheManager CacheManager { get; set; }
public ICommandExecuter CommandExecuter { get; set; }
public InvokeSucceedListener InvokeSucceedListener { get; set; }
public IDictionary<String, IIdGenerator> IdGenerators { get; set; }
public FilterCollection Filters { get; set; }
Expand Down
3 changes: 1 addition & 2 deletions src/SmartSql/Middlewares/CommandExecuterMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,7 @@ public override async Task InvokeAsync<TResult>(ExecutionContext executionContex

public override void SetupSmartSql(SmartSqlBuilder smartSqlBuilder)
{
_commandExecuter =
new CommandExecuter(smartSqlBuilder.SmartSqlConfig.LoggerFactory.CreateLogger<CommandExecuter>());
_commandExecuter = smartSqlBuilder.SmartSqlConfig.CommandExecuter;
}
}
}
13 changes: 12 additions & 1 deletion src/SmartSql/SmartSqlBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using SmartSql.Command;
using SmartSql.Deserializer;
using SmartSql.Filters;
using SmartSql.Reflection.TypeConstants;
Expand Down Expand Up @@ -39,11 +40,11 @@ public class SmartSqlBuilder : IDisposable
public ISqlMapper SqlMapper { get; private set; }
public ICacheManager CacheManager { get; private set; }
public IDataSourceFilter DataSourceFilter { get; private set; }
public ICommandExecuter CommandExecuter { get; private set; }
public bool? IsCacheEnabled { get; private set; }
public bool? IgnoreDbNull { get; private set; }
public bool Built { get; private set; }
public bool Registered { get; private set; } = true;

public IList<IDataReaderDeserializer> DataReaderDeserializers { get; } = new List<IDataReaderDeserializer>();
public IList<TypeHandler> TypeHandlers { get; } = new List<TypeHandler>();
public FilterCollection Filters { get; } = new FilterCollection();
Expand Down Expand Up @@ -155,6 +156,8 @@ private void BeforeBuildInitService()
SmartSqlConfig.Alias = Alias;
SmartSqlConfig.LoggerFactory = LoggerFactory;
SmartSqlConfig.DataSourceFilter = DataSourceFilter ?? new DataSourceFilter(SmartSqlConfig.LoggerFactory);
SmartSqlConfig.CommandExecuter =
CommandExecuter ?? new CommandExecuter(LoggerFactory.CreateLogger<CommandExecuter>());
if (IsCacheEnabled.HasValue)
{
SmartSqlConfig.Settings.IsCacheEnabled = IsCacheEnabled.Value;
Expand Down Expand Up @@ -259,6 +262,12 @@ private void BuildPipeline()

#region Instance

public SmartSqlBuilder UseCommandExecuter(ICommandExecuter commandExecuter)
{
CommandExecuter = commandExecuter;
return this;
}

public SmartSqlBuilder ListenInvokeSucceeded(Action<ExecutionContext> invokeSucceeded)
{
InvokeSucceeded = invokeSucceeded;
Expand Down Expand Up @@ -374,10 +383,12 @@ public SmartSqlBuilder UseProperties(IDictionary dictionary)

return this;
}

public SmartSqlBuilder UsePropertiesFromEnv(
EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
{
var envVars = Environment.GetEnvironmentVariables(target);

return UseProperties(envVars);
}

Expand Down

0 comments on commit 3878859

Please sign in to comment.