Skip to content

gh-133447: Add basic color to sqlite3 CLI #133461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
May 10, 2025
Merged
Show file tree
Hide file tree
Changes from 8 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
30 changes: 22 additions & 8 deletions Lib/sqlite3/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@
from argparse import ArgumentParser
from code import InteractiveConsole
from textwrap import dedent
import _colorize as colorize

def _clr(color, use_color):
if use_color:
return color
return ''

def execute(c, sql, suppress_errors=True):
def execute(c, sql, suppress_errors=True, use_color=False):
"""Helper that wraps execution of SQL code.

This is used both by the REPL and by direct execution from the CLI.
Expand All @@ -25,22 +30,27 @@ def execute(c, sql, suppress_errors=True):
for row in c.execute(sql):
print(row)
except sqlite3.Error as e:
theme = colorize.get_theme(force_color=True).traceback
tp = type(e).__name__
try:
print(f"{tp} ({e.sqlite_errorname}): {e}", file=sys.stderr)
print(f"{_clr(theme.type, use_color)}{tp} ({e.sqlite_errorname})"
f"{_clr(theme.reset, use_color)}: "
f"{_clr(theme.message, use_color)}{e}{_clr(theme.reset, use_color)}", file=sys.stderr)
except AttributeError:
print(f"{tp}: {e}", file=sys.stderr)
print(f"{_clr(theme.type, use_color)}{tp}{_clr(theme.reset, use_color)}: "
f"{_clr(theme.message, use_color)}{e}{_clr(theme.reset, use_color)}", file=sys.stderr)
if not suppress_errors:
sys.exit(1)


class SqliteInteractiveConsole(InteractiveConsole):
"""A simple SQLite REPL."""

def __init__(self, connection):
def __init__(self, connection, use_color=False):
super().__init__()
self._con = connection
self._cur = connection.cursor()
self._use_color = use_color

def runsource(self, source, filename="<input>", symbol="single"):
"""Override runsource, the core of the InteractiveConsole REPL.
Expand All @@ -58,7 +68,7 @@ def runsource(self, source, filename="<input>", symbol="single"):
case _:
if not sqlite3.complete_statement(source):
return True
execute(self._cur, source)
execute(self._cur, source, use_color=self._use_color)
return False


Expand Down Expand Up @@ -105,8 +115,12 @@ def main(*args):
Each command will be run using execute() on the cursor.
Type ".help" for more information; type ".quit" or {eofkey} to quit.
""").strip()
sys.ps1 = "sqlite> "
sys.ps2 = " ... "

use_color = colorize.can_colorize()
theme = colorize.get_theme(force_color=True).syntax

sys.ps1 = f"{_clr(theme.prompt, use_color)}sqlite> {_clr(theme.reset, use_color)}"
sys.ps2 = f"{_clr(theme.prompt, use_color)} ... {_clr(theme.reset, use_color)}"

con = sqlite3.connect(args.filename, isolation_level=None)
try:
Expand All @@ -115,7 +129,7 @@ def main(*args):
execute(con, args.sql, suppress_errors=False)
else:
# No SQL provided; start the REPL.
console = SqliteInteractiveConsole(con)
console = SqliteInteractiveConsole(con, use_color)
try:
import readline # noqa: F401
except ImportError:
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_sqlite3/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
captured_stderr,
captured_stdin,
force_not_colorized,
force_not_colorized_test_class,
)


Expand Down Expand Up @@ -69,6 +70,7 @@ def test_cli_on_disk_db(self):
self.assertIn("(0,)", out)


@force_not_colorized_test_class
class InteractiveSession(unittest.TestCase):
MEMORY_DB_MSG = "Connected to a transient in-memory database"
PS1 = "sqlite> "
Expand Down Expand Up @@ -158,6 +160,14 @@ def test_interact_on_disk_file(self):
out, _ = self.run_cli(TESTFN, commands=("SELECT count(t) FROM t;",))
self.assertIn("(0,)\n", out)

def test_color(self):
with unittest.mock.patch("_colorize.can_colorize", return_value=True):
out, err = self.run_cli(commands="\n")
self.assertIn("\x1b[1;35msqlite> \x1b[0m", out)
self.assertIn("\x1b[1;35m ... \x1b[0m\x1b", out)
out, err = self.run_cli(commands=("sel;",))
self.assertIn('\x1b[1;35mOperationalError (SQLITE_ERROR)\x1b[0m: '
'\x1b[35mnear "sel": syntax error\x1b[0m', err)

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add basic color to :mod:`sqlite3` CLI interface.
Loading