Add auto-migration on database startup

- Embed migrations/001_initial.sql into the binary
- Run migrations automatically when connecting to database
- Uses CREATE TABLE IF NOT EXISTS for idempotent execution
This commit is contained in:
2025-12-05 16:56:13 -06:00
parent 8afa4fc6d7
commit 055fa556df
3 changed files with 179 additions and 2 deletions

View File

@@ -3,6 +3,7 @@ package storage
import (
"context"
"database/sql"
_ "embed"
"fmt"
"time"
@@ -12,12 +13,15 @@ import (
_ "github.com/lib/pq"
)
//go:embed migrations/001_initial.sql
var migrationSQL string
// Database handles all database operations
type Database struct {
db *sql.DB
}
// NewDatabase creates a new database connection
// NewDatabase creates a new database connection and runs migrations
func NewDatabase(cfg *config.DatabaseConfig) (*Database, error) {
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode)
@@ -31,7 +35,20 @@ func NewDatabase(cfg *config.DatabaseConfig) (*Database, error) {
return nil, fmt.Errorf("failed to ping database: %w", err)
}
return &Database{db: db}, nil
d := &Database{db: db}
// Run migrations
if err := d.runMigrations(); err != nil {
return nil, fmt.Errorf("failed to run migrations: %w", err)
}
return d, nil
}
// runMigrations executes the embedded SQL migrations
func (d *Database) runMigrations() error {
_, err := d.db.Exec(migrationSQL)
return err
}
// Close closes the database connection