using System.Data.Common; using System.Globalization; using Khaemhat.Data.Schema; using Npgsql; namespace Khaemhat.Data.PostgreSql; /// Settings of the PostgreSQL provider (SPEC §5.2), from the instance settings. public sealed record PostgresProviderOptions { /// Maximum pooled connections per database (each database has its own pool). public int MaxPoolSize { get; init; } = 20; /// Server-side limit of a statement (statement_timeout of every session). public TimeSpan StatementTimeout { get; init; } = TimeSpan.FromSeconds(60); /// The application name shown in pg_stat_activity. public string ApplicationName { get; init; } = "khaemhat"; } /// /// The PostgreSQL engine (SPEC §1.3, §5.2), version 16 or later: one connection pool per database, a statement timeout /// per session, databases created with CREATE DATABASE on the server (the role needs CREATEDB). /// /// The provider settings. public sealed class PostgresProvider(PostgresProviderOptions options) : IDbProvider { /// The oldest supported major version. public const int MinimumMajorVersion = 16; /// Creates the provider with default settings. public PostgresProvider() : this(new PostgresProviderOptions()) { } /// public DbEngine Engine => DbEngine.PostgreSql; /// public ISqlDialect Dialect => PostgresDialect.Instance; /// public DdlGenerator Ddl { get; } = new PostgresSchemaBuilder(); /// The settings. public PostgresProviderOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options)); /// public string BuildConnectionString(DatabaseUrl url) { ArgumentNullException.ThrowIfNull(url); if (url.Engine != DbEngine.PostgreSql) { throw new ArgumentException("Not a PostgreSQL URL.", nameof(url)); } var builder = new NpgsqlConnectionStringBuilder { Host = url.Host, Port = url.Port ?? 5432, Username = url.UserName, Password = url.Password, Database = url.Database.Length == 0 ? "postgres" : url.Database, MaxPoolSize = Options.MaxPoolSize, ApplicationName = Options.ApplicationName, Options = string.Create(CultureInfo.InvariantCulture, $"-c statement_timeout={(long)Options.StatementTimeout.TotalMilliseconds}"), }; foreach (var (key, value) in url.Options) { try { builder[key] = value; } catch (ArgumentException) { throw new FormatException($"The PostgreSQL URL option '{key}' is not supported."); } } return builder.ToString(); } /// public DbConnection CreateConnection(string connectionString) => new NpgsqlConnection(connectionString); /// public Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) => PostgresDatabaseCreator.EnsureExistsAsync(connectionString, cancellationToken); /// public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default) => PostgresDatabaseCreator.DropAsync(connectionString, cancellationToken); /// public Task DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) => PostgresDatabaseCreator.ExistsAsync(connectionString, cancellationToken); /// public Task GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default) => PostgresServerInfo.ReadAsync(connectionString, cancellationToken); /// public bool IsTransient(Exception exception) => exception is NpgsqlException { IsTransient: true }; /// public ValueTask EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) => ValueTask.FromResult(NoScope.Instance); private sealed class NoScope : IAsyncDisposable { public static NoScope Instance { get; } = new(); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } }