From 6744df846510dacab1ed6e88dbd80746f047c1c9 Mon Sep 17 00:00:00 2001 From: Boulea7 <145515129+Boulea7@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:47:17 +0800 Subject: [PATCH] Add automatic query plans with the .eqp command Refs #144 --- CHANGELOG.md | 4 ++ litecli/clibuffer.py | 3 ++ litecli/packages/special/main.py | 12 ++++- litecli/packages/special/utils.py | 4 ++ litecli/sqlexecute.py | 85 +++++++++++++++++++++++++++---- tests/test_main.py | 53 +++++++++++++++++++ 6 files changed, 148 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d91317..8c9926b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Unreleased +### Features + +- Use `.eqp on` and `.eqp off` to show or hide SQLite query plans before query results. + ### Bug Fixes - Expand `~` in configured log file paths before opening the log. diff --git a/litecli/clibuffer.py b/litecli/clibuffer.py index cd67aa8..5de61ee 100644 --- a/litecli/clibuffer.py +++ b/litecli/clibuffer.py @@ -6,6 +6,8 @@ from prompt_toolkit.filters import Condition, Filter from prompt_toolkit.application import get_app +from .packages.special.utils import QUERY_PLAN_COMMAND + def cli_is_multiline(cli: Any) -> Filter: @Condition @@ -34,6 +36,7 @@ def _multiline_exception(text: str) -> bool: return ( text.startswith("\\") # Special Command + or QUERY_PLAN_COMMAND.match(text) is not None or text.endswith(";") # Ended with a semi-colon or text.endswith("\\g") # Ended with \g or text.endswith("\\G") # Ended with \G diff --git a/litecli/packages/special/main.py b/litecli/packages/special/main.py index 08f7bd5..3b2ad3f 100644 --- a/litecli/packages/special/main.py +++ b/litecli/packages/special/main.py @@ -2,10 +2,13 @@ import logging from collections import namedtuple from enum import Enum -from typing import Any, Callable, cast +from typing import TYPE_CHECKING, Any, Callable, cast from . import export +if TYPE_CHECKING: + from litecli.sqlexecute import SQLExecute + log = logging.getLogger(__name__) try: @@ -18,6 +21,7 @@ NO_QUERY = 0 PARSED_QUERY = 1 RAW_QUERY = 2 +EXECUTOR_QUERY = 3 SpecialCommand = namedtuple( "SpecialCommand", @@ -123,7 +127,7 @@ def register_special_command( @export -def execute(cur: Any, sql: str) -> list[tuple[Any, ...]]: +def execute(cur: Any, sql: str, executor: SQLExecute | None = None) -> list[tuple[Any, ...]]: """Execute a special command and return the results. If the special command is not supported a KeyError will be raised. """ @@ -148,6 +152,10 @@ def execute(cur: Any, sql: str) -> list[tuple[Any, ...]]: ) elif special_cmd.arg_type == RAW_QUERY: return cast(list[tuple[Any, ...]], special_cmd.handler(cur=cur, query=sql)) + elif special_cmd.arg_type == EXECUTOR_QUERY: + if executor is None: + raise CommandNotFound(f"{command} requires a SQL executor") + return cast(list[tuple[Any, ...]], special_cmd.handler(executor, arg)) raise CommandNotFound(f"Command type not found: {command}") diff --git a/litecli/packages/special/utils.py b/litecli/packages/special/utils.py index 6470ee1..0208be5 100644 --- a/litecli/packages/special/utils.py +++ b/litecli/packages/special/utils.py @@ -2,9 +2,13 @@ import os +import re import subprocess +QUERY_PLAN_COMMAND = re.compile(r"\.eqp(?=[\s;]|$)", re.IGNORECASE) + + def handle_cd_command(arg: str) -> tuple[bool, str | None]: """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = "cd" diff --git a/litecli/sqlexecute.py b/litecli/sqlexecute.py index 5e52b73..9a3f75b 100644 --- a/litecli/sqlexecute.py +++ b/litecli/sqlexecute.py @@ -7,6 +7,7 @@ from urllib.parse import urlparse import sqlparse +from sqlparse import lexer, tokens try: import sqlean as _sqlite3 @@ -16,7 +17,8 @@ import sqlite3 as _sqlite3 from litecli.packages import special -from litecli.packages.special.utils import check_if_sqlitedotcommand +from litecli.packages.special.main import EXECUTOR_QUERY, special_command +from litecli.packages.special.utils import QUERY_PLAN_COMMAND, check_if_sqlitedotcommand sqlite3 = cast(Any, _sqlite3) OperationalError = sqlite3.OperationalError @@ -29,6 +31,33 @@ # }) +def _first_sql_token(sql: str) -> tuple[int, str]: + offset = 0 + for kind, value in lexer.tokenize(sql): + if kind not in tokens.Whitespace and kind not in tokens.Comment and value != "\ufeff": + return offset, value + offset += len(value) + return offset, "" + + +def _split_statements(statement: str) -> Iterable[str]: + # A saved favorite can contain several SQL statements. + if statement.startswith("\\fs"): + yield statement + return + for sql in sqlparse.split(statement): + # The .eqp shell command ends at the newline, without a semicolon. + while QUERY_PLAN_COMMAND.search(sql): + start, first = _first_sql_token(sql) + if first != "." or not QUERY_PLAN_COMMAND.match(sql, start): + break + mode, _, sql = sql[start + 4 :].partition("\n") + yield ".eqp " + mode.strip() + sql = sql.lstrip() + if sql: + yield sql + + class SQLExecute(object): databases_query = """ PRAGMA database_list @@ -61,6 +90,7 @@ class SQLExecute(object): def __init__(self, database: str | None): self.dbname: str | None = database + self.show_query_plan = False self._server_type: tuple[str, str] | None = None # Connection can be sqlite3.Connection or sqlean.sqlite3 connection. self.conn: Any | None = None @@ -108,15 +138,7 @@ def run(self, statement: str) -> Iterable[tuple]: if not statement: # Empty string yield (None, None, None, None) - # Split the sql into separate queries and run each one. - # Unless it's saving a favorite query, in which case we - # want to save them all together. - if statement.startswith("\\fs"): - components = [statement] - else: - components = sqlparse.split(statement) - - for sql in components: + for sql in _split_statements(statement): # Remove spaces, eol and semi-colons. sql = sql.rstrip(";") @@ -127,6 +149,7 @@ def run(self, statement: str) -> Iterable[tuple]: if not self.conn and not ( sql.startswith(".open") + or QUERY_PLAN_COMMAND.match(sql) or sql.lower().startswith("use") or sql.startswith("\\u") or sql.startswith("\\?") @@ -143,7 +166,7 @@ def run(self, statement: str) -> Iterable[tuple]: cur = self.conn.cursor() if self.conn else None try: # Special command _logger.debug("Trying a dbspecial command. sql: %r", sql) - for result in special.execute(cur, sql): + for result in special.execute(cur, sql, self): yield result except special.CommandNotFound: # Regular SQL if check_if_sqlitedotcommand(sql): @@ -151,9 +174,49 @@ def run(self, statement: str) -> Iterable[tuple]: else: _logger.debug("Regular sql statement. sql: %r", sql) assert cur is not None + if self.show_query_plan: + plan = self.get_query_plan(cur, sql) + if plan: + yield (plan, None, None, None) cur.execute(sql) yield self.get_result(cur) + @special_command(".eqp", ".eqp on|off", "Show the query plan before each statement's results.", arg_type=EXECUTOR_QUERY) + def set_query_plan(self, arg: str) -> list[tuple]: + mode = arg.lower() + if mode not in ("on", "off"): + return [("Usage: .eqp on|off", None, None, None)] + self.show_query_plan = mode == "on" + return [] + + def get_query_plan(self, cursor: Any, sql: str) -> str | None: + _, first = _first_sql_token(sql) + # An explicit EXPLAIN is already a result. Some PRAGMAs take effect + # when prepared, even if they are prefixed with EXPLAIN QUERY PLAN. + if first.upper() in ("", "EXPLAIN", "PRAGMA"): + return None + + cursor.execute("EXPLAIN QUERY PLAN " + sql) + if cursor.description[1][0] != "parent": + # SQLite before 3.24 supplies descriptions without parent IDs. + details = [row[3] for row in cursor] + return "\n".join(["QUERY PLAN", *details]) if details else None + + children: dict[int, list[tuple[int, str]]] = {} + for node, parent, _, detail in cursor: + children.setdefault(parent, []).append((node, detail)) + if not children: + return None + + def branches(parent: int, prefix: str) -> Iterable[str]: + siblings = children.get(parent, []) + for index, (node, detail) in enumerate(siblings, 1): + last = index == len(siblings) + yield prefix + ("`--" if last else "|--") + detail + yield from branches(node, prefix + (" " if last else "| ")) + + return "\n".join(("QUERY PLAN", *branches(0, ""))) + def get_result(self, cursor: Any) -> tuple[str | None, list | None, list | None, str]: """Get the current result's data from the cursor.""" title = headers = None diff --git a/tests/test_main.py b/tests/test_main.py index 21ad5b6..b0953dd 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -14,6 +14,7 @@ from litecli.main import LiteCli, cli from litecli.packages.special.main import COMMANDS as SPECIAL_COMMANDS +from litecli.sqlexecute import SQLExecute from .utils import create_db, db_connection, dbtest, run @@ -90,6 +91,58 @@ def test_batch_mode(executor): assert "count(*)\n3\na\nabc\n" in "".join(result.output) +def test_automatic_query_plan(): + sql = """ + CREATE TABLE items(value); + INSERT INTO items VALUES (1), (2); + .eqp on + SELECT outer_item.value, + (SELECT max(value) FROM items AS inner_item WHERE inner_item.value = outer_item.value) AS largest + FROM items AS outer_item ORDER BY value; + .eqp off + SELECT count(*) AS total FROM items; + """ + result = CliRunner().invoke(cli, ["--liteclirc", default_config_file, ":memory:", "-e", sql]) + assert result.exit_code == 0, result.output + assert result.output == ( + "QUERY PLAN\n" + "|--SCAN outer_item\n" + "|--CORRELATED SCALAR SUBQUERY 1\n" + "| `--SEARCH inner_item\n" + "`--USE TEMP B-TREE FOR ORDER BY\n" + "value\tlargest\n1\t1\n2\t2\n" + "total\n2\n" + ) + + +def test_automatic_query_plan_preserves_statement_results(executor): + LiteCli(sqlexecute=executor, liteclirc=default_config_file) + # Register another client in the same process before changing the first. + LiteCli(sqlexecute=SQLExecute(None), liteclirc=default_config_file) + list(executor.run("CREATE TABLE items(value)")) + list(executor.run("INSERT INTO items VALUES (1)")) + assert list(executor.run("SELECT value FROM items"))[0][0] is None + list(executor.run(".eqp on")) + insertion = iter(executor.run("INSERT INTO items SELECT value FROM items")) + assert next(insertion) == ("QUERY PLAN\n`--SCAN items", None, None, None) + assert executor.conn.execute("SELECT count(*) FROM items").fetchone() == (1,) + assert list(insertion) == [(None, None, None, "Query OK, 1 row affected")] + assert list(executor.run("SELECT count(*) FROM items"))[-1][1] == [(2,)] + assert list(executor.run("/* manual */ EXPLAIN QUERY PLAN SELECT value FROM items"))[0][0] is None + assert list(executor.run("PRAGMA user_version = 7"))[0][0] is None + assert list(executor.run("PRAGMA user_version"))[0][1] == [(7,)] + assert list(executor.run(".eqp unknown"))[0][0] == "Usage: .eqp on|off" + assert list(executor.run("-- comment\nSELECT value FROM items"))[0][0] == "QUERY PLAN\n`--SCAN items" + + +def test_query_plan_command_boundaries(): + sql = "-- turn plans on\n.EQP\ton\nSELECT 'first\n.eqp off' AS text;\n.eqp off\n.eqp on\n.eqp off\nSELECT 2 AS final;" + result = CliRunner().invoke(cli, ["--liteclirc", default_config_file, ":memory:", "-e", sql]) + assert result.exit_code == 0, result.output + assert result.output.count("QUERY PLAN") == 1 + assert result.output.endswith("text\nfirst\\n.eqp off\nfinal\n2\n") + + @dbtest def test_batch_mode_table(executor): run(executor, """create table test(a text)""")