Skip to content
This repository has been archived by the owner on Oct 11, 2022. It is now read-only.

Commit

Permalink
Merge pull request #20 from winebarrel/support_update_grant
Browse files Browse the repository at this point in the history
Support update grant
  • Loading branch information
winebarrel authored Apr 9, 2020
2 parents c65be49 + 7558161 commit e702ab5
Showing 1 changed file with 76 additions and 2 deletions.
78 changes: 76 additions & 2 deletions mysql/resource_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type MySQLGrant struct {
func resourceGrant() *schema.Resource {
return &schema.Resource{
Create: CreateGrant,
Update: nil,
Update: UpdateGrant,
Read: ReadGrant,
Delete: DeleteGrant,
Importer: &schema.ResourceImporter{
Expand Down Expand Up @@ -69,7 +69,6 @@ func resourceGrant() *schema.Resource {
"privileges": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
Expand Down Expand Up @@ -272,6 +271,81 @@ func ReadGrant(d *schema.ResourceData, meta interface{}) error {
return nil
}

func UpdateGrant(d *schema.ResourceData, meta interface{}) error {
db := meta.(*MySQLConfiguration).Db

hasRoles, err := supportsRoles(db)

if err != nil {
return err
}

userOrRole, _, err := userOrRole(
d.Get("user").(string),
d.Get("host").(string),
d.Get("role").(string),
hasRoles)

if err != nil {
return err
}

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

if d.HasChange("privileges") {
err = updatePrivileges(d, db, userOrRole, database, table)

if err != nil {
return err
}
}

return nil
}

func updatePrivileges(d *schema.ResourceData, db *sql.DB, user string, database string, table string) error {
oldPrivsIf, newPrivsIf := d.GetChange("privileges")
oldPrivs := oldPrivsIf.(*schema.Set)
newPrivs := newPrivsIf.(*schema.Set)
grantIfs := newPrivs.Difference(oldPrivs).List()
revokeIfs := oldPrivs.Difference(newPrivs).List()

if len(grantIfs) > 0 {
grants := make([]string, len(grantIfs))

for i, v := range grantIfs {
grants[i] = v.(string)
}

sql := fmt.Sprintf("GRANT %s ON %s.%s TO %s", strings.Join(grants, ","), database, table, user)

log.Printf("[DEBUG] SQL: %s", sql)

if _, err := db.Exec(sql); err != nil {
return err
}
}

if len(revokeIfs) > 0 {
revokes := make([]string, len(revokeIfs))

for i, v := range revokeIfs {
revokes[i] = v.(string)
}

sql := fmt.Sprintf("REVOKE %s ON %s.%s FROM %s", strings.Join(revokes, ","), database, table, user)

log.Printf("[DEBUG] SQL: %s", sql)

if _, err := db.Exec(sql); err != nil {
return err
}
}

return nil
}

func DeleteGrant(d *schema.ResourceData, meta interface{}) error {
db := meta.(*MySQLConfiguration).Db

Expand Down

0 comments on commit e702ab5

Please sign in to comment.