| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- 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;
- /// <summary>A host-approved source mapping, scoped to one execution and credential reference.</summary>
- public sealed record RelationalSourceMapping(ConnectorExecution Execution, string SecretRef, string Database,
- string Schema, string Table, string PositionColumn, IReadOnlyList<string> Columns)
- {
- public bool IncludeFactoryInEnvelope { get; init; }
- }
- /// <summary>Native adapters for database reads through RelationalConnectorRuntime. Supply only the mapping
- /// authorized by the host. The credential resolver receives that exact binding and reference.</summary>
- 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<ConnectorBinding, string, CancellationToken, Task<string>> _resolve;
- public NativeRelationalDriver(RelationalSourceMapping mapping,
- Func<ConnectorBinding, string, CancellationToken, Task<string>> 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<ConnectorBinding, string, CancellationToken, Task<string>> 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<IRelationalReadSession> OpenReadOnlyAsync(
- ConnectorExecution execution, string secretRef, CancellationToken cancellationToken) =>
- OpenReadOnlyAsync(execution, secretRef, null, cancellationToken);
- internal async Task<IRelationalReadSession> 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;
- }
- }
- }
|