pcmt/modules/db/db.go
leo a879704535
All checks were successful
continuous-integration/drone/push Build is passing
go: partially rework how slogging works
2023-05-09 17:35:00 +02:00

102 lines
1.9 KiB
Go

package db
import (
"context"
"git.dotya.ml/mirre-mt/pcmt/ent"
"git.dotya.ml/mirre-mt/pcmt/ent/migrate"
"git.dotya.ml/mirre-mt/pcmt/slogging"
"golang.org/x/exp/slog"
)
// CtxKey serves as a key to context values for this package.
type CtxKey struct{}
// DropAll deletes an re-creates the whole db.
func DropAll(ctx context.Context, client *ent.Client) error {
slogger := ctx.Value(CtxKey{}).(*slogging.Logger)
log := *slogger
log.Logger = log.Logger.With(
slog.Group("pcmt extra", slog.String("module", "modules/db")),
)
err := client.Schema.
Create(
ctx,
migrate.WithDropIndex(true),
migrate.WithDropColumn(true),
)
if err != nil {
log.Errorf("failed to recreate schema resources: %v", err)
return err
}
return err
}
// IsSetUp deletes the whole db.
func IsSetUp(ctx context.Context, client *ent.Client) (bool, error) {
slogger := ctx.Value(CtxKey{}).(*slogging.Logger)
log := *slogger
log.Logger = log.Logger.With(
slog.Group("pcmt extra", slog.String("module", "modules/db")),
)
is, err := client.Setup.
Query().
Only(ctx)
if is != nil {
log.Debug("apparently the db is already set up")
} else {
log.Debug("apparently the db was not yet set up")
}
switch {
case ent.IsNotFound(err) && is == nil:
return false, nil
case ent.IsNotSingular(err):
return true, err
case err != nil:
return false, err
case err == nil && is != nil:
return true, nil
}
return false, nil
}
// SetUp creates the set-up record indicating that the DB has been set up.
func SetUp(ctx context.Context, client *ent.Client) error {
isSetup, err := IsSetUp(ctx, client)
switch {
case err == nil && isSetup:
return nil
case err != nil && isSetup:
return err
case err != nil && !isSetup:
err = DropAll(ctx, client)
if err != nil {
return nil
}
// create a set-up record.
_, err = client.Setup.
Create().
Save(ctx)
if err != nil {
return err
}
}
return err
}