Home > Software engineering >  Check if a user already exists in a DB
Check if a user already exists in a DB

Time:11-08

How can I check if a user already exists in the database using gorm? I cannot seem to find a proper way to do so without an error logging to the console if no user was found.

This is my code so far

result := models.User{}
err := connection.DB.First(&result, "username = ?", user.Username).Error

if err == gorm.ErrRecordNotFound {

    if err := connection.DB.Create(&user).Error; err != nil {

        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{

            "error": "internal server error",
        })
    }

    return c.Status(fiber.StatusCreated).JSON(fiber.Map{
        "message": "user created",
    })
}

if result.Username != "" {

    return c.Status(fiber.StatusConflict).JSON(fiber.Map{
        "error": "username already exists",
    })
}

return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
    "error": "internal server error",
})

but if a new user is created, an error is printed to the terminal saying the record was not found.

CodePudding user response:

Managed to find a way with raw MySQL.

var exists bool = false
if err := connection.DB.Raw(
    "SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)",
    user.Username).
    Scan(&exists).Error; err != nil {

    return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
        "error": "internal server error",
    })
}

if exists {

    return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
        "error": "Username already exists",
    })
}

if err := connection.DB.Create(&user).Error; err != nil {

    return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{

        "error": "internal server error",
    })
}

return c.Status(fiber.StatusCreated).JSON(fiber.Map{

    "message": "User created successfully",
})

CodePudding user response:

You can also use FirstOrCreate

From Doc:

Get first matched record or create a new one with given conditions (only works with struct, map conditions)

u := connection.DB.FirstOrCreate(user)

if u.Error != nil {
    return c.Status(fiber.StatusInternalServerError).JSON(
        fiber.Map{
            "error": "Internal server error",
        }
    )
}

if u.RowsAffected == 1 {
    return c.Status(fiber.StatusCreated).JSON(
        fiber.Map{
            "message": "User created successfully",
        }
    )
}

return c.Status(fiber.StatusBadRequest).JSON(
    fiber.Map{
        "error": "Username already exists",
    }
)
  • Related