How do I get `fragment` in scope in a `prepare` block?

I'm wanting to sort a query using a fragment. I found this https://elixirforum.com/t/how-do-i-sort-records-by-random-in-the-resource-action/58774 that looks like it would work. However, I get an error when I try. My code:
read :my_action do
argument :embedding, :vector, allow_nil?: false
prepare fn query, _ ->
Ash.Query.sort(query, Ash.Sort.expr_sort(fragment("1 - (embedding <=> ?)", arg(:embedding))))
end
end
read :my_action do
argument :embedding, :vector, allow_nil?: false
prepare fn query, _ ->
Ash.Query.sort(query, Ash.Sort.expr_sort(fragment("1 - (embedding <=> ?)", arg(:embedding))))
end
end
The error I get error: undefined function fragment/2 (expected MyModule to define such a function or for it to be imported, but none are available). How do I use fragment in the prepare function? Or is there a better way to do this?
7 Replies
bhelms
bhelmsOP4mo ago
I'm already requiring Ash.Query btw.
barnabasj
barnabasj4mo ago
fragment is part of AshPostgres IIRC do you use AshPostgres as the datalayer on the resource? maybe AshSqlite as well
bhelms
bhelmsOP4mo ago
Yes. Thanks. I'll look there.
barnabasj
barnabasj4mo ago
ok, I'm wrong the builtins support fragment too
bhelms
bhelmsOP4mo ago
Adding Ecto.Query.API.fragment at least got it to compile. I can't find how to fully qualify it in Ash. Nevermind, that didn't work either. Btw, trying prepare build(sort: [desc: fragment("1 - (embedding <=> ?)", arg(:embedding))]) gets the same error.
barnabasj
barnabasj4mo ago
try Ash.Query.sort(query, Ash.Sort.expr_sort(expr(fragment("1 - (embedding <=> ?)", arg(:embedding))))) I think you might need to wrap it in expr(..)
bhelms
bhelmsOP4mo ago
I got it! This works:
prepare fn query, _ ->
Ash.Query.sort(query, [
{calc(fragment("1 - (embedding <=> ?)", ^arg(:embedding))), :desc}
])
end
prepare fn query, _ ->
Ash.Query.sort(query, [
{calc(fragment("1 - (embedding <=> ?)", ^arg(:embedding))), :desc}
])
end
https://hexdocs.pm/ash/Ash.Query.html#sort/3-expression-sorts Thanks for your help.

Did you find this page helpful?