build-a-sql-database / lesson-16.md
Lesson 16 · Parsing SQL

Expression atoms

A WHERE clause is built from expressions, and every expression bottoms out in an atom - a literal or a column reference. Today you parse those two leaves of the expression tree.

The goal

Parse a single literal or a column name into an expression node.

Start here - the target
TO DO
Scenario: Parsing literal and column-reference atoms
Giventhe expression text "42"
Whenan expression is parsed
Thenthe result is an integer-literal node holding 42
And'alice' parses to a text-literal node holding alice
And"age" parses to a column-reference node naming age
Background

WHERE age > 18 is an expression, and expressions form a tree. Before you can parse the whole tree you need its leaves - the atoms that need no further breaking down. There are three: an integer literal, a text literal, and a column reference (a bare name that will be looked up in a row at execution time).

Each atom is a distinct node type so later stages can tell them apart without re-inspecting text: an IntLit carries a number, a StrLit carries a string, a ColRef carries a name to resolve. The parser picks which to build by looking at the current token’s kind - number, string, or identifier. These three leaves are what the comparison and boolean operators you add next will hang off of.

Make it work
type Expr interface{}
type IntLit struct { Value int64 }
type StrLit struct { Value string }
type ColRef struct { Name string }
// dispatch on the current token's kind to build the right leaf
CheckpointDONE
The parser reads the leaves of an expression - literals and column references. Commit and stop here.