0506: WHERE
解析 WHERE 表达式
这一步不增加功能,把 WHERE 部分改成表达式。
type StmtSelect struct {
table string
cols []interface{} // ExprUnOp | ExprBinOp | string | *Cell
// keys []NamedCell
cond interface{}
}
type StmtUpdate struct {
table string
// keys []NamedCell
cond interface{}
value []ExprAssign
}
type StmtDelete struct {
table string
// keys []NamedCell
cond interface{}
}修改语法解析:
func (p *Parser) parseSelect(out *StmtSelect) (err error) {
// ...
out.cond, err = p.parseWhere()
return err
}
func (p *Parser) parseWhere() (expr interface{}, err error)匹配表达式
执行时从表达式里识别出主键的值:
func (db *DB) execSelect(stmt *StmtSelect) ([]Row, error) {
// ...
row, err := matchPKey(&schema, stmt.cond)
if err != nil {
return nil, err
}
if ok, err = db.Select(&schema, row); err != nil {
return nil, err
}
// ...
}
func matchPKey(schema *Schema, cond interface{}) (Row, error) {
if keys, ok := matchAllEq(cond, nil); ok {
return makePKey(schema, keys)
}
return nil, errors.New("unimplemented WHERE")
}matchAllEq() 识别出 a = 123 AND b = 456 AND ... 这种表达式,输出列名和值。就是递归遍历表达式:
func matchAllEq(cond interface{}, out []NamedCell) ([]NamedCell, bool)您正在阅读免费版教程,从第4章起只有简单的指引,适合爱好挑战和自学的读者。
可以购买有详细指导+背景知识的完整版。