Create DbDriver and DI the driver + the python interface

This commit is contained in:
2026-02-16 12:06:40 -08:00
parent e26fd7a3fc
commit 63a38297c7
3 changed files with 96 additions and 13 deletions
+80
View File
@@ -0,0 +1,80 @@
using Microsoft.Data.Sqlite;
namespace DataBase {
public class DbDriver : IDisposable {
static SqliteConnection? singletonConnector = null;
public DbDriver() {
// Load in the datastore if not already loaded
if (singletonConnector == null) {
singletonConnector = new SqliteConnection("Data Source=test.db");
singletonConnector.Open();
// Create the key value store if not exist
using var command = singletonConnector.CreateCommand();
command.CommandText = """
CREATE TABLE IF NOT EXISTS KeyValuePair (
key TEXT NOT NULL,
value TEXT,
PRIMARY KEY(key)
);
""";
command.ExecuteReader();
}
}
// Return Values from keys
public string Get(string Key) {
if (singletonConnector != null) {
using var command = singletonConnector.CreateCommand();
command.CommandText = """
SELECT value
FROM KeyValuePair
Where key = $key;
""";
command.Parameters.AddWithValue("$key", Key);
command.ExecuteReader();
using var reader = command.ExecuteReader();
if (reader.Read()) {
return reader.GetString(0);
}
}
return "";
}
// Set a key value pair in the store
public void Set(string Key, string Value) {
if (singletonConnector != null) {
using var command = singletonConnector.CreateCommand();
command.CommandText = """
INSERT INTO KeyValuePair
(key,value)
VALUES
($key, $value)
ON CONFLICT(key)
DO UPDATE
SET value = excluded.value;
""";
command.Parameters.AddWithValue("$key", Key);
command.Parameters.AddWithValue("$value", Value);
command.ExecuteReader();
}
}
// Deconstructor
~DbDriver() {
Dispose();
}
// Deconstructor
public void Dispose() {
if (singletonConnector != null) {
singletonConnector.Close();
singletonConnector = null;
}
}
}
}