Sql --execute="" behaves strange inside exec.Command

Good day,

I have some weird behavior when I want to automate and trigger certain sql execute from inside an exec.Command shell.

In my normal Terminal this goes fine:

cockroach sql --certs-dir=app/database/certs --host=localhost:26257 --execute="CREATE DATABASE app"

CREATE DATABASE

Time: 5.378ms

But inside my code (yes I double check the variables etc. :slight_smile:) running:

out, err = exec.Command("cockroach", "sql", "--certs-dir="+certsDir,
	"--host="+fmt.Sprintf("%s:%d", host, portStart),
	`--execute="CREATE DATABASE app;"`).CombinedOutput()
if err != nil {
	log.Println(string(out))
	return errors.Trace(err)
}

I get:

2020/06/23 22:14:36 ERROR: at or near "CREATE DATABASE app;": syntax error
SQLSTATE: 42601
DETAIL: source SQL:
"CREATE DATABASE app;"
^
Failed running "sql"

2020/06/23 22:14:36 exit status 1

Tried with and without the ;.

Is this a security measure that falsely tells the output it’s just a syntax error or is it something else? Maybe it the parameters get modified/trimmed/stripped by Go in some way?

Thanks in advance!

Hey @Erwin001,

Can you try the following?

out, err = exec.Command("cockroach", "sql", "--certs-dir="+certsDir,
	"--host="+fmt.Sprintf("%s:%d", host, portStart),
	`--execute=CREATE DATABASE app;`).CombinedOutput()
if err != nil {
	log.Println(string(out))
	return errors.Trace(err)
}

I removed the quotes around CREATE DATABASE app.

Thanks,
Matt

That works, thanks! Feels counter intuitive tho. As if it would break the shell’s syntax. Glad it works now :slight_smile:

Glad to hear!

It does feel counter-intuitive - I agree.

What we saw earlier has to do with the way Go’s exec.Command function works.