Hey,
I am working on a library that manages existing resources. The user has to provide a schema and the library will display items based on certain options. This includes ordering, filtering and pagination. In an advanced setup the user is able to add a query which will then be executed before fetching items of the provided resource.
I built a generic ordering function with Ecto, but I still do not know how to handle scenarios where the user selects new fields in this query.
For example the user provides a user schema with username
, first_name
and last_name
. In the query the user selects a field full_name
with a fragment that combines first_name
and last_name
. Now, the user wants to order the items based on the full_name
field.
Currently, I have something like:
def apply_criteria(query, criteria) do
Enum.reduce(criteria, query, fn
{:order, %{by: by, direction: direction}}, query ->
query
|> order_by({^direction, ^by}
...
_, query ->
query
end)
end
But this will not work with full_name
, because the field is not part of the provided database schema.
How would I implement ordering by this field?
As far as I know the only way to order by such field is to copy the fragment into the order
function, but I do not know which fragments or computations the user adds to the query and by which field the items should be ordered. I could use fragment("full_name")
as the order field, but this doesn’t work, because fragment
doesn’t allow strings to be interpolated. In addition not every computation is a fragment. It could also be something like a count the user maybe wants to add.
Best regards