Hi dear all,
I would like to share our experimental tests about, writing UDF with python.
So the basic idea was writing a UDF for factorial calculation. The interesting part was to move factorial calculation logic to Python code and then calling this Python file inside UDF code.
Here is the repo link -> UDFs-written-in-Python
The factorial calculation is here -> factorial.py
UDF code is here -> factorial.cc
Basic idea with UDF code quite simple as it has 3 parts:
1. initialization part -> factorial_init() -> all necessary checks reside here
2. main logic -> factorial() -> calling Python script, reading data back and showing the result.
3. deinitialization -> factorial_deinit()
Compiled as:
gcc $(/home/sh/REPOS/mysql_DEV_ACTIONS/mysql-5.7/mysql-server/5.7.16/bin/mysql_config --cflags) -fPIC -shared -o factorial.so factorial.cc -std=c++11
Copied to plugin_dir:
cp factorial.so /home/sh/REPOS/MYSQL_DEV_ACTIONS/mysql-5.7/mysql-server/5.7.16/lib/plugin/ cp factorial.py /home/sh/REPOS/MYSQL_DEV_ACTIONS/mysql-5.7/mysql-server/5.7.16/lib/plugin/Activated as:
mysql > create function factorial returns integer soname 'factorial.so';Result:
root@test1:~# python --version Python 2.7.12 mysql> select factorial(5); +--------------+ | factorial(5) | +--------------+ | 120 | +--------------+ 1 row in set (0.02 sec)