From f454d780c2a5ead0e2ff00dacc12d7e393f32a68 Mon Sep 17 00:00:00 2001 From: Guillaume Marty Date: Mon, 30 Nov 2026 17:08:30 +0100 Subject: [PATCH] fix: escape double quotes in the --output CSV file A double quote in a query was written as \" and quotes in the other text fields were not escaped at all, so CSV readers split the row on the wrong delimiters. Double the quotes in every field, as in RFC 4180. --- pgactivity/utils.py | 46 ++++++++++++++++++++++------------------- tests/test_csv_write.py | 25 ++++++++++++++++++++++ 2 files changed, 50 insertions(+), 21 deletions(-) create mode 100644 tests/test_csv_write.py diff --git a/pgactivity/utils.py b/pgactivity/utils.py index 46f703da..b4898db2 100644 --- a/pgactivity/utils.py +++ b/pgactivity/utils.py @@ -256,8 +256,9 @@ def csv_write( "...-...-...T...Z";"25392";"4567";"pgbench";"pgbench";"postgres";"local";"N/A";"N/A";"N/A";"N/A";"0";"N";"N/A";"active";"BEGIN;" """ - def clean_str_csv(s: str) -> str: - return clean_str(s).replace('"', '\\"') + def quote(value: object) -> str: + # RFC 4180: a double quote inside a quoted field is doubled. + return '"{}"'.format(str(value).replace('"', '""')) if fobj.tell() == 0: # First line then write CSV header @@ -306,27 +307,30 @@ def yn_na(value: bool | None) -> str: wait = yn_na(p.get("wait")) io_wait = yn_na(p.get("io_wait")) state = p.get("state", "N/A") - query = clean_str_csv(p.get("query", "N/A")) + query = clean_str(p.get("query", "N/A")) fobj.write( delimiter.join( - [ - f'"{dt}"', - f'"{pid}"', - f'"{xmin}"', - f'"{database}"', - f'"{appname}"', - f'"{user}"', - f'"{client}"', - f'"{cpu}"', - f'"{mem}"', - f'"{read}"', - f'"{write}"', - f'"{duration}"', - f'"{wait}"', - f'"{io_wait}"', - f'"{state}"', - f'"{query}"', - ] + map( + quote, + [ + dt, + pid, + xmin, + database, + appname, + user, + client, + cpu, + mem, + read, + write, + duration, + wait, + io_wait, + state, + query, + ], + ) ) + "\n" ) diff --git a/tests/test_csv_write.py b/tests/test_csv_write.py new file mode 100644 index 00000000..dbd6f021 --- /dev/null +++ b/tests/test_csv_write.py @@ -0,0 +1,25 @@ +import csv + +import pytest + +from pgactivity import utils + + +@pytest.mark.parametrize( + "key,column", + [ + ("database", "database"), + ("application_name", "appname"), + ("user", "user"), + ("query", "query"), + ], +) +def test_csv_write_escapes_double_quotes(tmp_path, key, column): + value = 'SELECT * FROM "Users";' + path = tmp_path / "activities.csv" + with path.open("w") as f: + utils.csv_write(f, [{"pid": 1, key: value}]) + with path.open(newline="") as f: + header, row = csv.reader(f, delimiter=";") + assert len(row) == len(header) + assert row[header.index(column)] == value