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

Use Ecto.Multi to insert all hit data in a single #73

Open
1 task
nelsonic opened this issue May 20, 2019 · 3 comments
Open
1 task

Use Ecto.Multi to insert all hit data in a single #73

nelsonic opened this issue May 20, 2019 · 3 comments

Comments

@nelsonic
Copy link
Member

At present we are using 4 queries to insert a single hit.
This works "OK" and is "fast enough" but we can probably do better ...

Thankfully @katbow wrote this helpful guide:
https://github.com/dwyl/learn-phoenix-framework/blob/master/ecto-multi.md
So it should be pretty straightforward to refactor.

Todo

  • Refactor the insert_hit function (and supporting functions) to use Ecto.Multi
@nelsonic
Copy link
Member Author

nelsonic commented Jun 1, 2019

I don't think using Ecto.Multi is possible because the foreign keys of users, useragents and repositories are required for hits ...
see: https://github.com/dwyl/hits#view-the-entity-relationship-er-diagram
But I would be very happy if someone could show us how it can be done.

@katbow
Copy link

katbow commented Jun 3, 2019

You can use the result of previous operations in a Multi.

Multi.new
|> Multi.insert_or_update(:user_agent, user_agent_params)
|> Multi.insert_or_update(:user, user_params)
|> Multi.run(:repository, fn _repo, %{user: user} -> 
  # something that inserts/updates Repository with the user and returns {:ok, value} or {:error, value}
|> Multi.run(:hit, fn _repo, %{user_agent: user_agent, repository: repository} ->
  # something that inserts/updates Hit with the user agent & repository and returns {:ok, value} or {:error, value}

The multi tracks all the changes so far. You can see it in Healthlocker where the multi is accessed directly.

Check out run/3 & run/5, and basic usage with Result of a previous operation section.

@nelsonic
Copy link
Member Author

nelsonic commented Jun 3, 2019

@katbow nice! Thanks for sharing! ☀️

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

No branches or pull requests

2 participants