From fe274963aa997618b69c88e9675d69698f61185d Mon Sep 17 00:00:00 2001 From: acekingke Date: Fri, 23 Feb 2024 12:16:59 +0800 Subject: [PATCH] *: fix the bug of create user --- controllers/mysqluser_controller.go | 8 ++++++++ internal/sql_runner.go | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/controllers/mysqluser_controller.go b/controllers/mysqluser_controller.go index dfdabab4..a678a9c9 100644 --- a/controllers/mysqluser_controller.go +++ b/controllers/mysqluser_controller.go @@ -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 { diff --git a/internal/sql_runner.go b/internal/sql_runner.go index 2b867135..a8929b4a 100644 --- a/internal/sql_runner.go +++ b/internal/sql_runner.go @@ -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()