@Urvashi @RavindraNitwal
Users can define their own expression functions in C++ in <tigergraph.root.dir>/dev/gdk/gsql/src/QueryUdf/ExprFunctions.hpp. Only bool, int, float, double, and string (NOT std::string) are allowed as the return value type and the function argument type. However, any C++ type is allowed inside a function body. Once defined, the new functions will be added into GSQL automatically next time GSQL is executed.
If a user-defined struct or a helper function needs to be defined, define it in <tigergraph.root.dir>/dev/gdk/gsql/src/QueryUdf/ExprUtil.hpp.
STEP 1) Add – new code in ExprFunction.hpp
#include <algorithm> // for std::reverse
inline bool greater_than_three (double x) {
return x > 3;
}
inline string reverse(string str){
std::reverse(str.begin(), str.end());
return str;
}
STEP 2) Call – user defined expression function
CREATE QUERY udfExample() FOR GRAPH minimalNet {
DOUBLE x;
BOOL y;
x = 3.5;
PRINT greater_than_three(x);
y = greater_than_three(2.5);
PRINT y;
PRINT reverse("abc");
}
STEP 3) Execute – udfExample.json Results
GSQL > RUN QUERY udfExample()
{
"error": false,
"message": "",
"version": {
"edition": "developer",
"schema": 0,
"api": "v2"
},
"results": [
{"greater_than_three(x)": true},
{"y": false},
{"reverse(abc)": "cba"}
]
}
If any code in ExprFunctions.hpp or ExprUtil.hpp causes a compilation error, GSQL cannot install any GSQL query, even if the GSQL query doesn’t call any user-defined function. Therefore, please test each new user-defined expression function after adding it. One way of testing the function is creating a new cpp file test.cpp and compiling it by
g++ test.cpp
./a.out
You might need to remove the include header #include <gle/engine/cpplib/headers.hpp> in ExprFunction.hpp and ExprUtil.hpp in order to compile.
For Testing test.cpp
#include "ExprFunctions.hpp"
#include <iostream>
int main () {
std::cout << to_string (123) << std::endl; // to_string and str_to_int are two built-in functions in ExprFunction.hpp
std::cout << str_to_int ("123") << std::endl;
return 0;
}