remove all n+1 queries for real this time

This commit is contained in:
2023-03-19 15:05:09 -04:00
parent 071eb1b3c9
commit 03f8a2e8a7
24 changed files with 240 additions and 131 deletions

View File

@ -843,12 +843,39 @@ defmodule Cannery.Ammo do
"""
@spec get_percentage_remaining(AmmoGroup.t(), User.t()) :: non_neg_integer()
def get_percentage_remaining(%AmmoGroup{count: 0, user_id: user_id}, %User{id: user_id}) do
0
def get_percentage_remaining(%AmmoGroup{id: ammo_group_id} = ammo_group, user) do
[ammo_group]
|> get_percentages_remaining(user)
|> Map.fetch!(ammo_group_id)
end
def get_percentage_remaining(%AmmoGroup{count: count} = ammo_group, current_user) do
round(count / get_original_count(ammo_group, current_user) * 100)
@doc """
Calculates the percentages remaining of multiple ammo groups out of 100
## Examples
iex> get_percentages_remaining(
...> [%AmmoGroup{id: 123, count: 5, user_id: 456}],
...> %User{id: 456}
...> )
%{123 => 100}
"""
@spec get_percentages_remaining([AmmoGroup.t()], User.t()) ::
%{optional(AmmoGroup.id()) => non_neg_integer()}
def get_percentages_remaining(ammo_groups, %User{id: user_id} = user) do
original_counts = get_original_counts(ammo_groups, user)
ammo_groups
|> Map.new(fn %AmmoGroup{id: ammo_group_id, count: count, user_id: ^user_id} ->
percentage =
case count do
0 -> 0
count -> round(count / Map.fetch!(original_counts, ammo_group_id) * 100)
end
{ammo_group_id, percentage}
end)
end
@doc """

View File

@ -92,7 +92,7 @@ defmodule Cannery.Containers do
@doc """
Gets a single container.
Raises `Ecto.NoResultsError` if the Container does not exist.
Raises `KeyError` if the Container does not exist.
## Examples
@ -100,18 +100,37 @@ defmodule Cannery.Containers do
%Container{}
iex> get_container!(456, %User{id: 123})
** (Ecto.NoResultsError)
** (KeyError)
"""
@spec get_container!(Container.id(), User.t()) :: Container.t()
def get_container!(id, %User{id: user_id}) do
Repo.one!(
def get_container!(id, user) do
[id]
|> get_containers(user)
|> Map.fetch!(id)
end
@doc """
Gets multiple containers.
## Examples
iex> get_containers([123], %User{id: 123})
%{123 => %Container{}}
"""
@spec get_containers([Container.id()], User.t()) :: %{optional(Container.id()) => Container.t()}
def get_containers(ids, %User{id: user_id}) do
Repo.all(
from c in Container,
where: c.user_id == ^user_id,
where: c.id == ^id,
where: c.id in ^ids,
order_by: c.name,
preload: ^@container_preloads
preload: ^@container_preloads,
select: {c.id, c}
)
|> Map.new()
end
@doc """