persistence/DD.Persistence.Database.Postgres/Services/ArchiveService.cs
Olga Nemt c844131bbe
All checks were successful
Unit tests / test (push) Successful in 56s
Переименование базы данных
2025-01-24 17:31:58 +05:00

57 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}