using SQLite; namespace ModuleCore.Database; public class DatabaseManager { private readonly FileInfo _databaseLocation; /// /// Creates a new manager for the given database file by name /// /// /// Filename for the database with no extension. Slashes are accepted and will create directories as needed. /// public DatabaseManager(string databaseName) { // Even though the xmldoc says "with no extension", we strip off any extension regardless _databaseLocation = new FileInfo(Path.Combine(".", "data", $"{SanitiseFilename(databaseName)}.db")); Directory.CreateDirectory(_databaseLocation.DirectoryName!); if (!File.Exists(_databaseLocation.FullName)) { var file = File.Create(_databaseLocation.FullName); file.Close(); } } /// /// Runs the given action within a new database connection /// /// public void InConnection(Action dbAction) { using var conn = new SQLiteConnection(_databaseLocation.FullName); dbAction(conn); } /// /// Runs the given func in a new database connection, returning the result /// /// /// /// public T InConnection(Func dbAction) { using var conn = new SQLiteConnection(_databaseLocation.FullName); return dbAction(conn); } /// /// Returns a bool for the given query. Convenience method for . /// /// A query starting with SELECT 1, optionally paramaterised with ? /// Parameter values /// public bool Exists(string query, params object[] args) { using var conn = new SQLiteConnection(_databaseLocation.FullName); var exists = conn.ExecuteScalar(query, args); return exists ?? false; } /// /// Deletes the current database file. This will cause any future instance methods to fail on database action if /// a new instance is not created. /// /// This method should be avoided unless calling from a test. /// /// internal void DeleteDatabase() { _databaseLocation.Delete(); } /// /// Removes double dots from the filename and removes the file extension /// /// /// private string SanitiseFilename(string filename) { // Honestly not really needed seeing as its just me and this isn't coming from user supplied code, but eh. return Path.GetFileNameWithoutExtension(filename.Replace("..", string.Empty)); } }