Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

select on conflict #416

Open
tcurdt opened this issue Mar 2, 2020 · 2 comments
Open

select on conflict #416

tcurdt opened this issue Mar 2, 2020 · 2 comments

Comments

@tcurdt
Copy link

tcurdt commented Mar 2, 2020

I am currently using this to

  err := dbm.Insert(foo)
  if err != nil {
    msg := err.Error()
    if strings.HasPrefix(msg, "pq: duplicate key") || strings.HasPrefix(msg, "UNIQUE") || strings.HasPrefix(msg, "Error 1062:") {
      f := &Foo{}
      err := dbm.SelectOne(f, "select * from foo where a=$1 and b=$2",
        a,
        b,
      )
      if err != nil {
        return nil, err
      }
      return s, nil
    }

Is there a better way to handle a failed uniq constraint?

@nelsam
Copy link
Member

nelsam commented Mar 29, 2020

As of right now, that's probably your best bet. It might be worth checking with your sql driver (github.com/lib/pq I assume) to see if they have sentinel errors or something to compare against or type check with. Or maybe you can add a PR. Something like if dupErr, ok := err.(pq.DuplicateKey); ok { would be helpful in a lot of scenarios.

@bokwoon95
Copy link

err := dbm.Insert(foo)
if pqerror, _ := err.(*pq.Error); pqerror.Code == "23505" {
    err := dbm.SelectOne(f, "select * from foo where a=$1 and b=$2", a, b)
    if err != nil {
    }
}

Errors from pq expose the postgres error code. The postgres error code for duplicate key violation is 23505 which can be found from this table https://www.postgresql.org/docs/current/errcodes-appendix.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants