Files
BeWoPlaner/Tools/BeWoDatabaseUpdater/BeWoDatabaseUpdater/MySqlBeWoHelper.cs
2025-10-09 12:56:32 +02:00

86 lines
2.5 KiB
C#

using BeWoDatabaseUpdater.Extensions;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;
namespace BeWoDatabaseUpdater
{
public static class MySqlBeWoHelper
{
private static readonly object _Lock = new();
public static async Task<List<string>> LoadBeWoDatabaseNames(string connectionString)
{
var connection = new MySqlConnection(connectionString);
var result = new List<string>();
try
{
await connection.OpenAsync();
var command = new MySqlCommand("SELECT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES tables WHERE tables.TABLE_NAME = 'bewofile';") { Connection = connection };
await using var dataReader = command.ExecuteReader();
while(await dataReader.ReadAsync())
{
var schemaName = dataReader["TABLE_SCHEMA"]?.ToString();
if(schemaName is not null)
{
result.AddIfNotIn(schemaName);
}
}
}
catch(Exception exception)
{
Console.WriteLine(exception);
}
finally
{
if(connection.State is ConnectionState.Open or ConnectionState.Executing)
{
await connection.CloseAsync();
}
}
return result;
}
public static Dictionary<int, string> DistinctErrors = [];
public static void WriteSqlErrorsToFile()
{
lock(_Lock)
{
File.WriteAllLines(Program.FailedSqlCommandsFilePath, DistinctErrors.Values);
}
}
public static void ExecuteUpdateOrCreateAsync(string sql, string filePath, string connectionString)
{
var connection = new MySqlConnection(connectionString);
try
{
connection.Open();
new MySqlCommand(sql, connection).ExecuteNonQuery();
}
catch(MySqlException exception)
{
var errorMessage = $"{exception.Number} {new FileInfo(filePath).Name}: {exception.Message}";
DistinctErrors.AddAndIgnoreDuplicates(exception.Number, errorMessage);
}
finally
{
connection.Close();
}
}
}
}