Fixes for Blog.Accounts.create_user/1 #8
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix transaction in
Blog.Accounts.create_user/1
If
Blog.Accounts.create_user/1
is provided with data which doesn't pass the validations inBlog.Account.{User,Contact}.changeset/2
, the lambda function passed toEcto.Repo.transaction/2
will return{error, %Ecto.Changeset{valid?: false}}
. This will not automatically roll back the transaction, as transaction are rolled back only if an error is raised, as mentioned in the docs:Not only it results in stale records in the database, it messes the return value of
Blog.Accounts.create_user/1
as well. BecauseEcto.Repo.transaction/2
returns the value returned by the function wrapped in a tuple as{:ok, value}
, in case of validation errors it will return{:ok, {:error, %Ecto.Changeset{valid?: false}}}
.To fix both issues, we need to match on
{:error, changeset}
and manually roll back the transaction.Validate uniqueness of
(type, value)
for thecontacts
tablecontacts
table has a unique constraint on(type, value)
. If the user tries to insert the same contact twice, an error will be raised.