using System.Collections; using Anubis.Core; using Anubis.Db; using Anubis.Platform; namespace Anubis.Server; /// /// Command line export and import (SPEC 5.4), the way to change engine: with the server stopped, export from the old /// database, point the configuration to the new one, import. The import goes only into an empty database and renews /// the installation fingerprint, so the old copy is no longer accepted (SPEC 15.1). /// internal static class DatabaseCommand { public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null) { output ??= Console.Out; if (args.Length < 2 || args[0] is not ("export" or "import")) { await output.WriteLineAsync("Uso: anubis db export | anubis db import [--platform docker|desktop] [--data-dir ]").ConfigureAwait(false); return 2; } environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); var options = ServerOptions.Parse(args[2..], environment); var config = options.LoadConfig(environment); if (!config.IsComplete) { await output.WriteLineAsync("La configurazione d'avvio non รจ completa:").ConfigureAwait(false); foreach (var problem in config.Problems) { await output.WriteLineAsync($"- {problem.Setting}: {problem.What} {problem.Remedy}").ConfigureAwait(false); } return 1; } Redactor.Register(config.Db!.Password); var clock = new SystemClock(); var folder = Path.GetFullPath(args[1]); try { await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile)); if (args[0] == "export") { var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false); await output.WriteLineAsync($"Esportate {index.Tables.Sum(t => t.Count)} righe di {index.Tables.Count} tabelle in {folder}.").ConfigureAwait(false); return 0; } config.Data.Ensure(); var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false); await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false); await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " + "Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false); return 0; } catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException) { await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); return 1; } } }