added retries in database.Open()

This commit is contained in:
fanir 2022-01-25 23:58:41 +01:00
parent c81d7c3264
commit 0fd673cd19

View file

@ -3,6 +3,8 @@ package database
import (
"database/sql"
"fmt"
"log"
"time"
"git.zom.bi/fanir/feedizer/cmd/feedizer/config"
"git.zom.bi/fanir/feedizer/models/migrations"
@ -22,7 +24,25 @@ func Open(c config.DatabaseConfig) (*sql.DB, error) {
dsn = fmt.Sprintf("postgres://%s:%s@%s:%d/%s?%s", c.Username, c.Password, c.Host, c.Port, c.Database, c.Options)
LogName = fmt.Sprintf("%s:%d/%s", c.Host, c.Port, c.Database)
}
return sql.Open("postgres", dsn)
log.Printf("database: connecting...")
db, err := sql.Open("postgres", dsn)
if err != nil {
return nil, err
}
err = db.Ping()
for i := 1; err != nil && i < 10; i++ {
log.Printf("database: connection failed, retrying in %d seconds...", i)
time.Sleep(time.Duration(i) * time.Second)
err = db.Ping()
}
if err == nil {
log.Println("database: connection successful")
}
return db, err
}
func Migrate(db *sql.DB) error {