feat(db): embed migration files
Signed-off-by: SoXX <soxx@fenpa.ws>
This commit is contained in:
parent
549c1ca573
commit
b65e942f24
@ -3,6 +3,7 @@ package database
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"git.dragse.it/anthrove/otter-space-sdk/internal/postgres"
|
"git.dragse.it/anthrove/otter-space-sdk/internal/postgres"
|
||||||
@ -10,10 +11,14 @@ import (
|
|||||||
"git.dragse.it/anthrove/otter-space-sdk/pkg/models/graphModels"
|
"git.dragse.it/anthrove/otter-space-sdk/pkg/models/graphModels"
|
||||||
_ "github.com/lib/pq"
|
_ "github.com/lib/pq"
|
||||||
migrate "github.com/rubenv/sql-migrate"
|
migrate "github.com/rubenv/sql-migrate"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
gormPostgres "gorm.io/driver/postgres"
|
gormPostgres "gorm.io/driver/postgres"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/*.sql
|
||||||
|
var embedMigrations embed.FS
|
||||||
|
|
||||||
type postgresqlConnection struct {
|
type postgresqlConnection struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
}
|
}
|
||||||
@ -142,20 +147,24 @@ func (p postgresqlConnection) GetSourceByURL(ctx context.Context, sourceUrl stri
|
|||||||
|
|
||||||
func (p postgresqlConnection) migrateDatabase(connectionString string) error {
|
func (p postgresqlConnection) migrateDatabase(connectionString string) error {
|
||||||
dialect := "postgres"
|
dialect := "postgres"
|
||||||
migrations := &migrate.FileMigrationSource{
|
migrations := &migrate.EmbedFileSystemMigrationSource{FileSystem: embedMigrations, Root: "migrations"}
|
||||||
Dir: "db/migrations",
|
|
||||||
}
|
|
||||||
|
|
||||||
db, err := sql.Open(dialect, connectionString)
|
db, err := sql.Open(dialect, connectionString)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return fmt.Errorf("postgres migration: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := migrate.Exec(db, dialect, migrations, migrate.Up)
|
n, err := migrate.Exec(db, dialect, migrations, migrate.Up)
|
||||||
if err != nil {
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user