Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing EOL when formatting SQL files #260

Merged
merged 2 commits into from
Aug 30, 2024
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
3 changes: 2 additions & 1 deletion src/databricks/labs/lsql/dashboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,7 @@ def format(content: str, *, max_text_width: int = 120, normalize_case: bool = Tr
normalize_case : bool, optional (default: True)
If the query identifiers should be normalized to lower case
"""
has_eol = content.endswith("\n")
try:
parsed_query = sqlglot.parse(content, dialect=_SQL_DIALECT)
except sqlglot.ParseError:
Expand All @@ -453,7 +454,7 @@ def format(content: str, *, max_text_width: int = 120, normalize_case: bool = Tr
if "$" in content:
# replace ${x} with $x, because we use it in UCX view definitions for now
formatted_query = re.sub(r"\${(\w+)}", r"$\1", formatted_query)
return formatted_query
return formatted_query + ("\n" if has_eol else "")

def _get_abstract_syntax_tree(self) -> sqlglot.Expression | None:
try:
Expand Down
7 changes: 6 additions & 1 deletion tests/unit/test_dashboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,12 @@ def test_query_tile_keeps_original_query(tmp_path):
],
)
def test_query_formats(query, query_formatted):
assert QueryTile.format(query) == query_formatted
assert QueryTile.format(query).strip() == query_formatted.strip()


def test_query_format_preserves_eol():
assert not QueryTile.format("SELECT x, y FROM a, b").endswith("\n")
assert QueryTile.format("SELECT x, y FROM a, b\n").endswith("\n")


def test_query_formats_no_normalize():
Expand Down
Loading