From daba1aff9d5b113af323c6205d3951bb327f5130 Mon Sep 17 00:00:00 2001 From: pbthorste Date: Fri, 27 Jan 2017 01:46:37 +0100 Subject: [PATCH 1/2] grant role membership for when connection user is not superuser --- .../resource_postgresql_database.go | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/builtin/providers/postgresql/resource_postgresql_database.go b/builtin/providers/postgresql/resource_postgresql_database.go index d236b02d7..d98f65479 100644 --- a/builtin/providers/postgresql/resource_postgresql_database.go +++ b/builtin/providers/postgresql/resource_postgresql_database.go @@ -122,6 +122,12 @@ func resourcePostgreSQLDatabaseCreate(d *schema.ResourceData, meta interface{}) b := bytes.NewBufferString("CREATE DATABASE ") fmt.Fprint(b, pq.QuoteIdentifier(dbName)) + //needed in order to set the owner of the db if the connection user is not a superuser + err = grantRoleMembership(conn, d.Get(dbOwnerAttr).(string), c.username) + if err != nil { + return err + } + // Handle each option individually and stream results into the query // buffer. @@ -464,3 +470,18 @@ func doSetDBIsTemplate(conn *sql.DB, dbName string, isTemplate bool) error { return nil } + +func grantRoleMembership(conn *sql.DB, dbOwner string, connUsername string) error { + if dbOwner != "" && dbOwner != connUsername { + query := fmt.Sprintf("GRANT %s TO %s", pq.QuoteIdentifier(dbOwner), pq.QuoteIdentifier(connUsername)) + _, err := conn.Query(query) + if err != nil { + // is already member or role + if strings.Contains(err.Error(), "duplicate key value violates unique constraint") { + return nil + } + return errwrap.Wrapf("Error granting membership: {{err}}", err) + } + } + return nil +} From deb56bd93da2c7adce19b70185fdc0983df0cf42 Mon Sep 17 00:00:00 2001 From: pbthorste Date: Fri, 27 Jan 2017 01:50:45 +0100 Subject: [PATCH 2/2] improve error message --- builtin/providers/postgresql/resource_postgresql_database.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/builtin/providers/postgresql/resource_postgresql_database.go b/builtin/providers/postgresql/resource_postgresql_database.go index d98f65479..66f59fca1 100644 --- a/builtin/providers/postgresql/resource_postgresql_database.go +++ b/builtin/providers/postgresql/resource_postgresql_database.go @@ -125,7 +125,7 @@ func resourcePostgreSQLDatabaseCreate(d *schema.ResourceData, meta interface{}) //needed in order to set the owner of the db if the connection user is not a superuser err = grantRoleMembership(conn, d.Get(dbOwnerAttr).(string), c.username) if err != nil { - return err + return errwrap.Wrapf(fmt.Sprintf("Error granting role membership on database %s: {{err}}", dbName), err) } // Handle each option individually and stream results into the query