What I Talk About When I Talk About Query Optimizers (1) — IR Design
Start with the simplest possible SELECT, build a SQL IR in Rust, then see what happens to the design when we try predicate pushdown and correlated subqueries.
The other day I was talking to Chi (skyzh on GitHub) about optd, the query optimizer library he’s been working on at CMU. It’s based on the Cascades framework. We got to complaining about how various database optimizers are designed and implemented. Somewhere in the middle of that conversation it occurred to me that this stuff is fun to talk about, and that I ought to write some of it down.
So I’m starting a series on query optimizers. That leaves me plenty of room for algorithms, engineering decisions, how the technology evolved, how projects actually shipped, and the occasional bit of industry gossip.
I’ll start with IR design. A few patterns turn up over and over in optimizers, and the interesting part is how we end up with them.
What counts as a query optimizer?
Before we get going, a word about what I mean by “optimizer.”
Ordinarily, the term means the database component that optimizes a query’s execution plan. Actual databases are less tidy. Some rewrite the abstract syntax tree (AST) directly. Some do transformations while lowering the AST. Others rewrite parts of the plan while a query is running.
For this series, I’ll call everything between the SQL parser and the executor the query optimizer.
What’s an IR?
If you’ve spent time around compilers, you’ve met an intermediate representation (IR). Rust has HIR and MIR, and LLVM has LLVM IR. An IR gives the compiler a structured representation of the program that it can analyze and transform.
Think of SQL as a programming language and a relational database as the virtual machine that runs it, much as the JVM runs Java. The optimizer does most of the compilation. It takes a SQL statement (the Java source in this analogy), produces an execution plan (the bytecode), and hands that plan to the executor (the runtime). So a SQL optimizer designer gets to be an IR designer too.
What does SQL IR look like?
A typical database has a parser, an analyzer or binder, an optimizer, and an executor. A SQL statement passes through those stages on its way to becoming a result. Under the definition I just gave, both the analyzer and the optimizer proper fall under “query optimizer.”
SQL is a declarative language with a syntax modeled on natural language. Its basis in relational algebra lets it express operations on sets as queries over tables.
AST
Like most compilers, we start by parsing the source into an abstract syntax tree. Here’s a SQL AST.
SQL AST nodes generally fall into two families, statements (Stmt) and expressions (Expr). The root is a statement. It can contain clauses and expressions. Expressions are recursive: they can contain operators, function calls, and even another statement in the form of a subquery.
SELECT makes the boundary between statement and expression particularly fuzzy. A SELECT can itself contain other SELECTs, and its set operations (UNION, EXCEPT, INTERSECT) even have precedence rules. It’s also the one statement form that can participate in mutual recursion with an expression. That’s worth remembering when you design the AST.
Relational algebra
SQL rests on relational algebra. A query has a corresponding algebraic expression. Here’s an example.
These expressions naturally form trees. Many systems turn the SQL AST into an execution plan like the one below. Each node is an operator, and the tree of operators is the query plan.
There have been exceptions, including one from IBM, the grandparent of rather a lot of database technology. Its Starburst system used a Query Graph Model (QGM). I find QGM exceptionally hard to follow. It’s quite abstract, yet it hardcodes enough properties to make me skeptical of its claims to extensibility. I’ll spare you the detour here. The papers are Extensible Query Processing in Starburst and Extensible/Rule Based Query Rewrite Optimization in Starburst.
Most familiar databases use some form of relational algebra: IBM’s System R and DB2, Oracle’s products, Microsoft’s SQL Server, and open-source systems including PostgreSQL and MySQL 8.0. Whole families of optimizers and execution frameworks have grown up around it. It’s a pretty safe place to start a SQL IR.
The algebra gives us laws for transforming queries while preserving their results. I’ll get into individual rules and algorithms later in the series.
Engineering best practices (let’s see about that)
There’s a cognitive bias called the curse of knowledge. Once you know something, it’s easy to assume the person you’re talking to knows it too.
Software engineering is especially good at producing this effect. Two people can know the same algorithms and data structures and still talk past each other if one has written the code in question and the other hasn’t. There are a dozen ways to implement a feature, each with its own particular way of making your life difficult.
Idioms and design patterns help. They give people a way to talk about experience, and a new project somewhere sensible to start. Database engineers have these too. It’s a small, fairly commercial field, though, and a lot of what we’ve learned lives in bits of source code scattered across open-source projects.
I’ll build a SQL IR from scratch the way I’d build one myself. That way each decision can turn up at the point where we actually need it.
I’ll use Rust because that’s what I tend to write. If you can read a little C or C++, you should have no trouble following along.
Hello, world!
The first program most of us write in a new language is hello world.
fn main() { println!("Hello, world!");}Let’s start with SQL’s hello world, too.
create table t(a int);select * from t;The translation into relational algebra is straightforward. I’ll write Get(t) for “return everything in the relation t.” A single struct will do for this query.
pub struct Get { pub table: String,}
fn plan() -> Get { // select * from t; Get { table: "t".to_string(), }}There we are, a SQL IR. With Get, we can represent any query of the form select * from xxx. Easy enough so far?
Select & Project
Let’s teach it a couple more SQL clauses. Say we want to represent this query.
create table t(a int, b int);select a from t where a = 1;In relational algebra we could write this as Project(Select(Get(t), a = 1), a). Select filters the input using a predicate. Project narrows the tuples to the attributes we want to keep. We can add a couple of structs for those.
pub struct Get { pub table: String,}
pub struct Select { pub get: Get, pub predicate: String,}
pub struct Project { pub select: Select, pub project: String,}
fn plan() -> Project { // select a from t where a = 1; Project { select: Select { get: Get { table: "t".to_string(), }, predicate: "a = 1".to_string(), }, project: "a".to_string(), }}Already we have a problem. The algebra allows a Project under a Select. Do our structs? And the filter is optional in SQL. How do we leave it out?
We need some way to choose the operator at runtime. In C++ or Java, you’d usually reach for inheritance and give the operators a common Operator base class.
class Operator {};class Get : public Operator {};class Select : public Operator { Operator* _child;};class Project : public Operator { Operator* _child;};Rust offers another handy option. An enum is an algebraic data type, also known as a tagged union. We can choose the variant at runtime and still have the compiler check which fields belong to which operator.
pub enum Operator { Get { table: String, }, Select { child: Box<Self>, predicate: String, }, Project { child: Box<Self>, projects: String, },}
fn plan() -> Operator { // select a from t where a = 1; Operator::Project { child: Box::new(Operator::Select { child: Box::new(Operator::Get { table: "t".to_string(), }), predicate: "a = 1".to_string(), }), project: "a".to_string(), }}Now we can build operator trees of whatever shape we like. This is beginning to look like an IR.
Scalar expression
We’ve introduced Select and Project, but their predicates and projection expressions are still strings. An optimizer can’t do much analysis on a string. We’ll need an IR for expressions too.
Remember what we already have after parsing SQL. Each expression in the AST is an Expr node, something like this.
pub enum Expr { ColumnRef(ColumnRef), Literal(Literal), Function(Function), BinaryOp(BinaryOp), UnaryOp(UnaryOp), Subquery(SelectStmt),}Expressions are recursive, and so are the Expr nodes that represent them. Could we save ourselves some work and reuse the parser’s nodes inside the SQL IR? Let’s try it.
Replacing String with Expr gives us the following.
pub enum Operator { Get { table: String, }, Select { child: Box<Self>, predicate: Expr, }, Project { child: Box<Self>, projects: Vec<Expr>, },}Now take this SQL query and ask a few ordinary optimizer questions.
select a from twhere exists (select * from t1 where t.a = t1.a)- Which tables and columns does the expression in Project depend on? I can see a column called
a. I can’t tell which table it belongs to, or whether such a column even exists. - What type does that expression return? No idea. There’s no type information in
Expr. - Is the subquery in Select correlated? No idea about that either. All
Exprcontains is the unprocessed AST for a subquery.
So Expr didn’t get us quite as far as we’d hoped. Those questions need a representation with more information in it. I’ll call it ScalarExpr to distinguish it from the parser’s Expr.
For ScalarExpr to earn its keep, we need to do three things.
- Resolve every identifier to a fully qualified name.
- Attach type information and check that the types make sense.
- Lower each subquery into the SQL IR.
With those requirements and a little desugaring, ScalarExpr comes out looking like this.
pub enum ScalarExpr { ColumnRef(Vec<Identifier>, Type), Literal(Value, Type), Function(Signature, Vec<Self>), Subquery(Quantifier, Box<Operator>),}That’s the expression side in place. Let’s put the whole thing together.
The IR
So far we’ve got two pieces.
- An Operator tree that can express queries with different shapes.
- A ScalarExpr with the semantic information we need for analysis.
There are still a few conspicuous gaps, including Join, Union, and Aggregate. The pattern is clear enough now that we can fill them in the same way.
Put it all together and we have a pretty much perfect SQL IR.
pub enum ScalarExpr { ColumnRef(Vec<Identifier>, Type), Literal(Value, Type), Function(Signature, Vec<Self>), Subquery(Quantifier, Box<Operator>),}
pub enum Operator { Get { table: String, }, Select { child: Box<Self>, predicate: ScalarExpr, }, Project { child: Box<Self>, projects: Vec<ScalarExpr>, }, Join { kind: JoinKind, condition: ScalarExpr, left: Box<Self>, right: Box<Self>, }, UnionAll { left: Box<Self>, right: Box<Self>, }, Aggregate { group_by: Vec<ScalarExpr>, aggr_exprs: Vec<ScalarExpr>, child: Box<Self>, },}Such perfection deserves an appropriately grand name. I’ll call it The IR.
Property derivation
To analyze or optimize an IR, we need to know things about it. We could send an analyzer walking through the whole tree to calculate its properties. Then we’d have to keep track of what was in scope at every point in the walk, which sounds like quite a lot of bookkeeping.
Fortunately, data flows through a declarative SQL query in a way we can put to work.
In The IR, the flow of data follows the parent–child relationships between operators. The whole thing forms a directed acyclic graph (DAG), with data flowing up from children to parents.
To calculate a property for one node, first calculate the properties of its children, then use those to work out the property at the node itself. That’s property derivation.
pub struct Property;
fn derive_property(op: &Operator) -> Property { // Calculate the properties of the children operators. let children_property: Vec<Property> = op .children() .map(derive_property) .collect();
// Calculate property with the children properties. op.calculate_property(&children_property)}In query optimization, properties usually fall into two groups. Relational or logical properties describe the dataset. Physical properties describe how the data is organized or delivered.
Common relational properties include:
- The attributes, or columns, in the dataset.
- Cardinality, the number of records in it.
- Statistics describing the distribution of its attributes.
- Constraints, such as NOT NULL.
- Functional dependencies between attributes.
Common physical properties include:
- Ordering.
- Degree of parallelism (DOP).
- Distribution.
- Partitioning.
Relational algebra gives us a way to say what separates the two groups.
Take two relations, R and S. Write RPR and PPR for the relational and physical properties of R, and RPS and PPS for those of S.
Then ∀ R, S: R = S ⇒ RPR = RPS. Equal relations have the same relational properties.
The same relation can have quite different physical properties.
I’ll come back to how particular optimization algorithms use these properties in a later post.
With property derivation in hand, we can start using the laws of relational algebra to optimize The IR and keep the answers correct. Now for the awkward question. What should a property actually look like in code?
Relational properties
One of the most important relational properties is the set of attributes a node produces. In elementary relational algebra, a relation is a set of tuples, and each attribute in a tuple has a unique name. Using the tuple schema to represent those attributes seems entirely reasonable.
Let’s go back to how we create a table.
create table t(a int);In SQL we create and manage tables with the data definition language (DDL). When we create a table, we give it a schema with a definition for each column. Those columns correspond to attributes in the algebra. Here’s one way to represent the schema.
pub struct TableSchema { pub name: String, pub columns: Vec<ColumnDefinition>}
pub struct ColumnDefinition { pub name: String, pub column_type: Type, pub not_null: bool,}Each ColumnDefinition corresponds to an attribute. Could we use ColumnDefinition itself to represent the attribute in our relational properties?
Let’s give it a go and add attributes to The IR.
fn derive_attributes(op: &Operator) -> Vec<ColumnDefinition> { // Calculate the attributes of the children operators. let children_attributes: Vec<Vec<ColumnDefinition>> = op.children().iter().map(derive_attributes).collect();
// Calculate attributes with the children attributes. op.calculate_attributes(&children_attributes)}First we need to give Get the table’s schema.
pub enum Operator { Get { table: String, schema: Vec<ColumnDefinition>, }, // Nothing changed for other variants}Then we can implement attribute derivation on Operator.
impl Operator { fn calculate_attributes(&self, children: &[Vec<ColumnDefinition>]) -> Vec<ColumnDefinition> { match self { Operator::Get { schema, .. } => { let attributes = schema.clone(); attributes } Operator::Select { .. } => children[0].clone(), Operator::Join { .. } => { let mut attributes = children[0].clone(); attributes.extend(children[1].clone()); attributes } Operator::UnionAll { .. } => children[0].clone(),
Operator::Project { .. } => todo!(), Operator::Aggregate { .. } => todo!(), } }}Most of those cases were easy enough. Notice the two todos for Project and Aggregate, though. Neither operator can simply pass along its children’s attributes. In elementary relational algebra, projection changes the shape of a tuple or renames an attribute. A plain projection has no way to express SELECT a + 1 AS b FROM t. As for aggregation, the elementary algebra doesn’t even have that operation. It’s an extension.
So much for relational algebra!
We still have software to ship. Let’s make a couple of house rules to extend the algebra. Here’s what Project and Aggregate will mean in The IR.
- Project(R, (f1, …, fn)) → {(x1, …, xn)} takes the attributes of each tuple in R as input and emits a tuple containing the results of applying f1 through fn.
- Aggregate(R, (k1, …, km), (f1, …, fn)) → {(x1, …, xm, xm+1, …, xm+n)} groups the tuples in R by attributes k1 through km. Each output tuple contains the grouping keys followed by the results of f1 through fn for that group.
Our house rules introduce derived columns. A column read straight from a table is a base table column. One computed by Project or Aggregate is a derived column. Before we introduced these, you could trace any value in the tree all the way back to a Get. Now a column can come into existence partway up the tree. We’ve acquired something rather like scope in a programming language, and our optimizer will have to respect it.
With that settled, we can derive attributes for Project and Aggregate as well. We’ll have to make a few more changes to The IR along the way.
pub enum Operator { Project { child: Box<Self>, projects: Vec<(ScalarExpr, String)>, }, // Others}
impl Operator { fn calculate_attributes(&self, children: &[Vec<ColumnDefinition>]) -> Vec<ColumnDefinition> { match self { Operator::Project { projects, .. } => { let attributes: Vec<ColumnDefinition> = projects .iter() .map(|(expr, alias)| ColumnDefinition { name: alias.clone(), column_type: expr.column_type(), not_null: expr.nullable(), }) .collect();
attributes } Operator::Aggregate { group_by, aggr_exprs, .. } => { let mut attributes: Vec<ColumnDefinition> = group_by .iter() .map(|expr| ColumnDefinition { name: expr.name(), column_type: expr.column_type(), not_null: expr.nullable(), }) .collect();
attributes.extend(aggr_exprs.iter().map(|expr| ColumnDefinition { name: expr.name(), column_type: expr.column_type(), not_null: expr.nullable(), }));
attributes } // Others } }}We can now derive output attributes for every operator. Let’s put them to work.
Predicate pushdown is one of the most common SQL optimizations, and one of the most effective. Move a Select further down the tree and the operators above it have fewer rows to process. Done correctly, the query returns exactly the same answer. A lovely little optimization.
Let’s implement it in The IR. The algebra lets us swap a Select with a Project. There’s one catch now that we have derived columns. Before moving the Select, we have to check whether its predicate uses a column the Project creates.
fn push_down_select_project(op: &Operator) -> Option<Operator> { match op { Operator::Select { child: project @ box Operator::Project { child, projects }, predicate, } => { let project_attributes: Vec<ColumnDefinition> = derive_attributes(&project); let predicate_used_columns: Vec<String> = predicate.used_columns();
// Check if the predicate uses any column from the project. let used_derived_columns = predicate_used_columns.iter().any(|used_column| { project_attributes .iter() .any(|attr| attr.name == *used_column) });
if used_derived_columns { None } else { Some(Operator::Project { child: Box::new(Operator::Select { child: child.clone(), predicate: predicate.clone(), }), projects: projects.clone(), }) } } _ => None, }}That looks usable. Let’s try a slightly harder case, a query with a join.
Join doesn’t introduce derived columns the way Project does, which ought to make the check easier. Let’s write a rule that tries pushing a Select into the left child of a Join.
fn push_down_select_join_left(op: &Operator) -> Option<Operator> { match op { Operator::Select { child: join @ box Operator::Join { left, right, .. }, predicate, } => { let left_attributes: Vec<ColumnDefinition> = derive_attributes(&left); let predicate_used_columns: Vec<String> = predicate.used_columns();
// Check if the predicate only uses column from left. let only_left = predicate_used_columns .iter() .all(|used_column| left_attributes.iter().any(|attr| attr.name == *used_column));
if only_left { Some(Operator::Join { left: Box::new(Operator::Select { child: left.clone(), predicate: predicate.clone(), }), right: right.clone(), ..join.clone() }) } else { None } } _ => None, }}Everything looks fine so far. Now let’s run that example in PostgreSQL and see what comes back.
leiysky=# create table t(a int);CREATE TABLEleiysky=# create table t1(a int);CREATE TABLEleiysky=# insert into t values(1);INSERT 0 1leiysky=# insert into t1 values(1);INSERT 0 1leiysky=# select * from t, t1 where t.a = 1; a | a---+--- 1 | 1(1 row)The result has two attributes called a. With our current representation, how do we tell which side of the Join should get the Select? Ask each child whether it has the a that the predicate depends on, and both children say yes. A table can’t contain two columns with the same name. Two different tables are quite at liberty to have one each.
PostgreSQL takes the SQL standard seriously and handles this one just fine. Ask it for an EXPLAIN and you can see the filter land on the right input.
leiysky=# explain(verbose) select * from t, t1 where t.a = 1; QUERY PLAN---------------------------------------------------------------------- Nested Loop (cost=0.00..491.78 rows=33150 width=8) Output: t.a, t1.a -> Seq Scan on public.t1 (cost=0.00..35.50 rows=2550 width=4) Output: t1.a -> Materialize (cost=0.00..41.94 rows=13 width=4) Output: t.a -> Seq Scan on public.t (cost=0.00..41.88 rows=13 width=4) Output: t.a Filter: (t.a = 1)(9 rows)Surely a system as perfect as The IR can manage that too. Look closely at the query and you’ll see that the predicate uses a qualified name. Try the unqualified name in PostgreSQL and here’s what you get.
leiysky=# select * from t, t1 where a = 1;ERROR: column reference "a" is ambiguousLINE 1: select * from t, t1 where a = 1;In this scope a is ambiguous, but t.a is perfectly clear. Let’s try using qualified names to represent attributes. It takes a few changes.
pub struct QualifiedName(pub Vec<String>);
impl QualifiedName { /// If the current name can be used to refer another name pub fn can_refer(&self, other: &Self) -> bool { self.0.len() <= other.0.len() && self.0.iter().zip(other.0.iter()).all(|(a, b)| a == b) }}
pub struct ColumnDefinition { /// Use qualified name pub name: QualifiedName, pub column_type: Type, pub not_null: bool,}
fn resolve_attribute( attributes: &[ColumnDefinition], name: &QualifiedName,) -> Option<ColumnDefinition> { let candidates: Vec<ColumnDefinition> = attributes .iter() .filter(|attr| attr.name.can_refer(name)) .collect();
if candidates.len() == 1 { Some(candidates[0].clone()) } else if candidates.len() > 1 { panic!("Watch out, ambiguous reference found!") }else { None }}
fn push_down_select_join_left(op: &Operator) -> Option<Operator> { match op { Operator::Select { child: join @ box Operator::Join { left, right, .. }, predicate, } => { let left_attributes: Vec<ColumnDefinition> = derive_attributes(&left); let predicate_used_columns: Vec<QualifiedName> = predicate.used_columns();
// Check if the predicate only uses column from left. let only_left = predicate_used_columns .iter() .all(|used_column| resolve_attribute(&left_attributes, used_column).is_some());
if only_left { Some(Operator::Join { left: Box::new(Operator::Select { child: left.clone(), predicate: predicate.clone(), }), right: right.clone(), ..join.clone() }) } else { None } } _ => None, }}That fixes the problem we just saw. We can now handle more complicated attribute references. Are we done? Try this one.
leiysky=# select * from (select * from t1) as t, t1 where t.a = 1; a | a---+--- 1 | 1(1 row)Two inputs in the same FROM clause can’t go by the same table name, but an inline view or a CTE lets us refer to the underlying table again. In the example above, our code reaches t.a = 1 with two attributes called t1.a and none called t.a. We never handled the inline view’s alias. We’ll need a Project just to rename its attributes.
And now a mere change of name makes those columns look like derived columns, which is a nuisance of our own making when we try to push a Select through. Time to change The IR again, along with all the code that has to keep track of which name maps to which.
pub enum Operator { Project { child: Box<Self>, // (Expression, Source name, Alias) projects: Vec<(ScalarExpr, QualifiedName, QualifiedName)>, }, // Others}We could patch all that up with a little more code. Before you do, take a look at the next example. This is about where I start losing my mind.
leiysky=# select a from t natural join t1; a--- 1(1 row)
leiysky=# select t.a from t natural join t1; a--- 1(1 row)
leiysky=# select t1.a from t natural join t1; a--- 1(1 row)
leiysky=# select * from t natural join t1; a--- 1(1 row)
leiysky=# select a from t join t1 on t.a = t1.a;ERROR: column reference "a" is ambiguousLINE 1: select a from t join t1 on t.a = t1.a;Of course we can keep bolting restrictions and special cases onto The IR, then take great care to preserve every last one of them through every rewrite. Personally, I’m lazy enough to want a simpler design.
Welcome to the deep end.
The IR made simple
The IR started out small and rather elegant. Each feature gave us a reason to bolt on one more piece of information we never wanted to think about. What I wanted all along was an IR with:
- A simple algebraic structure.
- Operator nodes that can stand on their own.
- Names used only for debugging and display.
Let’s go back a step. Does The IR need names at all? We used names for attributes because we had a table schema lying around and it felt natural to reuse it. But a name carries a lot of information the optimizer doesn’t need. Much the same happens to symbol names in a compiled program. By the time it runs, you’re dealing in addresses and register numbers.
Are names really the only way to tell two attributes apart? Who designed this thing, anyway?
All an attribute needs is a unique ID. Integer or string, I don’t much care. Its job is to let us distinguish the attribute from every other one and refer to it again. Shove the whole business of name resolution into AST lowering. Just give me an attribute ID.
With that redesign, both the attribute representation and a few definitions in The IR change. We’ll use a 64-bit integer as the default attribute ID.
pub type Id = i64;
pub struct Attribute { pub id: Id, pub column_type: Type, pub nullable: Type,}
pub enum ScalarExpr { ColumnRef(Id), // Others}An ID gets its meaning from a context. In SQL IRs, there are two common choices for that context.
- Use the attribute’s position in a tuple as its local ID. The same logical attribute can have a different ID at different operators. An operator tree carries everything you need to work those IDs out, with no external state to maintain. The price is all the remapping you have to do when you transform the tree.
- Give every attribute a global ID from a shared ID generator. Now the attribute’s identity is independent of the tuple schema. You can store attributes in an unordered
HashMap<Id, Attribute>and use set operations to derive properties, which makes the bookkeeping much easier. The trade-off is that the operator tree now depends on state held outside the tree itself.
That choice has surprisingly far-reaching effects on the code for individual optimizations.
Take this rewrite, for instance.
With suitable indexes, this can avoid a full table scan.
With local IDs the implementation is straightforward. Copy the entire operator tree, then connect the two trees with a UnionAll.
With global IDs, copying a tree is a decidedly nontrivial operation. The copy has to be distinguishable from the original. Give its attributes fresh IDs and replace all the references that point to the old ones. In a sufficiently complicated query, keeping track of all that is painful.
Now consider join reordering.
Join is commutative, so we can swap its left and right children here. With global IDs the attributes form an unordered set, and the swap has no effect on attribute derivation. With local IDs, you’re back in the remapping business.
The choice also matters when representing correlated subqueries. A correlated subquery can reach outside its own scope to use an attribute. We call that use an outer reference.
Programming languages have a similar idea. A function can refer to a variable defined in an enclosing environment, and binding it to that environment lets it run with access to that variable. That’s a closure.
fn main() { let a = 1; let f = || { let b = a; // a is captured from outside println!("{}", b); }; // f is a closure
f(); // stdout: 1}With global IDs, we can tell from its attribute properties whether a subquery is correlated. With local IDs, a common solution is to carry a separate scope ID on every ColumnRef in a scalar expression. It’s fiddly to implement.
Correlated subqueries are a sizeable topic in their own right. Perhaps we’ll get to them later in the series.
Both designs have their uses. I’d make the choice based on the workload and the rewrites the optimizer needs to do. My own preference is for global IDs. Most of the time, they let me get the job done with less fuss.
Here’s how much simpler The IR gets once we switch to global IDs.
pub type Id = i64;
pub struct Context { pub id_gen: Id,}
pub struct Attribute { pub id: Id, pub column_type: Type, pub nullable: Type,}
pub type AttributeSet = HashMap<Id, Attribute>;
pub enum ScalarExpr { ColumnRef(Id), Literal(Value, Type), Function(Signature, Vec<Self>), Subquery(Quantifier, Box<Operator>),}
pub enum Operator { Get { table: String, output_columns: AttributeSet, }, Select { child: Box<Self>, predicate: ScalarExpr, }, Project { child: Box<Self>, projects: Vec<(ScalarExpr, Id)>, }, Join { kind: JoinKind, condition: ScalarExpr, left: Box<Self>, right: Box<Self>, }, UnionAll { left: Box<Self>, right: Box<Self>, }, Aggregate { group_by: Vec<ScalarExpr>, aggr_exprs: Vec<(ScalarExpr, Id)>, child: Box<Self>, },}Having handed the hard parts off to the AST lowerer, we can confidently declare The IR production-ready. It can express all the SQL operations and the usual optimizations. The API is easy to use, and you can still hold the design in your head. More importantly, nobody knows The IR better than the people who’ve read this far. If you need it to do something else, you know where to start.
Afterword
We’ve finally made it to the end.
As a first installment, this was a tour of a few SQL IR design decisions. There’ll be time for the algorithms later.
What I like about telling the story of an IR is that it can explain things the finished code never could. Picture a crooked tree by the side of a road. Everyone who walks past wonders what made it grow that way. The people who lived there when it was a sapling could tell you: someone used to hang slabs of bacon from the branches. That’s the detail that explains the whole tree. It was also such an ordinary thing to do that nobody ever thought to mention it. Admittedly, most days nobody asks.
Database development is a small field with a lot of hard-won engineering knowledge. Little of it travels by word of mouth. I’d hate to see it go the way of the know-how that once put Americans on the moon. That’s why I wanted to write this series.
Next time I’ll get into optimizer architecture.