I am making my first steps in Go. I have a cli command that, for the time being, just drop and recreate a DB with go and Postgres dropdb + createdb tools.
The following code produce inconsistent results. The checkout function print or do not print the "out" bytes variable.
I am suspecting some race condition and that I should use pointers somewhere instead of passing values to the same function.
Is this code that bad ?
func ensurepath(command string) string {
ensuredcommand, LookErr := exec.LookPath(command)
if LookErr != nil {
log.Fatalf("%v is not found", command)
}
log.Printf("ensure path for command '%v' : %v", command, ensuredcommand)
return command
}
// warning : cmd error message is also a "out" value, it is not in err
func checkout(err error, out []byte) {
if err != nil {
log.Printf("command error %v : %s", err, out)
} else {
log.Printf("command result %T : %s", out, out)
}
}
var restore = cli.Command{
Name: "restore",
Aliases: []string{"r"},
Usage: "restore backup",
Action: func(c *cli.Context) error {
cmdArgs := "devdb"
dropDB := ensurepath("dropdb")
createDB := ensurepath("createdb")
outErrDrop, err := exec.Command(dropDB, cmdArgs).CombinedOutput()
checkout(err, outErrDrop)
outErrCreate, createErr := exec.Command(createDB, cmdArgs).CombinedOutput()
checkout(createErr, outErrCreate)
return nil
},
}
EDIT
Example of weird output
If I comment the lines corresponding to the "createDB" part, meaning I only drop the db I have a consistent and expected output.
var restore = cli.Command{
Name: "restore",
Aliases: []string{"r"},
Usage: "restore backup",
Action: func(c *cli.Context) error {
cmdArgs := "devdb"
dropDB := ensurepath("dropdb")
//createDB := ensurepath("createdb")
outErrDrop, err := exec.Command(dropDB, cmdArgs).CombinedOutput()
checkout(err, outErrDrop)
//outErrCreate, createErr := exec.Command(createDB, cmdArgs).CombinedOutput()
//checkout(createErr, outErrCreate)
return nil
},
}
//output
2018/02/19 15:49:44 ensure path for command 'dropdb' : /usr/local/bin/dropdb
2018/02/19 15:49:44 command error exit status 1 : dropdb: database removal failed: ERROR: database "devdb" does not exist
But if introduce back the lines corresponding to the createdb part (exactly as my first code block above) I have the following result :
2018/02/19 15:53:11 ensure path for command 'dropdb' : /usr/local/bin/dropdb
2018/02/19 15:53:11 ensure path for command 'createdb' : /usr/local/bin/createdb
2018/02/19 15:53:11 command result []uint8 :
2018/02/19 15:53:11 command result []uint8 :