Add cli command to wipe the SQL DB

- Refactor the migrations code so that packr is only called (via an init
  function in `db/utils.go`).
- When loading the migrations, make sure there is at least one migration,
  otherwise panic (this would happen if the node is built incorrectly)
This commit is contained in:
Eduard S
2020-12-30 11:53:14 +01:00
parent 2e51860c37
commit e5fc403451
3 changed files with 100 additions and 17 deletions

View File

@@ -9,6 +9,7 @@ import (
ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/crypto"
"github.com/hermeznetwork/hermez-node/config"
dbUtils "github.com/hermeznetwork/hermez-node/db"
"github.com/hermeznetwork/hermez-node/log"
"github.com/hermeznetwork/hermez-node/node"
"github.com/hermeznetwork/tracerr"
@@ -19,6 +20,7 @@ const (
flagCfg = "cfg"
flagMode = "mode"
flagSK = "privatekey"
flagYes = "yes"
modeSync = "sync"
modeCoord = "coord"
)
@@ -55,6 +57,41 @@ func cmdImportKey(c *cli.Context) error {
return nil
}
func cmdWipeSQL(c *cli.Context) error {
_cfg, err := parseCli(c)
if err != nil {
return tracerr.Wrap(fmt.Errorf("error parsing flags and config: %w", err))
}
cfg := _cfg.node
yes := c.Bool(flagYes)
if !yes {
fmt.Print("*WARNING* Are you sure you want to delete the SQL DB? [y/N]: ")
var input string
if _, err := fmt.Scanln(&input); err != nil {
return tracerr.Wrap(err)
}
input = strings.ToLower(input)
if !(input == "y" || input == "yes") {
return nil
}
}
db, err := dbUtils.ConnectSQLDB(
cfg.PostgreSQL.Port,
cfg.PostgreSQL.Host,
cfg.PostgreSQL.User,
cfg.PostgreSQL.Password,
cfg.PostgreSQL.Name,
)
if err != nil {
return tracerr.Wrap(err)
}
log.Info("Wiping SQL DB...")
if err := dbUtils.MigrationsDown(db.DB); err != nil {
return tracerr.Wrap(err)
}
return nil
}
func cmdRun(c *cli.Context) error {
cfg, err := parseCli(c)
if err != nil {
@@ -159,6 +196,19 @@ func main() {
Required: true,
}},
},
{
Name: "wipesql",
Aliases: []string{},
Usage: "Wipe the SQL DB (HistoryDB and L2DB), " +
"leaving the DB in a clean state",
Action: cmdWipeSQL,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: flagYes,
Usage: "automatic yes to the prompt",
Required: false,
}},
},
{
Name: "run",
Aliases: []string{},