emissary/internal/command/server/database/ping.go

52 lines
1.2 KiB
Go
Raw Normal View History

2023-02-02 10:55:24 +01:00
package database
import (
"database/sql"
"forge.cadoles.com/Cadoles/emissary/internal/command/common"
2023-10-13 12:30:52 +02:00
"github.com/getsentry/sentry-go"
2023-02-02 10:55:24 +01:00
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
)
func PingCommand() *cli.Command {
return &cli.Command{
Name: "ping",
Usage: "Test database connectivity",
Action: func(ctx *cli.Context) error {
conf, err := common.LoadConfig(ctx)
if err != nil {
return errors.Wrap(err, "Could not load configuration")
}
logger.Info(ctx.Context, "connecting to database", logger.F("dsn", conf.Server.Database.DSN))
2023-02-02 10:55:24 +01:00
driver := string(conf.Server.Database.Driver)
dsn := string(conf.Server.Database.DSN)
2023-02-02 10:55:24 +01:00
db, err := sql.Open(driver, dsn)
if err != nil {
return errors.WithStack(err)
}
defer func() {
if err := db.Close(); err != nil {
2023-10-13 12:30:52 +02:00
err = errors.WithStack(err)
logger.Error(ctx.Context, "error while closing database connection", logger.E(err))
sentry.CaptureException(err)
2023-02-02 10:55:24 +01:00
}
}()
if err := db.PingContext(ctx.Context); err != nil {
return errors.WithStack(err)
}
logger.Info(ctx.Context, "connection succeeded", logger.F("dsn", conf.Server.Database.DSN))
2023-02-02 10:55:24 +01:00
return nil
},
}
}