Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ Filter t.k = 1 (rows est=25 actual=1 time=0.02ms self=0.01ms) <-- estimate o
Estimates are recomputed bottom-up over the finished plan using the same
statistics and formulas the join orderer uses. Timing is inclusive of
children, and `self` subtracts them. `--analyze --json` emits the plan and rows
as JSON.
as JSON, with each node's operator class alongside its label.

Profiling works from outside the operators: for one run, each instance gets
its `open`, `next_row`, and `close` wrapped with counters, and the originals
Expand All @@ -197,7 +197,8 @@ python -m tinyquery --analyze "SELECT o.region, SUM(l.revenue) AS total FROM ord

`--explain` prints the plan without running it. `--analyze` runs it and reports
estimated vs actual rows per operator. `--no-reorder` turns off the cost-based
join order, for comparison.
join order, and `--no-pushdown` keeps every `WHERE` filter above the joins, for
comparison.

`--data examples` is the default. Each `*.csv` becomes a table named after the file.

Expand Down
12 changes: 11 additions & 1 deletion tests/test_explain_analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,17 @@ def test_plan_serialises_to_json():
plan = explain_analyze(star_catalog(), THREE_TABLE_SQL).plan
data = json.loads(json.dumps(plan.to_dict()))
assert data["actual_rows"] == plan.actual_rows
assert {"label", "estimated_rows", "actual_rows", "total_ms", "self_ms", "children"} <= set(data)
assert {
"label", "operator", "estimated_rows", "actual_rows", "total_ms", "self_ms", "children"
} <= set(data)
operators = {node["operator"] for node in _json_nodes(data)}
assert {"Project", "Reorder", "HashJoin", "Filter", "Scan"} <= operators


def _json_nodes(data):
yield data
for child in data["children"]:
yield from _json_nodes(child)


def test_cli_analyze_prints_estimates_and_actuals(capsys):
Expand Down
64 changes: 64 additions & 0 deletions tests/test_pushdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,67 @@ def test_pushdown_does_not_change_results():
)
by_region = {row[0]: row[1] for row in rows}
assert by_region == {"west": 10, "east": 20, "north": 3}


def test_without_pushdown_the_filter_stays_above_the_join():
plan = explain(
sample_catalog(),
"""
SELECT o.region, l.revenue
FROM orders o
JOIN lineitem l ON o.id = l.order_id
WHERE o.year = 2024 AND l.sku = 'widget'
""",
pushdown=False,
)
lines = plan.splitlines()
filter_idx = next(i for i, line in enumerate(lines) if "Filter" in line)
join_idx = next(i for i, line in enumerate(lines) if "HashJoin" in line)
assert filter_idx < join_idx
assert "Filter o.year = 2024 AND l.sku = 'widget'" in plan
assert sum("Filter" in line for line in lines) == 1


def test_pushdown_off_returns_the_same_rows():
sql = """
SELECT o.region, SUM(l.revenue) AS total
FROM orders o
JOIN lineitem l ON o.id = l.order_id
WHERE o.year = 2024 AND l.sku = 'widget'
GROUP BY o.region
"""
on, _ = execute(sample_catalog(), sql)
off, _ = execute(sample_catalog(), sql, pushdown=False)
assert sorted(on) == sorted(off)


def test_pushdown_off_feeds_the_join_more_rows():
from tinyquery.engine import explain_analyze

sql = """
SELECT o.region, l.revenue
FROM orders o
JOIN lineitem l ON o.id = l.order_id
WHERE o.year = 2024
"""

def join_input_rows(pushdown):
plan = explain_analyze(sample_catalog(), sql, pushdown=pushdown).plan
join = plan
while join.operator != "HashJoin":
join = join.children[0]
return sum(child.actual_rows for child in join.children)

assert join_input_rows(pushdown=True) < join_input_rows(pushdown=False)


def test_cli_no_pushdown_flag(capsys):
from tinyquery.cli import main

sql = (
"SELECT o.region, l.revenue FROM orders o "
"JOIN lineitem l ON o.id = l.order_id WHERE o.year = 2024"
)
assert main(["--explain", "--no-pushdown", sql]) == 0
lines = capsys.readouterr().out.splitlines()
assert lines[1].strip().startswith("Filter o.year = 2024")
12 changes: 9 additions & 3 deletions tinyquery/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ def main(argv: list[str] | None = None) -> int:
action="store_true",
help="join tables in the order written instead of asking the cost model",
)
parser.add_argument(
"--no-pushdown",
action="store_true",
help="keep WHERE filters above the joins instead of pushing them down",
)
args = parser.parse_args(argv)

catalog = Catalog()
Expand All @@ -81,9 +86,10 @@ def main(argv: list[str] | None = None) -> int:
print(f"-- {name.strip()} at version {version}", file=sys.stderr)

reorder = not args.no_reorder
pushdown = not args.no_pushdown
try:
if args.analyze:
result = explain_analyze(catalog, args.sql, reorder=reorder)
result = explain_analyze(catalog, args.sql, reorder=reorder, pushdown=pushdown)
if args.json:
print(json.dumps({
"columns": result.schema.names(),
Expand All @@ -96,9 +102,9 @@ def main(argv: list[str] | None = None) -> int:
print(f"({n} row{'s' if n != 1 else ''})")
return 0
if args.explain:
print(explain(catalog, args.sql, reorder=reorder))
print(explain(catalog, args.sql, reorder=reorder, pushdown=pushdown))
return 0
rows, schema = execute(catalog, args.sql, reorder=reorder)
rows, schema = execute(catalog, args.sql, reorder=reorder, pushdown=pushdown)
print(_format_table(rows, schema))
return 0
except TinyQueryError as exc:
Expand Down
24 changes: 16 additions & 8 deletions tinyquery/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
from tinyquery.schema import Row, Schema


def compile_sql(catalog: Catalog, sql: str, reorder: bool = True) -> Operator:
return plan(catalog, parse(sql), reorder=reorder)
def compile_sql(
catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True
) -> Operator:
return plan(catalog, parse(sql), reorder=reorder, pushdown=pushdown)


def collect(operator: Operator) -> tuple[list[Row], Schema]:
Expand All @@ -26,12 +28,16 @@ def collect(operator: Operator) -> tuple[list[Row], Schema]:
return rows, operator.schema


def execute(catalog: Catalog, sql: str, reorder: bool = True) -> tuple[list[Row], Schema]:
return collect(compile_sql(catalog, sql, reorder=reorder))
def execute(
catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True
) -> tuple[list[Row], Schema]:
return collect(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown))


def explain(catalog: Catalog, sql: str, reorder: bool = True) -> str:
return format_explain(compile_sql(catalog, sql, reorder=reorder))
def explain(
catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True
) -> str:
return format_explain(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown))


def format_explain(operator: Operator, indent: int = 0) -> str:
Expand All @@ -41,6 +47,8 @@ def format_explain(operator: Operator, indent: int = 0) -> str:
return "\n".join(lines)


def explain_analyze(catalog: Catalog, sql: str, reorder: bool = True) -> AnalyzeResult:
def explain_analyze(
catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True
) -> AnalyzeResult:
"""Run the query and return its rows plus per-operator estimates and timings."""
return profile_plan(compile_sql(catalog, sql, reorder=reorder))
return profile_plan(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown))
17 changes: 13 additions & 4 deletions tinyquery/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,17 @@


class Planner:
def __init__(self, catalog: Catalog, reorder: bool = True) -> None:
def __init__(
self, catalog: Catalog, reorder: bool = True, pushdown: bool = True
) -> None:
self.catalog = catalog
# Off means "join in the order written", which is what the planner did
# before the cost model existed. Tests and the benchmark use it to
# compare the two plans on identical inputs.
self.reorder = reorder
# Off means every WHERE predicate stays in one Filter above the joins,
# so the cost model also sees each table at its full size.
self.pushdown = pushdown

def plan(self, query: Query) -> Operator:
# Validate WHERE against the full joined schema first so ambiguous
Expand Down Expand Up @@ -105,7 +110,9 @@ def _plan_joins(
filters: dict[str, list[Expr]] = {}
for ref in refs:
scan = self._scan(ref)
pushed, conjuncts = _take_resolvable(conjuncts, scan.schema)
pushed: list[Expr] = []
if self.pushdown:
pushed, conjuncts = _take_resolvable(conjuncts, scan.schema)
filters[ref.alias] = pushed
inputs[ref.alias] = _with_filter(scan, pushed)

Expand Down Expand Up @@ -300,8 +307,10 @@ def _restore_declared_order(
return Reorder(node, indices, schema)


def plan(catalog: Catalog, query: Query, reorder: bool = True) -> Operator:
return Planner(catalog, reorder=reorder).plan(query)
def plan(
catalog: Catalog, query: Query, reorder: bool = True, pushdown: bool = True
) -> Operator:
return Planner(catalog, reorder=reorder, pushdown=pushdown).plan(query)


def _alias_schema(table: Table, alias: str) -> Schema:
Expand Down
3 changes: 3 additions & 0 deletions tinyquery/profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class PlanStats:
"""One operator's numbers, with its children's beneath it."""

label: str
operator: str # class name, e.g. "HashJoin", so a frontend need not parse labels
estimated_rows: float
actual_rows: int
total_ms: float # this operator plus everything beneath it
Expand All @@ -67,6 +68,7 @@ def misestimate(self) -> float:
def to_dict(self) -> dict[str, Any]:
return {
"label": self.label,
"operator": self.operator,
"estimated_rows": round(self.estimated_rows, 1),
"actual_rows": self.actual_rows,
"total_ms": round(self.total_ms, 3),
Expand Down Expand Up @@ -165,6 +167,7 @@ def _build(
self_ms = max(0.0, total_ms - sum(child.total_ms for child in children))
return PlanStats(
label=op.explain_label(),
operator=type(op).__name__,
estimated_rows=estimates[id(op)],
actual_rows=rows,
total_ms=total_ms,
Expand Down
Loading