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
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Fuel Types
|
||||
CREATE TABLE IF NOT EXISTS fuels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(50) NOT NULL UNIQUE,
|
||||
unit VARCHAR(10) NOT NULL
|
||||
);
|
||||
|
||||
-- Vehicles
|
||||
CREATE TABLE IF NOT EXISTS vehicles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
manufacturer VARCHAR(100),
|
||||
model VARCHAR(100),
|
||||
fuel_id INTEGER,
|
||||
year INTEGER,
|
||||
description TEXT,
|
||||
purchase_date DATE,
|
||||
license_plate VARCHAR(20),
|
||||
weight_kg REAL,
|
||||
power_kw REAL,
|
||||
max_odometer REAL,
|
||||
current_odometer REAL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (fuel_id) REFERENCES fuels(id)
|
||||
);
|
||||
|
||||
-- Logbook
|
||||
CREATE TABLE IF NOT EXISTS logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
vehicle_id INTEGER NOT NULL,
|
||||
fuel_id INTEGER,
|
||||
log_type VARCHAR(20) NOT NULL,
|
||||
odometer REAL,
|
||||
datetime DATETIME NOT NULL,
|
||||
cost REAL,
|
||||
quantity REAL,
|
||||
unit VARCHAR(10),
|
||||
note TEXT,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (vehicle_id) REFERENCES vehicles(id),
|
||||
FOREIGN KEY (fuel_id) REFERENCES fuels(id)
|
||||
);
|
||||
@@ -0,0 +1,38 @@
|
||||
package db
|
||||
|
||||
import "database/sql"
|
||||
|
||||
// FuelType definiert einen verfügbaren Kraftstofftyp.
|
||||
type FuelType struct {
|
||||
ID int
|
||||
Name string
|
||||
Unit string
|
||||
}
|
||||
|
||||
// DefaultFuelTypes enthält die standardmäßigen Kraftstofftypen,
|
||||
// wie sie in der Migration-Datei definiert sind.
|
||||
var DefaultFuelTypes = []FuelType{
|
||||
{ID: 0, Name: "Diesel", Unit: "L"},
|
||||
{ID: 1, Name: "Benzin", Unit: "L"},
|
||||
{ID: 2, Name: "LPG", Unit: "L"},
|
||||
{ID: 3, Name: "CNG", Unit: "L"},
|
||||
{ID: 4, Name: "Strom", Unit: "kWh"},
|
||||
}
|
||||
|
||||
// SeedFuelTypes fügt die standardmäßigen Kraftstofftypen in die Datenbank ein,
|
||||
// falls sie noch nicht existieren (INSERT OR IGNORE).
|
||||
//
|
||||
// Diese Funktion wird automatisch beim Init() aufgerufen,
|
||||
// ist aber auch separat verfügbar, um z. B. in Tests
|
||||
// einen bekannten Seed-State zu setzen.
|
||||
func SeedFuelTypes(tx *sql.Tx) error {
|
||||
for _, fuel := range DefaultFuelTypes {
|
||||
if _, err := tx.Exec(
|
||||
"INSERT OR IGNORE INTO fuels (id, name, unit) VALUES (?, ?, ?)",
|
||||
fuel.ID, fuel.Name, fuel.Unit,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user