57 lines
2.0 KiB
C#
57 lines
2.0 KiB
C#
using DD.Persistence.Services.Interfaces;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.Extensions.Configuration;
|
||
using Microsoft.Extensions.Logging;
|
||
using Npgsql;
|
||
|
||
namespace DD.Persistence.Database.Postgres.Services;
|
||
|
||
/// <summary>
|
||
/// Сервис по работе с источником данных - базой postgres
|
||
/// </summary>
|
||
public class PostgresArchiveService : IArchiveService
|
||
{
|
||
private string connectionString;
|
||
private ILogger<PostgresArchiveService> logger;
|
||
|
||
/// <summary>
|
||
/// Сервис по работе с источником данных - базой postgres
|
||
/// </summary>
|
||
/// <param name="configuration"></param>
|
||
public PostgresArchiveService(IConfiguration configuration, ILogger<PostgresArchiveService> logger)
|
||
{
|
||
this.connectionString = configuration.GetConnectionString("SystemBaseConnection")!;
|
||
this.logger = logger;
|
||
}
|
||
public Task Create(string newName, CancellationToken token)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public async Task Rename(string newName, CancellationToken token)
|
||
{
|
||
await using var connection = new NpgsqlConnection(connectionString);
|
||
try
|
||
{
|
||
await connection.OpenAsync();
|
||
|
||
var sqlCloseConnect =
|
||
$"SELECT pg_terminate_backend(pg_stat_activity.pid) " +
|
||
$"FROM pg_stat_activity " +
|
||
$"WHERE pg_stat_activity.datname = 'persistence' AND pid <> pg_backend_pid();";
|
||
await using var command = new NpgsqlCommand(sqlCloseConnect, connection);
|
||
await command.ExecuteNonQueryAsync();
|
||
|
||
var rename = $"ALTER DATABASE persistence RENAME TO {newName};";
|
||
await using var sqlRenameDatabase = new NpgsqlCommand(rename, connection);
|
||
await sqlRenameDatabase.ExecuteNonQueryAsync();
|
||
}
|
||
catch (NpgsqlException exception)
|
||
{
|
||
this.logger.LogError(exception.Message);
|
||
throw;
|
||
}
|
||
|
||
}
|
||
}
|