Initial commit: gocarlog project — Milestones 1-10 completed
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
_ "embed"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
//go:embed migration.sql
|
||||
var migrationSQL string
|
||||
|
||||
// Database holds the database connection and provides common methods.
|
||||
type Database struct {
|
||||
*sql.DB
|
||||
}
|
||||
|
||||
// NewDatabase opens a SQLite database at the given path, runs migrations,
|
||||
// and seeds the fuel table if empty.
|
||||
func NewDatabase(path string) (*Database, error) {
|
||||
sqlDB, err := sql.Open("sqlite3", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Enable Foreign Keys (SQLite requires this per-connection)
|
||||
if _, err := sqlDB.Exec("PRAGMA foreign_keys = ON"); err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Run migrations
|
||||
if err := RunMigrations(sqlDB); err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Seed fuels
|
||||
tx, err := sqlDB.Begin()
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := SeedFuelTypes(tx); err != nil {
|
||||
tx.Rollback()
|
||||
sqlDB.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
sqlDB.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Database{DB: sqlDB}, nil
|
||||
}
|
||||
|
||||
// New creates a new Database instance from an existing sql.DB.
|
||||
func New(db *sql.DB) *Database {
|
||||
return &Database{DB: db}
|
||||
}
|
||||
|
||||
// RunMigrations applies the embedded migration SQL to the database.
|
||||
func RunMigrations(db *sql.DB) error {
|
||||
// Split by ; but handle multi-line statements that may start with --
|
||||
lines := strings.Split(migrationSQL, "\n")
|
||||
var stmtBuilder strings.Builder
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
// Skip pure comment lines
|
||||
if strings.HasPrefix(trimmed, "--") {
|
||||
continue
|
||||
}
|
||||
stmtBuilder.WriteString(line)
|
||||
stmtBuilder.WriteString("\n")
|
||||
}
|
||||
fullSQL := stmtBuilder.String()
|
||||
|
||||
// Split into individual statements
|
||||
rawStmts := strings.Split(fullSQL, ";")
|
||||
count := 0
|
||||
for _, raw := range rawStmts {
|
||||
stmt := strings.TrimSpace(raw)
|
||||
if stmt == "" {
|
||||
continue
|
||||
}
|
||||
count++
|
||||
display := stmt
|
||||
if len(display) > 80 {
|
||||
display = display[:80] + "..."
|
||||
}
|
||||
log.Printf(" [%d] %s", count, display)
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
return fmt.Errorf("exec migration stmt %d: %w", count, err)
|
||||
}
|
||||
}
|
||||
log.Printf("Migrations completed successfully (%d statements)", count)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user