You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.4 KiB
Go

package migrations
import (
"database/sql"
"embed"
"fmt"
"log/slog"
"github.com/golang-migrate/migrate/v4"
// "github.com/golang-migrate/migrate/v4/database"
"github.com/golang-migrate/migrate/v4/database/sqlite3"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/golang-migrate/migrate/v4/source/iofs"
)
//go:embed *.sql
var migrationFiles embed.FS
func Migrate(db *sql.DB, logger *slog.Logger) error {
// Create a database driver for the specific database type
driver, err := sqlite3.WithInstance(db, &sqlite3.Config{})
if err != nil {
return fmt.Errorf("failed to create database driver: %w", err)
}
// Create an IFS source from the embedded files
source, err := iofs.New(migrationFiles, ".")
if err != nil {
return fmt.Errorf("failed to create migration source: %w", err)
}
// Create a new migrate instance
m, err := migrate.NewWithInstance("iofs", source, "sqlite3", driver)
if err != nil {
return fmt.Errorf("failed to create migrate instance: %w", err)
}
// Run migrations
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
return fmt.Errorf("failed to run migrations: %w", err)
}
// set WAL mode
_, err = db.Exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")
if err != nil {
return fmt.Errorf("failed to set wall mode: %w", err)
}
logger.Info("Migrations completed successfully")
return nil
}