Skip to content

Commit

Permalink
--raw option, refs #123
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jul 26, 2020
1 parent a236a6b commit bc84099
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
11 changes: 11 additions & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,17 @@ You can use the ``--fmt`` (or ``-f``) option to specify different table formats,

For a full list of table format options, run ``sqlite-utils query --help``.

.. _cli_query_raw:

Returning raw data from a query, such as binary content
=======================================================

If your table contains binary data in a ``BLOB`` you can use the ``--raw`` option to output specific columns directly to standard out.

For example, to retrieve a binary image from a ``BLOB`` column and store it in a file you can use the following::

$ sqlite-utils photos.db "select contents from photos where id=1" --raw > myphoto.jpg

.. _cli_rows:

Returning all rows in a table
Expand Down
11 changes: 9 additions & 2 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,8 @@ def drop_view(path, view):
)
@click.argument("sql")
@output_options
def query(path, sql, nl, arrays, csv, no_headers, table, fmt, json_cols):
@click.option("-r", "--raw", is_flag=True, help="Raw output, first column of first row")
def query(path, sql, nl, arrays, csv, no_headers, table, fmt, json_cols, raw):
"Execute SQL query and return the results as JSON"
db = sqlite_utils.Database(path)
with db.conn:
Expand All @@ -686,7 +687,13 @@ def query(path, sql, nl, arrays, csv, no_headers, table, fmt, json_cols):
cursor = [[cursor.rowcount]]
else:
headers = [c[0] for c in cursor.description]
if table:
if raw:
data = cursor.fetchone()[0]
if isinstance(data, bytes):
sys.stdout.buffer.write(data)
else:
sys.stdout.write(str(data))
elif table:
print(tabulate.tabulate(list(cursor), headers=headers, tablefmt=fmt))
elif csv:
writer = csv_std.writer(sys.stdout)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,21 @@ def test_query_json_with_json_cols(db_path):
assert expected == result_rows.output.strip()


@pytest.mark.parametrize(
"content,is_binary",
[(b"\x00\x0Fbinary", True), ("this is text", False), (1, False), (1.5, False)],
)
def test_query_raw(db_path, content, is_binary):
Database(db_path)["files"].insert({"content": content})
result = CliRunner().invoke(
cli.cli, [db_path, "select content from files", "--raw"]
)
if is_binary:
assert result.stdout_bytes == content
else:
assert result.output == str(content)


def test_query_memory_does_not_create_file(tmpdir):
owd = os.getcwd()
try:
Expand Down

0 comments on commit bc84099

Please sign in to comment.