Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

failed to check if row with value exists In Postgres with Golang

I’am trying to create registration in my Telegram Bot with Golang and Postgres. When user writes "register", bot has to check if user’s uuid already exists in DB, and if not to create row with his uuid.

Here is my function to check if uuid already exists in DB:

func IsUserInDB(uuid int64) (bool, error) {
    var exists bool
    query := fmt.Sprintf("SELECT EXISTS(SELECT 1 FROM users WHERE uuid = %d);", uuid)
    err := Db.QueryRow(query).Scan(&exists)

    return exists, err
}

Here is my function for adding user’s uuid to DB:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func AddUserToDB(column string, row interface{}) error {
    query := fmt.Sprintf("INSERT INTO users (%s) VALUES (%v);", column, row)
    _, err := Db.Exec(query)

    return err
}

And the logic for bot:

func (b *Bot) handleMessages(message *tgbotapi.Message) error {
    switch message.Text {
    case "register":
        exists, err := data.IsUserInDB(message.From.ID)
        if err != nil {
            return err
        }
        if !exists {
            err := data.AddUserToDB("uuid", message.From.ID)
            return err
        }

        return nil
    default:
        msg := tgbotapi.NewMessage(message.Chat.ID, "unknown message...")
        _, err := b.bot.Send(msg)
        return err
    }
}

First time, when I send "register", bot successfully adds user’s id to db, but the problem happens if I try to send "register" 1 more time. IsUserInDB() returns me false and bot adds 1 more row with the same uuid. So, I think problem is with my IsUserInDb() function

>Solution :

Why not just a unique index on your users table?

CREATE UNIQUE INDEX unq_uuid ON users (uuid);

Then you don’t have to check, you just try to insert and it will return an error if it already exists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading