From 275a1016c5b1da43c316165e0bab137bb119626e Mon Sep 17 00:00:00 2001 From: Jorge Rojas Date: Tue, 9 Jul 2024 23:40:38 -0400 Subject: [PATCH] fix: allow postgres to switch between different database connections by selecting them in the tree --- drivers/postgres.go | 47 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/drivers/postgres.go b/drivers/postgres.go index 84b67f6..bb809b7 100644 --- a/drivers/postgres.go +++ b/drivers/postgres.go @@ -13,8 +13,10 @@ import ( ) type Postgres struct { - Connection *sql.DB - Provider string + Connection *sql.DB + Provider string + CurrentDatabase string + Urlstr string } func (db *Postgres) Connect(urlstr string) (err error) { @@ -30,6 +32,17 @@ func (db *Postgres) Connect(urlstr string) (err error) { return err } + db.Urlstr = urlstr + + // get current database + + rows := db.Connection.QueryRow("SELECT current_database();") + + err = rows.Scan(&db.CurrentDatabase) + if err != nil { + return err + } + return nil } @@ -58,6 +71,36 @@ func (db *Postgres) GetDatabases() (databases []string, err error) { func (db *Postgres) GetTables(database string) (tables map[string][]string, err error) { tables = make(map[string][]string) + if database != db.CurrentDatabase { + parsedConn, err := dburl.Parse(db.Urlstr) + if err != nil { + return tables, err + } + + user := parsedConn.User.Username() + password, _ := parsedConn.User.Password() + host := parsedConn.Host + port := parsedConn.Port() + dbname := parsedConn.Path + + if port == "" { + port = "5432" + } + + if dbname == "" { + dbname = database + } + + db.Connection.Close() + + db.Connection, err = sql.Open("postgres", fmt.Sprintf("host=%s port=%s user=%s password=%s dbname='%s' sslmode=disable", host, port, user, password, dbname)) + if err != nil { + return tables, err + } + + db.CurrentDatabase = database + } + rows, err := db.Connection.Query(fmt.Sprintf("SELECT table_name, table_schema FROM information_schema.tables WHERE table_catalog = '%s'", database)) if err != nil { return tables, err