otter-space-sdk/pkg/database/client.go
SoXX fefc777888 feat(impl): Add database client and migration functionality
Implement connection to PostgreSQL database using GORM. Embed SQL migrations and handle migration execution with logging capabilities. Define configuration structure for database settings.
2024-08-09 21:39:22 +02:00

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
}