37

When connecting to a Google Cloud SQL instance, is there a way to specify the database I want to connect to?

This is the command I execute and the error I get:

$ gcloud beta sql connect MY_INSTANCE --user=MY_USER
Whitelisting your IP for incoming connection for 5 minutes...done.
Connecting to database with SQL user [MY_USER].Password for user MY_USER:
psql: FATAL:  database "MY_USER" does not exist

It seems to try to connect to a database that has the same name than the user, but what when that's not the case? (I don't want to create a dummy DB called MY_USER just to be able to jump to the DB I want).

Here are the docs for the command gcloud beta sql, but I don't see anything useful for this there: https://cloud.google.com/sdk/gcloud/reference/beta/sql/connect

Daniel
  • 21,933
  • 14
  • 72
  • 101
  • Crazy, you asked it 3 years ago... I just came across it today. This is a super-weird issue, taking into account that `gcloud sql connect --help` shows `--database` parameter, but it just ignores it... – greatvovan Dec 04 '20 at 22:54

2 Answers2

57

gcloud sql connect does not currently allow you to specify the database name. There is a open issue to add it: https://issuetracker.google.com/issues/69314375

In the meantime, you can work around this by utilizing the PGDATABASE environment variable:

e.g.

PGDATABASE=mydb gcloud sql connect myinstance

You could create a shell alias to do this for you.

Vadim
  • 4,996
  • 1
  • 26
  • 30
  • is it possible to just execute sql statement from bash script? Instead of getting the interactive shell? – lisak Jun 29 '18 at 23:02
  • gcloud sql connect accepts now a --database flag in which you can indicate the database you want to connect to. – dmbarreiro Aug 08 '20 at 08:15
  • `gcloud sql connect --database` is legal syntax, but as of 307.0.0 that option is ignored. This solution (PGDATABASE env var) still works, though. – Chris Jones Aug 27 '20 at 17:31
  • (1) Is there a way to make it skip the password prompt? (2) Is there a way to make it execute a script? – Konstantin Tarkus Sep 02 '20 at 23:54
12

In the meanwhile the beta version of the gcloud sql connect command has added support for a --database=<dbname> flag

Entire command:
gcloud beta sql connect INSTANCE [--database=DATABASE, -d DATABASE] [--user=USER, -u USER] [GCLOUD_WIDE_FLAG …]

https://cloud.google.com/sdk/gcloud/reference/beta/sql/connect

Koesper
  • 533
  • 6
  • 19
  • Still fails for me. I tried booth "gcloud beta" and regular gcloud. Is by default expecting that user and database should have the same name. =( – Daniel Nelson May 09 '19 at 13:45
  • 1
    To date (March 2020) the mentioned flag `--database` is working as expected in the `gcloud beta` (2019.05.17) version, but not yet in the regular SDK (283.0.0). – vreyespue Mar 30 '20 at 10:44
  • this is still not working (why have a --database flag if its not supported?) – gvanto Jan 26 '22 at 08:37