diff --git a/changelog.md b/changelog.md index faaa32a4..7f5a6cef 100644 --- a/changelog.md +++ b/changelog.md @@ -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) ============== diff --git a/mycli/main.py b/mycli/main.py index 7258712c..d0bca605 100755 --- a/mycli/main.py +++ b/mycli/main.py @@ -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() @@ -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): @@ -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 @@ -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 diff --git a/test/test_main.py b/test/test_main.py index 076bd986..4f22a208 100644 --- a/test/test_main.py +++ b/test/test_main.py @@ -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}")