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
2 changes: 1 addition & 1 deletion docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ Use ``--ascii`` to escape non-ASCII characters as ``\uXXXX`` sequences instead:

[{"text": "\u65e5\u672c\u8a9e"}]

The ``--ascii`` option can help on systems that cannot display or process UTF-8, such as Windows consoles using a legacy code page. On Windows, setting the ``PYTHONUTF8=1`` environment variable is an alternative fix for ``UnicodeEncodeError`` crashes when redirecting output to a file.
The ``--ascii`` option can help on systems that cannot display or process UTF-8, such as Windows consoles using a legacy code page. Output redirected to a file or pipe is always written as UTF-8, matching the encoding ``sqlite-utils insert`` expects by default, unless the ``PYTHONIOENCODING`` environment variable selects a different encoding.

.. _cli_query_binary_json:

Expand Down
36 changes: 34 additions & 2 deletions sqlite_utils/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,36 @@ def functions_option(fn):
@click.version_option()
def cli():
"Commands for interacting with a SQLite database"
_use_utf8_for_redirected_stdout()


def _use_utf8_for_redirected_stdout():
"""Write UTF-8 when stdout is redirected to a file or pipe.

Python encodes redirected output with the locale encoding (cp1252 on most
Windows systems), so exported CSV and JSON could not be read back by
sqlite-utils, which reads UTF-8 by default, and characters outside the
locale encoding raised UnicodeEncodeError. Terminals and an explicit
PYTHONIOENCODING are left alone.
"""
stream = sys.stdout
if os.environ.get("PYTHONIOENCODING"):
return
if not isinstance(stream, io.TextIOWrapper) or stream.isatty():
return
if (stream.encoding or "").replace("_", "-").lower() not in ("utf-8", "utf8"):
stream.reconfigure(encoding="utf-8")


def _csv_stdout():
"""Return stdout ready for csv.writer, which writes its own line endings.

Without this, Windows newline translation turned every row ending into
CR CR LF. Translation is a no-op on other platforms.
"""
if isinstance(sys.stdout, io.TextIOWrapper):
sys.stdout.reconfigure(newline="")
return sys.stdout


@cli.command()
Expand Down Expand Up @@ -277,7 +307,7 @@ def _iter():
)
)
elif csv or tsv:
writer = csv_std.writer(sys.stdout, dialect="excel-tab" if tsv else "excel")
writer = csv_std.writer(_csv_stdout(), dialect="excel-tab" if tsv else "excel")
if not no_headers:
writer.writerow(headers)
for row in _iter():
Expand Down Expand Up @@ -2314,7 +2344,9 @@ def _execute_query(
)
)
elif csv or tsv:
writer = csv_std.writer(sys.stdout, dialect="excel-tab" if tsv else "excel")
writer = csv_std.writer(
_csv_stdout(), dialect="excel-tab" if tsv else "excel"
)
if not no_headers:
writer.writerow(headers)
for row in cursor:
Expand Down
111 changes: 111 additions & 0 deletions tests/test_cli_redirected_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""Output redirected to a file or pipe is UTF-8, and CSV rows end in a single CRLF.

On Windows, Python writes redirected stdout in the locale encoding (usually cp1252)
and translates "\n" to "\r\n". These tests swap in a stream that behaves the same
way, so they exercise the Windows behaviour on every platform.
"""

import io
import sys
from typing import cast

import click
import pytest

from sqlite_utils import Database, cli

CLI = cast(click.Group, cli.cli)


def run_redirected(args, encoding="cp1252"):
"""Run the CLI with stdout replaced by a Windows-like redirected stream.

stdout is swapped inside the test body because pytest's capture replaces it
between fixture setup and the test call.
"""
buffer = io.BytesIO()
stream = io.TextIOWrapper(buffer, encoding=encoding, newline="\r\n")
original = sys.stdout
sys.stdout = stream
try:
CLI.main(args, standalone_mode=False)
sys.stdout.flush()
return buffer.getvalue()
finally:
sys.stdout = original


@pytest.fixture(autouse=True)
def no_pythonioencoding(monkeypatch):
monkeypatch.delenv("PYTHONIOENCODING", raising=False)


@pytest.fixture
def db_with_non_ascii(tmpdir):
path = str(tmpdir / "test.db")
with Database(path) as db:
db.table("places").insert_all(
[{"name": "José", "city": "Zürich"}, {"name": "प्रिया", "city": "मुंबई"}]
)
return path


@pytest.mark.parametrize(
"args,expected",
(
(["--csv"], "name,city\r\nJosé,Zürich\r\nप्रिया,मुंबई\r\n"),
(["--tsv"], "name\tcity\r\nJosé\tZürich\r\nप्रिया\tमुंबई\r\n"),
(
["--nl"],
'{"name": "José", "city": "Zürich"}\r\n'
'{"name": "प्रिया", "city": "मुंबई"}\r\n',
),
),
)
def test_query_output_is_utf8(db_with_non_ascii, args, expected):
output = run_redirected([db_with_non_ascii, "select name, city from places"] + args)
assert output == expected.encode("utf-8")


def test_rows_csv_is_utf8(db_with_non_ascii):
output = run_redirected(["rows", db_with_non_ascii, "places", "--csv"])
assert output == "name,city\r\nJosé,Zürich\r\nप्रिया,मुंबई\r\n".encode("utf-8")


def test_tables_csv_has_single_crlf_line_endings(db_with_non_ascii):
output = run_redirected(["tables", db_with_non_ascii, "--csv", "--columns"])
# The newline inside the quoted columns cell is kept, rows end in one CRLF.
assert output == b'table,columns\r\nplaces,"name\ncity"\r\n'


def test_table_output_does_not_crash(db_with_non_ascii):
output = run_redirected(
[db_with_non_ascii, "select name, city from places", "--table"]
)
assert "मुंबई".encode("utf-8") in output


def test_exported_csv_can_be_inserted_again(db_with_non_ascii, tmpdir):
output = run_redirected(
[db_with_non_ascii, "select name, city from places", "--csv"]
)
exported = tmpdir / "exported.csv"
exported.write_binary(output)
copy_path = str(tmpdir / "copy.db")
CLI.main(
["insert", copy_path, "places", str(exported), "--csv"], standalone_mode=False
)
with Database(copy_path) as db:
assert list(db["places"].rows) == [
{"name": "José", "city": "Zürich"},
{"name": "प्रिया", "city": "मुंबई"},
]


def test_explicit_pythonioencoding_is_respected(monkeypatch, db_with_non_ascii):
monkeypatch.setenv("PYTHONIOENCODING", "cp1252")
output = run_redirected(
[db_with_non_ascii, "select name from places where name = 'José'", "--csv"]
)
# Encoding is left as requested; CSV rows still end in a single CRLF.
assert output == "name\r\nJosé\r\n".encode("cp1252")
Loading