检查 SQL 表中是否存在条目或 golang 中是否存在条目每次都会给出 false

问题描述 投票:0回答:1

这是我的 golang 代码。我正在尝试检查用户是否已申请工作。如果是,他应该会显示一条消息,表明您无法再申请,如果不是,则应该成功申请。 我在数据库中有 3 个表:用户、工作、工作申请。 用户以 UserID 作为主键, 作业的 JobID 作为 PK,作业应用程序的 Application_ID 作为 PK,其中 2 列(JobID 和 UserID)作为外键,分别指向作业表中的 JobID 和用户表中的 UserID。


func (d *Env) ApplyToJob(w http.ResponseWriter, r *http.Request) {
    claims := r.Context().Value("claims").(jwt.MapClaims)
    if claims["is_admin"].(bool) {
        SendResponse(w, models.Response{Message: "Only Applicant Users can apply to this job!", Status: "Error"})
        return
    }
    uuid := claims["uuid"].(string)
    jobID := r.URL.Query().Get("job_id") // Extract job_id from query parameters
    if jobID == "" {
        SendResponse(w, models.Response{Message: "job_id parameter is required", Status: "Error"})
        return
    }
    //! Check if the job with jobID exists
    var jobExists bool
    err := d.Driver.QueryRow("SELECT EXISTS(SELECT 1 FROM job WHERE JobID = ?)", jobID).Scan(&jobExists)
    if err != nil {
        SendResponse(w, models.Response{Message: "Error checking job existence: " + err.Error(), Status: "Error"})
        return
    }
    if !jobExists {
        SendResponse(w, models.Response{Message: "Job does not exist", Status: "Error"})
        return
    }
    //! Check if the user (UUID) has already applied to this job (jobID)
    hasApplied, err := rowExists(d.Driver, "SELECT 1 FROM job_application WHERE JobID = ? AND UserID = ?", jobID, uuid)
    if err != nil {
        SendResponse(w, models.Response{Message: err.Error(), Status: "Error"})
        return
    } else {
        if hasApplied {
            SendResponse(w, models.Response{Message: "Already Applied to this Job!" + err.Error(), Status: "Error"})
            return
        } else {
            // ! Generating new applicationID
            applicationID, err := exec.Command("uuidgen").Output()
            if err != nil {
                response := models.Response{Message: err.Error(), Status: "Error"}
                SendResponse(w, response)
                return
            }
            _, err = d.Driver.Exec(`INSERT INTO 
job_application(ApplicationID, JobID,UserID,AppliedOn) 
VALUES (?,?,?,?)`,
                applicationID,
                jobID,
                uuid,
                time.Now(),
            )
            if err != nil {
                response := models.Response{Message: err.Error(), Status: "Error"}
                SendResponse(w, response)
                return
            }
            response := models.Response{Message: "Successfully Applied!", Status: "Success"}
            SendResponse(w, response)
        }
    }

}

func rowExists(db *sql.DB, query string, args ...interface{}) (bool, error) {
    var exists bool
    query = fmt.Sprintf("SELECT EXISTS (%s)", query)
    err := db.QueryRow(query, args...).Scan(&exists)
    if err != nil && err != sql.ErrNoRows {
        return false, err
    }
    return exists, nil
}

这段代码似乎根本不起作用。我的代码总是说用户尚未申请。它会导致表中出现重复的条目。 用户 ID 来自 jwt 令牌,作业 ID 来自查询参数。我的代码哪里错了?

我做了一个 func,其唯一动机是检查 sql 表中是否存在一行,但它似乎每次都返回 false。

这是我每次得到的回应。

{
    "message": "Successfully Applied!",
    "status": "Success",
    "jwt": "",
    "data": null
}
mysql go
1个回答
0
投票

rowExists
函数看起来有一个错误。
exists
未显式初始化,因此它隐式初始化为
false
。这意味着无论查询结果如何,
rowExists
函数将始终返回
false
。在非错误分支中显式返回
true
应该可以解决这个问题:

func rowExists(db *sql.DB, query string, args ...interface{}) (bool, error) {
    query = fmt.Sprintf("SELECT EXISTS (%s)", query)
    err := db.QueryRow(query, args...).Scan(&exists)
    if err != nil && err != sql.ErrNoRows {
        return false, err
    }
    return true, nil // Here
}
© www.soinside.com 2019 - 2024. All rights reserved.