-
Notifications
You must be signed in to change notification settings - Fork 22k
Arel: Add support for FILTER clause (SQL:2003) #40491
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
Oh bot, just look at these reactions under first comment! How you even could think about closing this pull request? Heartless piece of code! |
_(table[:id].count.filter(table[:gdp_per_capita].gteq(40_000)).to_sql).must_be_like %{ | ||
COUNT("users"."id") FILTER (WHERE "users"."gdp_per_capita" >= 40000) | ||
} |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
_(table[:id].count.filter(table[:gdp_per_capita].gteq(40_000)).as("foo").to_sql).must_be_like %{ | ||
COUNT("users"."id") FILTER (WHERE "users"."gdp_per_capita" >= 40000) AS foo | ||
} |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
_(table[:id].count.filter(table[:gdp_per_capita].gteq(40_000)).over(window).to_sql).must_be_like %{ | ||
COUNT("users"."id") FILTER (WHERE "users"."gdp_per_capita" >= 40000) OVER (PARTITION BY "users"."year") | ||
} |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
Currently supported by PostgreSQL 9.4+ and SQLite 3.30+ See: - http://modern-sql.com/feature/filter - https://www.postgresql.org/docs/9.4/static/sql-expressions.html#SYNTAX-AGGREGATES - https://sqlite.org/lang_aggfunc.html#aggfilter Example: Model.all.pluck( Arel.star.count.as('records_total').to_sql, Arel.star.count.filter(Model.arel_table[:some_column].not_eq(nil)).as('records_filtered').to_sql, )
@sunny thanks for catching this weird naming of test examples (most probably I copied them from some project, but it was long time ago). Applied your suggestions and rebased on top of fresh |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I really like this extension of Arel. As a followup we can open another case to expose it via ActiveRecord public API. Also it is not supported by MySQL, but it can be implemented using CASE (https://modern-sql.com/feature/filter#conforming-alternatives). It could be added to MySQL adapter later as well if needed.
I'd love to see this merged! |
Reopened from rails/arel#518 due to the numerous requests of users (also in rails/arel#460).
Allows to write following Ruby code:
to get following SQL:
Database support:
See: