fanir
a7d08500f5
- database: - moved to jackc/pgx from database/sql - revised migrator and moved it into it's own package - separated ParseConfig into it's own function - config: - database config is now a DSN or URL instead of a struct - SearchPaths are now available through a function - improved help / usage output - modified data model
41 lines
994 B
Go
41 lines
994 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
)
|
|
|
|
var LogName string
|
|
|
|
// ParseConfig parses the database config string and sets LogName.
|
|
func ParseConfig(config string) (*pgxpool.Config, error) {
|
|
dbConfig, err := pgxpool.ParseConfig(config)
|
|
LogName = fmt.Sprintf("%s@%s:%s/%s", dbConfig.ConnConfig.User, dbConfig.ConnConfig.Host, dbConfig.ConnConfig.Port, dbConfig.ConnConfig.Database)
|
|
return dbConfig, err
|
|
}
|
|
|
|
func Open(dbConfig *pgxpool.Config) (*pgxpool.Pool, error) {
|
|
log.Printf("database: connecting...")
|
|
db, err := pgxpool.ConnectConfig(context.Background(), dbConfig)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = db.Ping(context.Background())
|
|
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(context.Background())
|
|
}
|
|
|
|
if err == nil {
|
|
log.Println("database: connection successful")
|
|
}
|
|
|
|
return db, err
|
|
}
|