otter-space-sdk/pkg/database/client.go

78 lines
1.7 KiB
Go
Raw Normal View History

package database
import (
"context"
"embed"
"fmt"
2024-08-10 22:26:20 +00:00
otterError "git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/error"
"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
}
2024-08-10 22:26:20 +00:00
func GetGorm(ctx context.Context) (*gorm.DB, error) {
if client == nil {
return nil, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
return client, nil
}