2022-06-18 09:45:45 +00:00
|
|
|
package sql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
2023-02-23 08:39:03 +00:00
|
|
|
"errors"
|
2023-12-04 10:22:49 +00:00
|
|
|
"log/slog"
|
2022-06-18 09:45:45 +00:00
|
|
|
|
2022-09-22 09:46:36 +00:00
|
|
|
"code.icb4dc0.de/prskr/nurse/check"
|
|
|
|
"code.icb4dc0.de/prskr/nurse/config"
|
|
|
|
"code.icb4dc0.de/prskr/nurse/grammar"
|
2023-12-04 15:59:10 +00:00
|
|
|
"code.icb4dc0.de/prskr/nurse/internal/retry"
|
2022-09-22 09:46:36 +00:00
|
|
|
"code.icb4dc0.de/prskr/nurse/validation"
|
2022-06-18 09:45:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ check.SystemChecker = (*SelectCheck)(nil)
|
|
|
|
|
|
|
|
type SelectCheck struct {
|
|
|
|
*sql.DB
|
|
|
|
validators validation.Validator[*sql.Rows]
|
|
|
|
Query string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SelectCheck) UnmarshalCheck(c grammar.Check, lookup config.ServerLookup) error {
|
|
|
|
const serverAndKeyArgsNumber = 2
|
|
|
|
inst := c.Initiator
|
|
|
|
if err := grammar.ValidateParameterCount(inst.Params, serverAndKeyArgsNumber); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
if s.DB, err = dbFromParam(inst.Params[0], lookup); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.Query, err = inst.Params[1].AsString(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.validators, err = registry.ValidatorsForFilters(c.Validators); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-08-07 10:22:21 +00:00
|
|
|
func (s *SelectCheck) Execute(ctx check.Context) error {
|
2023-12-04 15:59:10 +00:00
|
|
|
logger := slog.Default().With(
|
2023-12-04 10:22:49 +00:00
|
|
|
slog.String("check", "sql.SELECT"),
|
|
|
|
slog.String("query", s.Query),
|
|
|
|
)
|
|
|
|
|
2023-12-04 15:59:10 +00:00
|
|
|
return retry.Retry(ctx, ctx.AttemptCount(), ctx.AttemptTimeout(), func(ctx context.Context, attempt int) error {
|
|
|
|
logger.Debug("Execute check", slog.Int("attempt", attempt))
|
2022-08-07 10:22:21 +00:00
|
|
|
|
2023-12-04 15:59:10 +00:00
|
|
|
logger.Debug("")
|
|
|
|
|
|
|
|
rows, err := s.QueryContext(ctx, s.Query)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-18 09:45:45 +00:00
|
|
|
|
2023-12-04 15:59:10 +00:00
|
|
|
defer func() {
|
|
|
|
err = errors.Join(rows.Close(), rows.Err())
|
|
|
|
}()
|
2023-02-23 08:39:03 +00:00
|
|
|
|
2023-12-04 15:59:10 +00:00
|
|
|
return s.validators.Validate(rows)
|
|
|
|
})
|
2022-06-18 09:45:45 +00:00
|
|
|
}
|