415 lines
28 KiB
C#
415 lines
28 KiB
C#
using System.Diagnostics;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using System.Text.RegularExpressions;
|
|
using Microsoft.Data.SqlClient;
|
|
|
|
// Root-owned, separately provisioned worker. JSON-lines protocol; never emits SQL,
|
|
// connection strings, exception messages or business data. Holds the SQL session
|
|
// lock across backup, migrations, application activation and health checks.
|
|
internal static class Program
|
|
{
|
|
private static SqlConnection? connection;
|
|
private static string database = "";
|
|
private static bool locked;
|
|
private static JsonObject? manifest;
|
|
private static string packageRoot = "";
|
|
private static string deployment = "";
|
|
private static string packageHash = "";
|
|
private static string? currentMigration;
|
|
private static int currentBatch;
|
|
private static int executed;
|
|
private static int baselined;
|
|
private static readonly List<string> committed = [];
|
|
|
|
public static async Task<int> Main(string[] args)
|
|
{
|
|
if (args.Length != 1) return 2;
|
|
try
|
|
{
|
|
var config = JsonNode.Parse(await File.ReadAllTextAsync(args[0]))!.AsObject();
|
|
database = S(config, "database");
|
|
var builder = new SqlConnectionStringBuilder(S(config, "connection"));
|
|
if (builder.DataSource!=S(config,"expected_server") || Environment.MachineName!=S(config,"expected_host"))
|
|
throw new InvalidOperationException("server-identity");
|
|
if (builder.InitialCatalog != database || !Regex.IsMatch(database, "^[A-Za-z][A-Za-z0-9_]{0,100}$"))
|
|
throw new InvalidOperationException("target");
|
|
builder.ApplicationName = "PlotDirector deployment worker";
|
|
builder.ConnectTimeout = 10;
|
|
connection = new SqlConnection(builder.ConnectionString);
|
|
await connection.OpenAsync();
|
|
if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target");
|
|
if(Convert.ToInt32(await Scalar("SELECT CONVERT(int,is_trustworthy_on)+CONVERT(int,is_db_chaining_on) FROM sys.databases WHERE name=DB_NAME()"))!=0)
|
|
throw new InvalidOperationException("cross-database-security-boundary");
|
|
if(Convert.ToInt32(await Scalar("SELECT value_in_use FROM sys.configurations WHERE name=N'cross db ownership chaining'"))!=0)
|
|
throw new InvalidOperationException("server-cross-database-chaining");
|
|
Console.WriteLine("{\"ok\":true,\"ready\":true}");
|
|
while (await Console.In.ReadLineAsync() is { } line)
|
|
{
|
|
try
|
|
{
|
|
var request = JsonNode.Parse(line)!.AsObject();
|
|
var answer = await Execute(request);
|
|
Console.WriteLine(JsonSerializer.Serialize(new { ok = true, result = answer }));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(JsonSerializer.Serialize(new { ok = false,
|
|
error = e is SqlException se ? "SQL_" + se.Number : e.Message is "baseline" or "concurrent-deployment" or "immutable-migration-checksum" ? e.Message : e.GetType().Name,
|
|
migration = currentMigration, batch = currentBatch, executed, baselined, committed = committed.Take(256) }));
|
|
// A failed command poisons the session. Never proceed to activation.
|
|
return 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(JsonSerializer.Serialize(new { ok = false,
|
|
error = e is SqlException se ? "SQL_" + se.Number : e.GetType().Name }));
|
|
return 1;
|
|
}
|
|
finally { if (connection is not null) await connection.DisposeAsync(); }
|
|
}
|
|
|
|
private static string S(JsonObject o, string key) => o[key]!.GetValue<string>();
|
|
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
|
private static SqlCommand Command(string sql, SqlTransaction? transaction = null)
|
|
=> new(sql, connection, transaction) { CommandTimeout = 1800 };
|
|
private static async Task<object?> Scalar(string sql, SqlTransaction? t = null)
|
|
{ using var c = Command(sql, t); return await c.ExecuteScalarAsync(); }
|
|
private static async Task Run(string sql, SqlTransaction? t = null)
|
|
{ using var c = Command(sql, t); await c.ExecuteNonQueryAsync(); }
|
|
|
|
private static async Task<object> Execute(JsonObject request)
|
|
{
|
|
var op = S(request, "op");
|
|
if (op == "inspect") return new { schema = await Schema(), database };
|
|
if(op is "fingerprint" or "integrity")
|
|
{
|
|
if(!database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal))
|
|
throw new InvalidOperationException("qualification-only");
|
|
if(op=="fingerprint")return await Fingerprints(request["original"]?.AsObject());
|
|
await Run("DBCC CHECKDB WITH NO_INFOMSGS,ALL_ERRORMSGS;");
|
|
var violations=Convert.ToInt64(await Scalar("CREATE TABLE #violations([Table] nvarchar(512),[Constraint] nvarchar(512),[Where] nvarchar(max)); INSERT #violations EXEC('DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS,NO_INFOMSGS'); SELECT COUNT_BIG(*) FROM #violations; DROP TABLE #violations;"));
|
|
if(violations!=0)throw new InvalidOperationException("referential-integrity");
|
|
return new { integrity=true, constraint_violations=violations };
|
|
}
|
|
if (op == "begin")
|
|
{
|
|
if (locked) throw new InvalidOperationException("already-begun");
|
|
var result = Convert.ToInt32(await Scalar("DECLARE @r int; EXEC @r=sys.sp_getapplock @Resource=N'PlotDirector.Deployment',@LockMode='Exclusive',@LockOwner='Session',@LockTimeout=0; SELECT @r;"));
|
|
if (result < 0) throw new InvalidOperationException("concurrent-deployment");
|
|
locked = true;
|
|
packageRoot = Path.GetFullPath(S(request, "package_root"));
|
|
manifest = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(packageRoot, "manifest.json")))!.AsObject();
|
|
deployment = S(request, "deployment_id");
|
|
packageHash = S(request, "package_sha256");
|
|
if (!Regex.IsMatch(deployment, "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$") || !Regex.IsMatch(packageHash,"^[a-f0-9]{64}$"))
|
|
throw new InvalidOperationException("identity");
|
|
var actual = await Schema();
|
|
var historyTimer=Stopwatch.StartNew();
|
|
var complete = await ValidateHistory();
|
|
var historySeconds=historyTimer.Elapsed.TotalSeconds;
|
|
var history=await HistoryStatus();
|
|
if (actual != S(manifest, "starting_schema_sha256") && !(complete && actual == S(manifest,"resulting_schema_sha256")))
|
|
throw new InvalidOperationException("baseline");
|
|
await Idle();
|
|
await Conditions(manifest["prerequisites"]!.AsArray());
|
|
var databaseBytes=Convert.ToInt64(await Scalar("SELECT SUM(CONVERT(bigint,size))*8192 FROM sys.database_files"));
|
|
return new { schema = actual, complete, database_bytes=databaseBytes, history, history_verification_seconds=historySeconds };
|
|
}
|
|
if (!locked || manifest is null) throw new InvalidOperationException("not-begun");
|
|
if (op == "idle") { await Idle(); return new { idle = true }; }
|
|
if (op == "backup")
|
|
{
|
|
// Path comes only from the root-owned target configuration, not a release.
|
|
var path = S(request, "path");
|
|
if (!Regex.IsMatch(path, @"^/[A-Za-z0-9_./-]+\.bak$") || path.Split('/').Contains(".."))
|
|
throw new InvalidOperationException("backup-path");
|
|
using var backup = Command("BACKUP DATABASE " + Quote(database) + " TO DISK=@p WITH COPY_ONLY,CHECKSUM,NOINIT; RESTORE VERIFYONLY FROM DISK=@p WITH CHECKSUM;");
|
|
backup.Parameters.AddWithValue("@p", path);
|
|
await backup.ExecuteNonQueryAsync();
|
|
return new { verified = true };
|
|
}
|
|
if (op == "migrate")
|
|
{
|
|
await Idle();
|
|
foreach (var node in manifest["migrations"]!.AsArray()) await Migration(node!.AsObject());
|
|
// Fixed policy, never an executable hook supplied by a manifest. New
|
|
// business tables receive the reviewed runtime permissions on release.
|
|
if(await Scalar("SELECT OBJECT_ID(N'dbo.Deployment_ApplyRuntimePermissions',N'P')") is not DBNull)
|
|
await Run("EXEC dbo.Deployment_ApplyRuntimePermissions;");
|
|
var schema = await Schema();
|
|
if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema");
|
|
await Conditions(manifest["postconditions"]!.AsArray());
|
|
return new { schema, executed, baselined, committed=committed.Take(256), committed_list_truncated=committed.Count>256 };
|
|
}
|
|
if (op == "health")
|
|
{
|
|
if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target");
|
|
if (await Schema() != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("schema");
|
|
await Conditions(manifest["postconditions"]!.AsArray());
|
|
var timer=Stopwatch.StartNew();
|
|
var complete=await ValidateHistory();
|
|
if(!complete)throw new InvalidOperationException("migration-history-incomplete");
|
|
var seconds=timer.Elapsed.TotalSeconds;
|
|
return new { healthy = true, complete_history=complete, history=await HistoryStatus(), history_verification_seconds=seconds };
|
|
}
|
|
if (op == "activated")
|
|
{
|
|
// Caller must pass health checks BEFORE this operation. Failed activation
|
|
// remains in protected filesystem evidence, never in successful history.
|
|
await Conditions(manifest["postconditions"]!.AsArray());
|
|
using var cmd = Command("INSERT dbo.ApplicationReleaseHistory(DeploymentIdentifier,ReleaseIdentifier,ApplicationVersion,SourceCommit,PackageSha256,MigrationManifestSha256,EvidenceReference,ActivationKind,PreviousDeploymentIdentifier) VALUES(@id,@release,@version,@commit,@package,@manifest,@evidence,@kind,@previous)");
|
|
foreach (var (key, value) in new Dictionary<string,object> {
|
|
["@id"]=deployment,["@release"]=S(manifest,"release_id"),["@version"]=S(manifest,"version"),
|
|
["@commit"]=S(manifest,"source_commit"),["@package"]=packageHash,
|
|
["@manifest"]=Hash(await File.ReadAllBytesAsync(Path.Combine(packageRoot,"manifest.json"))),
|
|
["@evidence"]=S(request,"evidence"),["@kind"]=S(request,"kind"),
|
|
["@previous"]=request["previous_deployment"]?.GetValue<string>() is { } previous ? previous : DBNull.Value })
|
|
cmd.Parameters.AddWithValue(key,value);
|
|
await cmd.ExecuteNonQueryAsync();
|
|
var record=await ReleaseRecord(deployment);
|
|
if(record is null)throw new InvalidOperationException("activation-record-missing");
|
|
return record;
|
|
}
|
|
throw new InvalidOperationException("operation");
|
|
}
|
|
|
|
private static string Quote(string name) => "[" + name.Replace("]", "]]") + "]";
|
|
|
|
private static async Task<object> Fingerprints(JsonObject? original)
|
|
{
|
|
var tables=new Dictionary<string,List<string>>();
|
|
using(var cmd=Command("SELECT s.name,t.name,c.name FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.columns c ON c.object_id=t.object_id WHERE t.name NOT IN ('DatabaseMigrationHistory','ApplicationReleaseHistory') ORDER BY s.name,t.name,c.column_id"))
|
|
using(var reader=await cmd.ExecuteReaderAsync())
|
|
while(await reader.ReadAsync())
|
|
{
|
|
var key=reader.GetString(0)+"."+reader.GetString(1);
|
|
if(!tables.ContainsKey(key))tables[key]=[];
|
|
tables[key].Add(reader.GetString(2));
|
|
}
|
|
var answer=new Dictionary<string,object>();
|
|
var targets=original is null?tables.Keys.ToList():original.Select(x=>x.Key).ToList();
|
|
foreach(var name in targets)
|
|
{
|
|
if(!tables.TryGetValue(name,out var available))throw new InvalidOperationException("lost-business-table");
|
|
var columns=original is null?available:original[name]!["columns"]!.AsArray().Select(x=>x!.GetValue<string>()).ToList();
|
|
if(!columns.All(available.Contains))throw new InvalidOperationException("lost-business-column");
|
|
var parts=name.Split('.');
|
|
if(parts.Length!=2)throw new InvalidOperationException("table-name");
|
|
var projection=string.Join(',',columns.Select(x=>"t."+Quote(x)));
|
|
using var cmd=Command($"SELECT COUNT_BIG(*),LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',COALESCE(STRING_AGG(CONVERT(varchar(max),RowHash),'') WITHIN GROUP(ORDER BY RowHash),'')),2)) FROM {Quote(parts[0])}.{Quote(parts[1])} t CROSS APPLY (SELECT CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT {projection} FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES)),2) AS RowHash) h");
|
|
using var reader=await cmd.ExecuteReaderAsync();await reader.ReadAsync();
|
|
answer[name]=new { columns, rows=reader.GetInt64(0),sha256=reader.GetString(1) };
|
|
}
|
|
return answer;
|
|
}
|
|
|
|
private static async Task Idle()
|
|
{
|
|
foreach (var table in new[] { "StoryIntelligenceRuns", "StoryIntelligenceJobs", "WholeBookPlotSynthesisRuns", "CharacterEnrichmentRuns", "OnboardingManuscriptBuilds", "GeographicLookupJob", "NativeChapterReviews" })
|
|
{
|
|
var sql = $"IF OBJECT_ID(N'dbo.{table}',N'U') IS NOT NULL AND COL_LENGTH(N'dbo.{table}',N'Status') IS NOT NULL EXEC(N'IF EXISTS(SELECT 1 FROM dbo.{table} WHERE Status IN (N''Pending'',N''Queued'',N''Running'',N''Processing'',N''InProgress'',N''CancelRequested'')) THROW 51000,''Active background work'',1;');";
|
|
await Run(sql);
|
|
}
|
|
}
|
|
|
|
private static async Task<JsonObject?> ReleaseRecord(string? identifier=null)
|
|
{
|
|
if(await Scalar("SELECT OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U')") is DBNull)return null;
|
|
using var read=Command("SELECT TOP(1) DeploymentIdentifier,ReleaseIdentifier,ApplicationVersion,SourceCommit,PackageSha256,MigrationManifestSha256,ActivatedUtc,ActivationKind FROM dbo.ApplicationReleaseHistory WHERE (@id IS NULL OR DeploymentIdentifier=@id) ORDER BY ActivatedUtc DESC");
|
|
read.Parameters.Add("@id",System.Data.SqlDbType.VarChar,100).Value=identifier is null?DBNull.Value:identifier;
|
|
using var reader=await read.ExecuteReaderAsync();
|
|
if(!await reader.ReadAsync())return null;
|
|
return new JsonObject { ["recorded"]=true,["deployment_identifier"]=reader.GetString(0),["release_identifier"]=reader.GetString(1),
|
|
["application_version"]=reader.GetString(2),["source_commit"]=reader.GetString(3),["package_sha256"]=reader.GetString(4),
|
|
["manifest_sha256"]=reader.GetString(5),["activated_utc"]=DateTime.SpecifyKind(reader.GetDateTime(6),DateTimeKind.Utc).ToString("O"),
|
|
["activation_kind"]=reader.GetString(7)};
|
|
}
|
|
|
|
private static async Task<object> HistoryStatus()
|
|
{
|
|
var expected=manifest!["migrations"]!.AsArray().Count;
|
|
if(await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull)
|
|
return new {expected,recorded=0,baselined=0,executed=0};
|
|
int recorded,baselineCount,executedCount;
|
|
using(var command=Command("SELECT COUNT(*),COALESCE(SUM(CASE WHEN RecordingKind='Baselined' THEN 1 ELSE 0 END),0),COALESCE(SUM(CASE WHEN RecordingKind='Executed' THEN 1 ELSE 0 END),0) FROM dbo.DatabaseMigrationHistory"))
|
|
using(var reader=await command.ExecuteReaderAsync())
|
|
{await reader.ReadAsync();recorded=reader.GetInt32(0);baselineCount=reader.GetInt32(1);executedCount=reader.GetInt32(2);}
|
|
var latest=await ReleaseRecord();
|
|
var releaseCount=await Scalar("IF OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U') IS NOT NULL SELECT COUNT(*) FROM dbo.ApplicationReleaseHistory ELSE SELECT 0");
|
|
return new {expected,recorded,baselined=baselineCount,executed=executedCount,successful_release_count=Convert.ToInt32(releaseCount),latest_successful_release=latest};
|
|
}
|
|
|
|
private static async Task<bool> ValidateHistory()
|
|
{
|
|
if (await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull)
|
|
{
|
|
if (manifest!["migrations"]!.AsArray().Count==0) throw new InvalidOperationException("code-only-without-ledger");
|
|
return false;
|
|
}
|
|
var complete = true;
|
|
var identities = new HashSet<string>();
|
|
foreach (var node in manifest!["migrations"]!.AsArray())
|
|
{
|
|
var m = node!.AsObject();
|
|
identities.Add(S(m,"id"));
|
|
using var cmd = Command("SELECT ScriptSha256 FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
|
|
cmd.Parameters.AddWithValue("@id",S(m,"id"));
|
|
if (await cmd.ExecuteScalarAsync() is string checksum)
|
|
{ if(checksum!=S(m,"sha256"))throw new InvalidOperationException("immutable-migration-checksum"); }
|
|
else complete=false;
|
|
}
|
|
// Code-only plans retain their full immutable historical entries. A ledger
|
|
// identity absent from the approved plan is an unknown database state.
|
|
using var all = Command("SELECT MigrationIdentity FROM dbo.DatabaseMigrationHistory");
|
|
using var reader = await all.ExecuteReaderAsync();
|
|
while(await reader.ReadAsync()) if(!identities.Contains(reader.GetString(0)))throw new InvalidOperationException("unrecognised-history");
|
|
return complete;
|
|
}
|
|
|
|
private static async Task Migration(JsonObject migration)
|
|
{
|
|
var identity = S(migration,"id");
|
|
currentMigration = identity;
|
|
currentBatch = 0;
|
|
var expected = S(migration,"sha256");
|
|
var filename = S(migration,"file");
|
|
if (Path.GetFileName(filename) != filename) throw new InvalidOperationException("migration-path");
|
|
var bytes = await File.ReadAllBytesAsync(Path.Combine(packageRoot,"sql",filename));
|
|
if (Hash(bytes) != expected) throw new InvalidOperationException("migration-checksum");
|
|
var historyExists = await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is not DBNull;
|
|
if (historyExists)
|
|
{
|
|
using var existing = Command("SELECT ScriptSha256 FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
|
|
existing.Parameters.AddWithValue("@id",identity);
|
|
if (await existing.ExecuteScalarAsync() is string prior)
|
|
{
|
|
if (prior != expected) throw new InvalidOperationException("immutable-migration-checksum");
|
|
return;
|
|
}
|
|
}
|
|
await Conditions(migration["prerequisites"]!.AsArray());
|
|
foreach(var prerequisite in migration["requires"]!.AsArray())
|
|
{
|
|
using var check=Command("SELECT COUNT(*) FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
|
|
check.Parameters.AddWithValue("@id",prerequisite!.GetValue<string>());
|
|
if(Convert.ToInt32(await check.ExecuteScalarAsync())!=1)throw new InvalidOperationException("migration-dependency");
|
|
}
|
|
if (S(migration,"mode") is not ("execute" or "baseline"))
|
|
throw new InvalidOperationException("nontransactional-migration-requires-reviewed-recovery");
|
|
var stopwatch = Stopwatch.StartNew();
|
|
await using var transaction = (SqlTransaction)await connection!.BeginTransactionAsync();
|
|
try
|
|
{
|
|
if (S(migration,"mode") == "execute")
|
|
{
|
|
await Run("SET XACT_ABORT ON; SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON;",transaction);
|
|
foreach (var batch in Batches(Encoding.UTF8.GetString(bytes).TrimStart('\ufeff')))
|
|
{
|
|
currentBatch++;
|
|
await Run(batch,transaction);
|
|
if ((string?)await Scalar("SELECT DB_NAME()",transaction) != database || Convert.ToInt32(await Scalar("SELECT @@TRANCOUNT",transaction)) != 1)
|
|
throw new InvalidOperationException("migration-session-changed");
|
|
}
|
|
}
|
|
await Conditions(migration["postconditions"]!.AsArray(), transaction);
|
|
using var insert = Command("INSERT dbo.DatabaseMigrationHistory(MigrationIdentity,ScriptFilename,ScriptSha256,DeploymentIdentifier,DurationMilliseconds,RecordingKind,BaselineEvidenceReference) VALUES(@id,@file,@hash,@deployment,@duration,@kind,@evidence)",transaction);
|
|
insert.Parameters.AddWithValue("@id",identity);
|
|
insert.Parameters.AddWithValue("@file",filename);
|
|
insert.Parameters.AddWithValue("@hash",expected);
|
|
insert.Parameters.AddWithValue("@deployment",deployment);
|
|
var baseline = S(migration,"mode")=="baseline";
|
|
insert.Parameters.AddWithValue("@duration",baseline ? DBNull.Value : stopwatch.ElapsedMilliseconds);
|
|
insert.Parameters.AddWithValue("@kind",baseline ? "Baselined" : "Executed");
|
|
insert.Parameters.AddWithValue("@evidence",baseline ? S(migration,"evidence") : DBNull.Value);
|
|
await insert.ExecuteNonQueryAsync();
|
|
await transaction.CommitAsync();
|
|
if(baseline)baselined++;else executed++;
|
|
committed.Add(identity);
|
|
currentMigration=null;
|
|
currentBatch=0;
|
|
}
|
|
catch { try { await transaction.RollbackAsync(); } catch { } throw; }
|
|
}
|
|
|
|
private static async Task Conditions(JsonArray conditions, SqlTransaction? transaction = null)
|
|
{
|
|
foreach (var node in conditions)
|
|
{
|
|
var c = node!.AsObject();
|
|
string sql = S(c,"kind") switch {
|
|
"object" => "SELECT CASE WHEN OBJECT_ID(@name,@type) IS NOT NULL THEN 1 ELSE 0 END",
|
|
"column" => "SELECT CASE WHEN COL_LENGTH(@name,@column) IS NOT NULL THEN 1 ELSE 0 END",
|
|
"module_sha256" => "SELECT LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',CONVERT(varbinary(max),OBJECT_DEFINITION(OBJECT_ID(@name)))),2))",
|
|
"solver_graph" => "SELECT CASE WHEN COUNT(*)=1 THEN MIN(LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',CONVERT(varbinary(max),GraphJson)),2))) ELSE NULL END FROM dbo.WritingSolverVersions WHERE Active=1 AND Version=@version",
|
|
_ => throw new InvalidOperationException("condition-kind")
|
|
};
|
|
using var cmd = Command(sql,transaction);
|
|
if(c["name"] is not null)cmd.Parameters.AddWithValue("@name",S(c,"name"));
|
|
if(c["version"] is not null)cmd.Parameters.AddWithValue("@version",S(c,"version"));
|
|
if (c["type"] is not null) cmd.Parameters.AddWithValue("@type",S(c,"type"));
|
|
if (c["column"] is not null) cmd.Parameters.AddWithValue("@column",S(c,"column"));
|
|
var actual = await cmd.ExecuteScalarAsync();
|
|
if (S(c,"kind") is "module_sha256" or "solver_graph" ? actual is not string hash || hash!=S(c,"sha256") : Convert.ToInt32(actual)!=1)
|
|
throw new InvalidOperationException("condition-failed");
|
|
}
|
|
}
|
|
|
|
private static async Task<string> Schema()
|
|
{
|
|
// Object-name ordered, independent of restore-assigned object IDs and data.
|
|
// History is excluded so records do not change the application's schema ID.
|
|
const string filter = "t.name NOT IN ('DatabaseMigrationHistory','ApplicationReleaseHistory')";
|
|
var queries = new[] {
|
|
$"SELECT s.name AS [schema],t.name,c.name AS [column],c.column_id,TYPE_NAME(c.user_type_id) AS [type],c.max_length,c.precision,c.scale,c.is_nullable,c.is_identity,c.is_computed,OBJECT_DEFINITION(c.default_object_id) AS [default],cc.definition AS computed FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.columns c ON c.object_id=t.object_id LEFT JOIN sys.computed_columns cc ON cc.object_id=c.object_id AND cc.column_id=c.column_id WHERE {filter} ORDER BY s.name,t.name,c.column_id FOR JSON PATH,INCLUDE_NULL_VALUES",
|
|
"SELECT OBJECT_SCHEMA_NAME(m.object_id) AS [schema],o.name,o.type,REPLACE(m.definition,CHAR(13),'') AS definition,m.uses_ansi_nulls,m.uses_quoted_identifier FROM sys.sql_modules m JOIN sys.objects o ON o.object_id=m.object_id ORDER BY OBJECT_SCHEMA_NAME(m.object_id),o.name FOR JSON PATH,INCLUDE_NULL_VALUES",
|
|
$"SELECT s.name AS [schema],t.name,CASE WHEN EXISTS(SELECT 1 FROM sys.key_constraints k WHERE k.parent_object_id=i.object_id AND k.unique_index_id=i.index_id AND k.is_system_named=1) THEN NULL ELSE i.name END AS [index],i.type,i.is_unique,i.is_primary_key,i.is_disabled,i.has_filter,i.filter_definition,c.name AS [column],ic.key_ordinal,ic.is_descending_key,ic.is_included_column FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.indexes i ON i.object_id=t.object_id JOIN sys.index_columns ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id JOIN sys.columns c ON c.object_id=ic.object_id AND c.column_id=ic.column_id WHERE {filter} ORDER BY s.name,t.name,i.index_id,ic.index_column_id FOR JSON PATH,INCLUDE_NULL_VALUES",
|
|
$"SELECT s.name AS [schema],t.name AS [table],CASE WHEN COALESCE(f.is_system_named,ck.is_system_named,dc.is_system_named,kc.is_system_named,0)=1 THEN NULL ELSE o.name END AS [constraint],o.type,OBJECT_DEFINITION(o.object_id) AS definition,f.is_disabled AS fk_disabled,f.is_not_trusted AS fk_untrusted,ck.is_disabled AS check_disabled,ck.is_not_trusted AS check_untrusted,(SELECT pc.name AS parent_column,OBJECT_SCHEMA_NAME(fc.referenced_object_id) AS referenced_schema,OBJECT_NAME(fc.referenced_object_id) AS referenced_table,rc.name AS referenced_column FROM sys.foreign_key_columns fc JOIN sys.columns pc ON pc.object_id=fc.parent_object_id AND pc.column_id=fc.parent_column_id JOIN sys.columns rc ON rc.object_id=fc.referenced_object_id AND rc.column_id=fc.referenced_column_id WHERE fc.constraint_object_id=o.object_id ORDER BY fc.constraint_column_id FOR JSON PATH) AS foreign_key_columns FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.objects o ON o.parent_object_id=t.object_id LEFT JOIN sys.foreign_keys f ON f.object_id=o.object_id LEFT JOIN sys.check_constraints ck ON ck.object_id=o.object_id LEFT JOIN sys.default_constraints dc ON dc.object_id=o.object_id LEFT JOIN sys.key_constraints kc ON kc.object_id=o.object_id WHERE {filter} AND o.type IN ('C','D','F','PK','UQ') ORDER BY s.name,t.name,o.type,CASE WHEN COALESCE(f.is_system_named,ck.is_system_named,dc.is_system_named,kc.is_system_named,0)=0 THEN o.name END,o.object_id FOR JSON PATH,INCLUDE_NULL_VALUES"
|
|
};
|
|
var values = new List<string>();
|
|
foreach (var sql in queries)
|
|
{
|
|
using var cmd = Command(sql);
|
|
using var reader = await cmd.ExecuteReaderAsync();
|
|
var text = new StringBuilder();
|
|
while (await reader.ReadAsync()) text.Append(reader.GetString(0));
|
|
values.Add(text.ToString());
|
|
}
|
|
return Hash(Encoding.UTF8.GetBytes(string.Join("\n",values)));
|
|
}
|
|
|
|
internal static IEnumerable<string> Batches(string script)
|
|
{
|
|
var buffer = new StringBuilder();
|
|
int commentDepth=0;
|
|
char quote='\0';
|
|
foreach (var line in script.Replace("\r\n","\n").Split('\n'))
|
|
{
|
|
if (commentDepth==0 && quote=='\0' && Regex.IsMatch(line,@"^\s*GO\s*(?:--.*)?$",RegexOptions.IgnoreCase))
|
|
{ if (!string.IsNullOrWhiteSpace(buffer.ToString())) yield return buffer.ToString(); buffer.Clear(); continue; }
|
|
if (commentDepth==0 && quote=='\0' && Regex.IsMatch(line,@"^\s*(?:GO\s+\d|:|!!)",RegexOptions.IgnoreCase))
|
|
throw new InvalidOperationException("sqlcmd-directive");
|
|
buffer.AppendLine(line);
|
|
for(int i=0;i<line.Length;i++)
|
|
{
|
|
var ch=line[i]; var next=i+1<line.Length?line[i+1]:'\0';
|
|
if(commentDepth>0)
|
|
{ if(ch=='/'&&next=='*'){commentDepth++;i++;} else if(ch=='*'&&next=='/'){commentDepth--;i++;} continue; }
|
|
if(quote!='\0')
|
|
{ if(ch==quote){if(next==quote)i++;else quote='\0';} continue; }
|
|
if(ch=='-'&&next=='-')break;
|
|
if(ch=='/'&&next=='*'){commentDepth++;i++;}
|
|
else if(ch=='\''||ch=='"')quote=ch;
|
|
else if(ch=='[')quote=']';
|
|
}
|
|
}
|
|
if(quote!='\0'||commentDepth!=0)throw new InvalidOperationException("unclosed-sql-token");
|
|
if(!string.IsNullOrWhiteSpace(buffer.ToString()))yield return buffer.ToString();
|
|
}
|
|
}
|