chaosbot/ChaosBot/Database/Controller.cs

88 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ChaosBot.Database.Repository;
using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualBasic;
using NLog;
namespace ChaosBot.Database
{
public static class Controller
{
static SqliteConnection _conn = new SqliteConnection($"Data Source={System.IO.Directory.GetCurrentDirectory()}/{ConfigurationRepository.GetValue<string>("Bot:Database")}");
private static ILogger _logger = Dependency.GetInstance<ILogger>();
/// <summary>
/// Run a raw query on the database
/// </summary>
/// <code>
/// string query = "TRUNCATE SomeTable";
/// Controller.RawQuery(query);
/// </code>
/// <param name="query">Raw query to execute</param>
/// <param name="readOutput">Whether to read the output and return it as a <c>DataFrame</c></param>
/// <param name="throwError">Whether to throw any exceptions or to log and shrug.</param>
/// <returns></returns>
public static DataTable RawQuery(string query, Dictionary<string, object> parameters = null, bool readOutput = true, bool throwError = false)
{
DataTable dt = new DataTable();
try
{
using (_conn)
{
// Open the SQLite connection
_conn.Open();
// Start creating the command and assign the query given
SqliteCommand cmd = _conn.CreateCommand();
cmd.CommandText = query;
// Add parameters if they exist
if (parameters != null)
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.Key, parameter.Value);
}
}
// Prepare the statement
_logger.Trace($"Database.Controller.RawQuery: Running query {cmd.CommandText}");
cmd.Prepare();
if (readOutput)
{
// output needs to be read, make a reader and fill the datatable with the data
SqliteDataReader executeReader = cmd.ExecuteReader();
dt.Load(executeReader);
}
else
{
// output does not need to be read, just run the query without reading
cmd.ExecuteNonQuery();
}
// Clean up after ourselves
_conn.Close();
}
}
catch (Exception ex)
{
if (throwError)
{
// If we throw any exception, just throw it so other code can handle it
throw;
}
// We handle the exception, log it and be done
_logger.Fatal($"Database.Controller.RawQuery: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
return dt;
}
}
}