ECTO call to fragment getting out of module error

I’m sure I’m doing something stupid here that has something to do with call Ecto.Query.API fragment method.
In a context module called orders, I’m getting an " cannot invoke def/2 outside module…" for the following (abbreviated to include imports). I pretty sure it’s the call on fragment. I’m showing the modules I’m importing and the function call that is the source of the error. ??? What am I’m missing here.
Thanks in advance.

defmodule Trello.Orders do
  @moduledoc """
  The Orders context.
  """
  import Ecto.Query, warn: false
  import Ecto.Query.API
  alias Trello.Repo
  alias Trello.Orders.Order
...
 def orders_by_year() do
  q = from o in Order,
        select: %{trello_id: o.trello_id,
                customer: o.customer,
                year_2020: fragment("ROUND(SUM (case when date_part('year',o.invoice_date)=? THEN o.ext_total ELSE 0.0 END))", 2020),
                year_2021: fragment("ROUND(SUM (case when date_part('year',o.invoice_date)=? THEN o.ext_total ELSE 0.0 END))", 2021),
                year_2022: fragment("ROUND(SUM (case when date_part('year',o.invoice_date)=? THEN o.ext_total ELSE 0.0 END))", 2022),
                year_2023: fragment("ROUND(SUM (case when date_part('year',o.invoice_date)=? THEN o.ext_total ELSE 0.0 END))", 2023)
              },
        group_by: [o.trello_id, o.customer ],
        order_by: [o.customer]
end

...

Hey @wdtnh the Ecto.Query.Api module is a bit weird in that it says

Note the functions in this module exist for documentation purposes and one should never need to invoke them directly.

Basically, don’t import it at all, and import Ecto.Query handles making it actually work.

I don’t know how that would give the error message you’re getting though. If my suggestion to remove that import doesn’t work can you show a minimum complete example that exhibits the issue?

Thanks. Removed as suggested but compile still doesn’t work.

I just run iex -S mix and I get the error.

The module itself consists of what I’ve shown as imports and all the standard ecto boilerplate that mix.gen.context macro generates. I haven’t added anything else to this module other than this one single function.

Please paste the whole stacktrace.

Is the function somehow outside of the defmodule do end block? Did you place it at the end of the file after the last end?

2 Likes

Oh my flipping word… just shoot me now. Thanks

1 Like