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

Add replace function (py3 branch) #16

Open
wants to merge 5 commits into
base: allpy3-mod
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions tinyquery/evaluator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1339,6 +1339,11 @@ def test_other_timestamp_functions(self):
self.make_context([
('f0_', tq_types.INT, [1262304000000000])]))

def test_replace(self):
self.assert_query_result(
"SELECT REPLACE(str, 'o', 'e') FROM string_table_with_null",
self.make_context([('f0_', tq_types.STRING, ["helle", "werld", None])]))

def test_first(self):
# Test over the equivalent of a GROUP BY
self.assert_query_result(
Expand Down
16 changes: 16 additions & 0 deletions tinyquery/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,21 @@ def apply(*args):
values=values)


class ReplaceFunction(ScalarFunction):
def check_types(self, *arg_types):
if any(arg_type != tq_types.STRING for arg_type in arg_types):
raise TypeError('REPLACE only takes string arguments.')
return tq_types.STRING

def _evaluate(self, num_rows, values, old, new):
values = [value.replace(old, new) if value is not None else None
for value, old, new in zip(values.values,
old.values,
new.values)]
return context.Column(tq_types.STRING, tq_modes.NULLABLE,
values=values)


class JSONExtractFunction(ScalarFunction):
"""Extract from a JSON string based on a JSONPath expression.

Expand Down Expand Up @@ -1320,6 +1335,7 @@ def _evaluate(self, num_rows, json_expressions, json_paths):
lambda dt: dt.year,
return_type=tq_types.INT),
TimestampFunction()),
'replace': ReplaceFunction(),
'json_extract': JSONExtractFunction(),
'json_extract_scalar': JSONExtractFunction(scalar=True),
}
Expand Down