using System.Globalization; using System.Xml.Linq; using Microsoft.Data.SqlClient; namespace XmlTool.Importers { public sealed class DigimonEvolutionImportSummary { public int EvolutionRecordCount { get; init; } public int EvolutionLineRecordCount { get; init; } public int EvolutionStageRecordCount { get; init; } public int BattleEvolutionRecordCount { get; init; } public int DeletedEvolutionCount { get; init; } public int DeletedEvolutionLineCount { get; init; } public int DeletedEvolutionStageCount { get; init; } public int InsertedEvolutionCount { get; init; } public int InsertedEvolutionLineCount { get; init; } public int InsertedEvolutionStageCount { get; init; } } public static class DigimonEvolutionAssetImporter { public static DigimonEvolutionImportSummary ValidateXml(string digimonEvoXmlPath, string battleEvoXmlPath) { EvolutionImportPackage package = LoadPackage(digimonEvoXmlPath, battleEvoXmlPath); return new DigimonEvolutionImportSummary { EvolutionRecordCount = package.Evolutions.Count, EvolutionLineRecordCount = package.Lines.Count, EvolutionStageRecordCount = package.Stages.Count, BattleEvolutionRecordCount = package.BattleEvolutionCount }; } public static DigimonEvolutionImportSummary ImportReplace(string connectionString, string digimonEvoXmlPath, string battleEvoXmlPath) { EvolutionImportPackage package = LoadPackage(digimonEvoXmlPath, battleEvoXmlPath); if (package.Evolutions.Count == 0) { throw new InvalidOperationException("DigimonEvo.xml does not contain any Digimon evolution records."); } using SqlConnection connection = new(connectionString); connection.Open(); using SqlTransaction transaction = connection.BeginTransaction(); try { int deletedEvolutionStageCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[EvolutionStage];"); int deletedEvolutionLineCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[EvolutionLine];"); int deletedEvolutionCount = ExecuteScalarInt(connection, transaction, "SELECT COUNT(*) FROM [Asset].[Evolution];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[EvolutionStage];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[EvolutionLine];"); ExecuteNonQuery(connection, transaction, "DELETE FROM [Asset].[Evolution];"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Evolution] ON;"); using (SqlCommand evolutionCommand = new(@" INSERT INTO [Asset].[Evolution] ([Id], [Type], [EvolutionRank]) VALUES (@Id, @Type, @EvolutionRank);", connection, transaction)) { AddParameter(evolutionCommand, "@Id"); AddParameter(evolutionCommand, "@Type"); AddParameter(evolutionCommand, "@EvolutionRank"); foreach (EvolutionRecord record in package.Evolutions) { evolutionCommand.Parameters["@Id"].Value = record.Id; evolutionCommand.Parameters["@Type"].Value = record.Type; evolutionCommand.Parameters["@EvolutionRank"].Value = record.EvolutionRank; evolutionCommand.ExecuteNonQuery(); } } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[Evolution] OFF;"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[EvolutionLine] ON;"); using (SqlCommand evolutionLineCommand = new(@" INSERT INTO [Asset].[EvolutionLine] ([Id], [EvolutionId], [Type], [SlotLevel], [UnlockLevel], [UnlockQuestId], [UnlockItemSection], [UnlockItemSectionAmount], [RequiredItem], [RequiredAmount]) VALUES (@Id, @EvolutionId, @Type, @SlotLevel, @UnlockLevel, @UnlockQuestId, @UnlockItemSection, @UnlockItemSectionAmount, @RequiredItem, @RequiredAmount);", connection, transaction)) { AddParameter(evolutionLineCommand, "@Id"); AddParameter(evolutionLineCommand, "@EvolutionId"); AddParameter(evolutionLineCommand, "@Type"); AddParameter(evolutionLineCommand, "@SlotLevel"); AddParameter(evolutionLineCommand, "@UnlockLevel"); AddParameter(evolutionLineCommand, "@UnlockQuestId"); AddParameter(evolutionLineCommand, "@UnlockItemSection"); AddParameter(evolutionLineCommand, "@UnlockItemSectionAmount"); AddParameter(evolutionLineCommand, "@RequiredItem"); AddParameter(evolutionLineCommand, "@RequiredAmount"); foreach (EvolutionLineRecord record in package.Lines) { evolutionLineCommand.Parameters["@Id"].Value = record.Id; evolutionLineCommand.Parameters["@EvolutionId"].Value = record.EvolutionId; evolutionLineCommand.Parameters["@Type"].Value = record.Type; evolutionLineCommand.Parameters["@SlotLevel"].Value = record.SlotLevel; evolutionLineCommand.Parameters["@UnlockLevel"].Value = record.UnlockLevel; evolutionLineCommand.Parameters["@UnlockQuestId"].Value = record.UnlockQuestId; evolutionLineCommand.Parameters["@UnlockItemSection"].Value = record.UnlockItemSection; evolutionLineCommand.Parameters["@UnlockItemSectionAmount"].Value = record.UnlockItemSectionAmount; evolutionLineCommand.Parameters["@RequiredItem"].Value = record.RequiredItem; evolutionLineCommand.Parameters["@RequiredAmount"].Value = record.RequiredAmount; evolutionLineCommand.ExecuteNonQuery(); } } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[EvolutionLine] OFF;"); ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[EvolutionStage] ON;"); using (SqlCommand evolutionStageCommand = new(@" INSERT INTO [Asset].[EvolutionStage] ([Id], [Type], [Value], [EvolutionLineId]) VALUES (@Id, @Type, @Value, @EvolutionLineId);", connection, transaction)) { AddParameter(evolutionStageCommand, "@Id"); AddParameter(evolutionStageCommand, "@Type"); AddParameter(evolutionStageCommand, "@Value"); AddParameter(evolutionStageCommand, "@EvolutionLineId"); foreach (EvolutionStageRecord record in package.Stages) { evolutionStageCommand.Parameters["@Id"].Value = record.Id; evolutionStageCommand.Parameters["@Type"].Value = record.Type; evolutionStageCommand.Parameters["@Value"].Value = record.Value; evolutionStageCommand.Parameters["@EvolutionLineId"].Value = record.EvolutionLineId; evolutionStageCommand.ExecuteNonQuery(); } } ExecuteNonQuery(connection, transaction, "SET IDENTITY_INSERT [Asset].[EvolutionStage] OFF;"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[Evolution]', RESEED, {package.Evolutions.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[EvolutionLine]', RESEED, {package.Lines.Count});"); ExecuteNonQuery(connection, transaction, $"DBCC CHECKIDENT(N'[Asset].[EvolutionStage]', RESEED, {package.Stages.Count});"); transaction.Commit(); return new DigimonEvolutionImportSummary { EvolutionRecordCount = package.Evolutions.Count, EvolutionLineRecordCount = package.Lines.Count, EvolutionStageRecordCount = package.Stages.Count, BattleEvolutionRecordCount = package.BattleEvolutionCount, DeletedEvolutionCount = deletedEvolutionCount, DeletedEvolutionLineCount = deletedEvolutionLineCount, DeletedEvolutionStageCount = deletedEvolutionStageCount, InsertedEvolutionCount = package.Evolutions.Count, InsertedEvolutionLineCount = package.Lines.Count, InsertedEvolutionStageCount = package.Stages.Count }; } catch { TryDisableIdentityInsert(connection, transaction, "[Asset].[EvolutionStage]"); TryDisableIdentityInsert(connection, transaction, "[Asset].[EvolutionLine]"); TryDisableIdentityInsert(connection, transaction, "[Asset].[Evolution]"); transaction.Rollback(); throw; } } private static EvolutionImportPackage LoadPackage(string digimonEvoXmlPath, string battleEvoXmlPath) { if (!File.Exists(digimonEvoXmlPath)) { throw new FileNotFoundException("DigimonEvo.xml not found.", digimonEvoXmlPath); } XDocument document = XDocument.Load(digimonEvoXmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "DigimonEvolutionTable") { throw new InvalidOperationException("DigimonEvo.xml root node must be ."); } List evolutions = new(); List lines = new(); List stages = new(); int evolutionId = 1; int evolutionLineId = 1; int evolutionStageId = 1; int digimonRowIndex = 0; foreach (XElement digimonElement in root.Elements("Digimon")) { digimonRowIndex++; string digimonContext = BuildDigimonContext(digimonElement, digimonRowIndex); int digimonType = ReadRequiredInt(digimonElement, "DigimonId", digimonContext); int evolutionRank = ReadRequiredInt(digimonElement, "BattleEvoType", digimonContext); int currentEvolutionId = evolutionId++; evolutions.Add(new EvolutionRecord { Id = currentEvolutionId, Type = digimonType, EvolutionRank = evolutionRank }); int lineIndex = 0; foreach (XElement evolutionElement in digimonElement.Elements("Evolution")) { lineIndex++; string lineContext = BuildEvolutionLineContext(digimonType, lineIndex, evolutionElement); int currentLineId = evolutionLineId++; lines.Add(new EvolutionLineRecord { Id = currentLineId, EvolutionId = currentEvolutionId, Type = ReadRequiredInt(evolutionElement, "DigimonId", lineContext), SlotLevel = ReadRequiredByte(evolutionElement, "EvoSlot", lineContext), UnlockLevel = ReadRequiredByte(evolutionElement, "OpenLevel", lineContext), UnlockQuestId = ReadRequiredShort(evolutionElement, "OpenQuest", lineContext), UnlockItemSection = ReadRequiredInt(evolutionElement, "OpenItemTypeS", lineContext), UnlockItemSectionAmount = ReadRequiredInt(evolutionElement, "OpenItemNum", lineContext), RequiredItem = ReadRequiredInt(evolutionElement, "UseItem", lineContext), RequiredAmount = ReadRequiredInt(evolutionElement, "UseItemNum", lineContext) }); int stageIndex = 0; foreach (XElement linkElement in evolutionElement.Elements("EvolutionLink")) { stageIndex++; string stageContext = $"{lineContext}, link {stageIndex}"; int slot = ReadRequiredInt(linkElement, "Slot", stageContext); int linkType = ReadRequiredInt(linkElement, "Type", stageContext); int targetDigimonId = ReadRequiredInt(linkElement, "DigimonId", stageContext); stages.Add(new EvolutionStageRecord { Id = evolutionStageId++, EvolutionLineId = currentLineId, Type = targetDigimonId, Value = EncodeStageValue(linkType, slot) }); } } } return new EvolutionImportPackage { Evolutions = evolutions, Lines = lines, Stages = stages, BattleEvolutionCount = CountBattleEvolutionRecords(battleEvoXmlPath) }; } private static int CountBattleEvolutionRecords(string battleEvoXmlPath) { if (!File.Exists(battleEvoXmlPath)) { return 0; } XDocument document = XDocument.Load(battleEvoXmlPath); XElement? root = document.Root; if (root == null || root.Name.LocalName != "BattleEvolutionTable") { return 0; } return root.Elements("BattleEvolution").Count(); } private static int EncodeStageValue(int linkType, int slot) { unchecked { return (linkType << 16) | (slot & 0xFFFF); } } private static string BuildDigimonContext(XElement digimonElement, int rowIndex) { string digimonId = digimonElement.Element("DigimonId")?.Value?.Trim() ?? "?"; return $"DigimonEvo row {rowIndex} (DigimonId={digimonId})"; } private static string BuildEvolutionLineContext(int ownerDigimonId, int lineIndex, XElement evolutionElement) { string digimonId = evolutionElement.Element("DigimonId")?.Value?.Trim() ?? "?"; string evoSlot = evolutionElement.Element("EvoSlot")?.Value?.Trim() ?? "?"; return $"DigimonEvo line {lineIndex} (OwnerDigimonId={ownerDigimonId}, DigimonId={digimonId}, EvoSlot={evoSlot})"; } 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 byte ReadRequiredByte(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < byte.MinValue || value > byte.MaxValue) { throw new InvalidOperationException($"{recordContext} has out-of-range byte value in '{elementName}': '{value}'."); } return (byte)value; } private static short ReadRequiredShort(XElement parent, string elementName, string recordContext) { int value = ReadRequiredInt(parent, elementName, recordContext); if (value < short.MinValue || value > short.MaxValue) { throw new InvalidOperationException($"{recordContext} has out-of-range short value in '{elementName}': '{value}'."); } return (short)value; } 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 void ExecuteNonQuery(SqlConnection connection, SqlTransaction transaction, string sql) { using SqlCommand command = new(sql, connection, transaction); command.ExecuteNonQuery(); } private static void TryDisableIdentityInsert(SqlConnection connection, SqlTransaction transaction, string tableName) { try { ExecuteNonQuery(connection, transaction, $"SET IDENTITY_INSERT {tableName} OFF;"); } catch { // Best-effort cleanup before rollback. } } private static void AddParameter(SqlCommand command, string name) { command.Parameters.Add(new SqlParameter(name, DBNull.Value)); } private sealed class EvolutionImportPackage { public List Evolutions { get; init; } = new(); public List Lines { get; init; } = new(); public List Stages { get; init; } = new(); public int BattleEvolutionCount { get; init; } } private sealed class EvolutionRecord { public int Id { get; init; } public int Type { get; init; } public int EvolutionRank { get; init; } } private sealed class EvolutionLineRecord { public int Id { get; init; } public int EvolutionId { get; init; } public int Type { get; init; } public byte SlotLevel { get; init; } public byte UnlockLevel { get; init; } public short UnlockQuestId { get; init; } public int UnlockItemSection { get; init; } public int UnlockItemSectionAmount { get; init; } public int RequiredItem { get; init; } public int RequiredAmount { get; init; } } private sealed class EvolutionStageRecord { public int Id { get; init; } public int Type { get; init; } public int Value { get; init; } public int EvolutionLineId { get; init; } } } }