|
12 | 12 | We try to push the limit to the other side of PROJECTS |
13 | 13 | """ |
14 | 14 |
|
| 15 | +from typing import Optional |
| 16 | +from typing import Set |
| 17 | + |
15 | 18 | from opteryx.connectors.capabilities import LimitPushable |
16 | 19 | from opteryx.planner.logical_planner import LogicalPlan |
17 | 20 | from opteryx.planner.logical_planner import LogicalPlanNode |
|
23 | 26 |
|
24 | 27 |
|
25 | 28 | class LimitPushdownStrategy(OptimizationStrategy): |
| 29 | + """Push LIMIT operators towards scans when it is safe to do so.""" |
| 30 | + |
| 31 | + _BARRIER_TYPES = { |
| 32 | + LogicalPlanStepType.Aggregate, |
| 33 | + LogicalPlanStepType.AggregateAndGroup, |
| 34 | + LogicalPlanStepType.Distinct, |
| 35 | + LogicalPlanStepType.Filter, |
| 36 | + LogicalPlanStepType.FunctionDataset, |
| 37 | + LogicalPlanStepType.HeapSort, |
| 38 | + LogicalPlanStepType.Limit, |
| 39 | + LogicalPlanStepType.MetadataWriter, |
| 40 | + LogicalPlanStepType.Order, |
| 41 | + LogicalPlanStepType.Set, |
| 42 | + LogicalPlanStepType.Union, |
| 43 | + } |
| 44 | + |
26 | 45 | def visit(self, node: LogicalPlanNode, context: OptimizerContext) -> OptimizerContext: |
27 | 46 | if not context.optimized_plan: |
28 | | - context.optimized_plan = context.pre_optimized_tree.copy() # type: ignore |
| 47 | + context.optimized_plan = context.pre_optimized_tree.copy() # type: ignore[arg-type] |
29 | 48 |
|
30 | 49 | if node.node_type == LogicalPlanStepType.Limit: |
31 | | - if node.offset is not None: |
32 | | - # we can't push down limits with offset |
| 50 | + if node.offset is not None or node.limit in (None, 0): |
33 | 51 | return context |
34 | 52 | node.nid = context.node_id |
| 53 | + if not hasattr(node, "pushdown_targets"): |
| 54 | + node.pushdown_targets = set(node.all_relations or []) |
35 | 55 | context.collected_limits.append(node) |
36 | 56 | return context |
37 | 57 |
|
38 | | - if ( |
39 | | - node.node_type == LogicalPlanStepType.Scan |
40 | | - and LimitPushable in node.connector.__class__.mro() |
41 | | - ): |
42 | | - for limit_node in context.collected_limits: |
43 | | - if node.relation in limit_node.all_relations: |
44 | | - self.statistics.optimization_limit_pushdown += 1 |
45 | | - context.optimized_plan.remove_node(limit_node.nid, heal=True) |
46 | | - node.limit = limit_node.limit |
47 | | - context.optimized_plan[context.node_id] = node |
48 | | - elif node.node_type in ( |
49 | | - LogicalPlanStepType.Aggregate, |
50 | | - LogicalPlanStepType.AggregateAndGroup, |
51 | | - LogicalPlanStepType.Distinct, |
52 | | - LogicalPlanStepType.Filter, |
53 | | - LogicalPlanStepType.Join, |
54 | | - LogicalPlanStepType.Order, |
55 | | - LogicalPlanStepType.Union, |
56 | | - LogicalPlanStepType.Scan, |
57 | | - ): |
58 | | - # we don't push past here |
59 | | - for limit_node in context.collected_limits: |
60 | | - self.statistics.optimization_limit_pushdown += 1 |
61 | | - context.optimized_plan.remove_node(limit_node.nid, heal=True) |
62 | | - context.optimized_plan.insert_node_after( |
63 | | - limit_node.nid, limit_node, context.node_id |
64 | | - ) |
65 | | - limit_node.columns = [] |
66 | | - context.collected_limits.clear() |
| 58 | + remaining_limits = [] |
| 59 | + for limit_node in context.collected_limits: |
| 60 | + if self._should_skip_branch(limit_node, node): |
| 61 | + remaining_limits.append(limit_node) |
| 62 | + continue |
| 63 | + |
| 64 | + if node.node_type == LogicalPlanStepType.Scan: |
| 65 | + outcome = self._apply_to_scan(limit_node, node, context) |
| 66 | + if outcome is True: |
| 67 | + continue |
| 68 | + if outcome is None: |
| 69 | + remaining_limits.append(limit_node) |
| 70 | + continue |
| 71 | + self._place_before_node(limit_node, node, context) |
| 72 | + continue |
| 73 | + |
| 74 | + if node.node_type == LogicalPlanStepType.Join: |
| 75 | + if self._refine_targets_for_join(limit_node, node): |
| 76 | + remaining_limits.append(limit_node) |
| 77 | + continue |
| 78 | + self._place_before_node(limit_node, node, context) |
| 79 | + continue |
67 | 80 |
|
| 81 | + if node.node_type in self._BARRIER_TYPES: |
| 82 | + self._place_before_node(limit_node, node, context) |
| 83 | + continue |
| 84 | + |
| 85 | + remaining_limits.append(limit_node) |
| 86 | + |
| 87 | + context.collected_limits = remaining_limits |
68 | 88 | return context |
69 | 89 |
|
70 | 90 | def complete(self, plan: LogicalPlan, context: OptimizerContext) -> LogicalPlan: |
71 | | - # No finalization needed for this strategy |
| 91 | + context.collected_limits.clear() |
72 | 92 | return plan |
73 | 93 |
|
74 | | - def should_i_run(self, plan): |
75 | | - # only run if there are LIMIT clauses in the plan |
| 94 | + def should_i_run(self, plan: LogicalPlan) -> bool: |
76 | 95 | candidates = get_nodes_of_type_from_logical_plan(plan, (LogicalPlanStepType.Limit,)) |
77 | 96 | return len(candidates) > 0 |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def _collect_relations(node: LogicalPlanNode) -> Set[str]: |
| 100 | + relations = getattr(node, "all_relations", None) |
| 101 | + if relations: |
| 102 | + return set(relations) |
| 103 | + return set() |
| 104 | + |
| 105 | + def _should_skip_branch(self, limit_node: LogicalPlanNode, node: LogicalPlanNode) -> bool: |
| 106 | + targets: Set[str] = getattr(limit_node, "pushdown_targets", set()) |
| 107 | + if not targets: |
| 108 | + return False |
| 109 | + node_relations = self._collect_relations(node) |
| 110 | + return bool(node_relations) and targets.isdisjoint(node_relations) |
| 111 | + |
| 112 | + def _apply_to_scan( |
| 113 | + self, |
| 114 | + limit_node: LogicalPlanNode, |
| 115 | + scan_node: LogicalPlanNode, |
| 116 | + context: OptimizerContext, |
| 117 | + ) -> Optional[bool]: |
| 118 | + targets: Set[str] = getattr( |
| 119 | + limit_node, "pushdown_targets", set(limit_node.all_relations or []) |
| 120 | + ) |
| 121 | + relation_names = {scan_node.relation, getattr(scan_node, "alias", None)} |
| 122 | + if targets and targets.isdisjoint({name for name in relation_names if name}): |
| 123 | + return None |
| 124 | + |
| 125 | + connector = getattr(scan_node, "connector", None) |
| 126 | + if connector and LimitPushable in connector.__class__.mro(): |
| 127 | + current_limit = getattr(scan_node, "limit", None) |
| 128 | + scan_node.limit = ( |
| 129 | + limit_node.limit if current_limit is None else min(current_limit, limit_node.limit) |
| 130 | + ) |
| 131 | + if limit_node.nid in context.optimized_plan: |
| 132 | + context.optimized_plan.remove_node(limit_node.nid, heal=True) |
| 133 | + context.optimized_plan[context.node_id] = scan_node |
| 134 | + self.statistics.optimization_limit_pushdown += 1 |
| 135 | + return True |
| 136 | + |
| 137 | + return False |
| 138 | + |
| 139 | + def _refine_targets_for_join( |
| 140 | + self, limit_node: LogicalPlanNode, join_node: LogicalPlanNode |
| 141 | + ) -> bool: |
| 142 | + join_type = getattr(join_node, "type", None) |
| 143 | + if not join_type: |
| 144 | + return False |
| 145 | + |
| 146 | + targets: Set[str] = getattr( |
| 147 | + limit_node, "pushdown_targets", set(limit_node.all_relations or []) |
| 148 | + ) |
| 149 | + if not targets: |
| 150 | + targets = set(limit_node.all_relations or []) |
| 151 | + |
| 152 | + left_relations = set(getattr(join_node, "left_relation_names", []) or []) |
| 153 | + right_relations = set(getattr(join_node, "right_relation_names", []) or []) |
| 154 | + |
| 155 | + new_targets: Optional[Set[str]] = None |
| 156 | + |
| 157 | + if join_type == "left outer": |
| 158 | + new_targets = targets & left_relations |
| 159 | + elif join_type == "right outer": |
| 160 | + new_targets = targets & right_relations |
| 161 | + elif join_type == "cross join": |
| 162 | + left_size = getattr(join_node, "left_size", float("inf")) |
| 163 | + right_size = getattr(join_node, "right_size", float("inf")) |
| 164 | + left_choice = targets & left_relations |
| 165 | + right_choice = targets & right_relations |
| 166 | + if left_choice and right_choice: |
| 167 | + new_targets = left_choice if left_size <= right_size else right_choice |
| 168 | + elif left_choice: |
| 169 | + new_targets = left_choice |
| 170 | + elif right_choice: |
| 171 | + new_targets = right_choice |
| 172 | + else: |
| 173 | + return False |
| 174 | + |
| 175 | + if not new_targets: |
| 176 | + return False |
| 177 | + |
| 178 | + limit_node.pushdown_targets = new_targets |
| 179 | + limit_node.all_relations = set(new_targets) |
| 180 | + return True |
| 181 | + |
| 182 | + def _place_before_node( |
| 183 | + self, limit_node: LogicalPlanNode, _: LogicalPlanNode, context: OptimizerContext |
| 184 | + ) -> None: |
| 185 | + if limit_node.nid in context.optimized_plan: |
| 186 | + context.optimized_plan.remove_node(limit_node.nid, heal=True) |
| 187 | + context.optimized_plan.insert_node_after(limit_node.nid, limit_node, context.node_id) |
| 188 | + limit_node.columns = [] |
| 189 | + limit_node.pushdown_targets = set(limit_node.all_relations or []) |
| 190 | + self.statistics.optimization_limit_pushdown += 1 |
0 commit comments