Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Postgres and MySQL databases support #335

Merged
merged 12 commits into from
Sep 20, 2024
Prev Previous commit
Next Next commit
Add retries
  • Loading branch information
thomiceli committed Sep 16, 2024
commit b207ae15be87f7d0ffd73b145990bb2e1f312d1e
37 changes: 26 additions & 11 deletions internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"path/filepath"
"slices"
"strings"
"time"

"github.com/rs/zerolog/log"
"github.com/thomiceli/opengist/internal/config"
Expand Down Expand Up @@ -90,24 +91,38 @@ func Setup(dbUri string, sharedCache bool) error {
if err != nil {
return err
}

log.Info().Msgf("Setting up a %s database connection", dbInfo.Type)
var setupFunc func(databaseInfo, bool) error
switch dbInfo.Type {
case SQLite:
if err = setupSQLite(*dbInfo, sharedCache); err != nil {
return err
}
setupFunc = setupSQLite
case PostgreSQL:
if err = setupPostgres(*dbInfo); err != nil {
return err
}
setupFunc = setupPostgres
case MySQL:
if err = setupMySQL(*dbInfo); err != nil {
return err
}
setupFunc = setupMySQL
default:
return fmt.Errorf("unknown database type: %v", dbInfo.Type)
}

maxAttempts := 60
retryInterval := 1 * time.Second

for attempt := 1; attempt <= maxAttempts; attempt++ {
err = setupFunc(*dbInfo, sharedCache)
if err == nil {
log.Info().Msg("Database connection established")
break
}

if attempt < maxAttempts {
log.Warn().Err(err).Msgf("Failed to connect to database (attempt %d), retrying in %v...", attempt, retryInterval)
time.Sleep(retryInterval)
} else {
return err
}
}

DatabaseInfo = dbInfo

if err = db.SetupJoinTable(&Gist{}, "Likes", &Like{}); err != nil {
Expand Down Expand Up @@ -184,7 +199,7 @@ func setupSQLite(dbInfo databaseInfo, sharedCache bool) error {
return err
}

func setupPostgres(dbInfo databaseInfo) error {
func setupPostgres(dbInfo databaseInfo, sharedCache bool) error {
var err error
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", dbInfo.Host, dbInfo.Port, dbInfo.User, dbInfo.Password, dbInfo.Database)

Expand All @@ -196,7 +211,7 @@ func setupPostgres(dbInfo databaseInfo) error {
return err
}

func setupMySQL(dbInfo databaseInfo) error {
func setupMySQL(dbInfo databaseInfo, sharedCache bool) error {
var err error
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbInfo.User, dbInfo.Password, dbInfo.Host, dbInfo.Port, dbInfo.Database)

Expand Down