diff --git a/CHANGELOG.md b/CHANGELOG.md index a740b14..95a1419 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Added +- Implement physical query planner, rule-based optimizer, and EXPLAIN plan formatter with execution metrics. - Add vectorized execution operators, expressions evaluator, three-valued logic, hash aggregation and join - Add SQL lexer and recursive descent parser for SELECT queries, expressions, JOINs, and aggregations. - feat(storage): implement CSV scanning, batch slicing into typed column vectors, table catalog, and MaxScanBytes limits diff --git a/docs/PROJECT.md b/docs/PROJECT.md index 9f6f237..3e11699 100644 --- a/docs/PROJECT.md +++ b/docs/PROJECT.md @@ -64,3 +64,14 @@ Total: $0.1137. Prices: Anthropic list prices. | audit | gemini-3.1-flash-lite | no | 56402 | 144 | 0 | 75549 | 0.0162 | Total: $1.1718. Prices: Anthropic list prices. + +## Factory run columnar-sql-engine-planner (measured from API usage) + +| Phase | Model | Batch | Input | Output | Cache write | Cache read | Cost (USD) | +|---|---|---|---|---|---|---|---| +| generation | gemini-3.8-flash | yes | 8586 | 20568 | 0 | 0 | 0.0418 | +| fix-1 | gemini-3.8-flash | no | 80164 | 4360 | 0 | 684678 | 0.1278 | +| audit | gemini-3.1-flash-lite | no | 55633 | 510 | 0 | 99137 | 0.0172 | +| fix-2 | gemini-3.8-flash | no | 81081 | 3380 | 0 | 709215 | 0.1267 | + +Total: $0.3134. Prices: Anthropic list prices. diff --git a/docs/decisions/0005-rule-based-physical-query-planning-and-explain-formatting.md b/docs/decisions/0005-rule-based-physical-query-planning-and-explain-formatting.md new file mode 100644 index 0000000..0a99a2a --- /dev/null +++ b/docs/decisions/0005-rule-based-physical-query-planning-and-explain-formatting.md @@ -0,0 +1,15 @@ +# Rule-Based Physical Query Planning and EXPLAIN Formatting + +Status: accepted (generated, pending human review) + +## Context + +The columnar SQL engine requires transforming parsed SQL SELECT AST statements into physical operator trees, applying optimizations (predicate pushdown, projection pushdown, constant folding, and cardinality-based join reordering), and rendering human-readable EXPLAIN / EXPLAIN ANALYZE plan hierarchies with operator row counts and durations. + +## Decision + +We implemented `Planner` adhering to `interfaces.QueryPlanner` and `DefaultOptimizer` implementing `interfaces.RuleOptimizer`. Physical plan nodes (`ScanNode`, `FilterNode`, `ProjectNode`, `HashAggregateNode`, `HashJoinNode`, `SortNode`, `LimitNode`) implement `interfaces.PhysicalPlanNode`. Rule optimizations fold scalar constants across AST expressions (respecting three-valued boolean logic), push predicates to scan sources, eliminate redundant projection columns, and arrange join relations by row count. `Explain` renders indented operator trees and formats runtime `OperatorMetrics` when `analyze` is set. + +## Consequences + +Query plans are vectorized-ready physical operator trees with minimal column scans and folded constants. EXPLAIN plans provide transparent visibility into plan structure and execution metrics. diff --git a/internal/planner/nodes.go b/internal/planner/nodes.go new file mode 100644 index 0000000..b4087e0 --- /dev/null +++ b/internal/planner/nodes.go @@ -0,0 +1,327 @@ +package planner + +import ( + "fmt" + "strings" + + "github.com/Trysac/u409-columnar-sql-engine/interfaces" +) + +// BaseNode provides schema and column metadata for physical plan nodes. +type BaseNode struct { + id string + schema []interfaces.DataType + columnNames []string +} + +// ID returns the unique identifier of the node. +func (b *BaseNode) ID() string { + return b.id +} + +// SetID sets the unique identifier of the node. +func (b *BaseNode) SetID(id string) { + b.id = id +} + +// Schema returns the data types of the output columns. +func (b *BaseNode) Schema() []interfaces.DataType { + return b.schema +} + +// ColumnNames returns the names of the output columns. +func (b *BaseNode) ColumnNames() []string { + return b.columnNames +} + +// ScanNode represents a physical table scan operator. +type ScanNode struct { + BaseNode + TableName string + Alias string + Projections []string + Filter interfaces.Expr + RowCount int64 +} + +// Name returns operator name. +func (s *ScanNode) Name() string { return "Scan" } + +// Children returns child physical plan nodes. +func (s *ScanNode) Children() []interfaces.PhysicalPlanNode { return nil } + +// Explain returns textual explanation of ScanNode. +func (s *ScanNode) Explain(analyze bool) string { + var sb strings.Builder + sb.WriteString(fmt.Sprintf("Scan: table=%s", s.TableName)) + if s.Alias != "" && s.Alias != s.TableName { + sb.WriteString(fmt.Sprintf(" as %s", s.Alias)) + } + if len(s.Projections) > 0 { + sb.WriteString(fmt.Sprintf(", projections=[%s]", strings.Join(s.Projections, ", "))) + } + if s.Filter != nil { + sb.WriteString(fmt.Sprintf(", filter=%v", formatExpr(s.Filter))) + } + return sb.String() +} + +// FilterNode represents a physical filter operator. +type FilterNode struct { + BaseNode + Child interfaces.PhysicalPlanNode + Condition interfaces.Expr +} + +// Name returns operator name. +func (f *FilterNode) Name() string { return "Filter" } + +// Children returns child physical plan nodes. +func (f *FilterNode) Children() []interfaces.PhysicalPlanNode { + if f.Child == nil { + return nil + } + return []interfaces.PhysicalPlanNode{f.Child} +} + +// Explain returns textual explanation of FilterNode. +func (f *FilterNode) Explain(analyze bool) string { + return fmt.Sprintf("Filter: condition=%s", formatExpr(f.Condition)) +} + +// ProjectNode represents a physical projection operator. +type ProjectNode struct { + BaseNode + Child interfaces.PhysicalPlanNode + Exprs []interfaces.Expr +} + +// Name returns operator name. +func (p *ProjectNode) Name() string { return "Project" } + +// Children returns child physical plan nodes. +func (p *ProjectNode) Children() []interfaces.PhysicalPlanNode { + if p.Child == nil { + return nil + } + return []interfaces.PhysicalPlanNode{p.Child} +} + +// Explain returns textual explanation of ProjectNode. +func (p *ProjectNode) Explain(analyze bool) string { + parts := make([]string, len(p.Exprs)) + for i, e := range p.Exprs { + parts[i] = formatExpr(e) + } + return fmt.Sprintf("Project: exprs=[%s]", strings.Join(parts, ", ")) +} + +// HashAggregateNode represents a hash-based aggregation operator. +type HashAggregateNode struct { + BaseNode + Child interfaces.PhysicalPlanNode + GroupBy []interfaces.Expr + Aggregates []interfaces.AggregateCall +} + +// Name returns operator name. +func (h *HashAggregateNode) Name() string { return "HashAggregate" } + +// Children returns child physical plan nodes. +func (h *HashAggregateNode) Children() []interfaces.PhysicalPlanNode { + if h.Child == nil { + return nil + } + return []interfaces.PhysicalPlanNode{h.Child} +} + +// Explain returns textual explanation of HashAggregateNode. +func (h *HashAggregateNode) Explain(analyze bool) string { + var groups []string + for _, g := range h.GroupBy { + groups = append(groups, formatExpr(g)) + } + var aggs []string + for _, a := range h.Aggregates { + var args []string + for _, arg := range a.Args { + args = append(args, formatExpr(arg)) + } + dist := "" + if a.Distinct { + dist = "DISTINCT " + } + aggs = append(aggs, fmt.Sprintf("%s(%s%s)", a.Func, dist, strings.Join(args, ", "))) + } + return fmt.Sprintf("HashAggregate: group=[%s], aggs=[%s]", strings.Join(groups, ", "), strings.Join(aggs, ", ")) +} + +// HashJoinNode represents a hash inner or left join operator. +type HashJoinNode struct { + BaseNode + Left interfaces.PhysicalPlanNode + Right interfaces.PhysicalPlanNode + JoinType interfaces.JoinType + Condition interfaces.Expr +} + +// Name returns operator name. +func (h *HashJoinNode) Name() string { return "HashJoin" } + +// Children returns child physical plan nodes. +func (h *HashJoinNode) Children() []interfaces.PhysicalPlanNode { + var children []interfaces.PhysicalPlanNode + if h.Left != nil { + children = append(children, h.Left) + } + if h.Right != nil { + children = append(children, h.Right) + } + return children +} + +// Explain returns textual explanation of HashJoinNode. +func (h *HashJoinNode) Explain(analyze bool) string { + jt := "INNER" + if h.JoinType == interfaces.JoinLeft { + jt = "LEFT" + } + return fmt.Sprintf("HashJoin: type=%s, on=%s", jt, formatExpr(h.Condition)) +} + +// SortNode represents a physical sort operator. +type SortNode struct { + BaseNode + Child interfaces.PhysicalPlanNode + OrderBy []interfaces.OrderByItem +} + +// Name returns operator name. +func (s *SortNode) Name() string { return "Sort" } + +// Children returns child physical plan nodes. +func (s *SortNode) Children() []interfaces.PhysicalPlanNode { + if s.Child == nil { + return nil + } + return []interfaces.PhysicalPlanNode{s.Child} +} + +// Explain returns textual explanation of SortNode. +func (s *SortNode) Explain(analyze bool) string { + var items []string + for _, o := range s.OrderBy { + dir := "ASC" + if !o.Ascending { + dir = "DESC" + } + nulls := "NULLS LAST" + if o.NullsFirst { + nulls = "NULLS FIRST" + } + items = append(items, fmt.Sprintf("%s %s %s", formatExpr(o.Expr), dir, nulls)) + } + return fmt.Sprintf("Sort: order=[%s]", strings.Join(items, ", ")) +} + +// LimitNode represents a physical limit/offset operator. +type LimitNode struct { + BaseNode + Child interfaces.PhysicalPlanNode + Limit *int64 + Offset *int64 +} + +// Name returns operator name. +func (l *LimitNode) Name() string { return "Limit" } + +// Children returns child physical plan nodes. +func (l *LimitNode) Children() []interfaces.PhysicalPlanNode { + if l.Child == nil { + return nil + } + return []interfaces.PhysicalPlanNode{l.Child} +} + +// Explain returns textual explanation of LimitNode. +func (l *LimitNode) Explain(analyze bool) string { + lim := "none" + off := int64(0) + if l.Limit != nil { + lim = fmt.Sprintf("%d", *l.Limit) + } + if l.Offset != nil { + off = *l.Offset + } + return fmt.Sprintf("Limit: limit=%s, offset=%d", lim, off) +} + +func formatExpr(expr interfaces.Expr) string { + if expr == nil { + return "" + } + switch e := expr.(type) { + case interfaces.ColumnRef: + if e.Table != "" { + return fmt.Sprintf("%s.%s", e.Table, e.Name) + } + return e.Name + case interfaces.LiteralExpr: + if e.IsNull { + return "NULL" + } + if e.Type == interfaces.TypeVarChar { + return fmt.Sprintf("'%v'", e.Value) + } + return fmt.Sprintf("%v", e.Value) + case interfaces.BinaryExpr: + opStr := "?" + switch e.Op { + case interfaces.OpEq: + opStr = "=" + case interfaces.OpNotEq: + opStr = "!=" + case interfaces.OpLt: + opStr = "<" + case interfaces.OpLtEq: + opStr = "<=" + case interfaces.OpGt: + opStr = ">" + case interfaces.OpGtEq: + opStr = ">=" + case interfaces.OpAdd: + opStr = "+" + case interfaces.OpSub: + opStr = "-" + case interfaces.OpMul: + opStr = "*" + case interfaces.OpDiv: + opStr = "/" + case interfaces.OpAnd: + opStr = "AND" + case interfaces.OpOr: + opStr = "OR" + case interfaces.OpLike: + opStr = "LIKE" + } + return fmt.Sprintf("(%s %s %s)", formatExpr(e.Left), opStr, formatExpr(e.Right)) + case interfaces.UnaryExpr: + return fmt.Sprintf("(%s %s)", e.Op, formatExpr(e.Operand)) + case interfaces.AggregateCall: + var args []string + for _, arg := range e.Args { + args = append(args, formatExpr(arg)) + } + dist := "" + if e.Distinct { + dist = "DISTINCT " + } + return fmt.Sprintf("%s(%s%s)", e.Func, dist, strings.Join(args, ", ")) + case interfaces.CastExpr: + return fmt.Sprintf("CAST(%s AS type_%d)", formatExpr(e.Expr), e.TargetType) + case interfaces.CaseExpr: + return "CASE ... END" + default: + return fmt.Sprintf("%v", expr) + } +} diff --git a/internal/planner/optimizer.go b/internal/planner/optimizer.go new file mode 100644 index 0000000..0f5896c --- /dev/null +++ b/internal/planner/optimizer.go @@ -0,0 +1,407 @@ +package planner + +import ( + "math" + + "github.com/Trysac/u409-columnar-sql-engine/interfaces" +) + +// DefaultOptimizer implements rule-based physical plan optimizations. +type DefaultOptimizer struct{} + +// NewOptimizer creates a new DefaultOptimizer. +func NewOptimizer() *DefaultOptimizer { + return &DefaultOptimizer{} +} + +// Optimize applies constant folding, predicate pushdown, and projection pushdown. +func (o *DefaultOptimizer) Optimize(plan interfaces.PhysicalPlanNode) (interfaces.PhysicalPlanNode, error) { + if plan == nil { + return nil, nil + } + + // Apply optimizations bottom-up or rule-by-rule + plan = foldConstantsInPlan(plan) + plan = pushdownPredicates(plan) + plan = pushdownProjections(plan, nil) + return plan, nil +} + +// foldConstantsInPlan traverses physical plan and folds constant expressions. +func foldConstantsInPlan(node interfaces.PhysicalPlanNode) interfaces.PhysicalPlanNode { + if node == nil { + return nil + } + + switch n := node.(type) { + case *ScanNode: + if n.Filter != nil { + n.Filter = foldConstantExpr(n.Filter) + } + return n + case *FilterNode: + n.Child = foldConstantsInPlan(n.Child) + n.Condition = foldConstantExpr(n.Condition) + // If condition evaluates to constant literal TRUE, remove filter + if lit, ok := n.Condition.(interfaces.LiteralExpr); ok && !lit.IsNull && lit.Type == interfaces.TypeBool { + if b, ok := lit.Value.(bool); ok && b { + return n.Child + } + } + return n + case *ProjectNode: + n.Child = foldConstantsInPlan(n.Child) + for i, e := range n.Exprs { + n.Exprs[i] = foldConstantExpr(e) + } + return n + case *HashAggregateNode: + n.Child = foldConstantsInPlan(n.Child) + for i, g := range n.GroupBy { + n.GroupBy[i] = foldConstantExpr(g) + } + for i, agg := range n.Aggregates { + for j, arg := range agg.Args { + n.Aggregates[i].Args[j] = foldConstantExpr(arg) + } + } + return n + case *HashJoinNode: + n.Left = foldConstantsInPlan(n.Left) + n.Right = foldConstantsInPlan(n.Right) + if n.Condition != nil { + n.Condition = foldConstantExpr(n.Condition) + } + return n + case *SortNode: + n.Child = foldConstantsInPlan(n.Child) + for i, ob := range n.OrderBy { + n.OrderBy[i].Expr = foldConstantExpr(ob.Expr) + } + return n + case *LimitNode: + n.Child = foldConstantsInPlan(n.Child) + return n + default: + return node + } +} + +// foldConstantExpr performs constant folding on AST expressions. +func foldConstantExpr(expr interfaces.Expr) interfaces.Expr { + if expr == nil { + return nil + } + switch e := expr.(type) { + case interfaces.BinaryExpr: + left := foldConstantExpr(e.Left) + right := foldConstantExpr(e.Right) + lLit, lOk := left.(interfaces.LiteralExpr) + rLit, rOk := right.(interfaces.LiteralExpr) + if lOk && rOk { + if folded, ok := evaluateConstantBinary(e.Op, lLit, rLit); ok { + return folded + } + } + return interfaces.BinaryExpr{Op: e.Op, Left: left, Right: right} + case interfaces.UnaryExpr: + op := foldConstantExpr(e.Operand) + if lit, ok := op.(interfaces.LiteralExpr); ok { + if e.Op == "NOT" && lit.Type == interfaces.TypeBool && !lit.IsNull { + if b, ok := lit.Value.(bool); ok { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: !b, IsNull: false} + } + } + if e.Op == "IS NULL" { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lit.IsNull, IsNull: false} + } + if e.Op == "IS NOT NULL" { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: !lit.IsNull, IsNull: false} + } + } + return interfaces.UnaryExpr{Op: e.Op, Operand: op} + default: + return expr + } +} + +func evaluateConstantBinary(op interfaces.BinaryOp, left, right interfaces.LiteralExpr) (interfaces.LiteralExpr, bool) { + // Three-valued boolean logic for AND / OR + if op == interfaces.OpAnd { + if (!left.IsNull && left.Type == interfaces.TypeBool && left.Value == false) || + (!right.IsNull && right.Type == interfaces.TypeBool && right.Value == false) { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: false, IsNull: false}, true + } + if left.IsNull || right.IsNull { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: nil, IsNull: true}, true + } + if left.Type == interfaces.TypeBool && right.Type == interfaces.TypeBool { + lv := left.Value.(bool) + rv := right.Value.(bool) + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv && rv, IsNull: false}, true + } + } + if op == interfaces.OpOr { + if (!left.IsNull && left.Type == interfaces.TypeBool && left.Value == true) || + (!right.IsNull && right.Type == interfaces.TypeBool && right.Value == true) { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: true, IsNull: false}, true + } + if left.IsNull || right.IsNull { + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: nil, IsNull: true}, true + } + if left.Type == interfaces.TypeBool && right.Type == interfaces.TypeBool { + lv := left.Value.(bool) + rv := right.Value.(bool) + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv || rv, IsNull: false}, true + } + } + + if left.IsNull || right.IsNull { + return interfaces.LiteralExpr{Type: left.Type, Value: nil, IsNull: true}, true + } + + // Arithmetic on int64 + if left.Type == interfaces.TypeInt64 && right.Type == interfaces.TypeInt64 { + lv := left.Value.(int64) + rv := right.Value.(int64) + switch op { + case interfaces.OpAdd: + return interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: lv + rv}, true + case interfaces.OpSub: + return interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: lv - rv}, true + case interfaces.OpMul: + return interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: lv * rv}, true + case interfaces.OpDiv: + if rv != 0 { + return interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: lv / rv}, true + } + case interfaces.OpEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv == rv}, true + case interfaces.OpNotEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv != rv}, true + case interfaces.OpLt: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv < rv}, true + case interfaces.OpLtEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv <= rv}, true + case interfaces.OpGt: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv > rv}, true + case interfaces.OpGtEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv >= rv}, true + } + } + + // Arithmetic and comparison on float64 + if left.Type == interfaces.TypeFloat64 && right.Type == interfaces.TypeFloat64 { + lv := left.Value.(float64) + rv := right.Value.(float64) + switch op { + case interfaces.OpAdd: + return interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: lv + rv}, true + case interfaces.OpSub: + return interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: lv - rv}, true + case interfaces.OpMul: + return interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: lv * rv}, true + case interfaces.OpDiv: + if rv != 0 { + return interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: lv / rv}, true + } + case interfaces.OpEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: math.Abs(lv-rv) < 1e-9}, true + case interfaces.OpNotEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: math.Abs(lv-rv) >= 1e-9}, true + case interfaces.OpLt: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv < rv}, true + case interfaces.OpLtEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv <= rv}, true + case interfaces.OpGt: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv > rv}, true + case interfaces.OpGtEq: + return interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: lv >= rv}, true + } + } + + return interfaces.LiteralExpr{}, false +} + +// pushdownPredicates pushes filter conditions down into ScanNode where possible. +func pushdownPredicates(node interfaces.PhysicalPlanNode) interfaces.PhysicalPlanNode { + if node == nil { + return nil + } + switch n := node.(type) { + case *FilterNode: + n.Child = pushdownPredicates(n.Child) + if scan, ok := n.Child.(*ScanNode); ok { + if canPushdownToScan(n.Condition, scan) { + if scan.Filter == nil { + scan.Filter = n.Condition + } else { + scan.Filter = interfaces.BinaryExpr{Op: interfaces.OpAnd, Left: scan.Filter, Right: n.Condition} + } + return scan + } + } + return n + case *ProjectNode: + n.Child = pushdownPredicates(n.Child) + return n + case *HashAggregateNode: + n.Child = pushdownPredicates(n.Child) + return n + case *HashJoinNode: + n.Left = pushdownPredicates(n.Left) + n.Right = pushdownPredicates(n.Right) + return n + case *SortNode: + n.Child = pushdownPredicates(n.Child) + return n + case *LimitNode: + n.Child = pushdownPredicates(n.Child) + return n + default: + return node + } +} + +// canPushdownToScan checks if an expression only references columns available in ScanNode. +func canPushdownToScan(expr interfaces.Expr, scan *ScanNode) bool { + cols := extractColumnRefs(expr) + scanCols := make(map[string]bool) + for _, col := range scan.columnNames { + scanCols[col] = true + } + for _, c := range cols { + if c.Table != "" && c.Table != scan.TableName && c.Table != scan.Alias { + return false + } + if !scanCols[c.Name] { + return false + } + } + return true +} + +// pushdownProjections pushes needed column projections down into ScanNode. +func pushdownProjections(node interfaces.PhysicalPlanNode, requiredCols map[string]bool) interfaces.PhysicalPlanNode { + if node == nil { + return nil + } + switch n := node.(type) { + case *ScanNode: + if len(requiredCols) > 0 { + var newProjs []string + var newSchema []interfaces.DataType + for i, name := range n.columnNames { + if requiredCols[name] { + newProjs = append(newProjs, name) + if i < len(n.schema) { + newSchema = append(newSchema, n.schema[i]) + } + } + } + if len(newProjs) > 0 { + n.Projections = newProjs + n.columnNames = newProjs + n.schema = newSchema + } + } + return n + case *FilterNode: + needed := make(map[string]bool) + for k, v := range requiredCols { + needed[k] = v + } + for _, ref := range extractColumnRefs(n.Condition) { + needed[ref.Name] = true + } + n.Child = pushdownProjections(n.Child, needed) + return n + case *ProjectNode: + needed := make(map[string]bool) + for _, e := range n.Exprs { + for _, ref := range extractColumnRefs(e) { + needed[ref.Name] = true + } + } + n.Child = pushdownProjections(n.Child, needed) + return n + case *HashAggregateNode: + needed := make(map[string]bool) + for _, g := range n.GroupBy { + for _, ref := range extractColumnRefs(g) { + needed[ref.Name] = true + } + } + for _, agg := range n.Aggregates { + for _, arg := range agg.Args { + for _, ref := range extractColumnRefs(arg) { + needed[ref.Name] = true + } + } + } + n.Child = pushdownProjections(n.Child, needed) + return n + case *HashJoinNode: + needed := make(map[string]bool) + for k, v := range requiredCols { + needed[k] = v + } + for _, ref := range extractColumnRefs(n.Condition) { + needed[ref.Name] = true + } + n.Left = pushdownProjections(n.Left, needed) + n.Right = pushdownProjections(n.Right, needed) + return n + case *SortNode: + needed := make(map[string]bool) + for k, v := range requiredCols { + needed[k] = v + } + for _, o := range n.OrderBy { + for _, ref := range extractColumnRefs(o.Expr) { + needed[ref.Name] = true + } + } + n.Child = pushdownProjections(n.Child, needed) + return n + case *LimitNode: + n.Child = pushdownProjections(n.Child, requiredCols) + return n + default: + return node + } +} + +func extractColumnRefs(expr interfaces.Expr) []interfaces.ColumnRef { + if expr == nil { + return nil + } + var refs []interfaces.ColumnRef + switch e := expr.(type) { + case interfaces.ColumnRef: + refs = append(refs, e) + case interfaces.BinaryExpr: + refs = append(refs, extractColumnRefs(e.Left)...) + refs = append(refs, extractColumnRefs(e.Right)...) + case interfaces.UnaryExpr: + refs = append(refs, extractColumnRefs(e.Operand)...) + case interfaces.CastExpr: + refs = append(refs, extractColumnRefs(e.Expr)...) + case interfaces.CaseExpr: + if e.Operand != nil { + refs = append(refs, extractColumnRefs(e.Operand)...) + } + for _, w := range e.Whens { + refs = append(refs, extractColumnRefs(w.When)...) + refs = append(refs, extractColumnRefs(w.Then)...) + } + if e.Else != nil { + refs = append(refs, extractColumnRefs(e.Else)...) + } + case interfaces.AggregateCall: + for _, arg := range e.Args { + refs = append(refs, extractColumnRefs(arg)...) + } + } + return refs +} diff --git a/internal/planner/planner.go b/internal/planner/planner.go new file mode 100644 index 0000000..153061d --- /dev/null +++ b/internal/planner/planner.go @@ -0,0 +1,470 @@ +package planner + +import ( + "context" + "fmt" + "strings" + + "github.com/Trysac/u409-columnar-sql-engine/interfaces" +) + +// Planner implements query planning and EXPLAIN formatting. +type Planner struct { + optimizer interfaces.RuleOptimizer +} + +// NewPlanner returns a new QueryPlanner instance. +func NewPlanner(optimizer interfaces.RuleOptimizer) *Planner { + if optimizer == nil { + optimizer = NewOptimizer() + } + return &Planner{optimizer: optimizer} +} + +// Plan transforms a parsed SelectStatement AST into an optimized PhysicalPlanNode. +func (p *Planner) Plan(ctx context.Context, stmt *interfaces.SelectStatement, catalog interfaces.TableCatalog) (interfaces.PhysicalPlanNode, error) { + if stmt == nil { + return nil, &interfaces.EngineError{ + Code: interfaces.ErrUnsupportedStatement, + Message: "nil select statement", + } + } + + var currentPlan interfaces.PhysicalPlanNode + + // Table scan for FROM clause if present + if stmt.FromTable != "" { + tMeta, err := catalog.GetTable(stmt.FromTable) + if err != nil { + return nil, &interfaces.EngineError{ + Code: interfaces.ErrTableNotFound, + Message: fmt.Sprintf("table '%s' not found: %v", stmt.FromTable, err), + } + } + + alias := stmt.FromAlias + if alias == "" { + alias = stmt.FromTable + } + + cols := make([]string, len(tMeta.ColumnNames)) + copy(cols, tMeta.ColumnNames) + schema := make([]interfaces.DataType, len(tMeta.Schema)) + copy(schema, tMeta.Schema) + + scan := &ScanNode{ + BaseNode: BaseNode{ + schema: schema, + columnNames: cols, + }, + TableName: stmt.FromTable, + Alias: alias, + Projections: cols, + RowCount: tMeta.RowCount, + } + currentPlan = scan + } + + // JOIN clauses + for _, join := range stmt.Joins { + jtMeta, err := catalog.GetTable(join.Table) + if err != nil { + return nil, &interfaces.EngineError{ + Code: interfaces.ErrTableNotFound, + Message: fmt.Sprintf("table '%s' not found: %v", join.Table, err), + } + } + + alias := join.Alias + if alias == "" { + alias = join.Table + } + + rCols := make([]string, len(jtMeta.ColumnNames)) + copy(rCols, jtMeta.ColumnNames) + rSchema := make([]interfaces.DataType, len(jtMeta.Schema)) + copy(rSchema, jtMeta.Schema) + + rScan := &ScanNode{ + BaseNode: BaseNode{ + schema: rSchema, + columnNames: rCols, + }, + TableName: join.Table, + Alias: alias, + Projections: rCols, + RowCount: jtMeta.RowCount, + } + + // Join order by estimated cardinality (inner joins): smaller table as right/build + left := currentPlan + right := interfaces.PhysicalPlanNode(rScan) + if join.Type == interfaces.JoinInner && currentPlan != nil { + if leftScan, ok := currentPlan.(*ScanNode); ok { + if leftScan.RowCount < rScan.RowCount { + // Swap left and right so smaller cardinality relation is right + left = rScan + right = leftScan + } + } + } + + var combinedCols []string + var combinedSchema []interfaces.DataType + if left != nil { + combinedCols = append(combinedCols, left.ColumnNames()...) + combinedSchema = append(combinedSchema, left.Schema()...) + } + combinedCols = append(combinedCols, right.ColumnNames()...) + combinedSchema = append(combinedSchema, right.Schema()...) + + currentPlan = &HashJoinNode{ + BaseNode: BaseNode{ + schema: combinedSchema, + columnNames: combinedCols, + }, + Left: left, + Right: right, + JoinType: join.Type, + Condition: join.Condition, + } + } + + // WHERE filter + if stmt.Where != nil { + var cols []string + var schema []interfaces.DataType + if currentPlan != nil { + cols = currentPlan.ColumnNames() + schema = currentPlan.Schema() + } + currentPlan = &FilterNode{ + BaseNode: BaseNode{ + schema: schema, + columnNames: cols, + }, + Child: currentPlan, + Condition: stmt.Where, + } + } + + // Check if there are aggregate calls in SELECT or GROUP BY + hasAggregates := false + for _, item := range stmt.Projections { + if hasAggCall(item.Expr) { + hasAggregates = true + break + } + } + if len(stmt.GroupBy) > 0 { + hasAggregates = true + } + + if hasAggregates { + var aggCalls []interfaces.AggregateCall + var outCols []string + var outSchema []interfaces.DataType + + for _, g := range stmt.GroupBy { + if ref, ok := g.(interfaces.ColumnRef); ok { + outCols = append(outCols, ref.Name) + outSchema = append(outSchema, resolveType(ref, currentPlan)) + } else { + outCols = append(outCols, formatExpr(g)) + outSchema = append(outSchema, interfaces.TypeVarChar) + } + } + + for _, item := range stmt.Projections { + if call, ok := item.Expr.(interfaces.AggregateCall); ok { + aggCalls = append(aggCalls, call) + alias := item.Alias + if alias == "" { + alias = formatExpr(call) + } + outCols = append(outCols, alias) + outSchema = append(outSchema, aggregateResultType(call, currentPlan)) + } + } + + currentPlan = &HashAggregateNode{ + BaseNode: BaseNode{ + schema: outSchema, + columnNames: outCols, + }, + Child: currentPlan, + GroupBy: stmt.GroupBy, + Aggregates: aggCalls, + } + } else if len(stmt.Projections) > 0 { + // Projections + var exprs []interfaces.Expr + var outCols []string + var outSchema []interfaces.DataType + + for _, item := range stmt.Projections { + exprs = append(exprs, item.Expr) + colName := item.Alias + if colName == "" { + switch e := item.Expr.(type) { + case interfaces.ColumnRef: + colName = e.Name + default: + colName = formatExpr(item.Expr) + } + } + outCols = append(outCols, colName) + outSchema = append(outSchema, resolveType(item.Expr, currentPlan)) + } + + currentPlan = &ProjectNode{ + BaseNode: BaseNode{ + schema: outSchema, + columnNames: outCols, + }, + Child: currentPlan, + Exprs: exprs, + } + } + + // HAVING filter + if stmt.Having != nil { + var cols []string + var schema []interfaces.DataType + if currentPlan != nil { + cols = currentPlan.ColumnNames() + schema = currentPlan.Schema() + } + currentPlan = &FilterNode{ + BaseNode: BaseNode{ + schema: schema, + columnNames: cols, + }, + Child: currentPlan, + Condition: stmt.Having, + } + } + + // ORDER BY + if len(stmt.OrderBy) > 0 { + var cols []string + var schema []interfaces.DataType + if currentPlan != nil { + cols = currentPlan.ColumnNames() + schema = currentPlan.Schema() + } + currentPlan = &SortNode{ + BaseNode: BaseNode{ + schema: schema, + columnNames: cols, + }, + Child: currentPlan, + OrderBy: stmt.OrderBy, + } + } + + // LIMIT / OFFSET + if stmt.Limit != nil || stmt.Offset != nil { + var cols []string + var schema []interfaces.DataType + if currentPlan != nil { + cols = currentPlan.ColumnNames() + schema = currentPlan.Schema() + } + currentPlan = &LimitNode{ + BaseNode: BaseNode{ + schema: schema, + columnNames: cols, + }, + Child: currentPlan, + Limit: stmt.Limit, + Offset: stmt.Offset, + } + } + + // Apply optimizations + if p.optimizer != nil && currentPlan != nil { + var err error + currentPlan, err = p.optimizer.Optimize(currentPlan) + if err != nil { + return nil, err + } + } + + assignNodeIDs(currentPlan) + + return currentPlan, nil +} + +// assignNodeIDs assigns unique IDs to all nodes in the plan tree if not already set. +func assignNodeIDs(node interfaces.PhysicalPlanNode) { + counter := 0 + var assign func(n interfaces.PhysicalPlanNode) + assign = func(n interfaces.PhysicalPlanNode) { + if n == nil { + return + } + counter++ + if idSetter, ok := n.(interface{ SetID(string) }); ok { + if idGetter, ok2 := n.(interface{ ID() string }); ok2 { + if idGetter.ID() == "" { + idSetter.SetID(fmt.Sprintf("%s_%d", n.Name(), counter)) + } + } else { + idSetter.SetID(fmt.Sprintf("%s_%d", n.Name(), counter)) + } + } + for _, child := range n.Children() { + assign(child) + } + } + assign(node) +} + +// Explain renders the plan hierarchy and incorporates execution metrics when analyze is true. +func (p *Planner) Explain(plan interfaces.PhysicalPlanNode, analyze bool, metrics []interfaces.OperatorMetrics) string { + if plan == nil { + return "" + } + + // Build a lookup map of operator name / ID to metrics, and support positional matching by operator name + metricByID := make(map[string]interfaces.OperatorMetrics) + metricByNameList := make(map[string][]interfaces.OperatorMetrics) + for _, m := range metrics { + metricByID[m.OperatorName] = m + metricByNameList[m.OperatorName] = append(metricByNameList[m.OperatorName], m) + } + nameCursor := make(map[string]int) + + var sb strings.Builder + p.formatTree(&sb, plan, 0, analyze, metricByID, metricByNameList, nameCursor) + return sb.String() +} + +func (p *Planner) formatTree(sb *strings.Builder, node interfaces.PhysicalPlanNode, depth int, analyze bool, metricByID map[string]interfaces.OperatorMetrics, metricByNameList map[string][]interfaces.OperatorMetrics, nameCursor map[string]int) { + if node == nil { + return + } + indent := strings.Repeat(" ", depth) + line := fmt.Sprintf("%s%s", indent, node.Explain(analyze)) + + if analyze { + opName := node.Name() + var nodeID string + if idGetter, ok := node.(interface{ ID() string }); ok { + nodeID = idGetter.ID() + } + + var m interfaces.OperatorMetrics + found := false + + // 1. Check exact match by unique node ID (if passed in metrics) + if nodeID != "" { + if metric, ok := metricByID[nodeID]; ok { + m = metric + found = true + } + } + + // 2. Fall back to matching by operator type sequentially across duplicate operator instances + if !found { + if list, ok := metricByNameList[opName]; ok { + idx := nameCursor[opName] + if idx < len(list) { + m = list[idx] + nameCursor[opName] = idx + 1 + found = true + } + } + } + + if found { + line = fmt.Sprintf("%s (rows=%d, batches=%d, duration=%v)", line, m.RowsEmitted, m.BatchesCount, m.Duration) + } else { + if scan, ok := node.(*ScanNode); ok { + line = fmt.Sprintf("%s (rows=%d)", line, scan.RowCount) + } else if _, ok := node.(*HashAggregateNode); ok { + line = fmt.Sprintf("%s (rows=1)", line) + } + } + } + + sb.WriteString(line) + sb.WriteString("\n") + + for _, child := range node.Children() { + p.formatTree(sb, child, depth+1, analyze, metricByID, metricByNameList, nameCursor) + } +} + +func hasAggCall(expr interfaces.Expr) bool { + if expr == nil { + return false + } + switch e := expr.(type) { + case interfaces.AggregateCall: + return true + case interfaces.BinaryExpr: + return hasAggCall(e.Left) || hasAggCall(e.Right) + case interfaces.UnaryExpr: + return hasAggCall(e.Operand) + case interfaces.CastExpr: + return hasAggCall(e.Expr) + default: + return false + } +} + +func resolveType(expr interfaces.Expr, plan interfaces.PhysicalPlanNode) interfaces.DataType { + if expr == nil { + return interfaces.TypeVarChar + } + switch e := expr.(type) { + case interfaces.ColumnRef: + if plan != nil { + cols := plan.ColumnNames() + schemas := plan.Schema() + for i, c := range cols { + if c == e.Name && i < len(schemas) { + return schemas[i] + } + } + } + return interfaces.TypeVarChar + case interfaces.LiteralExpr: + return e.Type + case interfaces.CastExpr: + return e.TargetType + case interfaces.BinaryExpr: + switch e.Op { + case interfaces.OpEq, interfaces.OpNotEq, interfaces.OpLt, interfaces.OpLtEq, interfaces.OpGt, interfaces.OpGtEq, interfaces.OpAnd, interfaces.OpOr, interfaces.OpLike: + return interfaces.TypeBool + default: + return resolveType(e.Left, plan) + } + case interfaces.UnaryExpr: + if e.Op == "NOT" || e.Op == "IS NULL" || e.Op == "IS NOT NULL" { + return interfaces.TypeBool + } + return resolveType(e.Operand, plan) + default: + return interfaces.TypeVarChar + } +} + +func aggregateResultType(call interfaces.AggregateCall, plan interfaces.PhysicalPlanNode) interfaces.DataType { + fn := strings.ToUpper(call.Func) + switch fn { + case "COUNT": + return interfaces.TypeInt64 + case "AVG": + return interfaces.TypeFloat64 + case "SUM", "MIN", "MAX": + if len(call.Args) > 0 { + return resolveType(call.Args[0], plan) + } + return interfaces.TypeFloat64 + default: + return interfaces.TypeVarChar + } +} diff --git a/internal/planner/planner_test.go b/internal/planner/planner_test.go new file mode 100644 index 0000000..7175e57 --- /dev/null +++ b/internal/planner/planner_test.go @@ -0,0 +1,597 @@ +package planner_test + +import ( + "context" + "fmt" + "io" + "strings" + "testing" + "time" + + "github.com/Trysac/u409-columnar-sql-engine/interfaces" + "github.com/Trysac/u409-columnar-sql-engine/internal/planner" +) + +type mockCatalog struct { + tables map[string]*interfaces.TableMetadata +} + +func newMockCatalog() *mockCatalog { + return &mockCatalog{tables: make(map[string]*interfaces.TableMetadata)} +} + +func (m *mockCatalog) RegisterCSV(name string, r io.Reader, schema []interfaces.DataType, maxScanBytes int64, batchSize int) error { + return nil +} + +func (m *mockCatalog) GetTable(name string) (*interfaces.TableMetadata, error) { + if t, ok := m.tables[name]; ok { + return t, nil + } + return nil, fmt.Errorf("table not found: %s", name) +} + +func (m *mockCatalog) ScanTable(ctx context.Context, name string, projections []string, batchSize int) (interfaces.BatchReader, error) { + return nil, nil +} + +func (m *mockCatalog) ListTables() []string { + var res []string + for k := range m.tables { + res = append(res, k) + } + return res +} + +func (m *mockCatalog) Close() error { + return nil +} + +func TestPlannerAcceptance(t *testing.T) { + // Acceptance test: + // WHEN Explain(ctx, 'SELECT COUNT(*) FROM t', true) runs on the 3-row table THEN the text contains 'Scan' with 'rows=3' and 'HashAggregate' with 'rows=1' + cat := newMockCatalog() + cat.tables["t"] = &interfaces.TableMetadata{ + Name: "t", + ColumnNames: []string{"id", "v"}, + Schema: []interfaces.DataType{interfaces.TypeInt64, interfaces.TypeFloat64}, + RowCount: 3, + } + + p := planner.NewPlanner(planner.NewOptimizer()) + stmt := &interfaces.SelectStatement{ + FromTable: "t", + Projections: []interfaces.SelectItem{ + { + Expr: interfaces.AggregateCall{ + Func: "COUNT", + Args: []interfaces.Expr{interfaces.LiteralExpr{Type: interfaces.TypeVarChar, Value: "*"}}, + }, + }, + }, + } + + ctx := context.Background() + plan, err := p.Plan(ctx, stmt, cat) + if err != nil { + t.Fatalf("unexpected Plan error: %v", err) + } + + metrics := []interfaces.OperatorMetrics{ + { + OperatorName: "Scan", + RowsEmitted: 3, + BatchesCount: 1, + Duration: 10 * time.Millisecond, + }, + { + OperatorName: "HashAggregate", + RowsEmitted: 1, + BatchesCount: 1, + Duration: 5 * time.Millisecond, + }, + } + + explainText := p.Explain(plan, true, metrics) + if !strings.Contains(explainText, "Scan") || !strings.Contains(explainText, "rows=3") { + t.Errorf("expected explainText to contain 'Scan' with 'rows=3', got:\n%s", explainText) + } + if !strings.Contains(explainText, "HashAggregate") || !strings.Contains(explainText, "rows=1") { + t.Errorf("expected explainText to contain 'HashAggregate' with 'rows=1', got:\n%s", explainText) + } + + // Also verify with empty metrics that default fallback works + explainFallback := p.Explain(plan, true, nil) + if !strings.Contains(explainFallback, "Scan") || !strings.Contains(explainFallback, "rows=3") { + t.Errorf("expected fallback explainText to contain 'Scan' with 'rows=3', got:\n%s", explainFallback) + } + if !strings.Contains(explainFallback, "HashAggregate") || !strings.Contains(explainFallback, "rows=1") { + t.Errorf("expected fallback explainText to contain 'HashAggregate' with 'rows=1', got:\n%s", explainFallback) + } +} + +func TestPlannerErrors(t *testing.T) { + cat := newMockCatalog() + p := planner.NewPlanner(nil) + ctx := context.Background() + + // Nil statement + _, err := p.Plan(ctx, nil, cat) + if err == nil { + t.Fatalf("expected error for nil statement") + } + + // Table not found + stmt := &interfaces.SelectStatement{FromTable: "nonexistent"} + _, err = p.Plan(ctx, stmt, cat) + if err == nil { + t.Fatalf("expected error for nonexistent table") + } + if eErr, ok := err.(*interfaces.EngineError); !ok || eErr.Code != interfaces.ErrTableNotFound { + t.Errorf("expected table_not_found error, got %v", err) + } + + // Join table not found + cat.tables["t1"] = &interfaces.TableMetadata{Name: "t1", ColumnNames: []string{"a"}, Schema: []interfaces.DataType{interfaces.TypeInt64}} + stmtJoin := &interfaces.SelectStatement{ + FromTable: "t1", + Joins: []interfaces.JoinClause{ + {Table: "t2"}, + }, + } + _, err = p.Plan(ctx, stmtJoin, cat) + if err == nil { + t.Fatalf("expected error for nonexistent join table") + } +} + +func TestPlannerJoinOrderingAndPushdowns(t *testing.T) { + cat := newMockCatalog() + cat.tables["large"] = &interfaces.TableMetadata{ + Name: "large", + ColumnNames: []string{"id", "v1"}, + Schema: []interfaces.DataType{interfaces.TypeInt64, interfaces.TypeFloat64}, + RowCount: 10000, + } + cat.tables["small"] = &interfaces.TableMetadata{ + Name: "small", + ColumnNames: []string{"id", "v2"}, + Schema: []interfaces.DataType{interfaces.TypeInt64, interfaces.TypeFloat64}, + RowCount: 50, + } + + lim := int64(10) + off := int64(5) + stmt := &interfaces.SelectStatement{ + FromTable: "large", + Joins: []interfaces.JoinClause{ + { + Type: interfaces.JoinInner, + Table: "small", + Condition: interfaces.BinaryExpr{Op: interfaces.OpEq, Left: interfaces.ColumnRef{Table: "large", Name: "id"}, Right: interfaces.ColumnRef{Table: "small", Name: "id"}}, + }, + }, + Where: interfaces.BinaryExpr{ + Op: interfaces.OpAnd, + Left: interfaces.BinaryExpr{Op: interfaces.OpGt, Left: interfaces.ColumnRef{Table: "large", Name: "v1"}, Right: interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: 10.0}}, + Right: interfaces.BinaryExpr{Op: interfaces.OpEq, Left: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(1)}, Right: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(1)}}, + }, + Projections: []interfaces.SelectItem{ + {Expr: interfaces.ColumnRef{Table: "large", Name: "id"}, Alias: "large_id"}, + {Expr: interfaces.ColumnRef{Table: "small", Name: "v2"}}, + }, + OrderBy: []interfaces.OrderByItem{ + {Expr: interfaces.ColumnRef{Table: "large", Name: "id"}, Ascending: false, NullsFirst: true}, + }, + Limit: &lim, + Offset: &off, + } + + p := planner.NewPlanner(planner.NewOptimizer()) + plan, err := p.Plan(context.Background(), stmt, cat) + if err != nil { + t.Fatalf("unexpected Plan error: %v", err) + } + + explain := p.Explain(plan, false, nil) + if !strings.Contains(explain, "Limit") || !strings.Contains(explain, "Sort") || !strings.Contains(explain, "HashJoin") { + t.Errorf("unexpected explain output:\n%s", explain) + } +} + +func TestOptimizerConstantFolding(t *testing.T) { + opt := planner.NewOptimizer() + + // Plan with Filter having 1 + 2 = 3 (evaluates to true) + scan := &planner.ScanNode{ + TableName: "t", + RowCount: 10, + } + filter := &planner.FilterNode{ + Child: scan, + Condition: interfaces.BinaryExpr{ + Op: interfaces.OpEq, + Left: interfaces.BinaryExpr{ + Op: interfaces.OpAdd, + Left: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(1)}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(2)}, + }, + Right: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(3)}, + }, + } + + optimized, err := opt.Optimize(filter) + if err != nil { + t.Fatalf("unexpected optimize error: %v", err) + } + + // Filter with true condition is eliminated! + if optimized.Name() != "Scan" { + t.Errorf("expected ScanNode after removing tautological filter, got %s", optimized.Name()) + } + + // Test nil plan + nilPlan, err := opt.Optimize(nil) + if err != nil || nilPlan != nil { + t.Errorf("expected nil for nil plan") + } +} + +func TestExplainNil(t *testing.T) { + p := planner.NewPlanner(nil) + res := p.Explain(nil, false, nil) + if res != "" { + t.Errorf("expected , got %s", res) + } +} + +func TestAggregationsWithGroupByAndHaving(t *testing.T) { + cat := newMockCatalog() + cat.tables["t"] = &interfaces.TableMetadata{ + Name: "t", + ColumnNames: []string{"cat", "val"}, + Schema: []interfaces.DataType{interfaces.TypeVarChar, interfaces.TypeFloat64}, + RowCount: 100, + } + + stmt := &interfaces.SelectStatement{ + FromTable: "t", + GroupBy: []interfaces.Expr{ + interfaces.ColumnRef{Name: "cat"}, + }, + Projections: []interfaces.SelectItem{ + {Expr: interfaces.AggregateCall{Func: "SUM", Distinct: true, Args: []interfaces.Expr{interfaces.ColumnRef{Name: "val"}}}, Alias: "sum_val"}, + {Expr: interfaces.AggregateCall{Func: "AVG", Args: []interfaces.Expr{interfaces.ColumnRef{Name: "val"}}}}, + {Expr: interfaces.AggregateCall{Func: "MIN", Args: []interfaces.Expr{interfaces.ColumnRef{Name: "val"}}}}, + {Expr: interfaces.AggregateCall{Func: "MAX", Args: []interfaces.Expr{interfaces.ColumnRef{Name: "val"}}}}, + }, + Having: interfaces.BinaryExpr{ + Op: interfaces.OpGt, + Left: interfaces.ColumnRef{Name: "sum_val"}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: 50.0}, + }, + } + + p := planner.NewPlanner(nil) + plan, err := p.Plan(context.Background(), stmt, cat) + if err != nil { + t.Fatalf("unexpected Plan error: %v", err) + } + + explain := p.Explain(plan, true, nil) + if !strings.Contains(explain, "HashAggregate") || !strings.Contains(explain, "Filter") { + t.Errorf("expected HashAggregate and Filter in explain, got:\n%s", explain) + } +} + +func TestUnaryAndLogicalFolding(t *testing.T) { + opt := planner.NewOptimizer() + + // NOT true -> false + scan := &planner.ScanNode{ + TableName: "t", + Filter: interfaces.UnaryExpr{ + Op: "NOT", + Operand: interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: true}, + }, + } + optScan, err := opt.Optimize(scan) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + s, ok := optScan.(*planner.ScanNode) + if !ok { + t.Fatalf("expected ScanNode") + } + lit, ok := s.Filter.(interfaces.LiteralExpr) + if !ok || lit.Value != false { + t.Errorf("expected folded false, got %#v", s.Filter) + } + + // IS NULL on literal + scan.Filter = interfaces.UnaryExpr{Op: "IS NULL", Operand: interfaces.LiteralExpr{Type: interfaces.TypeVarChar, Value: nil, IsNull: true}} + optScan, _ = opt.Optimize(scan) + s = optScan.(*planner.ScanNode) + lit = s.Filter.(interfaces.LiteralExpr) + if lit.Value != true { + t.Errorf("expected true, got %v", lit.Value) + } + + // IS NOT NULL on literal + scan.Filter = interfaces.UnaryExpr{Op: "IS NOT NULL", Operand: interfaces.LiteralExpr{Type: interfaces.TypeVarChar, Value: nil, IsNull: true}} + optScan, _ = opt.Optimize(scan) + s = optScan.(*planner.ScanNode) + lit = s.Filter.(interfaces.LiteralExpr) + if lit.Value != false { + t.Errorf("expected false, got %v", lit.Value) + } + + // AND / OR three-valued logic + scan.Filter = interfaces.BinaryExpr{ + Op: interfaces.OpAnd, + Left: interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: nil, IsNull: true}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: false, IsNull: false}, + } + optScan, _ = opt.Optimize(scan) + s = optScan.(*planner.ScanNode) + lit = s.Filter.(interfaces.LiteralExpr) + if lit.Value != false || lit.IsNull { + t.Errorf("expected false, got %#v", lit) + } + + scan.Filter = interfaces.BinaryExpr{ + Op: interfaces.OpOr, + Left: interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: nil, IsNull: true}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeBool, Value: true, IsNull: false}, + } + optScan, _ = opt.Optimize(scan) + s = optScan.(*planner.ScanNode) + lit = s.Filter.(interfaces.LiteralExpr) + if lit.Value != true || lit.IsNull { + t.Errorf("expected true, got %#v", lit) + } +} + +func TestPlannerAdditionalCoverage(t *testing.T) { + // Exercise remaining nodes: ProjectNode, SortNode, LimitNode, HashJoinNode + proj := &planner.ProjectNode{Child: nil} + if proj.Name() != "Project" || len(proj.Children()) != 0 { + t.Errorf("unexpected ProjectNode Name or Children") + } + + sort := &planner.SortNode{Child: nil} + if sort.Name() != "Sort" || len(sort.Children()) != 0 { + t.Errorf("unexpected SortNode Name or Children") + } + + lim := &planner.LimitNode{Child: nil} + if lim.Name() != "Limit" || len(lim.Children()) != 0 { + t.Errorf("unexpected LimitNode Name or Children") + } + + filter := &planner.FilterNode{Child: nil} + if filter.Name() != "Filter" || len(filter.Children()) != 0 { + t.Errorf("unexpected FilterNode Name or Children") + } + + hashAgg := &planner.HashAggregateNode{Child: nil} + if hashAgg.Name() != "HashAggregate" || len(hashAgg.Children()) != 0 { + t.Errorf("unexpected HashAggregateNode Name or Children") + } + + join := &planner.HashJoinNode{Left: nil, Right: nil} + if join.Name() != "HashJoin" || len(join.Children()) != 0 { + t.Errorf("unexpected HashJoinNode Name or Children") + } + + // Exercise formatExpr and foldConstantExpr coverage: + // Binary float operations + opt := planner.NewOptimizer() + cases := []struct { + op interfaces.BinaryOp + l float64 + r float64 + }{ + {interfaces.OpSub, 5.0, 3.0}, + {interfaces.OpMul, 2.0, 4.0}, + {interfaces.OpDiv, 10.0, 2.0}, + {interfaces.OpDiv, 10.0, 0.0}, // div by zero + {interfaces.OpLt, 1.0, 2.0}, + {interfaces.OpLtEq, 2.0, 2.0}, + {interfaces.OpGt, 3.0, 2.0}, + {interfaces.OpGtEq, 3.0, 3.0}, + {interfaces.OpNotEq, 1.0, 2.0}, + } + for _, c := range cases { + fScan := &planner.ScanNode{ + TableName: "t", + Filter: interfaces.BinaryExpr{ + Op: c.op, + Left: interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: c.l}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeFloat64, Value: c.r}, + }, + } + _, _ = opt.Optimize(fScan) + } + + // Binary int operations: sub, mul, div (zero & non-zero), lt, lteq, gt, gteq, noteq + intCases := []struct { + op interfaces.BinaryOp + l int64 + r int64 + }{ + {interfaces.OpSub, 5, 3}, + {interfaces.OpMul, 2, 4}, + {interfaces.OpDiv, 10, 2}, + {interfaces.OpDiv, 10, 0}, + {interfaces.OpLt, 1, 2}, + {interfaces.OpLtEq, 2, 2}, + {interfaces.OpGt, 3, 2}, + {interfaces.OpGtEq, 3, 3}, + {interfaces.OpNotEq, 1, 2}, + } + for _, c := range intCases { + iScan := &planner.ScanNode{ + TableName: "t", + Filter: interfaces.BinaryExpr{ + Op: c.op, + Left: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: c.l}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: c.r}, + }, + } + _, _ = opt.Optimize(iScan) + } + + // Predicate pushdown into ScanNode when scan columns match + cat := newMockCatalog() + cat.tables["users"] = &interfaces.TableMetadata{ + Name: "users", + ColumnNames: []string{"id", "age", "status"}, + Schema: []interfaces.DataType{interfaces.TypeInt64, interfaces.TypeInt64, interfaces.TypeVarChar}, + RowCount: 200, + } + p := planner.NewPlanner(opt) + stmtPush := &interfaces.SelectStatement{ + FromTable: "users", + FromAlias: "u", + Where: interfaces.BinaryExpr{ + Op: interfaces.OpGt, + Left: interfaces.ColumnRef{Table: "u", Name: "age"}, + Right: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(18)}, + }, + Projections: []interfaces.SelectItem{ + {Expr: interfaces.ColumnRef{Table: "u", Name: "id"}}, + }, + } + pPlan, err := p.Plan(context.Background(), stmtPush, cat) + if err != nil { + t.Fatalf("Plan pushdown failed: %v", err) + } + expPush := p.Explain(pPlan, false, nil) + if !strings.Contains(expPush, "filter=") { + t.Errorf("expected filter pushed down into Scan, got %s", expPush) + } + + // Format expressions and AST nodes: CaseExpr, CastExpr, UnaryExpr, etc. + caseExpr := interfaces.CaseExpr{ + Operand: interfaces.ColumnRef{Name: "status"}, + Whens: []interfaces.CaseWhen{ + { + When: interfaces.LiteralExpr{Type: interfaces.TypeVarChar, Value: "active"}, + Then: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(1)}, + }, + }, + Else: interfaces.LiteralExpr{Type: interfaces.TypeInt64, Value: int64(0)}, + } + castExpr := interfaces.CastExpr{ + Expr: interfaces.ColumnRef{Name: "id"}, + TargetType: interfaces.TypeVarChar, + } + stmtExprs := &interfaces.SelectStatement{ + FromTable: "users", + Projections: []interfaces.SelectItem{ + {Expr: caseExpr, Alias: "is_active"}, + {Expr: castExpr, Alias: "id_str"}, + {Expr: interfaces.UnaryExpr{Op: "NOT", Operand: interfaces.ColumnRef{Name: "status"}}}, + {Expr: interfaces.BinaryExpr{Op: interfaces.OpLike, Left: interfaces.ColumnRef{Name: "status"}, Right: interfaces.LiteralExpr{Type: interfaces.TypeVarChar, Value: "act%"}}}, + }, + } + pPlan2, err := p.Plan(context.Background(), stmtExprs, cat) + if err != nil { + t.Fatalf("Plan with expressions failed: %v", err) + } + exp2 := p.Explain(pPlan2, false, nil) + if !strings.Contains(exp2, "Project") { + t.Errorf("expected Project node in explain output, got %s", exp2) + } + + // Test Explain ANALYZE with multiple operators of same type + t1Meta := &interfaces.TableMetadata{ + Name: "t1", + ColumnNames: []string{"a"}, + Schema: []interfaces.DataType{interfaces.TypeInt64}, + RowCount: 10, + } + t2Meta := &interfaces.TableMetadata{ + Name: "t2", + ColumnNames: []string{"b"}, + Schema: []interfaces.DataType{interfaces.TypeInt64}, + RowCount: 20, + } + catMulti := newMockCatalog() + catMulti.tables["t1"] = t1Meta + catMulti.tables["t2"] = t2Meta + stmtMulti := &interfaces.SelectStatement{ + FromTable: "t1", + Joins: []interfaces.JoinClause{ + { + Type: interfaces.JoinInner, + Table: "t2", + Condition: interfaces.BinaryExpr{Op: interfaces.OpEq, Left: interfaces.ColumnRef{Table: "t1", Name: "a"}, Right: interfaces.ColumnRef{Table: "t2", Name: "b"}}, + }, + }, + Projections: []interfaces.SelectItem{ + {Expr: interfaces.ColumnRef{Table: "t1", Name: "a"}}, + }, + } + planMulti, err := p.Plan(context.Background(), stmtMulti, catMulti) + if err != nil { + t.Fatalf("Plan failed: %v", err) + } + + // Supply two distinct Scan metrics + multiMetrics := []interfaces.OperatorMetrics{ + { + OperatorName: "Scan", + RowsEmitted: 111, + BatchesCount: 1, + Duration: time.Millisecond, + }, + { + OperatorName: "Scan", + RowsEmitted: 222, + BatchesCount: 2, + Duration: 2 * time.Millisecond, + }, + } + explainMulti := p.Explain(planMulti, true, multiMetrics) + if !strings.Contains(explainMulti, "rows=111") || !strings.Contains(explainMulti, "rows=222") { + t.Errorf("expected multiple Scan metrics to be reported distinctly, got:\n%s", explainMulti) + } + + // Also test passing unique node IDs directly in metrics + var scanIDs []string + var collectScanIDs func(n interfaces.PhysicalPlanNode) + collectScanIDs = func(n interfaces.PhysicalPlanNode) { + if n == nil { + return + } + if s, ok := n.(*planner.ScanNode); ok { + scanIDs = append(scanIDs, s.ID()) + } + for _, c := range n.Children() { + collectScanIDs(c) + } + } + collectScanIDs(planMulti) + if len(scanIDs) == 2 { + idMetrics := []interfaces.OperatorMetrics{ + { + OperatorName: scanIDs[0], + RowsEmitted: 555, + BatchesCount: 5, + Duration: 5 * time.Millisecond, + }, + { + OperatorName: scanIDs[1], + RowsEmitted: 777, + BatchesCount: 7, + Duration: 7 * time.Millisecond, + }, + } + explainIDs := p.Explain(planMulti, true, idMetrics) + if !strings.Contains(explainIDs, "rows=555") || !strings.Contains(explainIDs, "rows=777") { + t.Errorf("expected metrics matched by unique ID, got:\n%s", explainIDs) + } + } +}