package db import ( "database/sql" "errors" "log" "os" "path/filepath" "github.com/arpinfidel/p2p-llm/config" ) var ( // ErrNoRows is returned when a query returns no rows ErrNoRows = errors.New("no rows in result set") ) // Database defines the interface for database operations type Database interface { Init() error Close() Ping() error Exec(query string, args ...interface{}) (sql.Result, error) Query(query string, args ...interface{}) (*sql.Rows, error) QueryRow(query string, args ...interface{}) *sql.Row } // SQLiteDB implements the Database interface for SQLite type SQLiteDB struct { db *sql.DB } // NewSQLiteDB creates a new SQLite database connection func NewSQLiteDB(cfg *config.Config) (*SQLiteDB, error) { // Ensure the database directory exists dbDir := filepath.Dir(cfg.DBPath) if dbDir != "." { if err := os.MkdirAll(dbDir, 0755); err != nil { return nil, err } } // Open the database connection db, err := sql.Open("sqlite", cfg.DBPath) if err != nil { return nil, err } return &SQLiteDB{db: db}, nil } func (s *SQLiteDB) Init() error { // Test the connection if err := s.Ping(); err != nil { return err } log.Println("Database connection established successfully") return nil } func (s *SQLiteDB) Close() { if s.db != nil { s.db.Close() log.Println("Database connection closed") } } func (s *SQLiteDB) Ping() error { return s.db.Ping() } func (s *SQLiteDB) Exec(query string, args ...interface{}) (sql.Result, error) { return s.db.Exec(query, args...) } func (s *SQLiteDB) Query(query string, args ...interface{}) (*sql.Rows, error) { return s.db.Query(query, args...) } func (s *SQLiteDB) QueryRow(query string, args ...interface{}) *sql.Row { return s.db.QueryRow(query, args...) }