Following a Select Statement Through Postgres Internals
Join the DZone community and get the full member experience.Join For Free
preparing for this presentation over the summer, i decided to read through parts of the postgresql c source code. i executed a very simple select statement and watched what postgres did with it using lldb, a c debugger. how did postgres understand my query? how did it actually find the data i was looking for?
this post is an informal journal of my trip through the guts of postgres. i’ll describe the path i took and what i saw along the way. i’ll use a series of simple, conceptual diagrams to explain how postgres executed my query. in case you understand c, i’ll also leave you a few landmarks and signposts you can look for if you ever decide to hack on postgres internals.
in the end, the postgres source code delighted me. it was clean, well documented and easy to follow. find out for yourself how postgres works internally by following me on a journey deep inside a tool you use everyday.
finding captain nemo
here’s the example query from the first half of my presentation ; we’ll follow postgres as it searches for captain nemo:
finding a single name in string column like this should be straightforward, shouldn’t it? we’ll hold tightly onto this select statement while we explore postgres internals, like a rope deep sea divers use to find their way back to the surface.
the big picture
what does postgres do with this sql string? how does it understand what we meant? how does it know what data we are looking for?
postgres processes each sql command we send it using a four step process.
in the first step, postgres parses our sql statement and converts it into a series of c memory structures, a parse tree . next postgres analyzes and rewrites our query, optimizing and simplifying it using a series of complex algorithms. after that, postgres generates a plan for finding our data. like an obsessive compulsive person who won’t leave home without every suitcase packed perfectly, postgres doesn’t run our query until it has a plan. finally, postgres actually executes our query. in this presentation i’ll briefly touch on the first three topics, and then focus more on the last step: execute .
the c function inside of postgres that implements this 4 step process is called exec_simple_query. you can find a link to it below, along with an lldb backtrace which gives some context about exactly when and how postgres calls exec_simple_query.
how does postgres understand the sql string we sent it? how does it make sense of the sql keywords and expressions in our select statement? through a process called parsing , postgres converts our sql string into an internal data structure it understands, the parse tree.
it turns out that postgres uses the same parsing technology that ruby does, a parser generator called bison . bison runs during the postgres c build process and generates parser code based on a series of grammar rules. the generated parser code is what runs inside of postgres when we send it sql commands. each grammar rule is triggered when the generated parser finds a corresponding pattern or syntax in the sql string, and inserts a new c memory structure into the parse tree data structure.
i won’t take the time today to explain how parsing algorithms work in detail. if you’re interested in that sort of thing, i’d suggest taking a look at my book ruby under a microscope . in chapter one i go through a detailed example of the lalr parse algorithm used by bison and ruby. postgres parses sql statements in exactly the same way.
using lldb and enabling some c logging code, i observed the postgres parser produce this parse tree for our captain nemo query:
at the top is a node representing the entire sql statement, and below that are child nodes or branches that represent the different portions of the sql statement syntax: the target list (a list of columns), the from clause (a list of tables), the where clause, the sort order and a limit count.
if you want to learn more about how postgres parses sql statements, follow the flow of control down from exec_simple_query through another c function called pg_parse_query.
as you can see there are many helpful and detailed comments in the postgres source code that not only explain what is happening but also point out important design decisions.
all that hard work for nothing
the parse tree above should look familiar – it’s almost precisely the same as the abstract syntax tree (ast) we saw activerecord create earlier. recall from the first half of the presentation activerecord generated our captain nemo select statement when we executed this ruby query:
we saw that activerecord internally created an ast when we called methods such as where and first. later (see the second post ), we watched as the arel gem converted the ast into our example select statement using an algorithm based on the visitor pattern.
thinking about this, it’s ironic that the first thing postgres does with your sql statement is convert it from a string back into an ast. postgres’s parse process reverses everything activerecord did earlier; all of that hard work the arel gem did was for nothing! the only reason for creating the sql string at all was to communicate with postgres over a network connection. once postgres has the string, it converts it back into an ast, which is a much more convenient and useful way of representing queries.
learning this you might ask: is there a better way? is there some way of conceptually specifying the data we want to postgres without writing a sql statement? without learning the complex sql language or paying the performance overhead of using activerecord and arel? it seems like a waste of time to go to such lengths to generate a sql string from an ast, just to convert it back to an ast again. maybe we should be using a nosql database solution instead?
of course, the ast postgres uses is much different from the ast used by activerecord. activerecord’s ast was comprised of ruby objects, while postgres’s ast is formed of a series of c memory structures. same idea but very different implementations.
analyze and rewrite
once postgres has generated a parse tree, it then converts it into a another tree structure using a different set of nodes. this is known as the query tree . returning to the exec_simple_query c function, you can see it next calls another c function pg_analyze_and_rewrite.
waving my hands a bit and glossing over many important details, the analyze and rewrite process applies a series of sophisticated algorithms and heuristics to try to optimize and simplify your sql statement. if you had executed a complex select statement with sub-selects and multiple inner and outer joins, then there is a lot of room for optimization. it’s quite possible that postgres could reduce the number of sub-select clauses or joins to produce a simpler query that runs faster.
for our simple select statement, here’s the query tree that pg_analyze_and_rewrite produces:
i don’t pretend to understand the detailed algorithms behind pg_analyze_and_rewrite. i simply observed that for our example the query tree largely resembled the parse tree. this means the select statement was so straightforward postgres wasn’t able to simplify it further.
the last step postgres takes before starting to execute our query is to create a plan. this involves generating a third tree of nodes that form a list of instructions for postgres to follow. here’s the plan tree for our select statement.
imagine that each node in the plan tree is a machine or worker of some kind. the plan tree resembles a pipeline of data or a conveyor belt in a factory. in my simple example there is only one branch in the tree. each node in the plan tree takes some the output data from the node below, processes it, and returns results as input to the node above. we’ll follow postgres as it executes the plan in the next section.
the c function that starts the query planning process is called pg_plan_queries.
note the startup_cost and total_cost values in each plan node. postgres uses these values to estimate how long the plan will take to complete. you don’t have to use a c debugger to see the execution plan for your query. just prepend the sql explain command to your query, like this:
this is a powerful way to understand what postgres is doing internally with one of your queries, and why it might be slow or inefficient – despite the sophisticated planning algorithms in pg_plan_queries.
executing a limit plan node
by now, postgres has parsed your sql statement and converted it back into an ast. then it optimized and rewrote your query, possibly in a simpler way. third, postgres wrote a plan which it will follow to find and return the data you are looking for. finally it’s time for postgres to actually execute your query. how does it do this? it follows the plan, of course!
let’s start at the top of the plan tree and move down. skipping the root node, the first worker that postgres uses for our captain nemo query is called limit. the limit node, as you might guess, implements the limit sql command, which limits the result set to the specified number of records. the same plan node also implements the offset command, which starts the result set window at the specified row.
the first time postgres calls the limit node, it calculates what the limit and offset values should be, because they might be set to the result of some dynamic calculation. in our example, offset is 0 and limit is 1.
next, the limit plan node repeatedly calls the subplan, in our case sort, counting until it reaches the offset value:
in our example the offset value is zero, so this loop will load the first data value and stop iterating. then postgres returns the last data value loaded from the subplan to the calling or upper plan. for us, this will be that first value from the subplan.
finally when postgres continues to call the limit node, it will pass the data values through from the subplan one at a time:
in our example, because the limit value is 1 limit will immediately return null indicating to the upper plan there is no more data available.
postgres implements the limit node using code in a file called nodelimit.c
you can see the postgres source code uses words such as tuple (a set a values, one from each column) and subplan . the subplan in this example is the sort node, which appears below limit in the plan.
executing a sort plan node
where do the data values limit filters come from? from the sort plan node that appears under limit in the plan tree. sort loads data values from its subplan and returns them to its calling plan, limit. here’s what sort does when the limit node calls it for the first time, to get the first data value:
you can see that sort functions very differently from limit. it immediately loads all of the available data from the subplan into a buffer, before returning anything. then it sorts the buffer using the quicksort algorithm, and finally returns the first sorted value.
for the second and subsequent calls, sort simply returns additional values from the sorted buffer, and never needs to call the subplan again:
the sort plan node is implemented by a c function called execsort:
executing a seqscan plan node
where does execsort get its values? from its subplan, or the seqscan node that appears at the bottom of the plan tree. seqscan stands for sequence scan , which means to look through the values in a table, returning values that match a given filter. to understand how the scan works with our filter, let’s step through an imaginary users table filled with fake names, looking for captain nemo.
postgres starts at the first record in a table (known as a relation in the postgres source code) and executes the boolean expression from the plan tree. in simple terms, postgres asks the question: “is this captain nemo?” because laurianne goodwin is not captain nemo, postgres steps down to the next record.
no, candace is also not captain nemo. postgres continues:
… and eventually finds captain nemo!
postgres implements the seqscan node using a c function called execseqscan.
what are we doing wrong?
now we’re done! we’ve followed a simple select statement all the way through the guts of postgres, and have seen how it was parsed, rewritten, planned and finally executed. after executing many thousands of lines of c code, postgres has found the data we are looking for! now all postgres has to do is return the captain nemo string back to our rails application and activerecord can create a ruby object. we can finally return to the surface of our application.
but postgres doesn’t stop! instead of simply returning, postgres continues to scan through the users table, even though we’ve already found captain nemo:
what’s going on here? why is postgres wasting its time, continuing to search even though it’s already found the data we’re looking for?
the answer lies farther up the plan tree in the sort node. recall that in order to sort all of the users, execsort first loads all of the values into a buffer, by calling the subplan repeatedly until there are no values left. that means that execseqscan will continue to scan to the end of the table , until it has all of the matching users. if our users table contained thousands or even millions of records (imagine we work at facebook or twitter), execseqscan will have to loop over every single user record and execute the string comparison for each one. this is obviously inefficient and slow, and will get slower as more and more user records are added.
if we have only one captain nemo record, then execsort will “sort” just that single matching record, and execlimit will pass that single record through its offset/limit filter… but only after execseqscan has iterated over all of the names.
how do we fix this problem? what should we do if our sql queries on the users table take more and more time to execute? the answer is simple: we create an index.
in the next and final post in this series we’ll learn how to create a postgres index and to avoid the use of execseqscan. more importantly, i’ll show you what a postgres index looks like: how it works and why it speeds up queries like this one.
Published at DZone with permission of Pat Shaughnessy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.