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("Bot:Database")}"); private static ILogger _logger = Program.Logger; /// /// Run a raw query on the database /// /// /// string query = "TRUNCATE SomeTable"; /// Controller.RawQuery(query); /// /// Raw query to execute /// Whether to read the output and return it as a DataFrame /// Whether to throw any exceptions or to log and shrug. /// public static DataTable RawQuery(string query, Dictionary 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; } } }