import Database from "better-sqlite3";
import { IMemoryAdapter } from "../interfaces";
import { BaseMemoryType, CreateMemoryInput } from "../types";
/**
* @module BetterSQLiteAdapter
* @description Adaptateur SQLite pour le stockage persistant des mémoires.
*/
export class BetterSQLiteAdapter implements IMemoryAdapter {
private db: Database.Database;
/**
* Initialise l'adaptateur avec une base SQLite.
* @param {string} dbPath - Chemin vers le fichier SQLite
*/
constructor(dbPath: string = "./memory.db") {
this.db = new Database(dbPath);
this.initSchema();
}
/**
* Initialise la table SQLite si elle n'existe pas
*/
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS memories (
id TEXT PRIMARY KEY,
roomId TEXT,
data TEXT,
createdAt TEXT
)
`);
}
/**
* Initialise le stockage pour une salle spécifique (non nécessaire pour SQLite).
*/
async init(_roomId: string): Promise<void> {
return;
}
/**
* Stocke une nouvelle mémoire dans la base SQLite.
* @param {CreateMemoryInput} input - Données de la mémoire
* @returns {Promise<BaseMemoryType>} - Mémoire créée
*/
async createMemory(input: CreateMemoryInput): Promise<BaseMemoryType> {
const memory: BaseMemoryType = {
id: input.id || crypto.randomUUID(),
data: input.data,
roomId: input.roomId,
createdAt: new Date(),
};
const stmt = this.db.prepare(`
INSERT INTO memories (id, roomId, data, createdAt)
VALUES (?, ?, ?, ?)
`);
stmt.run(memory.id, memory.roomId, memory.data, memory.createdAt.toISOString());
return memory;
}
/**
* Récupère une mémoire par ID et salle.
* @param {string} id - Identifiant de la mémoire
* @param {string} roomId - Identifiant de la salle
* @returns {Promise<BaseMemoryType | null>} - Mémoire trouvée ou null
*/
async getMemoryById(id: string, roomId: string): Promise<BaseMemoryType | null> {
const stmt = this.db.prepare(`
SELECT * FROM memories WHERE id = ? AND roomId = ?
`);
const row = stmt.get(id, roomId);
return row ? { ...row, createdAt: new Date(row.createdAt) } : null;
}
/**
* Recherche des mémoires contenant un mot-clé.
*/
async getMemoryByIndex(query: string, options: { roomId: string; limit?: number }): Promise<BaseMemoryType[]> {
const stmt = this.db.prepare(`
SELECT * FROM memories WHERE roomId = ? AND data LIKE ? LIMIT ?
`);
return stmt.all(options.roomId, `%${query}%`, options.limit || 10);
}
/**
* Récupère toutes les mémoires d'une salle.
*/
async getAllMemories(roomId: string): Promise<BaseMemoryType[]> {
const stmt = this.db.prepare(`
SELECT * FROM memories WHERE roomId = ?
`);
return stmt.all(roomId);
}
/**
* Supprime une mémoire spécifique.
*/
async clearMemoryById(id: string, roomId: string): Promise<void> {
const stmt = this.db.prepare(`
DELETE FROM memories WHERE id = ? AND roomId = ?
`);
stmt.run(id, roomId);
}
/**
* Supprime toutes les mémoires.
*/
async clearAllMemories(): Promise<void> {
this.db.exec(`DELETE FROM memories`);
}
}