Skip to content

Instantly share code, notes, and snippets.

@mrcampbell
Last active February 27, 2020 17:25
Show Gist options
  • Save mrcampbell/abce2c556df7e7b913a8b96796c5ba99 to your computer and use it in GitHub Desktop.
Save mrcampbell/abce2c556df7e7b913a8b96796c5ba99 to your computer and use it in GitHub Desktop.
// an abbreviated, fictional example of a database method you might find at Weave
func (p personService) CreateOrUpdate(ctx context.Context, person app.Person) (app.Person, error) {
var result app.Person
query := `
INSERT INTO persons
(
id,
first_name,
last_name,
created_at,
updated_at
)
VALUES
(
$1,
$2,
$3,
now(),
now()
)
ON CONFLICT(id) DO UPDATE SET
(
first_name = $2,
last_name = $3,
updated_at = now()
)
RETURNING
id,
first_name,
last_name,
created_at,
updated_at;
`
row := hos.DB.QueryRowContext(
ctx,
query,
uuid.NewV4(),
person.FirstName,
person.LastName,
)
err := row.Scan(
&result.ID,
&result.FirstName,
&result.LastName,
&result.CreatedAt,
&result.UpdatedAt,
)
if err != nil {
return app.Person{}, werror.Wrap(err, "failed to insert or update person")
}
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment