⚠
The web version only has simple instructions since chapter 04, while the full book has detailed explanations and background info.
0502: Expression Evaluation
Interpreter
We can now add computation to SELECT and UPDATE statements:
select a + b, c * d from t where a = 123;
update t set x = x + 1 where a = 123;In the previous step, expressions were parsed into a tree structure. During evaluation, we must compute subtrees first, then compute the current node. So this is a recursive function that walks a tree:
func evalExpr(schema *Schema, row Row, expr interface{}) (*Cell, error) {
switch e := expr.(type) {
case string:
// TODO
case *Cell:
return e, nil
case *ExprBinOp:
left, err := evalExpr(schema, row, e.left)
if err != nil {
return nil, err
}
right, err := evalExpr(schema, row, e.right)
if err != nil {
return nil, err
}
// TODO
default:
panic("unreachable")
}
}The evalExpr() function takes column data (schema, row), uses a switch to check the expression type, and returns the computed result (*Cell).
ⓘ
CodeCrafters.io has similar courses in many programming languages, including build your own Redis, SQLite, Docker, etc. It’s worth checking out.