patbef-ServiceOutside/ServiceShared/Database/DbContext.cs

218 lines
6.8 KiB
C#

using MySql.Data.MySqlClient;
using ServiceShared.Database.Migrations;
using ServiceShared.Models.Database;
using System.Reflection;
namespace ServiceShared.Database
{
public class DbContext
{
/// <summary>
/// Current Application Version
/// </summary>
private static string _currentVersion = null;
/// <summary>
/// ConnectionString to the mysql server
/// </summary>
private readonly string _connectionString = null;
/// <summary>
/// Constructor of DbContext
/// </summary>
/// <param name="connectionString">ConnectionString to the mysql server</param>
public DbContext(string connectionString)
{
this._connectionString = connectionString;
}
/// <summary>
/// Runs a migration
/// </summary>
/// <param name="migration">Migration that should be run</param>
/// <param name="currentVersion">Application version</param>
/// <returns>returns true if migration was succssfully</returns>
public bool RunMigration(Migration migration, string currentVersion)
{
_currentVersion = currentVersion + (migration != null ? "_" + migration.Version.ToString() : "");
return migration.Run(this);
}
/// <summary>
/// Sets application version
/// </summary>
/// <param name="currentVersion"></param>
public static void setApplicationVersion(string currentVersion)
{
_currentVersion = currentVersion;
}
/// <summary>
/// Checks if database exists
/// </summary>
/// <returns>returns true if database exists</returns>
public bool DatabaseExists()
{
bool result = false;
try
{
MySqlConnection dbConnection = this.CreateConnection();
using (MySqlConnection client = this.CreateConnectionWithoutSelectedDatabase())
{
client.Open();
MySqlCommand cmd = client.CreateCommand();
cmd.CommandText = "show databases like '" + dbConnection.Database + "'";
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
result = true;
client.Close();
}
}
}
catch(Exception ex)
{
Log.Critical(ex, "ServiceShared.Database.DbContext", "DatabaseExists");
if(ex.InnerException != null)
{
Log.Critical(ex.InnerException, "ServiceShared.Database.DbContext", "DatabaseExists");
}
result = false;
}
return result;
}
/// <summary>
/// Creates a database if not exists
/// </summary>
/// <returns>returns true if the creation of database was successfully</returns>
public bool DatabaseCreate()
{
bool result = false;
try
{
MySqlConnection dbConnection = this.CreateConnection();
using (MySqlConnection client = this.CreateConnectionWithoutSelectedDatabase())
{
client.Open();
MySqlCommand cmd = client.CreateCommand();
cmd.CommandText = "create database if not exists " + dbConnection.Database + " character set utf8mb4 collate utf8mb4_general_ci";
cmd.ExecuteNonQuery();
client.Close();
result = true;
}
}
catch (Exception ex)
{
Log.Error(ex, "ServiceOutside.Database.DbContext", "DatabaseCreate");
}
return result;
}
/// <summary>
/// Maintenance flag
/// </summary>
/// <returns>returns true if Maintenance state has been activated</returns>
public bool GetMaintenance()
{
bool result = false;
try
{
using (MySqlConnection client = this.CreateConnection())
{
client.Open();
MySqlCommand cmd = client.CreateCommand();
cmd.CommandText = @"select maintenance from config limit 1";
MySqlDataReader reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
result = (reader["maintenance"] != null && reader["maintenance"] != DBNull.Value && Convert.ToInt32(reader["maintenance"].ToString()) == 1);
}
}
client.Close();
}
}
catch (Exception ex)
{
Log.Error(ex, "ServiceOutside.Database.DbContext", "Maintenance");
}
return result;
}
/// <summary>
/// Returns a new MySqlConnection
/// </summary>
/// <returns>MySqlConnection</returns>
public MySqlConnection CreateConnection()
{
return new MySqlConnection(this._connectionString);
}
/// <summary>
/// Returns a new MySqlConnection without selected database
/// </summary>
/// <returns>MySqlConnection</returns>
public MySqlConnection CreateConnectionWithoutSelectedDatabase()
{
string connectionString = null;
if (!string.IsNullOrEmpty(this._connectionString))
{
string[] parts = this._connectionString.Split(';');
if (parts.Length > 0)
{
connectionString = "";
foreach (string part in parts)
{
string[] values = part.Split('=');
if (values.Length > 0)
{
if (values[0].ToLower().Replace(" ", "") != "database")
{
connectionString += part + ";";
}
}
}
connectionString = connectionString.TrimEnd(';');
}
}
return new MySqlConnection(connectionString);
}
/// <summary>
/// Retursn current migration of app
/// </summary>
/// <returns>Migration object</returns>
public static string GetCurrentVersion()
{
return _currentVersion;
}
}
}