Skip to content

Commit

Permalink
Merge pull request petoju#9 from winebarrel/add_mysql_user_importer
Browse files Browse the repository at this point in the history
Add mysql user importer
  • Loading branch information
winebarrel authored Mar 16, 2020
2 parents 74708bb + a4c09b8 commit 1b60a7c
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions mysql/resource_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mysql
import (
"fmt"
"log"
"strings"

"errors"

Expand All @@ -16,6 +17,9 @@ func resourceUser() *schema.Resource {
Update: UpdateUser,
Read: ReadUser,
Delete: DeleteUser,
Importer: &schema.ResourceImporter{
State: ImportUser,
},

Schema: map[string]*schema.Schema{
"user": {
Expand Down Expand Up @@ -246,3 +250,37 @@ func DeleteUser(d *schema.ResourceData, meta interface{}) error {
}
return err
}

func ImportUser(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
userHost := strings.SplitN(d.Id(), "@", 2)

if len(userHost) != 2 {
return nil, fmt.Errorf("wrong ID format %s (expected USER@HOST)", d.Id())
}

user := userHost[0]
host := userHost[1]

db, err := connectToMySQL(meta.(*MySQLConfiguration))

if err != nil {
return nil, err
}

var count int
err = db.QueryRow("SELECT COUNT(1) FROM mysql.user WHERE user = ? AND host = ?", user, host).Scan(&count)

if err != nil {
return nil, err
}

if count == 0 {
return nil, fmt.Errorf("user '%s' not found", d.Id())
}

d.Set("user", user)
d.Set("host", host)
d.Set("tls_option", "NONE")

return []*schema.ResourceData{d}, nil
}

0 comments on commit 1b60a7c

Please sign in to comment.