Skip to content

nilclass/arel

 
 

Repository files navigation

ARel Build Status Dependency Status

DESCRIPTION

Arel is a SQL AST manager for Ruby. It

  1. Simplifies the generation of complex SQL queries
  2. Adapts to various RDBMS systems

It is intended to be a framework framework; that is, you can build your own ORM with it, focusing on innovative object and collection modeling as opposed to database compatibility and query generation.

Status

For the moment, Arel uses ActiveRecord's connection adapters to connect to the various engines, connection pooling, perform quoting, and do type conversion.

A Gentle Introduction

Generating a query with ARel is simple. For example, in order to produce

SELECT * FROM users

you construct a table relation and convert it to sql:

users = Arel::Table.new(:users)
query = users.project(Arel.sql('*'))
query.to_sql

More Sophisticated Queries

Here is a whirlwind tour through the most common relational operators. These will probably cover 80% of all interaction with the database.

First is the 'restriction' operator, where:

users.where(users[:name].eq('amy'))
# => SELECT * FROM users WHERE users.name = 'amy'

What would, in SQL, be part of the SELECT clause is called in Arel a projection:

users.project(users[:id]) # => SELECT users.id FROM users

Joins resemble SQL strongly:

users.join(photos).on(users[:id].eq(photos[:user_id]))
# => SELECT * FROM users INNER JOIN photos ON users.id = photos.user_id

What are called LIMIT and OFFSET in SQL are called take and skip in Arel:

users.take(5) # => SELECT * FROM users LIMIT 5
users.sk