Skip to content

change conn string #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 43 additions & 12 deletions Extensions.Caching.PostgreSql/DatabaseOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ internal sealed class DatabaseOperations : IDatabaseOperations

public DatabaseOperations(IOptions<PostgreSqlCacheOptions> options, ILogger<DatabaseOperations> logger)
{
var cacheOptions = options.Value;
cacheOptions = options.Value;

if (string.IsNullOrEmpty(cacheOptions.ConnectionString))
{
Expand All @@ -37,7 +37,7 @@ public DatabaseOperations(IOptions<PostgreSqlCacheOptions> options, ILogger<Data
$"{nameof(PostgreSqlCacheOptions.TableName)} cannot be empty or null.");
}

ConnectionString = cacheOptions.ConnectionString;
_connectionString = cacheOptions.ConnectionString;
SystemClock = cacheOptions.SystemClock;

SqlCommands = new SqlCommands(cacheOptions.SchemaName, cacheOptions.TableName);
Expand All @@ -50,14 +50,45 @@ public DatabaseOperations(IOptions<PostgreSqlCacheOptions> options, ILogger<Data
}

private SqlCommands SqlCommands { get; }
private string _connectionString;
private readonly PostgreSqlCacheOptions cacheOptions;
private ISystemClock SystemClock { get; }

private string ConnectionString { get; }
/// <summary>
/// Modify current conection string
/// </summary>
/// <param name="newConnectionString">the new connection string to replace </param>
public void ChangeConnectionString(string newConnectionString)
{
string original = _connectionString;
try
{
using var newConnection = new NpgsqlConnection(newConnectionString);
newConnection.Open();
bool connected = newConnection.ExecuteScalar<bool>("SELECT 1=1;");
if (connected)
{
_connectionString = newConnectionString;
_logger.LogDebug("ChangeConnectionString: new connection is valid and is use");
}
newConnection.Close();
if (cacheOptions.CreateInfrastructure)
{
CreateSchemaAndTableIfNotExist();
}
}
catch (System.Exception ex)
{
_connectionString = original;
throw new InvalidOperationException("ChangeConnectionString failed.\nPrevious connection restored.", ex);
}

private ISystemClock SystemClock { get; }

}

private void CreateSchemaAndTableIfNotExist()
{
using (var connection = new NpgsqlConnection(ConnectionString))
using (var connection = new NpgsqlConnection(_connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
Expand All @@ -76,7 +107,7 @@ private void CreateSchemaAndTableIfNotExist()

public void DeleteCacheItem(string key)
{
using var connection = new NpgsqlConnection(ConnectionString);
using var connection = new NpgsqlConnection(_connectionString);

var deleteCacheItem = new CommandDefinition(
SqlCommands.DeleteCacheItemSql,
Expand All @@ -88,7 +119,7 @@ public void DeleteCacheItem(string key)

public async Task DeleteCacheItemAsync(string key, CancellationToken cancellationToken)
{
await using var connection = new NpgsqlConnection(ConnectionString);
await using var connection = new NpgsqlConnection(_connectionString);

var deleteCacheItem = new CommandDefinition(
SqlCommands.DeleteCacheItemSql,
Expand Down Expand Up @@ -116,7 +147,7 @@ public async Task DeleteExpiredCacheItemsAsync(CancellationToken cancellationTok
{
var utcNow = SystemClock.UtcNow;

await using var connection = new NpgsqlConnection(ConnectionString);
await using var connection = new NpgsqlConnection(_connectionString);

var deleteExpiredCache = new CommandDefinition(
SqlCommands.DeleteExpiredCacheSql,
Expand All @@ -132,7 +163,7 @@ public void SetCacheItem(string key, byte[] value, DistributedCacheEntryOptions
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);

using var connection = new NpgsqlConnection(ConnectionString);
using var connection = new NpgsqlConnection(_connectionString);

var expiresAtTime = options.SlidingExpiration == null
? absoluteExpiration!.Value
Expand All @@ -159,7 +190,7 @@ public async Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEn
var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
ValidateOptions(options.SlidingExpiration, absoluteExpiration);

await using var connection = new NpgsqlConnection(ConnectionString);
await using var connection = new NpgsqlConnection(_connectionString);

var expiresAtTime = options.SlidingExpiration == null
? absoluteExpiration!.Value
Expand All @@ -185,7 +216,7 @@ private byte[] GetCacheItem(string key, bool includeValue)
var utcNow = SystemClock.UtcNow;
byte[] value = null;

using var connection = new NpgsqlConnection(ConnectionString);
using var connection = new NpgsqlConnection(_connectionString);

var updateCacheItem = new CommandDefinition(
SqlCommands.UpdateCacheItemSql,
Expand All @@ -208,7 +239,7 @@ private async Task<byte[]> GetCacheItemAsync(string key, bool includeValue, Canc
var utcNow = SystemClock.UtcNow;
byte[] value = null;

await using var connection = new NpgsqlConnection(ConnectionString);
await using var connection = new NpgsqlConnection(_connectionString);

var updateCacheItem = new CommandDefinition(
SqlCommands.UpdateCacheItemSql,
Expand Down
1 change: 1 addition & 0 deletions Extensions.Caching.PostgreSql/IDatabaseOperations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ public interface IDatabaseOperations
Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken cancellationToken);

Task DeleteExpiredCacheItemsAsync(CancellationToken cancellationToken);
void ChangeConnectionString(string newConnectionString);
}
}