Skip to content

Commit

Permalink
include nulls
Browse files Browse the repository at this point in the history
  • Loading branch information
klahnakoski committed Oct 31, 2024
1 parent a78daa6 commit f96191f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
6 changes: 5 additions & 1 deletion mo_sql_parsing/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,11 @@ def pivot(self, json, prec):

def unpivot(self, json, prec):
pivot = json["unpivot"]
return self._pivot("UNPIVOT", pivot, self.dispatch(pivot["value"]))
if "nulls" in pivot:
nulls = " INCLUDE NULLS" if pivot["nulls"] else " EXCLUDE NULLS"
else:
nulls = ""
return self._pivot(f"UNPIVOT{nulls}", pivot, self.dispatch(pivot["value"]))

def _pivot(self, op, pivot, value):
for_ = self.dispatch(pivot["for"])
Expand Down
21 changes: 18 additions & 3 deletions tests/test_format_and_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import re
from unittest import TestCase

from mo_logs import logger, Except
from mo_logs import logger
from mo_testing.fuzzytestcase import add_error_reporting

from mo_sql_parsing import format, parse
Expand Down Expand Up @@ -43,7 +43,6 @@ def verify_formatting(self, expected_sql, expected_json):
new_json = parse(new_sql)
self.assertEqual(new_json, expected_json)
except Exception as cause:
cause = Except.wrap(cause)
logger.error(
EXCEPTION_MESSAGE,
expected_sql=expected_sql,
Expand Down Expand Up @@ -1838,4 +1837,20 @@ def test_issue_255_unpivot(self):
"name": "u",
},
}
self.verify_formatting(sql, json)
self.verify_formatting(sql, json)

def test_issue_255_unpivot2(self):
sql = """SELECT col_a, col_b FROM tab UNPIVOT EXCLUDE NULLS (col_a FOR col_b IN (col_1, col_2)) AS u"""
json = {
"select": [{"value": "col_a"}, {"value": "col_b"}],
"from": "tab",
"unpivot": {
"nulls": False,
"value": "col_a",
"for": "col_b",
"in": ["col_1", "col_2"],
"name": "u",
},
}
self.verify_formatting(sql, json)

0 comments on commit f96191f

Please sign in to comment.