From ed0489315692a2aa710727d15f3efa70328d5247 Mon Sep 17 00:00:00 2001 From: Maxteabag Date: Fri, 27 Nov 2026 15:28:49 +0000 Subject: [PATCH] fix(cli): execute SQLite scripts in statement order Use SQLite statement boundaries and preserve existing query handling for other drivers. Based on the CLI script support proposed by Jay Hemnani (jayhemnani9910) in #352. --- README.md | 7 ++ sqlit/domains/query/cli/commands.py | 145 +++++++++++++++++++++------- tests/cli/test_cli_main.py | 88 +++++++++++++++++ 3 files changed, 207 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index fac2dbe0..e96a7a9f 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,13 @@ sqlit connections list sqlit connections delete "MyConnection" ``` +SQLite scripts can contain multiple semicolon-delimited statements, including +trigger definitions. The CLI runs them in order, stops at the first error with +a nonzero exit status, and displays only the final statement's result on +success. The CLI does not wrap the file in a transaction. Earlier committed +changes remain after an error. To group changes, use explicit `BEGIN` and +`COMMIT` statements in the file. + ## Keybindings | Key | Action | diff --git a/sqlit/domains/query/cli/commands.py b/sqlit/domains/query/cli/commands.py index c348e94c..1ebc5f65 100644 --- a/sqlit/domains/query/cli/commands.py +++ b/sqlit/domains/query/cli/commands.py @@ -4,8 +4,11 @@ import csv import json +import re +import sqlite3 import sys from collections.abc import Callable +from contextlib import closing from typing import Any from sqlit.domains.connections.app.session import ConnectionSession @@ -13,6 +16,7 @@ from sqlit.domains.connections.domain.config import ConnectionConfig from sqlit.domains.query.app.query_service import ( DialectQueryAnalyzer, + NonQueryResult, QueryKind, QueryResult, QueryService, @@ -21,6 +25,32 @@ from sqlit.shared.app.services import AppServices, build_app_services +_SQLITE_TRIVIA = re.compile(r"(?:[ \t\r\n\f;\ufeff]+|--[^\n]*|/\*.*?(?:\*/|\Z))+", re.DOTALL) + + +def _skip_sqlite_trivia(sql: str, start: int) -> int: + match = _SQLITE_TRIVIA.match(sql, start) + return match.end() if match else start + + +def _split_sqlite_script(sql: str) -> list[str]: + """Find SQLite statement boundaries, including complete trigger bodies.""" + statements = [] + start = _skip_sqlite_trivia(sql, 0) + for separator in re.finditer(";", sql): + end = separator.end() + if end <= start: + continue + statement = sql[start:end] + if "\0" not in statement and sqlite3.complete_statement(statement): + statements.append(statement) + start = _skip_sqlite_trivia(sql, end) + + if start < len(sql): + statements.append(sql[start:]) + return statements + + def _find_connection(connections: list[ConnectionConfig], name: str) -> ConnectionConfig | None: for conn in connections: if conn.name == name: @@ -100,6 +130,51 @@ def _stream_json_output(cursor: Any, columns: list[str]) -> int: return row_count +def _stream_output(cursor: Any, columns: list[str], fmt: str) -> int: + if fmt == "csv": + return _stream_csv_output(cursor, columns) + return _stream_json_output(cursor, columns) + + +def _execute_sqlite_script( + connection: sqlite3.Connection, + statements: list[str], + service: QueryService, + connection_name: str, + fmt: str, + max_rows: int | None, +) -> QueryResult | NonQueryResult | None: + # Keep SQLite's per-statement autocommit and honor explicit SQL transactions. + connection.isolation_level = None + for statement in statements[:-1]: + # SQLite may report an error while stepping through result rows. + with closing(connection.execute(statement)) as cursor: + for _ in cursor: + pass + service._save_to_history(connection_name, statement) + + statement = statements[-1] + with closing(connection.execute(statement)) as cursor: + if not cursor.description: + result = NonQueryResult(rows_affected=cursor.rowcount) + else: + columns = [col[0] for col in cursor.description] + if max_rows is None and fmt in ("csv", "json"): + row_count = _stream_output(cursor, columns, fmt) + print(f"\n({row_count} row(s) returned)", file=sys.stderr) + result = None + else: + fetched = cursor.fetchall() if max_rows is None else cursor.fetchmany(max_rows + 1) + truncated = max_rows is not None and len(fetched) > max_rows + if truncated: + for _ in cursor: + pass + rows = [tuple(row) for row in fetched[:max_rows]] + result = QueryResult(columns=columns, rows=rows, row_count=len(rows), truncated=truncated) + service._save_to_history(connection_name, statement) + return result + + def _output_table(columns: list[str], rows: list[tuple], truncated: bool) -> None: """Output query results in table format with optimized width calculation.""" max_col_width = 50 @@ -172,41 +247,45 @@ def cmd_query( try: with create_session(config) as session: - has_cursor = hasattr(session.connection, "cursor") and callable(getattr(session.connection, "cursor", None)) - - if _should_stream_results( - max_rows=max_rows, - fmt=args.format, - analyzer=analyzer, - query=query, - has_cursor=has_cursor, - ): - cursor = session.connection.cursor() - cursor.execute(query) - - if not cursor.description: - print("Query executed successfully (no results)") + statements = _split_sqlite_script(query) if config.db_type == "sqlite" else [] + if len(statements) > 1: + result = _execute_sqlite_script( + session.connection, statements, service, config.name, args.format, max_rows + ) + if result is None: + return 0 + else: + has_cursor = hasattr(session.connection, "cursor") and callable(getattr(session.connection, "cursor", None)) + + if _should_stream_results( + max_rows=max_rows, + fmt=args.format, + analyzer=analyzer, + query=query, + has_cursor=has_cursor, + ): + cursor = session.connection.cursor() + cursor.execute(query) + + if not cursor.description: + print("Query executed successfully (no results)") + return 0 + + columns = [col[0] for col in cursor.description] + + row_count = _stream_output(cursor, columns, args.format) + service._save_to_history(config.name, query) + print(f"\n({row_count} row(s) returned)", file=sys.stderr) return 0 - columns = [col[0] for col in cursor.description] - - if args.format == "csv": - row_count = _stream_csv_output(cursor, columns) - else: - row_count = _stream_json_output(cursor, columns) - - service._save_to_history(config.name, query) - print(f"\n({row_count} row(s) returned)", file=sys.stderr) - return 0 - - result = service.execute( - connection=session.connection, - executor=session.provider.query_executor, - query=query, - config=config, - max_rows=max_rows, - save_to_history=True, - ) + result = service.execute( + connection=session.connection, + executor=session.provider.query_executor, + query=query, + config=config, + max_rows=max_rows, + save_to_history=True, + ) if isinstance(result, QueryResult): columns = result.columns diff --git a/tests/cli/test_cli_main.py b/tests/cli/test_cli_main.py index 0e13e27b..99f06eb6 100644 --- a/tests/cli/test_cli_main.py +++ b/tests/cli/test_cli_main.py @@ -5,6 +5,8 @@ import sys from pathlib import Path +import pytest + from tests.conftest import run_cli @@ -249,3 +251,89 @@ def test_cli_version_short_option(tmp_path: Path): ) assert result.returncode == 0 assert "sqlit" in result.stdout + + +@pytest.fixture +def sqlite_cli(tmp_path: Path, monkeypatch): + monkeypatch.setenv("SQLIT_CONFIG_DIR", str(tmp_path)) + db = tmp_path / "demo.db" + created = run_cli("connections", "add", "sqlite", "--name", "d", "--file-path", str(db), check=False) + assert created.returncode == 0, created.stdout + created.stderr + + def query(*args: str) -> subprocess.CompletedProcess: + return run_cli("query", "-c", "d", "--format", "json", *args, check=False) + + return query + + +def test_sqlite_script_shows_only_last_result(tmp_path: Path, sqlite_cli): + script = tmp_path / "script.sql" + script.write_text( + "create table z(a int);\n" + "-- seed; comment\n" + "insert into z values (1) returning a;\n" + "/* last; result */ select a from z /* end of query */\n" + "-- trailing comment;", + encoding="utf-8", + ) + + result = sqlite_cli("-f", str(script)) + assert result.returncode == 0, result.stdout + result.stderr + assert json.loads(result.stdout) == [{"a": 1}] + + +@pytest.mark.parametrize( + ("explicit_transaction", "failing_statement", "error", "expected"), + [ + (False, "insert into z values (1)", "UNIQUE constraint failed: z.a", [{"a": 1}]), + (True, "insert into z values (1)", "UNIQUE constraint failed: z.a", []), + (False, "select abs(column1) from (values (1), (-9223372036854775808))", "integer overflow", [{"a": 1}]), + ], +) +def test_sqlite_script_stops_at_first_error( + tmp_path: Path, sqlite_cli, explicit_transaction, failing_statement, error, expected +): + setup = sqlite_cli("-q", "create table z(a int unique)") + assert setup.returncode == 0, setup.stdout + setup.stderr + script = tmp_path / "script.sql" + script.write_text( + ("begin;\n" if explicit_transaction else "") + + "insert into z values (1);\n" + + f"{failing_statement};\n" + + "insert into z values (2);\n" + + ("commit;\n" if explicit_transaction else "") + + "select * from z;", + encoding="utf-8", + ) + + result = sqlite_cli("-f", str(script)) + assert result.returncode == 1 + assert error in result.stdout + + readback = sqlite_cli("-q", "select * from z order by a") + assert readback.returncode == 0, readback.stdout + readback.stderr + assert json.loads(readback.stdout) == expected + + +@pytest.mark.parametrize("in_script", [False, True]) +def test_sqlite_trigger_body_with_internal_semicolons(tmp_path: Path, sqlite_cli, in_script): + setup = sqlite_cli("-q", "create table z(a int)") + assert setup.returncode == 0, setup.stdout + setup.stderr + trigger = ( + "create trigger log_insert after insert on z when new.a = 1 begin\n" + " insert into z values (2);\n" + " insert into z values (3);\n" + "end" + ) + script = tmp_path / "trigger.sql" + query = "insert into z values (1); select * from z order by a" + script.write_text(f"\ufeff{trigger};\n{query}" if in_script else trigger, encoding="utf-8") + + result = sqlite_cli("-f", str(script)) + assert result.returncode == 0, result.stdout + result.stderr + if not in_script: + inserted = sqlite_cli("-q", "insert into z values (1)") + assert inserted.returncode == 0, inserted.stdout + inserted.stderr + result = sqlite_cli("-q", "select * from z order by a") + assert result.returncode == 0, result.stdout + result.stderr + assert json.loads(result.stdout) == [{"a": 1}, {"a": 2}, {"a": 3}]