elixirmoney / money

Elixir library for working with Money safer, easier, and fun... Is an interpretation of the Fowler's Money pattern in fun.prog.
https://hex.pm/packages/money/
MIT License
826 stars 139 forks source link

Ecto aggregate functions sometimes return Decimal. #219

Closed aglassman closed 3 months ago

aglassman commented 3 months ago

Problem I modified a table's 'amount_in_cents' column to be the PostgreSQL type bigint rather than integer. This seems to have caused calls using Repo.aggregate calls to fail to load the result type into a Money struct.

schema "adjustments" do
  field :amount_in_cents, Money.Ecto.Amount.Type
  # ...
end

#

query = from(a in Adjustment, where a.wallet_id == ^wallet_id)
Repo.aggregate(query, :sum, :amount_in_cents)

This results in the following issue.

Screenshot 2024-05-14 at 1 00 57 PM

I'm not totally sure why aggregate changes it's return type from an integer to a Decimal. This causes Money.Ecto.Amount.Type.load/1 to fail to match.

Proposed Solution Add a new function head to the load function.

@spec load(integer()) :: {:ok, Money.t()}
    def load(int) when is_integer(int), do: {:ok, Money.new(int)}
    def load(%Decimal{} = decimal), do: Money.parse(decimal) 
Nitrino commented 3 months ago

Thanks for the description and solution!