Arel: Add support for FILTER clause (SQL:2003) by Envek · Pull Request #40491 ·...
source link: https://github.com/rails/rails/pull/40491
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
New issue
Arel: Add support for FILTER clause (SQL:2003) #40491
Merged
Merged
Conversation
Reopened from rails/arel#518 due to the numerous requests of users (also in rails/arel#460).
Allows to write following Ruby code:
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, )
to get following SQL:
SELECT COUNT(*) AS records_total COUNT(*) FILTER (WHERE some_column IS NOT NULL) AS records_filtered FROM models
Database support:
- PostgreSQL 9.4+ (december 2014, release notes)
- SQLite 3.30+ (october 2019, release notes)
_(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 has been hidden.
_(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 has been hidden.
_(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 has been hidden.
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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
No milestone
Successfully merging this pull request may close these issues.
None yet
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK