File size: 1,853 Bytes
48511d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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...)
}