You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
CaiQie/DB/DbCommandInterceptor.cs

81 lines
2.3 KiB
C#

3 months ago
using System.Data;
using System.Diagnostics;
using System.Text;
using Chloe.Infrastructure.Interception;
namespace DB;
public class DbCommandInterceptor : IDbCommandInterceptor
{
public void ReaderExecuting(IDbCommand command, DbCommandInterceptionContext<IDataReader> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
public void ReaderExecuted(IDbCommand command, DbCommandInterceptionContext<IDataReader> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
public void NonQueryExecuting(IDbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
public void NonQueryExecuted(IDbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
public void ScalarExecuting(IDbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
public void ScalarExecuted(IDbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
ToDb(command, interceptionContext.Exception);
}
private void ToDb(IDbCommand command, Exception? exception)
{
#if DEBUG
Trace.WriteLine(command.CommandText);
Trace.WriteLine(AppendDbCommandInfo(command));
#endif
}
private string AppendDbCommandInfo(IDbCommand command)
{
var sb = new StringBuilder();
foreach (IDbDataParameter param in command.Parameters)
{
if (param == null)
continue;
object value;
if (param.Value == null || param.Value == DBNull.Value)
{
value = "NULL";
}
else
{
value = param.Value;
if (param.DbType == DbType.String || param.DbType == DbType.AnsiString ||
param.DbType == DbType.DateTime)
value = "'" + value + "'";
}
sb.AppendFormat("{3} {0} {1} = {2};", Enum.GetName(typeof(DbType), param.DbType), param.ParameterName,
value, Enum.GetName(typeof(ParameterDirection), param.Direction));
sb.AppendLine();
}
return sb.ToString();
}
}