vibeStonk/server/repository/sqliteDB.go
2025-06-12 16:57:42 -04:00

47 lines
1.1 KiB
Go

package repository
import (
"database/sql"
"fmt"
"os"
"path/filepath"
_ "modernc.org/sqlite" // Import the SQLite driver
)
func getSqliteFilename(dir, name string) (string, error) {
if len(name) == 0 {
return "", ErrNoDBName
}
return filepath.Join(dir, name+".sqlite"), nil
}
func getSqliteConnection(dir, name string) (*sql.DB, error) {
// make sure the data directory exists
dbPath, err := getSqliteFilename(dir, name)
if err != nil {
return nil, err
}
err = os.MkdirAll(filepath.Dir(dbPath), 0755)
if err != nil {
return nil, fmt.Errorf("failed to ensure data directory for sqlite database: %w", err)
}
// Initialize and return the connection to the sqlite database
// Using the modernc.org/sqlite driver with the "sqlite" driver name
db, err := sql.Open("sqlite", dbPath)
if err != nil {
return nil, fmt.Errorf("failed to open sqlite database: %w", err)
}
// Test the connection
if err := db.Ping(); err != nil {
db.Close() // Close the connection if ping fails
return nil, fmt.Errorf("failed to ping sqlite database: %w", err)
}
return db, nil
}