Skip to content

Commit 1c1d26e

Browse files
authored
Fix missing EOL when formatting SQL files (#260)
Fixes #245 --------- Co-authored-by: Eric Vergnaud <eric.vergnaud@databricks.com>
1 parent 42d4cce commit 1c1d26e

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/databricks/labs/lsql/dashboards.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,7 @@ def format(content: str, *, max_text_width: int = 120, normalize_case: bool = Tr
429429
normalize_case : bool, optional (default: True)
430430
If the query identifiers should be normalized to lower case
431431
"""
432+
has_eol = content.endswith("\n")
432433
try:
433434
parsed_query = sqlglot.parse(content, dialect=_SQL_DIALECT)
434435
except sqlglot.ParseError:
@@ -453,7 +454,7 @@ def format(content: str, *, max_text_width: int = 120, normalize_case: bool = Tr
453454
if "$" in content:
454455
# replace ${x} with $x, because we use it in UCX view definitions for now
455456
formatted_query = re.sub(r"\${(\w+)}", r"$\1", formatted_query)
456-
return formatted_query
457+
return formatted_query + ("\n" if has_eol else "")
457458

458459
def _get_abstract_syntax_tree(self) -> sqlglot.Expression | None:
459460
try:

tests/unit/test_dashboards.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -829,7 +829,12 @@ def test_query_tile_keeps_original_query(tmp_path):
829829
],
830830
)
831831
def test_query_formats(query, query_formatted):
832-
assert QueryTile.format(query) == query_formatted
832+
assert QueryTile.format(query).strip() == query_formatted.strip()
833+
834+
835+
def test_query_format_preserves_eol():
836+
assert not QueryTile.format("SELECT x, y FROM a, b").endswith("\n")
837+
assert QueryTile.format("SELECT x, y FROM a, b\n").endswith("\n")
833838

834839

835840
def test_query_formats_no_normalize():

0 commit comments

Comments
 (0)