using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class DigimonBaseInfoImportSummary { public int RecordCount { get; init; } public int DeletedCount { get; init; } public int InsertedCount { get; init; } public int DeletedInvalidDigimonCount { get; init; } public int DeletedInvalidEvolutionCount { get; init; } public int DeletedInvalidEncyclopediaEvolutionCount { get; init; } } public static class DigimonBaseInfoImporter { public static DigimonBaseInfoImportSummary ValidateXml(string xmlPath) { List records = LoadRecords(xmlPath); return new DigimonBaseInfoImportSummary { RecordCount = records.Count }; } public static DigimonBaseInfoImportSummary ImportReplace(string connectionString, string xmlPath) { List records = LoadRecords(xmlPath); if (records.Count == 0) { throw new InvalidOperationException("DigimonList.xml does not contain any Digimon records."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[DigimonBaseInfo];"); CreateImportedTypesTempTable(connection, transaction, records); int deletedInvalidEncyclopediaEvolutionCount = ExecuteNonQuery(connection, transaction, @" DELETE encyclopediaEvolution FROM [Character].[EncyclopediaEvolutions] AS encyclopediaEvolution WHERE NOT EXISTS ( SELECT 1 FROM #ImportedDigimonTypes AS importedType WHERE importedType.[Type] = encyclopediaEvolution.[DigimonBaseType] );"); int deletedInvalidEvolutionCount = ExecuteNonQuery(connection, transaction, @" DELETE evolution FROM [Digimon].[Evolution] AS evolution WHERE NOT EXISTS ( SELECT 1 FROM #ImportedDigimonTypes AS importedType WHERE importedType.[Type] = evolution.[Type] );"); int deletedInvalidDigimonCount = ExecuteNonQuery(connection, transaction, @" DELETE digimon FROM [Digimon].[Digimon] AS digimon WHERE NOT EXISTS ( SELECT 1 FROM #ImportedDigimonTypes AS importedType WHERE importedType.[Type] = digimon.[BaseType] ) OR NOT EXISTS ( SELECT 1 FROM #ImportedDigimonTypes AS importedType WHERE importedType.[Type] = digimon.[CurrentType] );"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[DigimonBaseInfo];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[DigimonBaseInfo] ON;"); using SqlCommand insertCommand = new(@" INSERT INTO [Asset].[DigimonBaseInfo] ([Id], [Type], [Model], [Name], [Level], [ScaleType], [Attribute], [Element], [Family1], [Family2], [Family3], [ASValue], [ARValue], [ATValue], [BLValue], [CTValue], [DEValue], [DSValue], [EVValue], [HPValue], [HTValue], [MSValue], [WSValue], [EvolutionType]) VALUES (@Id, @Type, @Model, @Name, @Level, @ScaleType, @Attribute, @Element, @Family1, @Family2, @Family3, @ASValue, @ARValue, @ATValue, @BLValue, @CTValue, @DEValue, @DSValue, @EVValue, @HPValue, @HTValue, @MSValue, @WSValue, @EvolutionType);", connection, transaction); AddParameter(insertCommand, "@Id"); AddParameter(insertCommand, "@Type"); AddParameter(insertCommand, "@Model"); AddParameter(insertCommand, "@Name"); AddParameter(insertCommand, "@Level"); AddParameter(insertCommand, "@ScaleType"); AddParameter(insertCommand, "@Attribute"); AddParameter(insertCommand, "@Element"); AddParameter(insertCommand, "@Family1"); AddParameter(insertCommand, "@Family2"); AddParameter(insertCommand, "@Family3"); AddParameter(insertCommand, "@ASValue"); AddParameter(insertCommand, "@ARValue"); AddParameter(insertCommand, "@ATValue"); AddParameter(insertCommand, "@BLValue"); AddParameter(insertCommand, "@CTValue"); AddParameter(insertCommand, "@DEValue"); AddParameter(insertCommand, "@DSValue"); AddParameter(insertCommand, "@EVValue"); AddParameter(insertCommand, "@HPValue"); AddParameter(insertCommand, "@HTValue"); AddParameter(insertCommand, "@MSValue"); AddParameter(insertCommand, "@WSValue"); AddParameter(insertCommand, "@EvolutionType"); int identity = 1; foreach (DigimonBaseInfoRecord record in records) { insertCommand.Parameters["@Id"].Value = identity++; insertCommand.Parameters["@Type"].Value = record.Type; insertCommand.Parameters["@Model"].Value = record.Model; insertCommand.Parameters["@Name"].Value = record.Name; insertCommand.Parameters["@Level"].Value = record.Level; insertCommand.Parameters["@ScaleType"].Value = record.ScaleType; insertCommand.Parameters["@Attribute"].Value = record.Attribute; insertCommand.Parameters["@Element"].Value = record.Element; insertCommand.Parameters["@Family1"].Value = record.Family1; insertCommand.Parameters["@Family2"].Value = record.Family2; insertCommand.Parameters["@Family3"].Value = record.Family3; insertCommand.Parameters["@ASValue"].Value = record.ASValue; insertCommand.Parameters["@ARValue"].Value = record.ARValue; insertCommand.Parameters["@ATValue"].Value = record.ATValue; insertCommand.Parameters["@BLValue"].Value = record.BLValue; insertCommand.Parameters["@CTValue"].Value = record.CTValue; insertCommand.Parameters["@DEValue"].Value = record.DEValue; insertCommand.Parameters["@DSValue"].Value = record.DSValue; insertCommand.Parameters["@EVValue"].Value = record.EVValue; insertCommand.Parameters["@HPValue"].Value = record.HPValue; insertCommand.Parameters["@HTValue"].Value = record.HTValue; insertCommand.Parameters["@MSValue"].Value = record.MSValue; insertCommand.Parameters["@WSValue"].Value = record.WSValue; insertCommand.Parameters["@EvolutionType"].Value = record.EvolutionType; insertCommand.ExecuteNonQuery(); } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[DigimonBaseInfo] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[DigimonBaseInfo]', RESEED, {records.Count});"); transaction.Commit(); return new DigimonBaseInfoImportSummary { RecordCount = records.Count, DeletedCount = deletedCount, InsertedCount = records.Count, DeletedInvalidDigimonCount = deletedInvalidDigimonCount, DeletedInvalidEvolutionCount = deletedInvalidEvolutionCount, DeletedInvalidEncyclopediaEvolutionCount = deletedInvalidEncyclopediaEvolutionCount }; } catch { TryDisableIdentityInsert(connection, transaction); transaction.Rollback(); throw; } } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction) { try { ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[DigimonBaseInfo] OFF;"); } catch { // Best-effort cleanup before rollback. } } private static int ExecuteScalarInt(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); object? result = command.ExecuteScalar(); return Convert.ToInt32(result, CultureInfo.InvariantCulture); } private static int ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); return command.ExecuteNonQuery(); } private static void CreateImportedTypesTempTable(SqlConnection connection, SqlTransaction transaction, List records) { ExecuteNonQuery(connection, transaction, "CREATE TABLE #ImportedDigimonTypes ([Type] int NOT NULL PRIMARY KEY);"); using SqlCommand insertCommand = new( "INSERT INTO #ImportedDigimonTypes ([Type]) VALUES (@Type);", connection, transaction); AddParameter(insertCommand, "@Type"); foreach (int type in records.Select(record => record.Type).Distinct()) { insertCommand.Parameters["@Type"].Value = type; insertCommand.ExecuteNonQuery(); } } private static void AddParameter(SqlCommand command, string name) { command.Parameters.Add(new SqlParameter(name, DBNull.Value)); } private static List LoadRecords(string xmlPath) { if (!File.Exists(xmlPath)) { throw new FileNotFoundException("DigimonList.xml not found.", xmlPath); } XDocument document = XDocument.Load(xmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "DigimonList") { throw new InvalidOperationException("DigimonList.xml root node must be ."); } List records = new(); int rowIndex = 0; foreach (XElement digimonElement in root.Elements("Digimon")) { rowIndex++; string recordContext = BuildRecordContext(digimonElement, rowIndex); records.Add(new DigimonBaseInfoRecord { Type = ReadRequiredInt(digimonElement, "Species", recordContext), Model = ReadRequiredInt(digimonElement, "Model", recordContext), Name = ReadNameWithFallback(digimonElement, recordContext, 50), Level = ReadRequiredInt(digimonElement, "BaseLevel", recordContext), ScaleType = ReadRequiredInt(digimonElement, "DigimonType", recordContext), Attribute = ReadRequiredInt(digimonElement, "AttributeType", recordContext), Element = ReadOptionalInt(digimonElement, "NatureType"), Family1 = ReadOptionalInt(digimonElement, "Family1"), Family2 = ReadOptionalInt(digimonElement, "Family2"), Family3 = ReadOptionalInt(digimonElement, "Family3"), ASValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_AS", recordContext), ARValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_AR", recordContext), ATValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_AT", recordContext), BLValue = 0, CTValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_CR", recordContext), DEValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_DE", recordContext), DSValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_DS", recordContext), EVValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_EV", recordContext), HPValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_HP", recordContext), HTValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_HT", recordContext), MSValue = ReadRequiredUnsignedWordInt(digimonElement, "s_nBaseStat_MS", recordContext), WSValue = ReadRequiredRoundedInt(digimonElement, "WakkLen", recordContext), EvolutionType = ReadRequiredInt(digimonElement, "EvolutionType", recordContext) }); } return records; } private static string BuildRecordContext(XElement digimonElement, int rowIndex) { string? species = digimonElement.Element("Species")?.Value?.Trim(); string? model = digimonElement.Element("Model")?.Value?.Trim(); string speciesPart = string.IsNullOrWhiteSpace(species) ? "?" : species; string modelPart = string.IsNullOrWhiteSpace(model) ? "?" : model; return $"Digimon row {rowIndex} (Species={speciesPart}, Model={modelPart})"; } private static int ReadRequiredInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value)) { throw new InvalidOperationException($"{recordContext} has invalid integer value in '{elementName}': '{element.Value}'."); } return value; } private static int ReadRequiredRoundedInt(XElement parent, string elementName, string recordContext) { XElement? element = parent.Element(elementName); if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field '{elementName}'."); } if (!double.TryParse(element.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out double value)) { throw new InvalidOperationException($"{recordContext} has invalid numeric value in '{elementName}': '{element.Value}'."); } return Convert.ToInt32(Math.Round(value, MidpointRounding.AwayFromZero), CultureInfo.InvariantCulture); } private static int ReadRequiredUnsignedWordInt(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < 0) { if (value < short.MinValue) { throw new InvalidOperationException($"{recordContext} field '{elementName}' has invalid negative value '{value}'."); } return (ushort)(short)value; } if (value > ushort.MaxValue) { throw new InvalidOperationException($"{recordContext} field '{elementName}' exceeds ushort range: '{value}'."); } return value; } private static int ReadOptionalInt(XElement parent, string elementName) { XElement? element = parent.Element(elementName); if (element == null || string.IsNullOrWhiteSpace(element.Value)) { return 0; } return int.TryParse(element.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value) ? value : 0; } private static string ReadNameWithFallback(XElement parent, string recordContext, int maxLength) { XElement? element = parent.Element("Name"); string species = parent.Element("Species")?.Value?.Trim() ?? "Unknown"; if (element == null) { throw new InvalidOperationException($"{recordContext} is missing required field 'Name'."); } string value = element.Value.Trim(); if (string.IsNullOrWhiteSpace(value)) { value = $"Digimon_{species}"; } if (value.Length > maxLength) { throw new InvalidOperationException($"{recordContext} field 'Name' exceeds {maxLength} characters."); } return value; } private sealed class DigimonBaseInfoRecord { public int Type { get; init; } public int Model { get; init; } public string Name { get; init; } = string.Empty; public int Level { get; init; } public int ScaleType { get; init; } public int Attribute { get; init; } public int Element { get; init; } public int Family1 { get; init; } public int Family2 { get; init; } public int Family3 { get; init; } public int ASValue { get; init; } public int ARValue { get; init; } public int ATValue { get; init; } public int BLValue { get; init; } public int CTValue { get; init; } public int DEValue { get; init; } public int DSValue { get; init; } public int EVValue { get; init; } public int HPValue { get; init; } public int HTValue { get; init; } public int MSValue { get; init; } public int WSValue { get; init; } public int EvolutionType { get; init; } } } }