60 lines
3.8 KiB
C#

using System.Data;
using System.Text.RegularExpressions;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using PlotLine.Data;
using PlotLine.Services;
if (args.Length < 2) throw new ArgumentException("Usage: validate|publish FILE | backup development | migrate SQL | inspect development | query SQLFILE");
var operation = args[0];
if (operation is "validate" or "publish")
{
var graph = WritingSolverRepository.Parse(await File.ReadAllTextAsync(args[1]));
Console.WriteLine($"Valid graph {graph.Version}: {graph.Nodes.Count} nodes, {graph.Solutions.Count} solutions, {graph.Features.Count} features.");
foreach(var warning in WritingSolverValidator.Warnings(graph)) Console.WriteLine(warning);
if (operation == "validate") return;
}
// Protected development environment is parsed as data, never evaluated by a shell.
var line = File.ReadLines("/etc/plotdirector/plotdirector.env").Single(l => l.StartsWith("ConnectionStrings__DefaultConnection="));
var raw = line[(line.IndexOf('=')+1)..].Trim();
if (raw.Length > 1 && (raw[0]=='\'' || raw[0]=='"') && raw[^1]==raw[0]) raw=raw[1..^1];
var cs = new SqlConnectionStringBuilder(raw);
if (!string.Equals(cs.InitialCatalog,"PlotDirector_Development",StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Configured database is not development.");
await using var connection = new SqlConnection(cs.ConnectionString);
await connection.OpenAsync();
if (await connection.ExecuteScalarAsync<string>("SELECT DB_NAME()") != "PlotDirector_Development") throw new InvalidOperationException("Wrong database.");
Console.WriteLine("Verified PlotDirector_Development.");
if (operation is "migrate" or "backup")
{
var backup=$"/var/opt/mssql/backup/PlotDirector_Development_solver_{DateTime.UtcNow:yyyyMMdd_HHmmss}_{Guid.NewGuid():N}.bak";
await connection.ExecuteAsync("BACKUP DATABASE [PlotDirector_Development] TO DISK=@path WITH COPY_ONLY, INIT, CHECKSUM",new {path=backup}, commandTimeout:180);
var hostBackup = new FileInfo(backup.Replace("/var/opt/mssql/", "/sql/mssql/", StringComparison.Ordinal));
if (!hostBackup.Exists || hostBackup.Length == 0) throw new IOException("Backup command succeeded but the mapped backup file is missing/empty.");
Console.WriteLine($"Backup completed with CHECKSUM; file verified: {backup} ({hostBackup.Length} bytes). This is not a restore test.");
if (operation == "backup") return;
var sql=await File.ReadAllTextAsync(args[1]);
await connection.ExecuteAsync("SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON;");
foreach(var batch in Regex.Split(sql,@"^\s*GO\s*$",RegexOptions.Multiline|RegexOptions.IgnoreCase))
if (!string.IsNullOrWhiteSpace(batch)) await connection.ExecuteAsync(batch,commandTimeout:120);
Console.WriteLine("Migration applied.");
}
else if(operation == "publish")
{
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?> { ["ConnectionStrings:DefaultConnection"]=cs.ConnectionString }).Build();
await new WritingSolverRepository(new SqlConnectionFactory(configuration)).PublishAsync(await File.ReadAllTextAsync(args[1]),Environment.UserName);
Console.WriteLine("Graph published atomically.");
}
else if(operation == "query")
{
var sql=await File.ReadAllTextAsync(args[1]);
using var results = await connection.QueryMultipleAsync(sql);
while (!results.IsConsumed)
foreach(var row in await results.ReadAsync()) Console.WriteLine(System.Text.Json.JsonSerializer.Serialize((IDictionary<string,object>)row));
}
else if(operation == "inspect")
{
foreach(var row in await connection.QueryAsync("SELECT Version,PublishedUtc,Active FROM dbo.WritingSolverVersions")) Console.WriteLine($"{row.Version} | {row.PublishedUtc} | active={row.Active}");
}
else throw new ArgumentException("Unknown operation.");