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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user