DapperLib / Dapper

Dapper - a simple object mapper for .Net
https://www.learndapper.com/
Other
17.29k stars 3.67k forks source link

Add query execution listeners #2078

Open ah1508 opened 2 months ago

ah1508 commented 2 months ago

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.

sovetkin commented 2 months ago

Hello Dapper`s community!!!

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