using System.Diagnostics.CodeAnalysis; using Npgsql; namespace Khaemhat.Data.PostgreSql; /// /// Creates and drops company databases on the server of KHAEMHAT_DB_SERVER (SPEC ยง5.4). It connects to the /// maintenance database postgres with the same credentials. Database names are validated identifiers: they /// cannot be parameters in DDL, so nothing else may reach the statement. /// public static class PostgresDatabaseCreator { private const string MaintenanceDatabase = "postgres"; /// Creates the database of if it does not exist (UTF-8, from template0). /// The connection string of the database to create. /// Cancellation. /// A task. public static async Task EnsureExistsAsync(string connectionString, CancellationToken cancellationToken = default) { var name = DatabaseName(connectionString); if (await ExistsAsync(connectionString, cancellationToken).ConfigureAwait(false)) { return; } try { await ExecuteOnMaintenanceAsync( connectionString, $"CREATE DATABASE \"{name}\" TEMPLATE template0 ENCODING 'UTF8'", cancellationToken).ConfigureAwait(false); } catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.DuplicateDatabase) { // Created concurrently by another instance: the goal is reached. } } /// Drops the database, closing its connections (WITH (FORCE)). Used only by the registry and restores. /// The connection string of the database to drop. /// Cancellation. /// A task. public static async Task DropAsync(string connectionString, CancellationToken cancellationToken = default) { var name = DatabaseName(connectionString); if (name == MaintenanceDatabase) { throw new InvalidOperationException("The maintenance database cannot be dropped."); } using (var connection = new NpgsqlConnection(connectionString)) { NpgsqlConnection.ClearPool(connection); } await ExecuteOnMaintenanceAsync(connectionString, $"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", cancellationToken).ConfigureAwait(false); } /// Whether the database exists. /// The connection string of the database. /// Cancellation. /// if it exists. public static async Task ExistsAsync(string connectionString, CancellationToken cancellationToken = default) { var name = DatabaseName(connectionString); await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString)); await connection.OpenAsync(cancellationToken).ConfigureAwait(false); await using var command = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @name", connection); command.Parameters.AddWithValue("name", name); return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is not null; } private static string DatabaseName(string connectionString) { var name = new NpgsqlConnectionStringBuilder(connectionString).Database ?? string.Empty; return SqlNames.IsValidIdentifier(name) ? name : throw new ArgumentException("The database name must be lower-case letters, digits and underscore.", nameof(connectionString)); } private static string MaintenanceConnectionString(string connectionString) => new NpgsqlConnectionStringBuilder(connectionString) { Database = MaintenanceDatabase, Pooling = false }.ToString(); [SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "The only variable part is a database name validated as a snake_case identifier.")] private static async Task ExecuteOnMaintenanceAsync(string connectionString, string sql, CancellationToken cancellationToken) { await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString)); await connection.OpenAsync(cancellationToken).ConfigureAwait(false); await using var command = new NpgsqlCommand(sql, connection); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } }