2b37986218
Small Go tool + distroless container used as a K8s initContainer to block an app until its database (Postgres/MySQL) is reachable. Env-var configured (WAITFORDB_* + libpq PG* fallback), configurable timeout/interval, redacted logs, exit codes. Woodpecker CI publishes docker-internal/waitfordb on tag.
32 lines
783 B
Go
32 lines
783 B
Go
package driver
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
)
|
|
|
|
// sqlPinger runs the liveness query against a database/sql handle. It is shared
|
|
// by every engine whose Go driver plugs into database/sql.
|
|
type sqlPinger struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func openSQL(driverName, dsn string) (*sqlPinger, error) {
|
|
db, err := sql.Open(driverName, dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// A readiness check only ever needs one connection; keep the pool tiny so a
|
|
// failed attempt does not leave idle half-open connections behind.
|
|
db.SetMaxOpenConns(1)
|
|
db.SetMaxIdleConns(0)
|
|
return &sqlPinger{db: db}, nil
|
|
}
|
|
|
|
func (p *sqlPinger) Ping(ctx context.Context) error {
|
|
var one int
|
|
return p.db.QueryRowContext(ctx, "SELECT 1").Scan(&one)
|
|
}
|
|
|
|
func (p *sqlPinger) Close() error { return p.db.Close() }
|