|
11 | 11 | from .helper import SQLHelper |
12 | 12 | from .retry import execute_with_retry |
13 | 13 | from .sql.delete_builder import DeleteExecutionPlan |
| 14 | +from .sql.explain_builder import ExplainExecutionPlan |
14 | 15 | from .sql.insert_builder import InsertExecutionPlan |
15 | 16 | from .sql.parser import SQLParser |
16 | 17 | from .sql.query_builder import QueryExecutionPlan |
@@ -758,10 +759,93 @@ def execute( |
758 | 759 | return self._execute_execution_plan(self._execution_plan, connection, parameters) |
759 | 760 |
|
760 | 761 |
|
| 762 | +class ExplainExecution(ExecutionStrategy): |
| 763 | + """Execution strategy for ``EXPLAIN [ (opt val, ...) ] <statement>`` wrappers. |
| 764 | +
|
| 765 | + Parses via :class:`SQLParser` (grammar-native EXPLAIN production) to obtain |
| 766 | + an :class:`ExplainExecutionPlan`, delegates command construction and result |
| 767 | + flattening to the plan, and runs the resulting ``explain`` command through |
| 768 | + the shared connection/retry path. |
| 769 | + """ |
| 770 | + |
| 771 | + _EXPLAIN_PATTERN = re.compile(r"^\s*EXPLAIN\b", re.IGNORECASE) |
| 772 | + |
| 773 | + @property |
| 774 | + def execution_plan(self) -> QueryExecutionPlan: |
| 775 | + return self._execution_plan |
| 776 | + |
| 777 | + def supports(self, context: ExecutionContext) -> bool: |
| 778 | + return bool(self._EXPLAIN_PATTERN.match(context.query)) |
| 779 | + |
| 780 | + def _parse_sql(self, sql: str) -> ExplainExecutionPlan: |
| 781 | + try: |
| 782 | + parser = SQLParser(sql) |
| 783 | + plan = parser.get_execution_plan() |
| 784 | + if not isinstance(plan, ExplainExecutionPlan): |
| 785 | + raise SqlSyntaxError("Expected EXPLAIN execution plan") |
| 786 | + if not plan.validate(): |
| 787 | + raise SqlSyntaxError("Generated EXPLAIN plan is invalid") |
| 788 | + return plan |
| 789 | + except SqlSyntaxError: |
| 790 | + raise |
| 791 | + except Exception as e: |
| 792 | + _logger.error(f"SQL parsing failed: {e}") |
| 793 | + raise SqlSyntaxError(f"Failed to parse SQL: {e}") |
| 794 | + |
| 795 | + def execute( |
| 796 | + self, |
| 797 | + context: ExecutionContext, |
| 798 | + connection: Any, |
| 799 | + parameters: Optional[Union[Sequence[Any], Dict[str, Any]]] = None, |
| 800 | + ) -> Optional[Dict[str, Any]]: |
| 801 | + _logger.debug(f"Using explain execution for query: {context.query[:100]}") |
| 802 | + |
| 803 | + # Normalize named parameters to positional, matching StandardQueryExecution. |
| 804 | + processed_query = context.query |
| 805 | + processed_params = parameters |
| 806 | + if isinstance(parameters, dict): |
| 807 | + param_names = re.findall(r":(\w+)", context.query) |
| 808 | + processed_params = [parameters[name] for name in param_names] |
| 809 | + processed_query = re.sub(r":(\w+)", "?", context.query) |
| 810 | + |
| 811 | + explain_plan = self._parse_sql(processed_query) |
| 812 | + # Store the synthesized result plan (QueryExecutionPlan) so the cursor |
| 813 | + # can wire it directly into the ResultSet for column description. |
| 814 | + self._execution_plan = explain_plan.result_plan |
| 815 | + |
| 816 | + # Build the explain command (validates inner plan is a supported SELECT). |
| 817 | + explain_cmd = explain_plan.build_command(processed_params) |
| 818 | + |
| 819 | + if not connection: |
| 820 | + raise OperationalError("No connection provided") |
| 821 | + |
| 822 | + _logger.debug(f"Executing MongoDB explain command: {explain_cmd}") |
| 823 | + |
| 824 | + try: |
| 825 | + explain_result = _run_db_command(connection.database, explain_cmd, connection, "explain command") |
| 826 | + except PyMongoError as e: |
| 827 | + _logger.error(f"MongoDB explain execution failed: {e}") |
| 828 | + raise DatabaseError(f"Explain execution failed: {e}") |
| 829 | + |
| 830 | + # Return flattened rows as a command result. The cursor handles |
| 831 | + # ExplainExecutionPlan -> result_plan translation when wiring the ResultSet. |
| 832 | + return { |
| 833 | + "cursor": {"id": 0, "firstBatch": explain_plan.flatten_result(explain_result)}, |
| 834 | + "ok": 1, |
| 835 | + } |
| 836 | + |
| 837 | + |
761 | 838 | class ExecutionPlanFactory: |
762 | 839 | """Factory for creating appropriate execution strategy based on query context""" |
763 | 840 |
|
764 | | - _strategies = [ViewExecution(), StandardQueryExecution(), InsertExecution(), UpdateExecution(), DeleteExecution()] |
| 841 | + _strategies = [ |
| 842 | + ExplainExecution(), |
| 843 | + ViewExecution(), |
| 844 | + StandardQueryExecution(), |
| 845 | + InsertExecution(), |
| 846 | + UpdateExecution(), |
| 847 | + DeleteExecution(), |
| 848 | + ] |
765 | 849 |
|
766 | 850 | @classmethod |
767 | 851 | def get_strategy(cls, context: ExecutionContext) -> ExecutionStrategy: |
|
0 commit comments