Added common.IsUniqueConstraintViolationErr

This commit is contained in:
Crom (Thibaut CHARLES) 2017-12-14 00:24:49 +01:00
parent 2ded148e0b
commit c1badc0510
No known key found for this signature in database
GPG key ID: 45A3D5F880B9E6D0
2 changed files with 11 additions and 6 deletions

View file

@ -24,7 +24,7 @@ import (
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
// Import the postgres database driver. // Import the postgres database driver.
"github.com/lib/pq" _ "github.com/lib/pq"
) )
// Database represents an account database // Database represents an account database
@ -128,11 +128,8 @@ func (d *Database) CreateAccount(
return nil, err return nil, err
} }
if err := d.profiles.insertProfile(ctx, localpart); err != nil { if err := d.profiles.insertProfile(ctx, localpart); err != nil {
if err, ok := err.(*pq.Error); ok { if common.IsUniqueConstraintViolationErr(err) {
if err.Code.Class() == "23" { return nil, nil
// 23 => unique_violation => Account already exists
return nil, nil
}
} }
return nil, err return nil, err
} }

View file

@ -16,6 +16,8 @@ package common
import ( import (
"database/sql" "database/sql"
"github.com/lib/pq"
) )
// A Transaction is something that can be committed or rolledback. // A Transaction is something that can be committed or rolledback.
@ -66,3 +68,9 @@ func TxStmt(transaction *sql.Tx, statement *sql.Stmt) *sql.Stmt {
} }
return statement return statement
} }
// IsUniqueConstraintViolationErr returns true if the error is a postgresql unique_violation error
func IsUniqueConstraintViolationErr(err error) bool {
pqErr, ok := err.(*pq.Error)
return ok && pqErr.Code == "23505"
}