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
3 changes: 2 additions & 1 deletion CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
Development Version
-------------------

Nothing yet.
* Escape embedded line breaks in Python output so multiline SQL strings,
quoted identifiers and comments produce valid Python string literals.


Release 0.6.0 (Aug 13, 2026)
Expand Down
4 changes: 3 additions & 1 deletion sqlparse/filters/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def _process(self, stream, varname, has_nl):
# quote cannot break out of the generated string literal
# (GHSA-3496-9g83-7v6x).
else:
token.value = token.value.replace('\\', '\\\\').replace("'", "\\'")
token.value = (token.value.replace('\\', '\\\\')
.replace("'", "\\'")
.replace('\r', '\\r').replace('\n', '\\n'))

# Put the token
yield sql.Token(T.Text, token.value)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_format.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import ast

import pytest

import sqlparse
Expand Down Expand Up @@ -651,6 +653,20 @@ def test_insert_values(self):


class TestOutputFormat:
@pytest.mark.parametrize('line_break', ['\n', '\r', '\r\n', r'\n'])
@pytest.mark.parametrize('template', [
"SELECT 'first{}second''quote\\path'",
'SELECT "first{}second"',
'SELECT $body$first{}second$body$',
'SELECT 1 /* first{}second */',
'SELECT 1 -- first{}FROM t',
])
def test_python_multiline_tokens(self, line_break, template):
sql = template.format(line_break)
formatted = sqlparse.format(sql, output_format='python')
assignment = ast.parse(formatted).body[0]
assert ast.literal_eval(assignment.value) == sql

def test_python(self):
sql = 'select * from foo;'
f = lambda sql: sqlparse.format(sql, output_format='python')
Expand Down