69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
|
package database
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"embed"
|
||
|
"fmt"
|
||
|
"git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/models"
|
||
|
migrate "github.com/rubenv/sql-migrate"
|
||
|
log "github.com/sirupsen/logrus"
|
||
|
"gorm.io/driver/postgres"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
//go:embed migrations/*.sql
|
||
|
var embedMigrations embed.FS
|
||
|
var client *gorm.DB
|
||
|
|
||
|
func Connect(_ context.Context, config models.DatabaseConfig) error {
|
||
|
var localSSL string
|
||
|
|
||
|
if config.SSL {
|
||
|
localSSL = "require"
|
||
|
} else {
|
||
|
localSSL = "disable"
|
||
|
}
|
||
|
|
||
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s", config.Endpoint, config.Username, config.Password, config.Database, config.Port, localSSL, config.Timezone)
|
||
|
sqlDB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||
|
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
client = sqlDB
|
||
|
err = migrateDatabase(sqlDB, config)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func migrateDatabase(dbPool *gorm.DB, config models.DatabaseConfig) error {
|
||
|
dialect := "postgres"
|
||
|
migrations := &migrate.EmbedFileSystemMigrationSource{FileSystem: embedMigrations, Root: "migrations"}
|
||
|
|
||
|
db, err := dbPool.DB()
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("postgres migration: %v", err)
|
||
|
}
|
||
|
|
||
|
n, err := migrate.Exec(db, dialect, migrations, migrate.Up)
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("postgres migration: %v", err)
|
||
|
}
|
||
|
|
||
|
if config.Debug {
|
||
|
if n != 0 {
|
||
|
log.Infof("postgres migration: applied %d migrations!", n)
|
||
|
|
||
|
} else {
|
||
|
log.Info("postgres migration: nothing to migrate")
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|