Skip to content

Commit fe27496

Browse files
committed
*: fix the bug of create user
1 parent 97f4cfe commit fe27496

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

controllers/mysqluser_controller.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,14 @@ func (r *MysqlUserReconciler) reconcileUserInDB(ctx context.Context, mysqlUser *
180180
if password == "" {
181181
return fmt.Errorf("the MySQL user's password must not be empty")
182182
}
183+
var exists bool
184+
var err2 error
185+
if exists, err2 = internal.CheckUserExists(sqlRunner, mysqlUser.Spec.User); err2 != nil {
186+
return fmt.Errorf("failed to check if user exists: %v", err2)
187+
}
188+
if !exists {
189+
mysqlUser.Status.Revision = ""
190+
}
183191
// Remove allowed hosts for user.
184192
toRemove := utils.StringDiffIn(mysqlUser.Status.AllowedHosts, mysqlUser.Spec.Hosts)
185193
for _, host := range toRemove {

internal/sql_runner.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,19 @@ func GetGlobalVariable(sqlRunner SQLRunner, param string, val interface{}) error
320320
return sqlRunner.QueryRowContext(ctx, NewQuery("select @@global.?", param), val)
321321
}
322322

323+
// Check user exists or not.
324+
func CheckUserExists(sqlRunner SQLRunner, userName string) (bool, error) {
325+
var rows *sql.Rows
326+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
327+
defer cancel()
328+
rows, err := sqlRunner.QueryRowsContext(ctx, NewQuery("select user from mysql.user where user =?", userName))
329+
if err != nil {
330+
return false, err
331+
}
332+
defer rows.Close()
333+
return rows.Next(), nil
334+
}
335+
323336
func CheckProcesslist(sqlRunner SQLRunner) (bool, error) {
324337
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
325338
defer cancel()

0 commit comments

Comments
 (0)