Skip to content

Commit c8855c3

Browse files
authored
Merge pull request #54 from macbre/having-query-fix
Add test_query_with_having
2 parents 4d11c57 + 8658734 commit c8855c3

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

sql_metadata.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,11 @@ def get_query_tables(query: str) -> List[str]:
223223
elif str(token) == '(':
224224
# reset the last_keyword for INSERT `foo` VALUES(id, bar) ...
225225
last_keyword = None
226-
elif token.is_keyword and str(token) in ['FORCE', 'ORDER']:
227-
# reset the last_keyword for "SELECT x FORCE INDEX" queries and "SELECT x ORDER BY"
226+
elif token.is_keyword and str(token) in ['FORCE', 'ORDER', 'GROUP BY']:
227+
# reset the last_keyword for queries like:
228+
# "SELECT x FORCE INDEX"
229+
# "SELECT x ORDER BY"
230+
# "SELECT x FROM y GROUP BY x"
228231
last_keyword = None
229232
elif token.is_keyword and str(token) == 'SELECT' and last_keyword in ['INTO', 'TABLE']:
230233
# reset the last_keyword for "INSERT INTO SELECT" and "INSERT TABLE SELECT" queries

test/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""
2+
Enable logging when running tests
3+
"""
4+
import logging
5+
logging.basicConfig(level=logging.DEBUG)

test/test_query.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,16 @@ def test_sql_server_cte_sales_by_year():
343343

344344
# TODO
345345
# assert get_query_columns(sales_query) == ['staff_id', 'order_count', 'order_date']
346+
347+
348+
def test_table_name_with_group_by():
349+
expected_tables = ['SH.sales']
350+
351+
assert get_query_tables("SELECT s.cust_id,count(s.cust_id) FROM SH.sales s") == expected_tables
352+
353+
assert get_query_tables("SELECT s.cust_id,count(s.cust_id) FROM SH.sales s GROUP BY s.cust_id") == expected_tables
354+
355+
assert get_query_tables("""
356+
SELECT s.cust_id,count(s.cust_id) FROM SH.sales s
357+
GROUP BY s.cust_id HAVING s.cust_id != '1660' AND s.cust_id != '2'
358+
""".strip()) == expected_tables

0 commit comments

Comments
 (0)