百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
Q

query-composer

> 编程语言
开源

一个库,用于通过定义其子组件和它们之间的依赖关系来编写复杂的 SQL 查询。

165 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

一个库,用于通过定义其子组件和它们之间的依赖关系来编写复杂的 SQL 查询。

Query::Composer

Simple SQL queries are, well, simple. But when you start needing to deal with nested subqueries, and especially when those nested subqueries themselves require nested subqueries...things start getting difficult to manage.

Query::Composer was extracted from a real application, where reporting queries were dynamically generated and typically exceeded 50KB of text for the query alone!

This library allows you to specify each component of query independently, as well as allowing you to indicate which other components each component depends on. The composer will then build the correct query from those components, on demand.

Features

  • Define your queries in terms of components, each of which is more easily tested and debugged
  • A dependency-resolution system for determining the proper ordering of query subcomponents within a complex query
  • A simple class (Query::Base) for more conveniently defining queries using Arel
  • The ability to generate the same query using either derived tables (nested subqueries), or CTEs (Common Table Expressions)

Usage

First, instantiate a composer object:

ruby
require 'query/composer'

composer = Query::Composer.new

Then, declare the components of your query with the #use method:

ruby
composer.use(:patrons) { Patron.all }

Declare dependent components by providing parameters to the block that are named the same as the components that should be depended on:

ruby
# `patrons` must exist as another component in the composer...
composer.use(:books) { |patrons| ... }

Component definitions must return an object that responds to either #arel, or #to_sql:

ruby
# ActiveRecord scopes respond to #arel
composer.use(:patrons) { Patron.all }

require 'query/base'

# Arel objects and Query::Base (a thin wrapper around
# Arel::SelectManager) respond to #to_sql
composer.use(:books_by_patron) do |patrons|
  books = Book.arel_table
  lendings = Lending.arel_table

  Query::Base.new(books).
    project(patrons[:first_name], books[:name]).
    join(lendings).
      on(lendings[:book_id].eq(books[:id])).
    join(patrons).
      on(patrons[:id].eq(lendings[:patron_id]))
end

Generate the query by calling #build on the composer, and telling it which component will be the root of the query:

ruby
# Builds the query using the books_by_patron component as the root.
query = composer.build(:books_by_patron)
# SELECT "patrons"."first_name", "books"."name"
# FROM "books"
# INNER JOIN "lendings"
# ON "lendings"."book_id" = "books"."id"
# INNER JOIN (
#   SELECT "patrons".* FROM "patrons"
# ) "patrons"
# ON "patrons"."id" = "lendings"."patron_id"

# Builds the query using the patrons component as the root
query = composer.build(:patrons)
# SELECT "patrons".* FROM "patrons"

Run the query by converting it to SQL and executing it:

ruby
sql = query.to_sql

# using raw ActiveRecord connection
rows = ActiveRecord::Base.connection.execute(sql)

# using ActiveRecord models
rows = Book.find_by_sql(sql)

Example

Let's use a library system as an example. (See this full example in examples/library.rb.) We'll imagine that there is some administrative interface where users can generate reports. One report in particular is used to show:

  • All patrons from a specified set of libraries,
  • Who have checked out books this month,
  • From a specified set of topics,
  • And compare that with the same period of the previous month.

We will assume that we have a data model consisting of libraries, topics, books, patrons, and lendings, where books belong to libraries and topics, and lendings relate patrons to books, and include the date the lending was created.

First, instantiate a composer object:

ruby
require 'query/composer'
require 'query/base'

composer = Query::Composer.new

We'll assume we have some object that describes the parameters for the query, as given by the user:

ruby
today = Date.today

config.current_period_from = today.beginning_of_month
config.current_period_to   = today
config.prior_period_from   = today.last_month.beginning_of_month
config.prior_period_to     = today.last_month

config.library_ids         = [ ... ]
config.topic_ids           = [ ... ]

Then, we tell the composer about the components of our query:

…

Note the use of the parameters in the block for books_set. The names for the parameters are explicitly chosen here to match the names of other query components. Query::Composer uses these names to determine which components a component depends on--in this case, books_set depends on both libraries_set and topics_set.

We still need to tell the composer how to find the lendings. Because we'll need the same query with two different date spans (one for the "current" period, and one for the "prior" period), we'll create a helper method:

ruby
# books_set -- the set of books to be considered
# from_date -- the beginning of the period to consider
# to_date -- the end of the period to consider
def lendings_set(books_set, from_date, to_date)
  lendings = Lending.arel_table

  patron_id = lendings[:patron_id]
  count = patron_id.count.as("total")

  Query::Base.new(lendings).
    project(patron_id, count).
    join(books_set).
      on(lendings[:book_id].eq(books_set[:id])).
    where(lendings[:created_at].between(from_date..to_date)).
    group(patron_id)
end

This lendings set will be all patron ids who borrowed any of the books in the given set, between the given dates, and will include how many books were borrowed by each patron during that period.

With that, we can now finish defining our query components:

…

There--our query is defined. Now we just need to tell the composer to generate the SQL. Once we have the SQL, we can use it to query the database:

ruby
sql = composer.build(:combined_set).to_sql

Patron.find_by_sql(sql).each do |patron|
  puts "#{patron.name} :: #{patron.current_total} :: #{patron.prior_total}"
end

The generated query, assuming a current month of Feb 2016, might look like this (formatted for readability):

…

For databases that support Common Table Expressions (CTE, or "with" queries), you can pass use_cte: true to the composer#build method to have the composer generate a CTE query instead. (NOTE that CTE queries can be very inefficient in some DBMS's, like PostgreSQL!)

ruby
sql = composer.build(:combined_set, use_cte: true)

The CTE query looks like this:

…

Also, to make it easier to debug queries, you can also pass use_aliases: false to composer#build in order to make the composer use the full component names, instead of shorter aliases.

ruby
sql = composer.build(:combined_set, use_aliases: false)

The resulting query:

…

License

Query::Composer is distributed under the MIT license. (See the LICENSE file for more information.)

Author

Query::Composer is written and maintained by Jamis Buck . Many thanks to T2 Modus for permitting this code to be released as open source!

Issues· 1 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言