package database import ( "database/sql" "fmt" "log" "os" "path/filepath" _ "modernc.org/sqlite" ) // DB wraps the database connection type DB struct { *sql.DB } // New creates a new database connection func New(dbPath string) (*DB, error) { // Ensure the directory exists dir := filepath.Dir(dbPath) if err := os.MkdirAll(dir, 0755); err != nil { return nil, fmt.Errorf("failed to create database directory: %w", err) } // Open database connection db, err := sql.Open("sqlite", dbPath) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } // Configure connection pool db.SetMaxOpenConns(1) // SQLite works best with single connection db.SetMaxIdleConns(1) // Enable WAL mode for better concurrency if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil { db.Close() return nil, fmt.Errorf("failed to enable WAL mode: %w", err) } // Enable foreign keys if _, err := db.Exec("PRAGMA foreign_keys=ON"); err != nil { db.Close() return nil, fmt.Errorf("failed to enable foreign keys: %w", err) } // Test connection if err := db.Ping(); err != nil { db.Close() return nil, fmt.Errorf("failed to ping database: %w", err) } log.Printf("Connected to database: %s", dbPath) return &DB{db}, nil } // Close closes the database connection func (db *DB) Close() error { return db.DB.Close() }