Allow numeric expression as mod argument to hash function

This commit is contained in:
Yonatan Most 2020-08-27 14:50:42 +03:00
Родитель e7642ef358
Коммит 0f6ff9a350
4 изменённых файлов: 16 добавлений и 6 удалений

Просмотреть файл

@ -42,7 +42,7 @@ class BaseExpression:
def __bool__(self) -> bool:
raise TypeError(
"Conversion of expression to boolean is not allowed, to prevent accidental use of the logical operators: 'and', 'or', and 'not. "
"Conversion of expression to boolean is not allowed, to prevent accidental use of the logical operators: 'and', 'or', and 'not'. "
"Instead either use the bitwise operators '&', '|' and '~' (but note the difference in operator precedence!), "
"or the functions 'all_of', 'any_of' and 'not_of'"
)
@ -53,12 +53,14 @@ class BaseExpression:
def get_type(self) -> '_StringExpression':
return _StringExpression(KQL(f'gettype({self.kql})'))
def __hash__(self, mod: int = None) -> '_StringExpression':
def __hash__(self, mod: _NumberType = None) -> '_StringExpression':
"""
https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/hashfunction
"""
if mod:
return _StringExpression(KQL(f'hash({self.kql}, {mod})'))
if mod is not None:
if not isinstance(mod, (_NumberExpression, int)):
raise ValueError("'mod' argument must be an integer")
return _StringExpression(KQL(f'hash({self.kql}, {_to_kql(mod)})'))
return _StringExpression(KQL(f'hash({self.kql})'))
def hash_sha256(self) -> '_StringExpression':

Просмотреть файл

@ -339,7 +339,7 @@ class Functions:
return expr.get_year()
@staticmethod
def hash(expr: _ExpressionType, mod: int = None) -> _StringExpression:
def hash(expr: _ExpressionType, mod: _NumberType = None) -> _StringExpression:
"""
https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/hashfunction
"""

Просмотреть файл

@ -461,7 +461,7 @@ class TestExpressions(TestBase):
def test_boolean_operators(self):
self.assertRaises(
TypeError(
"Conversion of expression to boolean is not allowed, to prevent accidental use of the logical operators: 'and', 'or', and 'not. "
"Conversion of expression to boolean is not allowed, to prevent accidental use of the logical operators: 'and', 'or', and 'not'. "
"Instead either use the bitwise operators '&', '|' and '~' (but note the difference in operator precedence!), "
"or the functions 'all_of', 'any_of' and 'not_of'"
),

Просмотреть файл

@ -173,6 +173,14 @@ class TestFunction(TestBase):
" | where (hash(stringField, 100)) == 3",
Query().where(f.hash(t.stringField, 100) == 3).render()
)
self.assertRaises(
ValueError("'mod' argument must be an integer"),
lambda: Query().where(f.hash(t.stringField, 1.5) == 3).render()
)
self.assertEqual(
" | where (hash(stringField, numField)) == 3",
Query().where(f.hash(t.stringField, t.numField) == 3).render()
)
def test_hash_sha256(self):
self.assertEqual(