2018-05-27 22:40:42 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2020-02-14 08:12:52 +08:00
|
|
|
"net/url"
|
2018-05-27 22:40:42 +08:00
|
|
|
_ "github.com/lib/pq"
|
|
|
|
"os"
|
2018-08-17 01:42:21 +08:00
|
|
|
"strconv"
|
2018-06-20 11:50:11 +08:00
|
|
|
"time"
|
2018-05-27 22:40:42 +08:00
|
|
|
)
|
|
|
|
|
2018-07-24 14:50:14 +08:00
|
|
|
func dbConnect(retriesLeft int) error {
|
2018-05-27 22:40:42 +08:00
|
|
|
con := os.Getenv("POSTGRES")
|
2020-02-14 08:12:52 +08:00
|
|
|
u, err := url.Parse(con)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("invalid postgres connection URI: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.User = url.UserPassword(u.User.Username(), "redacted")
|
|
|
|
logger.Infof("opening connection to postgres: %s", u.String())
|
2018-05-27 22:40:42 +08:00
|
|
|
|
|
|
|
db, err = sql.Open("postgres", con)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("cannot open connection to postgres: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-06-20 11:49:39 +08:00
|
|
|
err = db.Ping()
|
|
|
|
if err != nil {
|
|
|
|
if retriesLeft > 0 {
|
|
|
|
logger.Errorf("cannot talk to postgres, retrying in 10 seconds (%d attempts left): %v", retriesLeft-1, err)
|
|
|
|
time.Sleep(10 * time.Second)
|
2018-07-24 14:50:14 +08:00
|
|
|
return dbConnect(retriesLeft - 1)
|
2018-06-20 11:49:39 +08:00
|
|
|
} else {
|
|
|
|
logger.Errorf("cannot talk to postgres, last attempt failed: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-27 22:40:42 +08:00
|
|
|
statement := `
|
2019-12-28 09:31:27 +08:00
|
|
|
CREATE TABLE IF NOT EXISTS migrations (
|
|
|
|
filename TEXT NOT NULL UNIQUE
|
|
|
|
);
|
|
|
|
`
|
2018-05-27 22:40:42 +08:00
|
|
|
_, err = db.Exec(statement)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("cannot create migrations table: %v", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-08-17 01:42:21 +08:00
|
|
|
maxIdleConnections, err := strconv.Atoi(os.Getenv("MAX_IDLE_PG_CONNECTIONS"))
|
|
|
|
if err != nil {
|
|
|
|
logger.Warningf("cannot parse COMMENTO_MAX_IDLE_PG_CONNECTIONS: %v", err)
|
|
|
|
maxIdleConnections = 50
|
|
|
|
}
|
|
|
|
|
|
|
|
db.SetMaxIdleConns(maxIdleConnections)
|
2018-05-27 22:40:42 +08:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|