How to know the schema of a variable in Ecto query?

Hi.
I am writting a custom macro for using in Ecto queries. This macro will generate a SQL fragment that will be added to the query, similar to the example provided by the Ecto docs.

Imagine something like this:

query = from a in Article,
  where: my_macro(a)

The caveat is that I need to know the schema module of a (in this case Article). I’ve thought on passing it explicitly as the second argument to the macro, but it would be much more elegant to infer it automatically.

At the moment I haven’t figured out how to do it.
Is there any way to infer the schema of the variable? Would it be desirable, or would it be better to pass the schema module name explicitly?

2 Likes

I suspect you’d be better off composing; something like

query = from(a in Article) |>  my_macro(a)

since in this case your macro will receive a Queryable that you can interrogate.

1 Like

Thanks @kip, this is actually how I am currently doing it in my library. But I am not sure if I could pass the a variable declared in the query as in your example.

I am looking forward to replace it because of two reasons:

  • I have to build the query, and then pass it to my function to refine it. I would prefer to add the required conditions directly when building the query itself.
  • If my query select multiple schemas, the filters added by my function apply only to the first one.
1 Like