Plinth.Database.MSSql 1.5.4

The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org. Prefix Reserved
.NET 6.0
dotnet add package Plinth.Database.MSSql --version 1.5.4
NuGet\Install-Package Plinth.Database.MSSql -Version 1.5.4
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Plinth.Database.MSSql" Version="1.5.4" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Plinth.Database.MSSql --version 1.5.4
#r "nuget: Plinth.Database.MSSql, 1.5.4"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Plinth.Database.MSSql as a Cake Addin
#addin nuget:?package=Plinth.Database.MSSql&version=1.5.4

// Install Plinth.Database.MSSql as a Cake Tool
#tool nuget:?package=Plinth.Database.MSSql&version=1.5.4

README

Plinth.Database.MSSql

Stored Procedure based mini-framework for Microsoft SQL Server

Provides Transaction management, stored procedure execution, rowset handling, and transient error detection

1. Register the transaction factory and provider with DI in Setup

  // IConfiguration configuration;

   var txnFactory = new SqlTransactionFactory(
       configuration,
       "MyDB",
       config.GetConnectionString("MyDB"));

   services.AddSingleton(txnFac);              // for injecting the SqlTransactionFactory
   services.AddSingleton(txnFac.GetDefault()); // for injecting the ISqlTransactionProvider

2. Settings in appsettings.json

Example appsettings.json 👉 All settings in PlinthMSSqlSettings are optional. The defaults are shown below.

{
  "ConnectionStrings": {
    "MyDB": "Data Source=...."
  },
  "PlinthMSSqlSettings": {
    "SqlCommandTimeout": "00:00:50",
    "SqlRetryCount": 3,
    "SqlRetryInterval": "00:00:00.200",
    "SqlRetryFastFirst": true,
    "DisableTransientRetry": false
  }
}
  • SqlCommandTimeout: A TimeSpan formatted time for the default time for each SQL operation. Default is 50 seconds.
  • SqlRetryCount: If a transient error is detected, maximum number of retries after the initial failure. Default is 3. This allows up to 4 attempts.
  • SqlRetryInterval: If a transient error is detected, this is how long between retry attempts. Default is 200 milliseconds.
  • SqlRetryFastFirst: If true, upon the first transient error, the first retry will happen immediately. Subsequent transient errors will wait the SqlRetryInterval. Default is true.
  • DisableTransientRetry: If true, transient errors will not trigger retries. Default is false.

3. Transient Errors

It is very common on cloud hosted databases (especially on Azure SQL) to have the database return transient errors that will work perfectly if retried. These errors can be things like deadlocks, timeouts, throttling, and transport errors.

The framework accepts a function to execute the whole transaction. When a transient error occurs, the entire transaction is rolled back and the function is executed again.

⚠️ Your code inside a transaction should be re-entrant. Anything that is performed that cannot be rolled back (such as sending an email), should be performed outside the transaction or be checked to confirm that it won't execute more than once.

4. Creating a Transaction

Below is an example controller that creates a transaction, executes a stored procedure, and returns the result.

[Route("api/[controller]")]
[ApiController]
public class MyThingController : Controller
{
    private readonly ISqlTransactionProvider _txnProvider;

    public MyThingController(ISqlTransactionProvider _txnProvider)
    {
        _txnProvider = txnProvider;
    }

    [HttpGet]
    [Route("{thingId}")]
    [ProducesResponseType(200)]
    public async Task<ActionResult<MyThing>> GetMyThing(Guid thingId, CancellationToken ct)
    {
        var myThing = await _txnProvider.ExecuteTxnAsync(connection =>
        {
            return await connection.ExecuteQueryProcOneAsync(
                "usp_GetMyThingById",
                row => Task.FromResult(new MyThing
                {
                    Field1 = row.GetInt("Field1"),
                    Filed2 = row.GetDateTimeNull("Field2")
                    ... etc
                }),
                new SqlParameter("@ThingID", thingId)).Value;
        }, ct);

        if (myThing is null)
            throw new LogicalNotFoundException($"MyThing {thingId} was not found");

        return Ok(myThing);        
    }
}

5. Executing Stored Procedures with no Result Set

To execute a stored procedure that does not return a result set, use one of these three options. Typically used with DML procedures that insert/update/delete. 👉 All forms also have an overload that accepts a CancellationToken

  1. ExecuteProcAsync(string procName, params SqlParameter[] parameters)
    • This will execute the procedure, 👉 and fail if no rows were modified
  2. ExecuteProcAsync(string procName, int expectedRows, params SqlParameter[] parameters)
    • This will execute the procedure, and fail if the rows modified does not match expectedRows
  3. ExecuteProcUncheckedAsync(string procName, params SqlParameter[] parameters)
    • This will execute the procedure, and return the number of rows modified

6. Executing Stored Procedures that return a Result Set

To execute a stored procedure returns a result set, use one of these three options. Typically used with SELECT queries. 👉 All forms also have an overload that accepts a CancellationToken

  1. ExecuteQueryProcAsync(string procName, params SqlParameter[] parameters)
    • Returns an IAsyncEnumerable<IResult> which can be enumerated to extract objects from rows.
  2. ExecuteQueryProcListAsync<T>(string procName, Func<IResult, Task<T>> readerFunc, params SqlParameter[] parameters)
    • Returns a List<T> of objects returned from the Func called on each row returned.
    • 👉 Always returns a non-null List<T> that may be empty.
  3. ExecuteQueryProcOneAsync(string procName, Func<IResult, Task> readerFunc, params SqlParameter[] parameters)
    • Calls the Func with a single row result (if one found), returns true/false if row was found.
  4. ExecuteQueryProcOneAsync<T>(string procName, Func<IResult, Task<T>> readerFunc, params SqlParameter[] parameters)
    • Calls the Func with a single row result and returns the output inside a SqlSingleResult<T> object.
    • Use .Value to get the result and .RowReturned to determine if a row was returned.

7. Special Connection Features

  • SetRollback(): Will mark this transaction for later rollback when the transaction function is complete
  • _WillBeRollingBack(): Determine if SetRollback() has been called on this transaction
  • IsAsync(): Determine if this transaction supports async operations
  • CommandTimeout {get; set;}: The default timeout for sql commands (in seconds)

8. Rollback and Post Commit Actions

These allow you to have code execute after a rollback or a commit occurs. Useful for cleaning up non-transaction items or taking actions after database operations are committed.

Post Rollback Actions:

  • AddRollbackAction(string? desc, Action onRollback) AddAsyncRollbackAction(string? desc, Func<Task> onRollbackAsync)
    • These will execute the action/func after a rollback has completed
    • Common use case: Undoing a non-transactional thing that should only exist if the transaction succeeded

Post Commit Actions:

  • AddPostCommitAction(string? desc, Action postCommit) AddAsyncPostCommitAction(string? desc, Func<Task> postCommitAsync)
    • These will execute the action/func after the transaction has been committed
    • Common use case: Performing some action that should only occur if the database operations are confirmed.

9. Multiple Result Sets

Some stored procedures can actually return multiple result sets in a single call.

To execute and process each result set, use this method: ExecuteQueryProcMultiResultSetAsync(string procName, Func<IAsyncMultiResultSet, Task> readerFunc, params SqlParameter[] parameters)

Example

  await c.ExecuteQueryProcMultiResultSetAsync(
      "usp_GetMultipleResults", 
      async (mrs) =>
      {
          var rs = await mrs.NextResultSetAsync();
          await processSet1(rs);

          rs = await mrs.NextResultSetAsync();
          await processSet2(rs);

          rs = await mrs.NextResultSetAsync();
          await processSet3(rs);
      },
      new SqlParameter("@Int1", 10));

10. IDeferredSqlConnection

This allows for recording a sequence of stored procedure calls (without actually executing them) and then executing them all at one at a later time.

Example:

    var deferred = _txnProvider.GetDeferred();

    // no sql actions occur
    deferred.ExecuteProc("usp_InsertThing". new SqlParameter("@ID", 5));
    deferred.ExecuteProc("usp_InsertThing". new SqlParameter("@ID", 10));    

    await _txnProvider.ExecuteTxnAsync(connection =>
    {
        // now the sql actions are executed
        await connection.ExecuteDeferredAsync(deferred);
    });
    

11. Raw SQL Transactions

Normal transactions as shown above only allow for executing stored procedures. There are times and cases where executing a raw SQL statement is required. To do so, use ExecuteRawTxnAsync as shown in the below example:

        var myThing = await _txnProvider.ExecuteRawTxnAsync(connection =>
        {
            return await connection.ExecuteRawQueryOneAsync(
                "SELECT Field1, Field2 FROM MyThings WHERE ThingID = @ThingID",
                row => Task.FromResult(new MyThing
                {
                    Field1 = row.GetInt("Field1"),
                    Filed2 = row.GetDateTimeNull("Field2")
                    ... etc
                }),
                new SqlParameter("@ThingID", thingId)).Value;
        }, ct);

The methods are analogues of the methods in sections 5, 6 and 9.

  • ExecuteRawAsync for DML
  • ExecuteRawQueryListAsync for queries that return a list of results
  • ExecuteRawQueryOneAsync for queries that return a single result
  • ExecuteRawQueryMultiResultSetAsync for queries that return multiple result sets
Product Versions
.NET net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Plinth.Database.MSSql:

Package Downloads
Plinth.Hangfire.MSSql The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

Plinth Hangfire Utilities for SQL Server

Plinth.Storage.MSSql The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

SQL Server driver for Plinth.Storage

Plinth.Database.Dapper.MSSql The ID prefix of this package has been reserved for one of the owners of this package by NuGet.org.

Dapper extensions for plinth database framework for MS Sql Server

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.5.4 146 3/7/2023
1.5.3 125 3/3/2023
1.5.2 283 1/11/2023
1.5.2-b92.7c961f5f 54 1/11/2023
1.5.0 537 11/9/2022
1.5.0-b88.7a7c20cd 57 11/9/2022
1.4.7 2,130 10/20/2022
1.4.6 801 10/17/2022
1.4.5 988 10/1/2022
1.4.4 892 8/16/2022
1.4.3 692 8/2/2022
1.4.2 709 7/19/2022
1.4.2-b80.7fdbfd04 84 7/19/2022
1.4.2-b74.acaf86f5 72 6/15/2022
1.4.1 971 6/13/2022
1.4.0 839 6/6/2022
1.3.8 2,139 4/12/2022
1.3.7 789 3/21/2022
1.3.6 769 3/17/2022
1.3.6-b67.ca5053f3 83 3/16/2022
1.3.6-b66.4a9683e6 79 3/16/2022
1.3.5 796 2/23/2022
1.3.4 1,122 1/20/2022
1.3.3 532 12/29/2021
1.3.2 502 12/11/2021
1.3.1 418 11/12/2021
1.3.0 423 11/8/2021
1.2.3 1,616 9/22/2021
1.2.2 685 8/20/2021
1.2.1 1,074 8/5/2021
1.2.0 554 8/1/2021
1.2.0-b37.a54030b9 111 6/24/2021
1.1.6 2,920 3/22/2021
1.1.5 634 3/9/2021
1.1.4 1,816 2/27/2021
1.1.3 486 2/17/2021
1.1.2 531 2/12/2021
1.1.1 867 2/1/2021
1.1.0 555 12/16/2020
1.1.0-b27.b66c309b 237 11/15/2020
1.0.12 1,195 10/18/2020
1.0.11 573 10/6/2020
1.0.10 803 9/30/2020
1.0.9 548 9/29/2020
1.0.8 730 9/26/2020
1.0.7 674 9/19/2020
1.0.6 591 9/3/2020
1.0.5 611 9/2/2020
1.0.4 941 9/1/2020
1.0.3 539 9/1/2020
1.0.2 616 8/29/2020
1.0.1 620 8/29/2020
1.0.0 599 8/29/2020
1.0.0-b1.c22f563d 205 8/28/2020

net7.0 support and removed netcoreapp3.1