package main import ( "database/sql" "embed" "fmt" "github.com/mattn/go-sqlite3" "log" "os" ) //go:embed migrations/*.sql var migrations embed.FS func openDatabase() *sql.DB { // Initialize the database connection db, err := sqlite3.Open("videos.db") if err != nil { log.Fatalf("Error opening database: %v\n", err) } // Get current migration version from user_version var currentVersion int err = db.QueryRow("PRAGMA user_version").Scan(¤tVersion) if err != nil { fmt.Printf("Error getting current version: %v\n", err) os.Exit(1) } // Read all migrations migrationFiles, err := migrations.ReadDir(migrationDir) if err != nil { fmt.Printf("Error reading migration files: %v\n", err) os.Exit(1) } // Sort and process each migration file (assuming filenames are versioned like 1.sql, 2.sql, etc.) for _, f := range migrationFiles { if !f.IsDir() { versionStr := f.Name() version, err := extractVersion(versionStr) if err != nil { fmt.Printf("Error extracting version from %s: %v\n", versionStr, err) continue } if version > currentVersion { // Apply the migration sqlContent, err := readMigrationFile(f.Name()) if err != nil { fmt.Printf("Error reading migration file %s: %v\n", f.Name(), err) os.Exit(1) } _, err = db.Exec(sqlContent) if err != nil { fmt.Printf("Error applying migration %d: %v\n", version, err) os.Exit(1) } // Update the user_version _, err = db.Exec(fmt.Sprintf("PRAGMA user_version=%d", version)) if err != nil { fmt.Printf("Error updating user_version to %d: %v\n", version, err) os.Exit(1) } fmt.Printf("Applied migration %d successfully\n", version) } } } fmt.Println("All migrations applied") }