Files
TentacleBot/Services/Memory/DatabaseInitializer.cs
Garret Patti a794e387f3
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 16s
add memory
2026-07-11 10:06:48 -04:00

66 lines
2.2 KiB
C#

using Microsoft.Data.Sqlite;
namespace TentacleBot.Services.Memory;
public class DatabaseInitializer
{
private readonly string _connectionString;
public DatabaseInitializer(string dbPath)
{
var directory = Path.GetDirectoryName(dbPath);
if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
_connectionString = $"Data Source={dbPath}";
}
public string ConnectionString => _connectionString;
public void Initialize()
{
using var connection = new SqliteConnection(_connectionString);
connection.Open();
using var cmd = connection.CreateCommand();
cmd.CommandText = @"
CREATE TABLE IF NOT EXISTS user_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
rule_text TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
content TEXT NOT NULL,
category TEXT,
importance INTEGER NOT NULL DEFAULT 5,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_accessed TEXT
);
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
content, content=memories, content_rowid=id
);
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
INSERT INTO memories_fts(rowid, content) VALUES (new.id, new.content);
END;
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
INSERT INTO memories_fts(memories_fts, rowid, content) VALUES ('delete', old.id, old.content);
END;
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
INSERT INTO memories_fts(memories_fts, rowid, content) VALUES ('delete', old.id, old.content);
INSERT INTO memories_fts(rowid, content) VALUES (new.id, new.content);
END;
";
cmd.ExecuteNonQuery();
}
}