using Khaemhat.Data.Execution;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Migrations;
/// A row of schema_version.
/// The owning module.
/// The version.
/// The name.
/// When it was applied (UTC).
/// SHA-256 of the statements that were run, in hexadecimal.
public sealed record AppliedMigration(string Module, long Version, string Name, DateTime AppliedAt, string Checksum);
///
/// The schema_version(module, version, name, applied_at, checksum) table present in every database (SPEC ยง5.3).
///
public static class SchemaVersionStore
{
/// The table name.
public const string Table = "schema_version";
/// The operation creating the table if it is missing.
public static CreateTableOperation CreateOperation { get; } = BuildCreateOperation();
/// Creates the table if it is missing.
/// The unit of work.
/// Cancellation.
/// A task.
public static async Task EnsureCreatedAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
foreach (var statement in unitOfWork.Provider.Ddl.Generate([CreateOperation]))
{
await unitOfWork.ExecuteAsync(SqlFragment.Literal(statement), cancellationToken).ConfigureAwait(false);
}
}
/// All applied migrations.
/// The unit of work.
/// Cancellation.
/// The rows, ordered by version.
public static Task> ReadAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
return unitOfWork.QueryAsync(
SqlFragment.Literal("SELECT module, version, name, applied_at, checksum FROM ") + SqlFragment.Identifier(Table)
+ SqlFragment.Literal(" ORDER BY version, module"),
cancellationToken);
}
/// Whether a version is applied (read inside the migration transaction).
/// The unit of work.
/// The module.
/// The version.
/// Cancellation.
/// if applied.
public static async Task IsAppliedAsync(UnitOfWork unitOfWork, string module, long version, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
var count = await unitOfWork.QuerySingleAsync(
SqlFragment.Of($"SELECT COUNT(*) FROM {SqlFragment.Identifier(Table)} WHERE module = {module} AND version = {version}"),
cancellationToken).ConfigureAwait(false);
return count > 0;
}
/// Records an applied migration.
/// The unit of work, inside the migration transaction.
/// The row.
/// Cancellation.
/// A task.
public static Task RecordAsync(UnitOfWork unitOfWork, AppliedMigration applied, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentNullException.ThrowIfNull(applied);
return unitOfWork.ExecuteAsync(
SqlFragment.Of(
$"INSERT INTO {SqlFragment.Identifier(Table)} (module, version, name, applied_at, checksum) VALUES ({applied.Module}, {applied.Version}, {applied.Name}, {applied.AppliedAt}, {applied.Checksum})"),
cancellationToken);
}
private static CreateTableOperation BuildCreateOperation()
{
var builder = new SchemaBuilder();
builder.CreateTable(Table, t =>
{
t.String("module", 50).NotNull();
t.Int64("version").NotNull();
t.String("name", 200).NotNull();
t.DateTimeUtc("applied_at").NotNull();
t.String("checksum", 64).NotNull();
t.PrimaryKey("module", "version");
});
return ((CreateTableOperation)builder.Operations[0]) with { IfNotExists = true };
}
}