-
Notifications
You must be signed in to change notification settings - Fork 265
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
218 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
def My_SimpleUDF(cls, x:int)->int: | ||
return x + 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
# coding=utf-8 | ||
# Copyright 2018-2023 EvaDB | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import numpy as np | ||
import pandas as pd | ||
import importlib | ||
import pickle | ||
from pathlib import Path | ||
import typing | ||
|
||
from evadb.catalog.catalog_type import NdArrayType | ||
from evadb.functions.abstract.abstract_function import AbstractFunction | ||
from evadb.functions.decorators.decorators import forward, setup | ||
from evadb.functions.decorators.io_descriptors.data_types import PandasDataframe | ||
from evadb.configuration.constants import EvaDB_ROOT_DIR | ||
|
||
class SimpleUDF(AbstractFunction): | ||
@setup(cacheable=False, function_type="SimpleUDF", batchable=False) | ||
def setup(self): | ||
in_labels = [] | ||
in_types = [] | ||
for label in self.types: | ||
if label == "return": continue | ||
in_labels.append(label) | ||
in_types.append(self.convert_python_types(self.types[label])) | ||
out_types = [self.convert_python_types(self.types['return'])] | ||
|
||
self.forward.tags["input"] = [PandasDataframe( | ||
columns=in_labels, | ||
column_types=in_types, | ||
column_shapes=[(1) * len(in_labels)] | ||
)] | ||
|
||
self.forward.tags["output"] = [PandasDataframe( | ||
columns=["output"], | ||
column_types=out_types, | ||
column_shapes=[(1) * len(out_types)], | ||
)] | ||
|
||
@property | ||
def name(self) -> str: | ||
return "SimpleUDF" | ||
|
||
@forward(None, None) | ||
def forward(self, df: pd.DataFrame) -> pd.DataFrame: | ||
def _forward(row: pd.Series) -> np.ndarray: | ||
temp = self.udf | ||
return temp(row) | ||
|
||
ret = pd.DataFrame() | ||
ret["output"] = df.apply(_forward, axis=1) | ||
return ret | ||
|
||
def set_udf(self, classname:str, filepath: str): | ||
if f"{EvaDB_ROOT_DIR}/simple_udfs/" in filepath: | ||
f = open(f"{EvaDB_ROOT_DIR}/simple_udfs/Func_SimpleUDF", 'rb') | ||
self.udf = pickle.load(f) | ||
else: | ||
try: | ||
abs_path = Path(filepath).resolve() | ||
spec = importlib.util.spec_from_file_location(abs_path.stem, abs_path) | ||
module = importlib.util.module_from_spec(spec) | ||
spec.loader.exec_module(module) | ||
except ImportError as e: | ||
# ImportError in the case when we are able to find the file but not able to load the module | ||
err_msg = f"ImportError : Couldn't load function from {filepath} : {str(e)}. Not able to load the code provided in the file {abs_path}. Please ensure that the file contains the implementation code for the function." | ||
raise ImportError(err_msg) | ||
except FileNotFoundError as e: | ||
# FileNotFoundError in the case when we are not able to find the file at all at the path. | ||
err_msg = f"FileNotFoundError : Couldn't load function from {filepath} : {str(e)}. This might be because the function implementation file does not exist. Please ensure the file exists at {abs_path}" | ||
raise FileNotFoundError(err_msg) | ||
except Exception as e: | ||
# Default exception, we don't know what exactly went wrong so we just output the error message | ||
err_msg = f"Couldn't load function from {filepath} : {str(e)}." | ||
raise RuntimeError(err_msg) | ||
|
||
# Try to load the specified class by name | ||
if classname and hasattr(module, classname): | ||
self.udf = getattr(module, classname) | ||
|
||
self.types = typing.get_type_hints(self.udf) | ||
|
||
def convert_python_types(self, type): | ||
if type == bool: | ||
return NdArrayType.BOOL | ||
elif type == int: | ||
return NdArrayType.INT32 | ||
elif type == float: | ||
return NdArrayType.FLOAT32 | ||
elif type == str: | ||
return NdArrayType.STR | ||
else: | ||
return NdArrayType.ANYTYPE |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
# coding=utf-8 | ||
# Copyright 2018-2023 EvaDB | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
import unittest | ||
from test.util import suffix_pytest_xdist_worker_id_to_dir | ||
|
||
import pytest | ||
import pandas as pd | ||
|
||
from evadb.configuration.constants import EvaDB_DATABASE_DIR, EvaDB_ROOT_DIR | ||
from evadb.interfaces.relational.db import connect | ||
from evadb.server.command_handler import execute_query_fetch_all | ||
|
||
def Func_SimpleUDF(cls, x:int)->int: | ||
return x + 10 | ||
|
||
@pytest.mark.notparallel | ||
class SimpleFunctionTests(unittest.TestCase): | ||
def setUp(self): | ||
self.db_dir = suffix_pytest_xdist_worker_id_to_dir(EvaDB_DATABASE_DIR) | ||
self.conn = connect(self.db_dir) | ||
self.evadb = self.conn._evadb | ||
self.evadb.catalog().reset() | ||
|
||
def tearDown(self): | ||
execute_query_fetch_all(self.evadb, "DROP TABLE IF EXISTS test_table;") | ||
execute_query_fetch_all(self.evadb, "DROP FUNCTION IF EXISTS My_SimpleUDF;") | ||
execute_query_fetch_all(self.evadb, "DROP FUNCTION IF EXISTS Func_SimpleUDF;") | ||
|
||
def test_from_file(self): | ||
cursor = self.conn.cursor() | ||
|
||
execute_query_fetch_all(self.evadb, "CREATE TABLE IF NOT EXISTS test_table (val INTEGER);") | ||
cursor.insert("test_table", "(val)", "(1)").df() | ||
|
||
cursor.create_function( | ||
"My_SimpleUDF", | ||
True, | ||
f"{EvaDB_ROOT_DIR}/evadb/functions/My_SimpleUDF.py", | ||
).df() | ||
|
||
result = cursor.query("SELECT My_SimpleUDF(val) FROM test_table;").df() | ||
expected = pd.DataFrame({'output': [6]}) | ||
|
||
self.assertTrue(expected.equals(result)) | ||
|
||
def test_from_function(self): | ||
cursor = self.conn.cursor() | ||
|
||
execute_query_fetch_all(self.evadb, "CREATE TABLE IF NOT EXISTS test_table (val INTEGER);") | ||
cursor.insert("test_table", "(val)", "(1)").df() | ||
|
||
cursor.create_simple_function( | ||
"Func_SimpleUDF", | ||
Func_SimpleUDF, | ||
True, | ||
).df() | ||
|
||
result = cursor.query("SELECT Func_SimpleUDF(val) FROM test_table;").df() | ||
expected = pd.DataFrame({'output': [11]}) | ||
|
||
self.assertTrue(expected.equals(result)) |