feat(db): embed migration files

Signed-off-by: SoXX <soxx@fenpa.ws>
This commit is contained in:
SoXX 2024-06-04 13:28:14 +02:00
parent 549c1ca573
commit b65e942f24
12 changed files with 15 additions and 6 deletions

View File

@ -3,6 +3,7 @@ package database
import (
"context"
"database/sql"
"embed"
"fmt"
"git.dragse.it/anthrove/otter-space-sdk/internal/postgres"
@ -10,10 +11,14 @@ import (
"git.dragse.it/anthrove/otter-space-sdk/pkg/models/graphModels"
_ "github.com/lib/pq"
migrate "github.com/rubenv/sql-migrate"
log "github.com/sirupsen/logrus"
gormPostgres "gorm.io/driver/postgres"
"gorm.io/gorm"
)
//go:embed migrations/*.sql
var embedMigrations embed.FS
type postgresqlConnection struct {
db *gorm.DB
}
@ -142,20 +147,24 @@ func (p postgresqlConnection) GetSourceByURL(ctx context.Context, sourceUrl stri
func (p postgresqlConnection) migrateDatabase(connectionString string) error {
dialect := "postgres"
migrations := &migrate.FileMigrationSource{
Dir: "db/migrations",
}
migrations := &migrate.EmbedFileSystemMigrationSource{FileSystem: embedMigrations, Root: "migrations"}
db, err := sql.Open(dialect, connectionString)
if err != nil {
return err
return fmt.Errorf("postgres migration: %v", err)
}
n, err := migrate.Exec(db, dialect, migrations, migrate.Up)
if err != nil {
return err
return fmt.Errorf("postgres migration: %v", err)
}
if n != 0 {
log.Infof("postgres migration: applied %d migrations!", n)
} else {
log.Info("postgres migration: nothing to migrate")
}
fmt.Printf("Applied %d migrations!\n", n)
return nil
}