How Arel Converts Ruby Queries Into SQL Statements
Join the DZone community and get the full member experience.Join For Free
this is the second in a series of posts based on a presentation i did at the barcelona ruby conference called “20,000 leagues under activerecord.” i took an innocent and unsuspecting audience on an adventure inside and underneath activerecord to find out how rails and postgresql actually execute a simple sql query.
in the first part of the presentation i showed what activerecord does internally when you call methods such as where and limit. we saw how each scoping method returns a new instance of the activerecord::relation class, gradually building up a description of your query.
today i’ll continue by looking at what activerecord does next: how it uses the arel gem to convert the activerecord::relation object describing your query into a string containing a sql statement. later, in the third post we’ll dive down inside the postgresql database server itself to see how it executes this sql statement.
the arel gem
here again is the instance of the activerecord::relation class that represents our query to find the user named “captain nemo:”
now that we’ve specified the query we want to execute, what does activerecord do next? how does it actually execute the query and return the results to us? we can find a clue by looking more closely at the relation object and the metadata values it stores:
if you inspect an activerecord::relation object in the rails console, you’ll find that its instance variables are not simple values, but instead references to other ruby objects. these objects have class names such as arel::nodes::equality and arel::nodes::attribute. what are these ruby objects? where are they created? what do these class names mean?
it turns out that activerecord itself doesn’t convert your activerecord::relation query to sql; instead, it uses a separate gem called arel to do that. googling for “arel” we can easily find its github repo:
the gem’s description is simply “a relational algebra.” what in the world does this mean? and farther down in the readme there’s another interesting line: “arel is a sql ast manager for ruby.” what does “ast” mean, and what does an “ast manager” do?
ast stands for “abstract syntax tree,” an important concept from computer science. i’ll explain what that means in a minute. but first let’s look at some computer science history to find out what relational algebra is.
relational algebra is a branch of computer science that forms the mathematical foundation underpinning relational database servers and the sql language. an influential computer scientist named edgar codd first described relational algebra in his groundbreaking academic paper a relational model of data for large shared data banks , published in 1970. codd described the term “relation” as follows:
1.3. a relational view of data
the term relation is used here in its accepted mathematical sense. given sets s 1 , s 2 , ... , s n , (not necessarily distinct), r is a relation on these n sets if it is a set of n-tuples each of which has its first element from s 1 , its second element from s 2 , and so on.
he later went on to define various mathematical operations on relations, including projection , restriction , and join . he also used terms such as normal form , primary key and foreign key . today, almost 45 years later, we still use codd’s terminology and the associated mathematical theories when discussing database tables and queries.
in another interesting passage, codd wrote about the need for a language we could use to articulate and describe relational algebra concepts:
1.5. some linguistic aspects
the adoption of a relational model of data, as described above, permits the development of a universal data sublanguage based on an applied predicate calculus.
this “universal sublanguage” is the structured query language or sql. i find the term “sublanguage” to be very appropriate; sql is a language used inside larger applications written in some other programming language, such as ruby.
returning to our example, here’s the sql statement that represents our search for the user named captain nemo:
the sql language existed before codd wrote his paper on relational algebra in 1970, but it didn’t resemble the version of sql we all know and love today. the mathematical concepts codd first described form the basis for the modern version of sql.
now let’s return to the question of what an “ast manager” is.
abstract syntax trees
an abstract syntax tree is a hierarchical arrangement of objects or memory structures that represent a series of words or some syntax from a text language. in this case, the ast inside of arel is a tree of ruby objects that represents a sql statement.
here’s the ast arel creates internally for our example query:
you can see the top or root of the tree is a ruby object called selectstatement, and under that the various branches of the tree represent the from, where, order by and limit clauses in our select statement.
the arel gem “is a relational algebra” in the sense that it provides a ruby api that contains methods such as project, where and order that represent concepts from relational algebra. internally, these methods create ruby objects and save them in the ast. arel’s api is similar to activerecord’s, but is somewhat more granular and detailed. when we call activerecord methods such as where and limit, internally activerecord calls the corresponding methods in the arel gem.
here’s our example query written using both activerecord (top) and arel (bottom) method calls:
professor aronnax, conseil and ned land spent hours marveling
notice the arel query is longer and more verbose. expressing our query using arel we call:
- project to specify which columns or attributes we are looking for ( projection in codd’s relational algebra)
- where and eq to specify how to filter the result set ( restriction in relational algebra)
- order to specify the sort order, and
- limit to specify how many records we want.
each time you call an activerecord scoping method, it calls down into one of these arel methods, inserting objects into the same ast.
the visitor pattern
creating an ast containing ruby objects is one thing, but generating an actual sql statement is another. how does arel do this? why is building up an ast useful in any way?
using a very elegant algorithm, arel iterates over the nodes in the ast and concatenates different sql fragments to form a complete sql statement. this algorithm is an example of the “visitor pattern.” the term visitor pattern simply means that some object, function or other piece of code is executed once for each node in some data structure, such as an array, linked list or tree.
to understand this a bit better, let’s take our example ast and follow arel’s visitor as it traverses the tree, starting at the selectstatement root node:
the blue arrow at the top is the visitor, a ruby object. depending on which database server you are using, arel creates a different visitor object. this is a fascinating detail about arel’s internal design: arel can generate different variations of sql equally well by using different visitor objects. if you connect your rails app to sqlite, arel uses a sqlite visitor. if you are using mysql, arel uses a mysql visitor. because we’re using postgresql today, arel creates a postgres visitor.
visiting all the nodes in the ast
now let’s follow arel’s visitor as it iterates over the ruby objects in the ast, shown as a moving blue arrow. above each diagram i’ll show the sql string the visitor cumulatively builds up as it goes.
here you can see the visitor arrow next to the selectstatement node. above the diagram i’ve written the word “select.” arel’s visitor knows to write select when it encounters selectstatement root node.
next arel moves down to the left:
this time arel doesn’t write anything new into the string; selectcode is just a container for other branches of the tree.
next, arel moves down and left again:
now arel’s visitor see the attribute node. this represents the projection or list of attributes we want in the result set. arel appends "users".* to the sql string.
next, the visitor moves to the right:
encountering the joinsource node, arel writes from "users" onto the end of the sql statement. joinsource and its child nodes list the tables that our query will read from. in this example, we don’t have any joins and just a single table, so joinsource has only one table child node.
next, the visitor moves to the right again:
now arel writes the where clause for our sql statement: where "users"."name" = $1. the and node is the root of a subbranch of the ast that represents the boolean expression we want the database server to use to filter our result set. in our example we are only checking that the name column equals “captain nemo” so the ast contains a single equality node under and. the and node doesn’t really do anything in this case.
now the visitor continues to the right:
here you can see arel finds the ascending node and appends our order by clause.
finally, the visitor moves to the right one last time:
finding the limit node, arel’s visitor completes the sql statement by concatenating limit 1 onto our select statement.
using the visitor pattern in this way, arel has converted our query from a collection of ruby objects into a single string containing a sql select statement. arel has expressed our ruby query using codd’s relational algebra.
every time you execute a simple database query using activerecord in your rails app, you are relying on a series of elegant algorithms and computer science theories developed many years ago. rails is so simple and easy to use only because we are standing on the shoulders of giants – computer scientists like edgar codd – who have already done the difficult theoretical work that makes building apps today possible.
why stop here?
we’ve learned a lot about activerecord and the arel gem. now we know what happens when we call scoping methods such as where and first. we’ve seen how activerecord calls arel’s lower level, more granular api, and now we know how arel uses the visitor pattern and an ast to convert these ruby method calls into a sql string.
but why stop here? why not dive even deeper? … farther below the surface of your rails app into the postgresql server itself! next we’ll leave the world of ruby entirely and look at what the postgres server does when it receives this select statement. how does it understand the sql we send it? how does it actually find our data, the user record with the name “captain nemo?” in my next post, i’ll continue our underwater adventure by looking at postgres internals.
Published at DZone with permission of Pat Shaughnessy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Turbocharge Ab Initio ETL Pipelines: Simple Tweaks for Maximum Performance Boost
Front-End: Cache Strategies You Should Know
How To Scan and Validate Image Uploads in Java
Building a Robust Data Engineering Pipeline in the Streaming Media Industry: An Insider’s Perspective