⚠
The web version only has simple instructions since chapter 04, while the full book has detailed explanations and background info.
0505: SELECT Expression
Modify Structs
In this step, we’ll allow expressions in SELECT and UPDATE:
select a * 4 - b, d + c from t where d = 123;
update t set a = a - b, b = a, c = d + c where d = 123;In StmtSelect, cols changes from string to interface{}. StmtUpdate is updated in a similar way, adding ExprAssign:
type StmtSelect struct {
table string
// cols []string
cols []interface{} // ExprUnOp | ExprBinOp | string | *Cell
keys []NamedCell
}
type StmtUpdate struct {
table string
keys []NamedCell
// value []ExprEqual
value []ExprAssign
}
type ExprAssign struct {
column string
expr interface{} // ExprUnOp | ExprBinOp | string | *Cell
}Modify Parser
- In
parseSelect(), replacetryName()withparseExpr(). - In
parseUpdate(), replaceparseEqual()withparseAssign().
func (p *Parser) parseAssign(out *ExprAssign) (err error) {
var ok bool
out.column, ok = p.tryName()
if !ok {
return errors.New("expect column")
}
if !p.tryPunctuation("=") {
return errors.New("expect =")
}
out.expr, err = p.parseExpr()
return err
}Modify Execution
Update select and update to call evalExpr() to produce results:
func (db *DB) execSelect(stmt *StmtSelect) ([]Row, error)
func (db *DB) execUpdate(stmt *StmtUpdate) (count int, err error)ⓘ
CodeCrafters.io has similar courses in many programming languages, including build your own Redis, SQLite, Docker, etc. It’s worth checking out.