using System.Data; using System.Data.Common; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational; internal sealed partial class NativeReadSession { private DbTransaction? _snapshot; private long? _logUpperBound; public async Task CaptureAsync(int pageSize, Func freeze, CancellationToken token, RelationalLogWindow? log = null) { ArgumentOutOfRangeException.ThrowIfLessThan(pageSize, 1); ArgumentOutOfRangeException.ThrowIfGreaterThan(pageSize, 100); if (_snapshot is not null || !(await ProbeAsync(token)).Full) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); if (dialect == SourceDialect.MySql) { await using var engine = CreateCommand(); engine.CommandText = """ SELECT ENGINE FROM information_schema.tables WHERE TABLE_SCHEMA=@schema AND TABLE_NAME=@table """; BindTarget(engine, includeKey: false); if (!string.Equals(await engine.ExecuteScalarAsync(token) as string, "InnoDB", StringComparison.OrdinalIgnoreCase)) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); } var isolation = dialect switch { SourceDialect.SqlServer => IsolationLevel.Snapshot, SourceDialect.Oracle => IsolationLevel.Serializable, _ => IsolationLevel.RepeatableRead, }; await using var tx = await connection.BeginTransactionAsync(isolation, token); _snapshot = tx; try { if (log is { LookbackPositions: < 0 } or { Completed: < 0 }) throw new ConnectorContractException(ConnectorError.InvalidManifest); var start = log?.Start; _logUpperBound = log is { ReplayOnly: true } ? log.Completed : null; long expected; long? upper = null; await using (var count = CreateCommand()) { var aggregate = dialect == SourceDialect.SqlServer ? "COUNT_BIG(*)" : "COUNT(*)"; if (log is null) { count.CommandText = $"SELECT {aggregate} FROM {Table}"; using var cancel = CancelOdbc(count, token); expected = Convert.ToInt64(await count.ExecuteScalarAsync(token)); } else { var key = Quote(mapping.PositionColumn); var where = start.HasValue ? $" WHERE {key}>{Marker("@after", ":after", 1)}" : ""; if (_logUpperBound.HasValue) where += $" AND {key}<={Marker("@upper", ":upper", 2)}"; if (start.HasValue) Add(count, "after", DbType.Int64, start.Value); if (_logUpperBound is { } limit) Add(count, "upper", DbType.Int64, limit); count.CommandText = $"SELECT {aggregate},MAX({key}),MIN({key}) FROM {Table}{where}"; using var cancel = CancelOdbc(count, token); await using var rows = await count.ExecuteReaderAsync(token); if (!await rows.ReadAsync(token)) throw new ConnectorContractException(ConnectorError.InvalidBatch); expected = Convert.ToInt64(rows.GetValue(0)); upper = rows.IsDBNull(1) ? start ?? 0 : Convert.ToInt64(rows.GetValue(1)); if (start.HasValue && !rows.IsDBNull(2) && Convert.ToInt64(rows.GetValue(2)) - 1 > start.Value) throw new ConnectorContractException(ConnectorError.HistoryExpired); if (upper < (log.Completed ?? 0) || expected != upper - (start ?? 0) || (!rows.IsDBNull(2) && Convert.ToInt64(rows.GetValue(2)) != (start ?? 0) + 1)) throw new ConnectorContractException(ConnectorError.UnsupportedCapability); } } string? after = start?.ToString(System.Globalization.CultureInfo.InvariantCulture); var ordinal = 0; long total = 0; while (true) { token.ThrowIfCancellationRequested(); var page = await ReadPageAsync(new(after, pageSize), token); if (page is null) break; using var doc = JsonDocument.Parse(page.Payload); if (page.Payload.Length > 3_000_000) throw new ConnectorContractException(ConnectorError.InvalidBatch); total += doc.RootElement.GetProperty("data").GetProperty("list").GetArrayLength(); await freeze(page, ++ordinal, token); after = page.NextCheckpoint; if (!page.HasMore) break; } if (total != expected) throw new ConnectorContractException(ConnectorError.InvalidBatch); await tx.RollbackAsync(token); return new(total, ordinal, upper); } finally { _snapshot = null; _logUpperBound = null; } } }