Skip to content

Commit

Permalink
Use pgLockRole instead of a mutex
Browse files Browse the repository at this point in the history
By using the pgLockRole locking methods (which uses `pg_advisory_xact_lock`) we avoid locking to the provider and instead let postgres handle this.
  • Loading branch information
boekkooi-lengoo committed Jan 4, 2022
1 parent 58af8c5 commit 10a59da
Showing 1 changed file with 10 additions and 11 deletions.
21 changes: 10 additions & 11 deletions postgresql/resource_postgresql_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"log"
"strings"
"sync"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
Expand All @@ -32,10 +31,6 @@ var objectTypes = map[string]string{
"schema": "n",
}

// grantMutex is used to ensure we only apply a single grant/revoke at the same time.
// doing so avoids the "tuple concurrently updated" postgres error
var grantMutex sync.Mutex

func resourcePostgreSQLGrant() *schema.Resource {
return &schema.Resource{
Create: PGResourceFunc(resourcePostgreSQLGrantCreate),
Expand Down Expand Up @@ -148,15 +143,17 @@ func resourcePostgreSQLGrantCreate(db *DBConnection, d *schema.ResourceData) err

database := d.Get("database").(string)

grantMutex.Lock()
defer grantMutex.Unlock()

txn, err := startTransaction(db.client, database)
if err != nil {
return err
}
defer deferredRollback(txn)

role := d.Get("role").(string)
if err := pgLockRole(txn, role); err != nil {
return err
}

owners, err := getRolesToGrant(txn, d)
if err != nil {
return err
Expand Down Expand Up @@ -199,15 +196,17 @@ func resourcePostgreSQLGrantDelete(db *DBConnection, d *schema.ResourceData) err
)
}

grantMutex.Lock()
defer grantMutex.Unlock()

txn, err := startTransaction(db.client, d.Get("database").(string))
if err != nil {
return err
}
defer deferredRollback(txn)

role := d.Get("role").(string)
if err := pgLockRole(txn, role); err != nil {
return err
}

owners, err := getRolesToGrant(txn, d)
if err != nil {
return err
Expand Down

0 comments on commit 10a59da

Please sign in to comment.