-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathPostgresDatabaseConnection.cs
67 lines (57 loc) · 2.61 KB
/
PostgresDatabaseConnection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using Medallion.Threading.Internal;
using Medallion.Threading.Internal.Data;
using Npgsql;
using System.Data;
namespace Medallion.Threading.Postgres;
internal sealed class PostgresDatabaseConnection : DatabaseConnection
{
public PostgresDatabaseConnection(IDbConnection connection)
: base(connection, isExternallyOwned: true)
{
}
public PostgresDatabaseConnection(IDbTransaction transaction)
: base(transaction, isExternallyOwned: true)
{
}
public PostgresDatabaseConnection(string connectionString)
: base(new NpgsqlConnection(connectionString), isExternallyOwned: false)
{
}
// see https://www.npgsql.org/doc/prepare.html
public override bool ShouldPrepareCommands => true;
public override bool IsCommandCancellationException(Exception exception) =>
exception is PostgresException postgresException
// cancellation error code from https://www.postgresql.org/docs/10/errcodes-appendix.html
&& postgresException.SqlState == "57014";
public override async Task SleepAsync(TimeSpan sleepTime, CancellationToken cancellationToken, Func<DatabaseCommand, CancellationToken, ValueTask<int>> executor)
{
Invariant.Require(sleepTime >= TimeSpan.Zero);
// if we're in a transaction, we need to establish a savepoint so that we can roll back if we
// get canceled without the whole transaction being aborted
const string SavePointName = "medallion_threading_postgres_database_connection_sleep";
var hasTransaction = this.HasTransaction;
if (hasTransaction)
{
using var setSavePointCommand = this.CreateCommand();
setSavePointCommand.SetCommandText("SAVEPOINT " + SavePointName);
await executor(setSavePointCommand, CancellationToken.None).ConfigureAwait(false);
}
try
{
using var sleepCommand = this.CreateCommand();
sleepCommand.SetCommandText("SELECT pg_catalog.pg_sleep(@sleepTimeSeconds)");
sleepCommand.AddParameter("sleepTimeSeconds", sleepTime.TotalSeconds, DbType.Double);
sleepCommand.SetTimeout(sleepTime);
await executor(sleepCommand, cancellationToken).ConfigureAwait(false);
}
finally
{
if (hasTransaction)
{
using var rollBackSavePointCommand = this.CreateCommand();
rollBackSavePointCommand.SetCommandText("ROLLBACK TO SAVEPOINT " + SavePointName);
await executor(rollBackSavePointCommand, CancellationToken.None).ConfigureAwait(false);
}
}
}
}