Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Bug Fixes

- Support `.schema --indent` to display table columns, constraints, and indexed expressions on separate lines.
- Expand `~` in configured log file paths before opening the log.

### Internal
Expand Down
51 changes: 48 additions & 3 deletions litecli/packages/special/dbcommands.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import csv
import logging
import os
import re
import sys
import platform
import shlex
Expand Down Expand Up @@ -103,16 +104,58 @@ def list_views(
return [(None, views, headers, status)]


# Skip quoted SQL and comments when looking for punctuation between column definitions.
_SCHEMA_TOKENS = re.compile(
r"""'[^']*'|"[^"]*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|/\*.*?\*/|[(),]""",
re.DOTALL,
)


def _indent_schema(sql: str) -> str:
"""Indent the outer column list, preserving SQL expressions and quoted text."""
if not sql.startswith(("CREATE TABLE ", "CREATE INDEX ", "CREATE UNIQUE INDEX ")):
return sql

sql_whitespace = " \t\n\f\r"
lines = []
depth = 0
start = 0
for match in _SCHEMA_TOKENS.finditer(sql):
token = match.group()
if token == "(":
depth += 1
if depth == 1:
lines.append(sql[: match.end()])
start = match.end()
elif token == "," and depth == 1:
lines.append(" " + sql[start : match.end()].lstrip(sql_whitespace))
start = match.end()
elif token == ")":
depth -= 1
if depth == 0:
if len(lines) == 1: # A single column needs no line breaks.
return sql
lines.append(" " + sql[start : match.start()].strip(sql_whitespace))
lines.append(sql[match.start() :])
return "\n".join(lines)
return sql


@special_command(
".schema",
".schema[+] [table]",
".schema[+] [--indent] [table]",
"The complete schema for the database or a single table",
arg_type=PARSED_QUERY,
case_sensitive=True,
)
def show_schema(cur: DBCursor, arg: str | None = None, **_: Any) -> list[tuple]:
if arg:
args: tuple[str, ...] = (arg,)
# The table name can contain spaces, so only recognize the option at either end.
table, indent = re.subn(r"^--indent(?:\s+|$)|\s+--indent$", "", arg or "")
if table:
if len(table) >= 2 and table[0] in ('"', "'") and table[0] == table[-1]:
quote = table[0]
table = table[1:-1].replace(quote * 2, quote)
args: tuple[str, ...] = (table,)
query = """
SELECT sql FROM sqlite_master
WHERE tbl_name==? AND sql IS NOT NULL
Expand All @@ -129,6 +172,8 @@ def show_schema(cur: DBCursor, arg: str | None = None, **_: Any) -> list[tuple]:
log.debug(query)
cur.execute(query, args)
tables = cur.fetchall()
if indent:
tables = [(_indent_schema(sql),) for (sql,) in tables]
status = ""
if cur.description:
headers = [x[0] for x in cur.description]
Expand Down
53 changes: 53 additions & 0 deletions tests/test_dbspecial.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import pytest

from litecli.packages.completion_engine import suggest_type
from litecli.packages.special.utils import check_if_sqlitedotcommand, format_uptime

Expand Down Expand Up @@ -101,3 +103,54 @@ def test_special_d_w_arg(executor):
assert_result_equal(
results, headers=["cid", "name", "type", "notnull", "dflt_value", "pk"], rows=[(0, "a", "TEXT", 0, None, 0)], status=""
)


@dbtest
@pytest.mark.parametrize("command", [".schema runstats --indent", ".schema --indent runstats"])
def test_schema_indent_table(executor, command):
run(executor, """CREATE TABLE runstats("run,id" INTEGER, label TEXT DEFAULT 'a,b', CHECK("run,id" IN (1, 2)))""")
index = 'CREATE INDEX runstats_id ON runstats("run,id")'
run(executor, index)
run(executor, "CREATE TABLE other(id)")

table = """CREATE TABLE runstats(
"run,id" INTEGER,
label TEXT DEFAULT 'a,b',
CHECK("run,id" IN (1, 2))
)"""
assert_result_equal(run(executor, command), headers=["sql"], rows=[(table,), (index,)], status="")


@dbtest
def test_schema_indent_all(executor):
existing = set(run(executor, ".schema --indent")[0]["rows"])
run(executor, 'CREATE TABLE "run stats"(a, b)')
run(executor, "CREATE TABLE tags(name)")

rows = set(run(executor, ".schema --indent")[0]["rows"])
assert rows == existing | {('CREATE TABLE "run stats"(\n a,\n b\n)',), ("CREATE TABLE tags(name)",)}
assert_result_equal(run(executor, ".schema run stats"), headers=["sql"], rows=[('CREATE TABLE "run stats"(a, b)',)], status="")


@dbtest
def test_schema_indent_quoted_table_and_partial_index(executor):
run(executor, 'CREATE TABLE "--indent"(a, b)')
run(executor, """CREATE UNIQUE INDEX by_value ON "--indent"(ifnull(a, 'x,y'), b) WHERE b IN (1, 2)""")

table = 'CREATE TABLE "--indent"(\n a,\n b\n)'
index = """CREATE UNIQUE INDEX by_value ON "--indent"(\n ifnull(a, 'x,y'),\n b\n) WHERE b IN (1, 2)"""
assert_result_equal(run(executor, '.schema "--indent" --indent'), headers=["sql"], rows=[(table,), (index,)], status="")


@dbtest
def test_schema_indent_preserves_comments_and_literals(executor):
run(
executor,
"""CREATE TABLE messages(a /* comma, paren) */, msg TEXT DEFAULT 'it''s (a,b)' -- last column
)""",
)
[(sql,)] = run(executor, ".schema messages --indent")[0]["rows"]
run(executor, "DROP TABLE messages")
run(executor, sql)
run(executor, "INSERT INTO messages DEFAULT VALUES")
assert run(executor, "SELECT msg FROM messages")[0]["rows"] == [("it's (a,b)",)]