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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1144,14 +1144,16 @@ INPUT:
rsv (REGEXP-separated values, default),
csv (comma-separated valued, Excel dialect),
jsonl (one JSON object per line)
sqlite (file in SQLite3 format)
-T TABLE, --table TABLE table name in sqlite db
-s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace)

FORMAT:
--headers HEADERS HEADERS can be one of:
"firstrow" (for csv and rsv data),
"keys" (for jsonl data),
"keys" (for jsonl or sqlite data),
"HEADER1,HEADER2,..." (for csv and rsv data),
"KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data)
"KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl or sqlite data)
-1 use the first row of input data as a table header
(the same as --headers firstrow)
-F FPFMT, --float FPFMT floating point number format (default: g)
Expand Down
Binary file added examples/people.sqlite
Binary file not shown.
39 changes: 34 additions & 5 deletions tabulate/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import re
import sys
import textwrap
import functools

try:
from . import (
Expand Down Expand Up @@ -46,14 +47,16 @@ def _main():
rsv (REGEXP-separated values, default),
csv (comma-separated valued, Excel dialect),
jsonl (one JSON object per line)
sqlite (file in SQLite3 format)
-T TABLE, --table TABLE table name in sqlite db
-s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace)

FORMAT:
--headers HEADERS HEADERS can be one of:
"firstrow" (for csv and rsv data),
"keys" (for jsonl data),
"keys" (for jsonl or sqlite data),
"HEADER1,HEADER2,..." (for csv and rsv data),
"KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data)
"KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl or sqlite data)
-1 use the first row of input data as a table header
(the same as --headers firstrow)
-F FPFMT, --float FPFMT floating point number format (default: g)
Expand All @@ -76,7 +79,7 @@ def _main():
try:
opts, args = getopt.getopt(
sys.argv[1:],
"h1H:r:o:s:F:I:f:",
"h1H:r:o:s:F:I:f:T:",
[
"help",
"header", # deprecated in CLI > 0.10
Expand All @@ -88,6 +91,7 @@ def _main():
"int=",
"colalign=",
"format=",
"table=",
],
)
except getopt.GetoptError as e:
Expand All @@ -100,6 +104,7 @@ def _main():
colalign = None
tablefmt = "simple"
fileformat = "rsv"
tablename = None
sep = r"\s+"
outfile = "-"
special_headers_values = ["firstrow", "keys"]
Expand Down Expand Up @@ -129,6 +134,8 @@ def _main():
print(usage)
sys.exit(3)
tablefmt = value
elif opt in ["-T", "--table"]:
tablename = value
elif opt in ["-s", "--sep"]:
sep = value
elif opt in ["-h", "--help"]:
Expand All @@ -145,8 +152,7 @@ def _main():
if type(headers) is str and headers not in special_headers_values:
# parse as CSV values
headers = headers.split(",")
elif fileformat == "jsonl":
reader = _read_jsonl_file
elif fileformat in ("jsonl", "sqlite", "sqlite3"):
if not headers:
headers = "keys" # reasonable default
if type(headers) is str and headers not in special_headers_values:
Expand All @@ -157,6 +163,10 @@ def _main():
print(f"cannot parse headers parameter: {headers}", file=sys.stderr)
headers2 = []
headers = headers2
if fileformat == "jsonl":
reader = _read_jsonl_file
else:
reader = functools.partial(_read_sqlite_file, tablename=tablename)
else:
print(f"{fileformat} is not a supported file format")
sys.exit(3)
Expand Down Expand Up @@ -200,6 +210,25 @@ def _read_csv_file(fobject):
return table


def _read_sqlite_file(fobject, tablename=None):
import json
import sqlite3

con = sqlite3.connect(':memory:')
if hasattr(fobject, 'buffer'):
fobject = fobject.buffer
if hasattr(fobject, 'raw'):
fobject = fobject.raw
con.deserialize(fobject.read())
if tablename is None:
tablename = con.execute(
"select name from sqlite_master where type='table' order by rootpage desc"
).fetchone()[0]
cursor = con.execute("select * from " + json.dumps(tablename, ensure_ascii=False))
cursor.row_factory = sqlite3.Row
return cursor


def _open_and_pprint_file(reader, f, *args, **kwargs):
if _is_file(f):
_pprint_file(reader, f, *args, **kwargs)
Expand Down
42 changes: 42 additions & 0 deletions test/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,48 @@ def test_module_csv_from_stdin():
assert_equal(out.splitlines(), expected.splitlines())


SAMPLE_INPUT_SQL = (
'BEGIN TRANSACTION;\n'
'CREATE TABLE people (id INTEGER, name TEXT, email TEXT, """favorite"" fruit" TEXT);\n'
"INSERT INTO people VALUES(1,'Alice','alice@example.com','apple, kiwi');\n"
"INSERT INTO people VALUES(2,'Bob','bob@example.com','banana,\norange,\n\"lychee');\n"
"INSERT INTO people VALUES(3,'Carol',NULL,'pear');\n"
'COMMIT;'
)


SAMPLE_SQL_FORMAT = "\n".join(
[
' id name email "favorite" fruit',
"---- ------ ----------------- ------------------",
" 1 Alice alice@example.com apple, kiwi",
" 2 Bob bob@example.com banana,",
" orange,",
" \"lychee",
" 3 Carol pear",
]
)


class FakeString(bytes):
def encode(self):
return self


def test_module_sqlite_from_stdin():
"""Command line utility: python -m tabulate with SQLITE3 input from stdin"""
import sqlite3
con = sqlite3.connect('')
con.executescript(SAMPLE_INPUT_SQL)
inputbytes = FakeString(con.serialize())
cmd = [sys.executable, "-m", "tabulate", "-r", "sqlite"]
out = run_and_capture_stdout(cmd, input=inputbytes)
expected = SAMPLE_SQL_FORMAT
print("got: ", "\n", (out), sep='')
print("expected:", "\n", (expected), sep='')
assert_equal(out.splitlines(), expected.splitlines())


def test_module_jsonl_remapped_headers():
"""Command line utility: --headers with key:header remapping for JSONL input"""
cmd = [
Expand Down