Skip to content
Merged
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
15 changes: 8 additions & 7 deletions sqlglot/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -1007,23 +1007,24 @@ def maybe_comment(
if not comments or isinstance(expression, self.EXCLUDE_COMMENTS):
return sql

comments_sql = " ".join(
f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment
)
comments_list = [
f"/*{self._replace_line_breaks(self.sanitize_comment(comment))}*/"
for comment in comments
if comment
]

if not comments_sql:
if not comments_list:
return sql

comments_sql = self._replace_line_breaks(comments_sql)

if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS):
comments_sql = self.sep().join(comments_list)
return (
f"{self.sep()}{comments_sql}{sql}"
if not sql or sql[0].isspace()
else f"{comments_sql}{self.sep()}{sql}"
)

return f"{sql} {comments_sql}"
return f"{sql} {' '.join(comments_list)}"

def wrap(self, expression: exp.Expr | str) -> str:
this_sql = (
Expand Down
34 changes: 30 additions & 4 deletions tests/test_transpile.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ def test_comments(self):
-- comment 2
-- comment 3
SELECT * FROM foo""",
"""/* comment 1 */ /* comment 2 */ /* comment 3 */
"""/* comment 1 */
/* comment 2 */
/* comment 3 */
SELECT
*
FROM foo""",
Expand Down Expand Up @@ -367,7 +369,9 @@ def test_comments(self):
-- comment3
DROP TABLE IF EXISTS db.tba
""",
"""/* comment1 */ /* comment2 */ /* comment3 */
"""/* comment1 */
/* comment2 */
/* comment3 */
DROP TABLE IF EXISTS db.tba""",
pretty=True,
)
Expand Down Expand Up @@ -428,7 +432,8 @@ def test_comments(self):
"""SELECT
*
FROM a
/* comment 1 */ /* comment 2 */
/* comment 1 */
/* comment 2 */
LEFT OUTER JOIN b""",
pretty=True,
)
Expand Down Expand Up @@ -619,7 +624,8 @@ def test_comments(self):
SELECT
2 AS n /* b */
FROM (
/* c */ /* c2 */
/* c */
/* c2 */
SELECT
a /* d */
FROM t
Expand All @@ -639,6 +645,26 @@ def test_comments(self):
pretty=True,
)

# Round-trip stress: multiple trailing comments on the same expression must
# stay space-separated (same line) in pretty mode. Re-parsing would otherwise
# detach the later ones onto the next token.
self.validate(
"SELECT a /* foo */ /* bar */ FROM tbl",
"""SELECT
a /* foo */ /* bar */
FROM tbl""",
pretty=True,
)
self.validate(
"SELECT x FROM t WHERE x = 1 /* a */ /* b */ /* c */",
"""SELECT
x
FROM t
WHERE
x = 1 /* a */ /* b */ /* c */""",
pretty=True,
)

self.validate(
"""SELECT
*
Expand Down
Loading