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" ) // 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 { log := ctx.Value(CtxKey{}).(*slogging.Logger) 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) { log := ctx.Value(CtxKey{}).(*slogging.Logger) 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 }