I have a table with no relationship. I need to SELECT COUNT(*) FROM table WHERE condition; How do I do that inside an action/calculation/aggregate?
Thanks.
I have a table with no relationship. I need to SELECT COUNT(*) FROM table WHERE condition; How do I do that inside an action/calculation/aggregate?
Thanks.
This is likely what you are looking for.
User
|> Ash.Query.filter(....)
|> YourApi.count() # uses the primary read action for authorization rules
Thanks, @zachdaniel. Should I use a generic action to run the query or can I do it inside a read action?
It depends on what you want to do with it. What are you trying to do with the count of records that you’re getting? Do you want an API endpoint that displays it? Do you want to put it in a view somewhere?
The count is used to decide if an engine (the electrical one) is started or not.
In what context? In some other resource? In a script? If there is some other code somewhere that needs to know the count, it should be able to do YourApi.count
. You can’t make a :read
action return an :integer
or :boolean
, though. If you want to put it behind an action, you’d need something like this:
action :is_started?, :boolean do
argument ...
run fn input, _ ->
query = build_your_query()
{:ok, YourApi.exists?(query)}
end
end
Or
action :count_of_stuff, :integer do
argument ...
run fn input, _ ->
query = build_your_query()
{:ok, YourApi.count(query)}
end
end
This is what I need. Thanks.
If anybody is coming from Ash Tutorial (Livebook), here is how to define action inside Tutorial.Support.Ticket
module to get the total tickets count.
actions do
action :count_of_tickets, :integer do
run fn input, _ ->
{:ok, Tutorial.Support.Ticket |> Ash.count()}
end
end
end