2023-05-05 22:52:59 +02:00
|
|
|
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"
|
2023-05-09 17:35:00 +02:00
|
|
|
"golang.org/x/exp/slog"
|
2023-05-05 22:52:59 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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 {
|
2023-05-11 17:06:20 +02:00
|
|
|
slogger := ctx.Value(CtxKey{}).(*slogging.Slogger)
|
2023-05-09 17:35:00 +02:00
|
|
|
log := *slogger
|
|
|
|
|
|
|
|
log.Logger = log.Logger.With(
|
|
|
|
slog.Group("pcmt extra", slog.String("module", "modules/db")),
|
|
|
|
)
|
2023-05-05 22:52:59 +02:00
|
|
|
|
|
|
|
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) {
|
2023-05-11 17:06:20 +02:00
|
|
|
slogger := ctx.Value(CtxKey{}).(*slogging.Slogger)
|
2023-05-09 17:35:00 +02:00
|
|
|
log := *slogger
|
|
|
|
|
|
|
|
log.Logger = log.Logger.With(
|
|
|
|
slog.Group("pcmt extra", slog.String("module", "modules/db")),
|
|
|
|
)
|
|
|
|
|
2023-05-05 22:52:59 +02:00
|
|
|
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
|
|
|
|
}
|