rails / arel

A Relational Algebra
2.06k stars 390 forks source link

Add #to_sql method for attributes #515

Closed Envek closed 6 years ago

Envek commented 6 years ago

It allows to more easily and safely construct complicated SQL expressions by using string interpolation for SQL features not supported in Arel yet.

Consider this ActiveRecord example:

facts = Feature::Fact.arel_table
recs  = Feature::Recommendation.arel_table
Feature::Recommendation.left_outer_joins(:fact).pluck_to_struct(
  "COUNT(*) AS recommendations_total",
  "SUM(#{facts[:value]}) FILTER (WHERE #{recs[:some_flag].not_eq(nil)}) AS recommendations_applied",
).first

Which will produce something like:

SELECT
  COUNT(*) AS recommendations_total,
  SUM("feature_facts"."value") FILTER (WHERE "feature_recommendations"."some_flag" IS NOT NULL) AS recommendations_applied
FROM "feature_recommendations"
  LEFT OUTER JOIN "feature_facts" ON …

I believe it will be most useful in case of namespaced long table names.

matthewd commented 6 years ago

Per #523, Arel development is moving to rails/rails.

If this PR is still relevant, please consider reopening it over there.