From 9c2d1cbe22d7a2dd381952289488c37b66d5cdd7 Mon Sep 17 00:00:00 2001 From: Michael Dubner Date: Sat, 21 Nov 2026 02:57:24 +0300 Subject: [PATCH] support sqlite3 format in CLI (#510) --- README.md | 6 ++++-- examples/people.sqlite | Bin 0 -> 12288 bytes tabulate/cli.py | 39 +++++++++++++++++++++++++++++++++----- test/test_cli.py | 42 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 80 insertions(+), 7 deletions(-) create mode 100644 examples/people.sqlite diff --git a/README.md b/README.md index 0283a0c..234d21e 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/examples/people.sqlite b/examples/people.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..a519ccbf839240a05ac5a1a129a15f17b29d5af1 GIT binary patch literal 12288 zcmeI$ze)o!90%~^;`!%5qllDlAr2}nb#QWPtA_}ps5f*gxteP5u2;@#D^Aj9=->;u z`!qg>lZ%7twPJB`D~R7alH4!9{1W(Vx%1N_)6t@tq_OIV9kNU)C1oK9A+Bv~+^8LA z#?21dGo1VFaY^avWznvpyia(a=YK0e9s&@600bZa0SG_<0uX=z1RyX~fxwx~74r1P zv@Ued^y+P$v?E>5!qGR|JM$}nFAk6Q{hE+J*2t4%Ax8_P*pykF+n6GFCBtfdJ2T9Ac0RwkN=rEIFZ zB(*nvDMd5AHJwq?+Zx`@86Qyo%AfgQs=_!70uX=z1Rwwb2tWV=5P$##An>0BRv2e4 z&5<>>r_v;9Yn7H9m#!9eooW(>Nm$lB72BT?rA88ms%77zm!zt7sf%88-?-9RZ&16# z_ByRZrlHlan=DdoTU`{_rfa^S`3HaJZ(k8c2tWV=5P$##AOHafKmY;|fB*#kw1CSf Nb=VABusxe!_yiQ~bk6_) literal 0 HcmV?d00001 diff --git a/tabulate/cli.py b/tabulate/cli.py index cfae6fe..d922bb5 100644 --- a/tabulate/cli.py +++ b/tabulate/cli.py @@ -4,6 +4,7 @@ import re import sys import textwrap +import functools try: from . import ( @@ -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) @@ -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 @@ -88,6 +91,7 @@ def _main(): "int=", "colalign=", "format=", + "table=", ], ) except getopt.GetoptError as e: @@ -100,6 +104,7 @@ def _main(): colalign = None tablefmt = "simple" fileformat = "rsv" + tablename = None sep = r"\s+" outfile = "-" special_headers_values = ["firstrow", "keys"] @@ -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"]: @@ -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: @@ -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) @@ -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) diff --git a/test/test_cli.py b/test/test_cli.py index 154f1a2..ebdd3fd 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -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 = [