luckyframework/lucky_record

Create a simpler type safe way to write custom queries

edwardloveall opened this issue · 2 comments

Some way to reference columns, tables, and functions to compose sql.

This came up because I was trying to order records by the sum of a bunch of fields. Here's what the sql looked like:

SELECT * FROM shards
ORDER BY shards.forks_count +
  shards.stargazers_count +
  shards.subscribers_count +
  shards.watchers_count
DESC

This orders all shards by the sum of each of those columns. Here's how I made it type safe:

class ShardQuery < Shard::BaseQuery
  def popular_first
    table = ShardForm.new.table_name
    query = [
      forks_count.column,
      "#{table}.#{stargazers_count.column}",
      "#{table}.#{subscribers_count.column}",
      "#{table}.#{watchers_count.column}"
    ].join(" + ")
    order_by(query, :desc)
  end
end

It's a little funky, like calling ShardForm to get the table name, and leaving off the table for the first column. I had to leave it off because order_by adds the table at the start (because it only expects one column to be passed in).

It'd be great to have an easier way to compose these queries so they can remain type safe.

Some other suggestions were things like

order_by_sum_of([stargazers, watchers, etc], :desc)

sum(stargazers_count, watchers_count).desc_order

ShardQuery.new.aggregate(stargazers_count, watchers_count).sum.desc_order

Similar discussion in #174 Closing.