Spaces:
Running
Running
File size: 2,275 Bytes
84ffb7a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | package database
import (
"context"
"database/sql"
"embed"
"fmt"
"sort"
"time"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// Connect opens a SQLite database and verifies connectivity.
func Connect(ctx context.Context, databaseURL string) (*sql.DB, error) {
db, err := sql.Open("sqlite", databaseURL)
if err != nil {
return nil, fmt.Errorf("open DATABASE_URL: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return db, nil
}
// Migrate applies pending SQL migrations in filename order.
func Migrate(ctx context.Context, db *sql.DB) error {
entries, err := migrationsFS.ReadDir("migrations")
if err != nil {
return fmt.Errorf("read migrations: %w", err)
}
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, e.Name())
}
sort.Strings(names)
if _, err := db.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)`); err != nil {
return fmt.Errorf("ensure schema_migrations: %w", err)
}
for _, name := range names {
var applied bool
err := db.QueryRowContext(ctx,
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = ?)", name).
Scan(&applied)
if err != nil {
return fmt.Errorf("check migration %s: %w", name, err)
}
if applied {
continue
}
body, err := migrationsFS.ReadFile("migrations/" + name)
if err != nil {
return fmt.Errorf("read migration %s: %w", name, err)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin migration %s: %w", name, err)
}
if _, err := tx.ExecContext(ctx, string(body)); err != nil {
tx.Rollback() //nolint:errcheck
return fmt.Errorf("apply migration %s: %w", name, err)
}
if _, err := tx.ExecContext(ctx,
"INSERT INTO schema_migrations (version) VALUES (?)", name); err != nil {
tx.Rollback() //nolint:errcheck
return fmt.Errorf("record migration %s: %w", name, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %s: %w", name, err)
}
}
return nil
}
|