Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Add query execution listeners

Open ah1508 opened this issue 9 months ago • 1 comments

Dapper could offer several AddListener methods: before query execution, after query execution, after exception.

AddBeforeQueryExectutionListener(Action<DbCommand> action, bool failOnError = false);

AddAfterQueryExectutionListener(Action<DbCommand, object/*the result*/, long /*execution time*/> action, bool failOnError = false);

AddAfterQueryExceptionListener(Action<DbCommand, Exception> action);

failOnError: should an exception thrown by the action stop the query execution or should it be ignored ?

execution time could be replaced by a Statistics object (connection acquisition time, query execution time, mapping execution time...).

These methods could be static:

Dapper.Listeners.AddAfterQueryExecutionListener((command, result, executionTime) => {
    Console.WriteLine($"it took {executionTime} to execute {command.CommandText}");
});
namespace Dapper;

public static class Listeners
{
    public static bool Enabled { get;  set ;} // To enabled or disable listeners at runtime
    internal static List<(Action<DbCommand> action, bool failOnError)> BeforeExecutionListeners { get; } = [];
    internal static List<(Action<DbCommand, object, long> action, bool failOnError)> AfterExecutionListeners { get; } = [];
    internal static List<Action<DbCommand, Exception>> AfterExceptionListeners { get; } = [];

    public static void AddBeforeExecutionListener(Action<DbCommand> action, bool failOnError = false)
    {
        BeforeExecutionListeners.Add((action, failOnError));
        Enabled = true;
    }

    public static void AddAfterQueryExecutionListener(Action<DbCommand, object, long> action, bool failOnError = false)
    {
        AfterExecutionListeners.Add((action, failOnError));
        Enabled = true;
    }

    public static void AddAfterExceptionListeners(Action<DbCommand, Exception> action)
    {
        AfterExceptionListeners.Add(action);
        Enabled = true;
    }
}

With named listeners, RemoveListener methods could also be implemented.

SqlMapper Query and Execute method would check Listeners.Enabled value and, if it is true, call the listeners before and after query executions.

It would be useful for profiling and exception handling, in my case I need to expose the execution time of some queries to Prometheus.

ah1508 avatar Apr 25 '24 20:04 ah1508

Hello Dapper`s community!!!

This is really useful feature, that I'm waiting for too.

sovetkin avatar May 04 '24 20:05 sovetkin