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();
}
}
public void InConnection(Action dbAction)
{
using var conn = new SQLiteConnection(_databaseLocation.FullName);
dbAction(conn);
}
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;
}
///
/// 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));
}
}