Skip to content

Commit

Permalink
*: fix the bug of create user
Browse files Browse the repository at this point in the history
  • Loading branch information
acekingke committed Mar 1, 2024
1 parent 97f4cfe commit fe27496
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions controllers/mysqluser_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,14 @@ func (r *MysqlUserReconciler) reconcileUserInDB(ctx context.Context, mysqlUser *
if password == "" {
return fmt.Errorf("the MySQL user's password must not be empty")
}
var exists bool
var err2 error
if exists, err2 = internal.CheckUserExists(sqlRunner, mysqlUser.Spec.User); err2 != nil {
return fmt.Errorf("failed to check if user exists: %v", err2)
}
if !exists {
mysqlUser.Status.Revision = ""
}
// Remove allowed hosts for user.
toRemove := utils.StringDiffIn(mysqlUser.Status.AllowedHosts, mysqlUser.Spec.Hosts)
for _, host := range toRemove {
Expand Down
13 changes: 13 additions & 0 deletions internal/sql_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,19 @@ func GetGlobalVariable(sqlRunner SQLRunner, param string, val interface{}) error
return sqlRunner.QueryRowContext(ctx, NewQuery("select @@global.?", param), val)
}

// Check user exists or not.
func CheckUserExists(sqlRunner SQLRunner, userName string) (bool, error) {
var rows *sql.Rows
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
rows, err := sqlRunner.QueryRowsContext(ctx, NewQuery("select user from mysql.user where user =?", userName))
if err != nil {
return false, err
}
defer rows.Close()
return rows.Next(), nil
}

func CheckProcesslist(sqlRunner SQLRunner) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Expand Down

0 comments on commit fe27496

Please sign in to comment.