using System.Data.Common; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors; using Microsoft.Data.SqlClient; using MySqlConnector; using Npgsql; using Oracle.ManagedDataAccess.Client; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational; /// A host-approved source mapping, scoped to one execution and credential reference. public sealed record RelationalSourceMapping(ConnectorExecution Execution, string SecretRef, string Database, string Schema, string Table, string PositionColumn, IReadOnlyList Columns) { public bool IncludeFactoryInEnvelope { get; init; } } /// Native adapters for database reads through RelationalConnectorRuntime. Supply only the mapping /// authorized by the host. The credential resolver receives that exact binding and reference. public sealed class NativeRelationalDriver : IRelationalSourceDriver { public const string MySqlId = "mdp.mysql"; public const string SqlServerId = "mdp.sqlserver"; public const string PostgreSqlId = "mdp.postgresql"; public const string OracleId = "mdp.oracle"; public const string Version = "1.0.0"; private readonly RelationalSourceMapping _mapping; private readonly Func> _resolve; public NativeRelationalDriver(RelationalSourceMapping mapping, Func> resolve) : this(mapping, resolve, false) { } private readonly bool _odbc; // The ODBC driver delegates only the shared binding and session lifecycle here. internal NativeRelationalDriver(RelationalSourceMapping mapping, Func> resolve, bool odbc) { var id = mapping.Execution.ConnectorId; if ((odbc ? id != OdbcRelationalDriver.Id : id is not (MySqlId or SqlServerId or PostgreSqlId or OracleId)) || mapping.Execution.ConnectorVersion != Version) throw new ConnectorContractException(ConnectorError.UnsupportedVersion); if (mapping.Execution.Mode != ConnectorManifest.Database) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); var columns = mapping.Columns?.ToArray() ?? []; var limit = id == PostgreSqlId ? 63 : id == MySqlId ? 64 : 128; if (string.IsNullOrWhiteSpace(mapping.SecretRef) || columns.Length == 0 || columns.Distinct(StringComparer.OrdinalIgnoreCase).Count() != columns.Length || columns.Concat(new[] { mapping.Database, mapping.Schema, mapping.Table, mapping.PositionColumn }) .Any(name => string.IsNullOrWhiteSpace(name) || name.Length > limit || name.Any(char.IsControl)) || (id == MySqlId && mapping.Database != mapping.Schema) || (id == PostgreSqlId && new[] { mapping.Schema, mapping.Table, mapping.PositionColumn } .Concat(columns).Any(name => System.Text.Encoding.UTF8.GetByteCount(name) > 63))) throw new ConnectorContractException(ConnectorError.InvalidManifest); _mapping = mapping with { Columns = columns }; _resolve = resolve ?? throw new ArgumentNullException(nameof(resolve)); _odbc = odbc; } public string ConnectorId => _mapping.Execution.ConnectorId; public string ConnectorVersion => Version; private static MySqlConnection CreateMySqlConnection(string connectionString) { var options = new MySqlConnectionStringBuilder(connectionString); // With the host's current provider, certificate verification needs an explicit CA // before password authentication (GHSA-473q-m89c-ghf8). if (options.SslMode is MySqlSslMode.VerifyCA or MySqlSslMode.VerifyFull && string.IsNullOrWhiteSpace(options.SslCa)) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); return new MySqlConnection(options.ConnectionString); } public Task OpenReadOnlyAsync( ConnectorExecution execution, string secretRef, CancellationToken cancellationToken) => OpenReadOnlyAsync(execution, secretRef, null, cancellationToken); internal async Task OpenReadOnlyAsync( ConnectorExecution execution, string secretRef, string? odbcFamily, CancellationToken cancellationToken) { if (execution != _mapping.Execution || secretRef != _mapping.SecretRef) throw new ConnectorContractException(ConnectorError.ScopeMismatch); cancellationToken.ThrowIfCancellationRequested(); var connectionString = await _resolve(execution.Binding, secretRef, cancellationToken); DbConnection connection = ConnectorId switch { MySqlId => CreateMySqlConnection(connectionString), SqlServerId => new SqlConnection(connectionString), PostgreSqlId => new NpgsqlConnection(connectionString), OracleId => new OracleConnection(connectionString), _ => OdbcRelationalDriver.CreateConnection(connectionString), }; try { // System.Data.Odbc uses synchronous I/O even for its async-shaped methods. if (_odbc) await Task.Run(connection.Open, cancellationToken); else await connection.OpenAsync(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var dialect = ConnectorId switch { MySqlId => SourceDialect.MySql, SqlServerId => SourceDialect.SqlServer, PostgreSqlId => SourceDialect.PostgreSql, OracleId => SourceDialect.Oracle, _ => OdbcRelationalDriver.GetDialect((System.Data.Odbc.OdbcConnection)connection, odbcFamily), }; var database = connection.Database; if (dialect == SourceDialect.Oracle) { await using var identity = connection.CreateCommand(); identity.CommandTimeout = 8; identity.CommandText = "SELECT SYS_CONTEXT('USERENV', 'CON_NAME') FROM DUAL"; database = (string?)await identity.ExecuteScalarAsync(cancellationToken); } if (dialect != SourceDialect.Unknown && !string.Equals(database, _mapping.Database, StringComparison.Ordinal)) throw new ConnectorContractException(ConnectorError.ScopeMismatch); return new NativeReadSession(connection, _mapping, dialect, _odbc); } catch { await connection.DisposeAsync(); throw; } } }