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
8 changes: 8 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
TBD
==============

Bug Fixes
--------
* Respect `--logfile` when using `--execute` or standard input at the shell CLI.


1.44.2 (2026/01/13)
==============

Expand Down
13 changes: 9 additions & 4 deletions mycli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,10 +992,7 @@ def one_iteration(text: str | None = None) -> None:
logger.debug("sql: %r", text)

special.write_tee(self.get_prompt(self.prompt_format) + text)
if self.logfile:
self.logfile.write(f"\n# {datetime.now()}\n")
self.logfile.write(text)
self.logfile.write("\n")
self.log_query(text)

successful = False
start = time()
Expand Down Expand Up @@ -1176,6 +1173,12 @@ def reconnect(self, database: str = "") -> bool:
self.echo(str(e), err=True, fg="red")
return False

def log_query(self, query: str) -> None:
if isinstance(self.logfile, TextIOWrapper):
self.logfile.write(f"\n# {datetime.now()}\n")
self.logfile.write(query)
self.logfile.write("\n")

def log_output(self, output: str) -> None:
"""Log the output in the audit log, if it's enabled."""
if isinstance(self.logfile, TextIOWrapper):
Expand Down Expand Up @@ -1355,6 +1358,7 @@ def get_prompt(self, string: str) -> str:
def run_query(self, query: str, new_line: bool = True) -> None:
"""Runs *query*."""
assert self.sqlexecute is not None
self.log_query(query)
results = self.sqlexecute.run(query)
for result in results:
title = result.title
Expand All @@ -1371,6 +1375,7 @@ def run_query(self, query: str, new_line: bool = True) -> None:
self.null_string,
)
for line in output:
self.log_output(line)
click.echo(line, nl=new_line)

# get and display warnings if enabled
Expand Down
19 changes: 19 additions & 0 deletions test/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -878,3 +878,22 @@ def test_global_init_commands(executor):
expected = "sql_select_limit\t9999\n"
assert result.exit_code == 0
assert expected in result.output


@dbtest
def test_execute_with_logfile(executor):
"""Test that --execute combines with --logfile"""
sql = 'select 1'
runner = CliRunner()

with NamedTemporaryFile(mode="w", delete=False) as logfile:
result = runner.invoke(mycli.main.cli, args=CLI_ARGS + ["--logfile", logfile.name, "--execute", sql])
assert result.exit_code == 0

assert os.path.getsize(logfile.name) > 0

try:
if os.path.exists(logfile.name):
os.remove(logfile.name)
except Exception as e:
print(f"An error occurred while attempting to delete the file: {e}")