I’m attempting to translate a query I’ve written into Ecto. Here’s what I have:
def select_merged_prs(query \\ GithubPullRequest, period) do
query
|> select([github_pull_request], %{
count: count(github_pull_request.id),
date: fragment("DATE_TRUNC(?, (?->>'merged_at')::timestamp) as date", ^period, github_pull_request.data),
name: fragment("?->'user'->>'login' as name", github_pull_request.data),
})
|> group_by(fragment("date, name"))
end
I feel like I’m missing something having to alias the fields using fragment
so I can reference them in the group_by
. Could this be more elegant?
For reference, the original SQL query is:
SELECT
count(github_pull_requests.id) as merged_prs,
DATE_TRUNC('day',
(
github_pull_requests.data ->> 'merged_at'
)
::timestamp) as date,
github_pull_requests.data ->'user'->>'login' as name
FROM
github_pull_requests
WHERE
github_pull_requests.github_repository_id = 35
GROUP BY
date, name
ORDER BY
date;