Nulah.PowerShell/src/ModuleCore/Database/DatabaseManager.cs
Scott fc3fe217e4 chore: Add comments to public methods
- rename GetRepo to GetDirectoryForRegisteredRepo so it's actually doing what it says
2026-09-05 13:42:05 +10:00

86 lines
No EOL
2.7 KiB
C#

using SQLite;
namespace ModuleCore.Database;
public class DatabaseManager
{
private readonly FileInfo _databaseLocation;
/// <summary>
/// Creates a new manager for the given database file by name
/// </summary>
/// <param name="databaseName">
/// Filename for the database with no extension. Slashes are accepted and will create directories as needed.
/// </param>
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();
}
}
/// <summary>
/// Runs the given action within a new database connection
/// </summary>
/// <param name="dbAction"></param>
public void InConnection(Action<SQLiteConnection> dbAction)
{
using var conn = new SQLiteConnection(_databaseLocation.FullName);
dbAction(conn);
}
/// <summary>
/// Runs the given func in a new database connection, returning the result
/// </summary>
/// <param name="dbAction"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T InConnection<T>(Func<SQLiteConnection, T> dbAction)
{
using var conn = new SQLiteConnection(_databaseLocation.FullName);
return dbAction(conn);
}
/// <summary>
/// Returns a bool for the given query. Convenience method for <see cref="SQLiteConnection.ExecuteScalar"/>.
/// </summary>
/// <param name="query">A query starting with SELECT 1, optionally paramaterised with ?</param>
/// <param name="args">Parameter values</param>
/// <returns></returns>
public bool Exists(string query, params object[] args)
{
using var conn = new SQLiteConnection(_databaseLocation.FullName);
var exists = conn.ExecuteScalar<bool?>(query, args);
return exists ?? false;
}
/// <summary>
/// Deletes the current database file. This will cause any future instance methods to fail on database action if
/// a new instance is not created.
/// <para>
/// This method should be avoided unless calling from a test.
/// </para>
/// </summary>
internal void DeleteDatabase()
{
_databaseLocation.Delete();
}
/// <summary>
/// Removes double dots from the filename and removes the file extension
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
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));
}
}