|
@@ -1,49 +1,130 @@
|
|
|
using DbType = System.Data.DbType;
|
|
using DbType = System.Data.DbType;
|
|
|
using System.Data.Common;
|
|
using System.Data.Common;
|
|
|
|
|
+using System.Data.Odbc;
|
|
|
using System.Globalization;
|
|
using System.Globalization;
|
|
|
|
|
+using System.Text;
|
|
|
using System.Text.Json;
|
|
using System.Text.Json;
|
|
|
using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
|
|
using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
|
|
|
|
|
+using Npgsql;
|
|
|
|
|
+using Oracle.ManagedDataAccess.Client;
|
|
|
|
|
+using Oracle.ManagedDataAccess.Types;
|
|
|
|
|
|
|
|
namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
|
|
namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
|
|
|
|
|
|
|
|
-internal sealed class NativeReadSession(DbConnection connection, RelationalSourceMapping mapping) : IRelationalReadSession
|
|
|
|
|
|
|
+internal enum SourceDialect { Unknown, MySql, SqlServer, PostgreSql, Oracle }
|
|
|
|
|
+
|
|
|
|
|
+internal sealed partial class NativeReadSession(DbConnection connection, RelationalSourceMapping mapping, SourceDialect dialect, bool odbc)
|
|
|
|
|
+ : IRelationalReadSession, IRelationalSourceInspection
|
|
|
{
|
|
{
|
|
|
private bool _verified;
|
|
private bool _verified;
|
|
|
- private bool IsMySql => mapping.Execution.ConnectorId == NativeRelationalDriver.MySqlId;
|
|
|
|
|
- private string Quote(string name) => IsMySql ? "`" + name.Replace("`", "``") + "`" : "[" + name.Replace("]", "]]") + "]";
|
|
|
|
|
|
|
+ private string Quote(string name) => dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.MySql => "`" + name.Replace("`", "``") + "`",
|
|
|
|
|
+ SourceDialect.SqlServer => "[" + name.Replace("]", "]]") + "]",
|
|
|
|
|
+ _ => "\"" + name.Replace("\"", "\"\"") + "\"",
|
|
|
|
|
+ };
|
|
|
private string Table => Quote(mapping.Schema) + "." + Quote(mapping.Table);
|
|
private string Table => Quote(mapping.Schema) + "." + Quote(mapping.Table);
|
|
|
private string Columns => string.Join(", ", mapping.Columns.Select(Quote));
|
|
private string Columns => string.Join(", ", mapping.Columns.Select(Quote));
|
|
|
-
|
|
|
|
|
public async Task<RelationalReadCapabilities> ProbeAsync(CancellationToken token)
|
|
public async Task<RelationalReadCapabilities> ProbeAsync(CancellationToken token)
|
|
|
{
|
|
{
|
|
|
_verified = false;
|
|
_verified = false;
|
|
|
- var readOnly = await HasReadOnlyGrantsAsync(token);
|
|
|
|
|
- if (!readOnly)
|
|
|
|
|
- return new(false, false, false);
|
|
|
|
|
-
|
|
|
|
|
- await using var key = connection.CreateCommand();
|
|
|
|
|
- key.CommandText = IsMySql ? NativeSourceSql.MySqlKey : NativeSourceSql.SqlServerKey;
|
|
|
|
|
- Add(key, "@schema", DbType.String, mapping.Schema);
|
|
|
|
|
- Add(key, "@table", DbType.String, mapping.Table);
|
|
|
|
|
- Add(key, "@key", DbType.String, mapping.PositionColumn);
|
|
|
|
|
- if (Convert.ToInt32(await key.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) != 1)
|
|
|
|
|
- return new(true, false, false);
|
|
|
|
|
|
|
+ if (dialect == SourceDialect.Unknown)
|
|
|
|
|
+ return Blocked("driver-family-unverified");
|
|
|
|
|
+
|
|
|
|
|
+ if (dialect == SourceDialect.PostgreSql)
|
|
|
|
|
+ {
|
|
|
|
|
+ if (mapping.Columns.Append(mapping.Schema).Append(mapping.Table).Append(mapping.PositionColumn)
|
|
|
|
|
+ .Any(name => Encoding.UTF8.GetByteCount(name) > 63))
|
|
|
|
|
+ return Blocked("identifier-unverified");
|
|
|
|
|
+ await using var searchPath = CreateCommand();
|
|
|
|
|
+ searchPath.CommandText = "SET search_path TO pg_catalog";
|
|
|
|
|
+ using var cancel = CancelOdbc(searchPath, token);
|
|
|
|
|
+ await searchPath.ExecuteNonQueryAsync(token);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (!await HasReadOnlyGrantsAsync(token))
|
|
|
|
|
+ return Blocked("read-only-permission-unverified");
|
|
|
|
|
+
|
|
|
|
|
+ try
|
|
|
|
|
+ {
|
|
|
|
|
+ await using var key = CreateCommand();
|
|
|
|
|
+ key.CommandText = dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.MySql => NativeSourceSql.MySqlKey,
|
|
|
|
|
+ SourceDialect.SqlServer when odbc => NativeSourceSql.SqlServerKey
|
|
|
|
|
+ .Replace("@schema", "?").Replace("@table", "?").Replace("@key", "?"),
|
|
|
|
|
+ SourceDialect.SqlServer => NativeSourceSql.SqlServerKey,
|
|
|
|
|
+ SourceDialect.PostgreSql => PostgreSqlSql(NativeSourceSql.PostgreSqlKey),
|
|
|
|
|
+ _ => NativeSourceSql.OracleKey,
|
|
|
|
|
+ };
|
|
|
|
|
+ BindTarget(key, includeKey: true);
|
|
|
|
|
+ using var cancel = CancelOdbc(key, token);
|
|
|
|
|
+ if (Convert.ToInt32(await key.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) != 1)
|
|
|
|
|
+ return Blocked("stable-key-unverified", readOnly: true);
|
|
|
|
|
+ }
|
|
|
|
|
+ catch (DbException) when (!token.IsCancellationRequested)
|
|
|
|
|
+ {
|
|
|
|
|
+ return Blocked("stable-key-unverified", readOnly: true);
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
// Validate access to the actual projection too (column-level grants are possible).
|
|
// Validate access to the actual projection too (column-level grants are possible).
|
|
|
- await using var projection = connection.CreateCommand();
|
|
|
|
|
- projection.CommandText = $"SELECT {Quote(mapping.PositionColumn)}, {Columns} FROM {Table} WHERE 1=0";
|
|
|
|
|
- await using var reader = await projection.ExecuteReaderAsync(token);
|
|
|
|
|
|
|
+ try
|
|
|
|
|
+ {
|
|
|
|
|
+ await using var projection = CreateCommand();
|
|
|
|
|
+ projection.CommandText = $"SELECT {Quote(mapping.PositionColumn)}, {Columns} FROM {Table} WHERE 1=0";
|
|
|
|
|
+ using var cancel = CancelOdbc(projection, token);
|
|
|
|
|
+ await using var reader = await projection.ExecuteReaderAsync(token);
|
|
|
|
|
+ }
|
|
|
|
|
+ catch (DbException) when (!token.IsCancellationRequested)
|
|
|
|
|
+ {
|
|
|
|
|
+ return Blocked("projection-unverified", readOnly: true);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (odbc || dialect is SourceDialect.PostgreSql or SourceDialect.Oracle)
|
|
|
|
|
+ {
|
|
|
|
|
+ try
|
|
|
|
|
+ {
|
|
|
|
|
+ // Exercises both bound markers, including resumed reads. No sample is submitted.
|
|
|
|
|
+ await using var paging = CreatePageCommand(long.MinValue, 1);
|
|
|
|
|
+ using var cancel = CancelOdbc(paging, token);
|
|
|
|
|
+ await using var reader = await paging.ExecuteReaderAsync(token);
|
|
|
|
|
+ if (await reader.ReadAsync(token))
|
|
|
|
|
+ _ = reader.GetDecimal(0);
|
|
|
|
|
+ }
|
|
|
|
|
+ catch (Exception error) when (!token.IsCancellationRequested && error is DbException or InvalidCastException or OverflowException)
|
|
|
|
|
+ {
|
|
|
|
|
+ return Blocked("parameterized-paging-unverified", readOnly: true);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
_verified = true;
|
|
_verified = true;
|
|
|
return new(true, true, false);
|
|
return new(true, true, false);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ private static RelationalReadCapabilities Blocked(string reason, bool readOnly = false) =>
|
|
|
|
|
+ new(readOnly, false, false) { Reason = reason };
|
|
|
|
|
+
|
|
|
private async Task<bool> HasReadOnlyGrantsAsync(CancellationToken token)
|
|
private async Task<bool> HasReadOnlyGrantsAsync(CancellationToken token)
|
|
|
{
|
|
{
|
|
|
- await using var command = connection.CreateCommand();
|
|
|
|
|
- if (!IsMySql)
|
|
|
|
|
|
|
+ await using var command = CreateCommand();
|
|
|
|
|
+ using var cancel = CancelOdbc(command, token);
|
|
|
|
|
+ if (dialect != SourceDialect.MySql)
|
|
|
{
|
|
{
|
|
|
- command.CommandText = NativeSourceSql.SqlServerReadOnly;
|
|
|
|
|
- return Convert.ToInt32(await command.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) == 1;
|
|
|
|
|
|
|
+ command.CommandText = dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.SqlServer => NativeSourceSql.SqlServerReadOnly,
|
|
|
|
|
+ SourceDialect.PostgreSql => PostgreSqlSql(NativeSourceSql.PostgreSqlReadOnly),
|
|
|
|
|
+ _ => NativeSourceSql.OracleReadOnly,
|
|
|
|
|
+ };
|
|
|
|
|
+ if (dialect != SourceDialect.SqlServer)
|
|
|
|
|
+ BindTarget(command, includeKey: false);
|
|
|
|
|
+ try
|
|
|
|
|
+ {
|
|
|
|
|
+ return Convert.ToInt32(await command.ExecuteScalarAsync(token), CultureInfo.InvariantCulture) == 1;
|
|
|
|
|
+ }
|
|
|
|
|
+ catch (DbException) when (!token.IsCancellationRequested)
|
|
|
|
|
+ {
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
command.CommandText = "SHOW GRANTS";
|
|
command.CommandText = "SHOW GRANTS";
|
|
@@ -68,24 +149,18 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
|
|
|
if (request.BatchSize < 1 || request.BatchSize == int.MaxValue)
|
|
if (request.BatchSize < 1 || request.BatchSize == int.MaxValue)
|
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
|
|
|
|
|
- await using var command = connection.CreateCommand();
|
|
|
|
|
- var key = Quote(mapping.PositionColumn);
|
|
|
|
|
- var where = "";
|
|
|
|
|
decimal? previous = null;
|
|
decimal? previous = null;
|
|
|
if (request.LastCommittedCheckpoint is { } checkpoint)
|
|
if (request.LastCommittedCheckpoint is { } checkpoint)
|
|
|
{
|
|
{
|
|
|
if (!decimal.TryParse(checkpoint, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var after)
|
|
if (!decimal.TryParse(checkpoint, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var after)
|
|
|
|| after.ToString(CultureInfo.InvariantCulture) != checkpoint
|
|
|| after.ToString(CultureInfo.InvariantCulture) != checkpoint
|
|
|
- || after < long.MinValue || after > (IsMySql ? (decimal)ulong.MaxValue : long.MaxValue))
|
|
|
|
|
|
|
+ || !FitsPosition(after))
|
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
previous = after;
|
|
previous = after;
|
|
|
- where = $" WHERE {key} > @after";
|
|
|
|
|
- Add(command, "@after", DbType.Decimal, after);
|
|
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- Add(command, "@take", DbType.Int32, request.BatchSize + 1);
|
|
|
|
|
- var projection = $"CAST({key} AS DECIMAL(20,0)), {Columns} FROM {Table}{where} ORDER BY {key}";
|
|
|
|
|
- command.CommandText = IsMySql ? $"SELECT {projection} LIMIT @take" : $"SELECT TOP (@take) {projection}";
|
|
|
|
|
|
|
+ await using var command = CreatePageCommand(previous, request.BatchSize + 1);
|
|
|
|
|
+ using var cancel = CancelOdbc(command, token);
|
|
|
await using var reader = await command.ExecuteReaderAsync(token);
|
|
await using var reader = await command.ExecuteReaderAsync(token);
|
|
|
using var buffer = new MemoryStream();
|
|
using var buffer = new MemoryStream();
|
|
|
using var json = new Utf8JsonWriter(buffer);
|
|
using var json = new Utf8JsonWriter(buffer);
|
|
@@ -98,6 +173,8 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
|
|
|
while (count < request.BatchSize && await reader.ReadAsync(token))
|
|
while (count < request.BatchSize && await reader.ReadAsync(token))
|
|
|
{
|
|
{
|
|
|
var position = reader.GetDecimal(0);
|
|
var position = reader.GetDecimal(0);
|
|
|
|
|
+ if (!FitsPosition(position))
|
|
|
|
|
+ throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
if (previous.HasValue && position <= previous.Value)
|
|
if (previous.HasValue && position <= previous.Value)
|
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
previous = position;
|
|
previous = position;
|
|
@@ -108,7 +185,7 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
|
|
|
if (reader.IsDBNull(i + 1))
|
|
if (reader.IsDBNull(i + 1))
|
|
|
json.WriteNullValue();
|
|
json.WriteNullValue();
|
|
|
else
|
|
else
|
|
|
- JsonSerializer.Serialize(json, reader.GetValue(i + 1));
|
|
|
|
|
|
|
+ WriteValue(json, reader, i + 1);
|
|
|
}
|
|
}
|
|
|
json.WriteEndObject();
|
|
json.WriteEndObject();
|
|
|
count++;
|
|
count++;
|
|
@@ -126,14 +203,112 @@ internal sealed class NativeReadSession(DbConnection connection, RelationalSourc
|
|
|
return new(batchId, batchId, buffer.ToArray(), next, next, more);
|
|
return new(batchId, batchId, buffer.ToArray(), next, next, more);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ private bool FitsPosition(decimal position) => dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.MySql => position >= long.MinValue && position <= ulong.MaxValue,
|
|
|
|
|
+ SourceDialect.Oracle => position >= -9999999999999999999m && position <= 9999999999999999999m,
|
|
|
|
|
+ _ => position >= long.MinValue && position <= long.MaxValue,
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ private DbCommand CreateCommand()
|
|
|
|
|
+ {
|
|
|
|
|
+ var command = connection.CreateCommand();
|
|
|
|
|
+ if (odbc || dialect is SourceDialect.PostgreSql or SourceDialect.Oracle)
|
|
|
|
|
+ command.CommandTimeout = 8;
|
|
|
|
|
+ if (command is OracleCommand oracle)
|
|
|
|
|
+ oracle.BindByName = true;
|
|
|
|
|
+ return command;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private DbCommand CreatePageCommand(decimal? after, int take)
|
|
|
|
|
+ {
|
|
|
|
|
+ var command = CreateCommand();
|
|
|
|
|
+ var position = Quote(mapping.PositionColumn);
|
|
|
|
|
+ var afterParameter = Marker("@after", ":after", 1);
|
|
|
|
|
+ var takeParameter = Marker("@take", ":take", after.HasValue ? 2 : 1);
|
|
|
|
|
+ var filter = after.HasValue ? $" WHERE {position} > {afterParameter}" : "";
|
|
|
|
|
+ var ordered = $"CAST({position} AS DECIMAL(20,0)), {Columns} FROM {Table} src{filter} ORDER BY src.{position}";
|
|
|
|
|
+ command.CommandText = dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.SqlServer => $"SELECT TOP ({takeParameter}) {ordered}",
|
|
|
|
|
+ SourceDialect.Oracle => $"SELECT {ordered} FETCH NEXT {takeParameter} ROWS ONLY",
|
|
|
|
|
+ _ => $"SELECT {ordered} LIMIT {takeParameter}",
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ // With ODBC, TOP appears before WHERE. LIMIT uses the opposite parameter order.
|
|
|
|
|
+ var topFirst = odbc && dialect == SourceDialect.SqlServer;
|
|
|
|
|
+ if (topFirst) Add(command, "take", DbType.Int32, take);
|
|
|
|
|
+ if (after is { } value)
|
|
|
|
|
+ {
|
|
|
|
|
+ if (dialect == SourceDialect.PostgreSql)
|
|
|
|
|
+ Add(command, "after", DbType.Int64, (long)value);
|
|
|
|
|
+ else
|
|
|
|
|
+ Add(command, "after", DbType.Decimal, value);
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!topFirst) Add(command, "take", DbType.Int32, take);
|
|
|
|
|
+ return command;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private string Marker(string named, string oracle, int position) =>
|
|
|
|
|
+ odbc ? "?" : dialect switch
|
|
|
|
|
+ {
|
|
|
|
|
+ SourceDialect.Oracle => oracle,
|
|
|
|
|
+ SourceDialect.PostgreSql => "$" + position.ToString(CultureInfo.InvariantCulture),
|
|
|
|
|
+ _ => named,
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ private string PostgreSqlSql(string format) => string.Format(CultureInfo.InvariantCulture, format,
|
|
|
|
|
+ Marker("", "", 1), Marker("", "", 2), Marker("", "", 3));
|
|
|
|
|
+
|
|
|
|
|
+ private void BindTarget(DbCommand command, bool includeKey)
|
|
|
|
|
+ {
|
|
|
|
|
+ var oracle = dialect == SourceDialect.Oracle;
|
|
|
|
|
+ Add(command, "schema", DbType.String, mapping.Schema);
|
|
|
|
|
+ Add(command, oracle ? "source_table" : "table", DbType.String, mapping.Table);
|
|
|
|
|
+ if (includeKey) Add(command, oracle ? "source_key" : "key", DbType.String, mapping.PositionColumn);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static void WriteValue(Utf8JsonWriter json, DbDataReader reader, int index)
|
|
|
|
|
+ {
|
|
|
|
|
+ if (reader is OracleDataReader oracle && oracle.GetDataTypeName(index) == "NUMBER")
|
|
|
|
|
+ {
|
|
|
|
|
+ try
|
|
|
|
|
+ {
|
|
|
|
|
+ var number = oracle.GetOracleDecimal(index);
|
|
|
|
|
+ var value = number.Value;
|
|
|
|
|
+ if (new OracleDecimal(value).CompareTo(number) != 0)
|
|
|
|
|
+ throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
|
|
+ json.WriteNumberValue(value);
|
|
|
|
|
+ }
|
|
|
|
|
+ catch (Exception error) when (error is OverflowException or InvalidCastException)
|
|
|
|
|
+ {
|
|
|
|
|
+ throw new ConnectorContractException(ConnectorError.InvalidBatch);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ else
|
|
|
|
|
+ JsonSerializer.Serialize(json, reader.GetValue(index));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
private static void Add(DbCommand command, string name, DbType type, object value)
|
|
private static void Add(DbCommand command, string name, DbType type, object value)
|
|
|
{
|
|
{
|
|
|
var parameter = command.CreateParameter();
|
|
var parameter = command.CreateParameter();
|
|
|
- parameter.ParameterName = name;
|
|
|
|
|
|
|
+ parameter.ParameterName = command switch
|
|
|
|
|
+ {
|
|
|
|
|
+ NpgsqlCommand => "",
|
|
|
|
|
+ OracleCommand => name,
|
|
|
|
|
+ _ => "@" + name,
|
|
|
|
|
+ };
|
|
|
parameter.DbType = type;
|
|
parameter.DbType = type;
|
|
|
parameter.Value = value;
|
|
parameter.Value = value;
|
|
|
command.Parameters.Add(parameter);
|
|
command.Parameters.Add(parameter);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ private static CancellationTokenRegistration CancelOdbc(DbCommand command, CancellationToken token) =>
|
|
|
|
|
+ command is OdbcCommand ? token.UnsafeRegister(static state =>
|
|
|
|
|
+ {
|
|
|
|
|
+ try { ((OdbcCommand)state!).Cancel(); }
|
|
|
|
|
+ catch (Exception error) when (error is DbException or InvalidOperationException or NotSupportedException) { }
|
|
|
|
|
+ }, command) : default;
|
|
|
|
|
+
|
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
public ValueTask DisposeAsync() => connection.DisposeAsync();
|
|
|
}
|
|
}
|