Fixes #6 Added ON CONFLICT clause to INSERT in CreateUser
parent
a9adc633ab
commit
d84bde9b4d
14
handlers.go
14
handlers.go
|
@ -39,14 +39,20 @@ func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request, _ httproute
|
||||||
log.Print(user)
|
log.Print(user)
|
||||||
|
|
||||||
// Insert
|
// Insert
|
||||||
_, err = h.db.Exec(`
|
var finalId string
|
||||||
INSERT INTO "user" (id, first_name, last_name, phone_number) VALUES ($1, $2, $3, $4)
|
err = h.db.QueryRow(`
|
||||||
`, user.ID, user.FirstName, user.LastName, user.PhoneNumber)
|
INSERT INTO "user" (id, first_name, last_name, phone_number)
|
||||||
|
VALUES ($1, $2, $3, $4)
|
||||||
|
ON CONFLICT(phone_number)
|
||||||
|
DO UPDATE SET phone_number=EXCLUDED.phone_number, first_name=$2, last_name=$3
|
||||||
|
RETURNING id
|
||||||
|
`, user.ID, user.FirstName, user.LastName, user.PhoneNumber).Scan(&finalId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
log.Print(err)
|
log.Print(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
user.ID = finalId
|
||||||
|
|
||||||
// Respond
|
// Respond
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
@ -474,7 +480,7 @@ func (h *Handler) CreateContact(w http.ResponseWriter, r *http.Request, p httpro
|
||||||
|
|
||||||
// Insert
|
// Insert
|
||||||
_, err = h.db.Exec(`
|
_, err = h.db.Exec(`
|
||||||
INSERT INTO contact ("user", contact) VALUES ($1, $2)
|
INSERT INTO contact ("user", contact) VALUES ($1, $2)
|
||||||
`, userID, contactId)
|
`, userID, contactId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
|
|
Loading…
Reference in New Issue