From 7427a9137f60de961b6331d0922a3f03da0d1890 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 22 Sep 2021 13:20:04 -0700 Subject: [PATCH] Output [] in JSON mode if no rows, closes #328 --- sqlite_utils/cli.py | 3 +++ tests/test_cli.py | 13 ++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 10a11c6..5217965 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -2225,6 +2225,9 @@ def output_rows(iterator, headers, nl, arrays, json_cols): ) yield line first = False + if first: + # We didn't output any rows, so yield the empty list + yield "[]" def maybe_json(value): diff --git a/tests/test_cli.py b/tests/test_cli.py index a6ddca0..47920c6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -994,6 +994,13 @@ def test_query_json(db_path, sql, args, expected): assert expected == result.output.strip() +def test_query_json_empty(db_path): + result = CliRunner().invoke( + cli.cli, [db_path, "select * from sqlite_master where 0"] + ) + assert result.output.strip() == "[]" + + LOREM_IPSUM_COMPRESSED = ( b"x\x9c\xed\xd1\xcdq\x03!\x0c\x05\xe0\xbb\xabP\x01\x1eW\x91\xdc|M\x01\n\xc8\x8e" b"f\xf83H\x1e\x97\x1f\x91M\x8e\xe9\xe0\xdd\x96\x05\x84\xf4\xbek\x9fRI\xc7\xf2J" @@ -2098,7 +2105,11 @@ _TRIGGERS_EXPECTED = ( @pytest.mark.parametrize( "extra_args,expected", - [([], _TRIGGERS_EXPECTED), (["articles"], _TRIGGERS_EXPECTED), (["counter"], "")], + [ + ([], _TRIGGERS_EXPECTED), + (["articles"], _TRIGGERS_EXPECTED), + (["counter"], "[]\n"), + ], ) def test_triggers(tmpdir, extra_args, expected): db_path = str(tmpdir / "test.db")