eXtremeSQL User Defined Functions

eXtremeSQL supports “stored procedures” by allowing developers to create their own Lua User-Defined Functions (UDFs). An eXtremeSQL UDF can also be written in Python or C/C++. These methods are described in the sections below.

The eXtremeSQL server provides an internal service that lists all UDFs through a meta table called Metafunction, which can be queried like any SQL table:

    select * from Metafunction;
    Name        Profile       ReturnType  nArguments  Language
    ----------------------------------------------------------
    format      String(...)   15          2           C++
    choice      String(...)   15          3           C++
    trim        String(...)   15          1           C++
    ...

Note that the Metafunction pseudo-table returns information about statically registered functions (written in C++) as well as dynamically created functions that were registered by the current connection via the CREATE FUNCTION statement. A complete list of all user-defined functions can be found in the Functions table (if it exists).

If the preloadUDF parameter of SqlOptimizerParameters is set to true, all functions are loaded at database open time, and the Metafunction table will contain the complete list (both dynamically loaded and statically linked).

Also note that if the number of arguments is listed as -1, this indicates a variable number of arguments.

Lua UDFs

Lua is an elegant, widely adopted scripting language with a rich grammar that supports operator overloading, encapsulation, inheritance, polymorphism, and more. Lua's sophisticated and fast Just-In-Time compiler (LuaJIT) and small footprint make it an excellent procedural language for developing complex database UDFs and stored procedures for the eXtremeSQL server. Lua-based UDFs run in the context of the SQL server, eliminating client-server IPC and network overhead while fully utilizing modern multi-core hardware.

(Please see Using Lua with eXtremeSQL for further details.)

Python UDFs

It is also possible to create UDFs in Python if the Python class SqlEngine is used to create the eXtremeDB database. The following steps are required:

  1. Ensure that Python 3.9 or higher is installed and the corresponding shared library is available on the system (e.g., libpython3.9.so on Linux). By default, the runtime searches for the library in the standard system library paths. You can override this behavior by setting the PYTHONLIB or MCO_PYTHONLIB environment variable:
        export PYTHONLIB=/opt/build/my/python/libpython3.9.so
    
    To locate the exact path of the Python shared library on a Linux system, you can run the following command:
        python3 -c '
        import sysconfig, os
        libdir = sysconfig.get_config_var("LIBDIR")
        libname = sysconfig.get_config_var("LDLIBRARY")
        print(os.path.join(libdir, libname) if libname else "Not found")
        '
    
  2. Declare the Python function that performs the desired operations. The function arguments will map to the UDF parameters, and the return value will be translated to an SQL value. For example:
        def gen_quotes(Bid, BidSize):
            ...
            Bid.append(some_bids)
            BidSize.append(some_bid_sizes)
            return len(some_bids)
    
    The code indicated by the ellipsis (…) would use sequence iterators to generate a list of bid values and sizes from the Bid and BidSz fields into the variables some_bids and some_bid_sizes.
  3. Register the UDF in the SQL engine using the SqlEngine object created (by default) for the local connection:
        conn.engine.registerFunction(int, "gen_quotes", gen_quotes, -1)
    
  4. Call the UDF as part of a SQL SELECT statement. Assuming a table with columns Bid and BidSz populated with records, you can generate bids and return the total count as follows:
        SELECT sum(gen_quotes(Bid, BidSz)) FROM Bids FOR UPDATE;
    
    (Note that the FOR UPDATE clause is required because the UDF modifies sequences Bid and BidSz using sequence iterators.)

C/C++ UDFs

A C/C++ scalar UDF must be defined to return type static String* and accept arguments of type Value*. A user-defined aggregate function must return static Value* and also accept Value* arguments. (Please see Dynamic Memory Allocation in SQL for details on processing queries in UDFs.)

The UDF can be statically linked by registering it with the eXtremeSQL runtime via the C/C++ API. This is done by declaring a function of type static SqlFunctionDeclaration udf() with arguments specifying the return type, the name used to call it, a pointer to the implementation, and the number of required arguments. (Note that eXtremeDB has a separate concept of user-defined functions for indexes; this section covers only SQL UDFs.) For example:

    extern "C"
    {
        McoSql::Value* toggleTrace(McoSql::SqlEngine* engine,
                                   McoSql::Vector<McoSql::Value>* args)
        {
            McoSql::Value *enable = args->getAt(0);
            return BoolValue::create(engine->trace(enable->isTrue()));
        }
    }

(Note that the extern "C" declaration is necessary to prevent C++ name mangling.)

The UDF can also be loaded dynamically using the SQL CREATE FUNCTION statement, which has the following syntax:

    create function NAME ( param1_name param1_type, ...,
                           paramN_name paramN_type)
    returns result_type as 'LIBRARY-NAME' [, 'C_FUNCTION-NAME'];

For example:

    create function toggleTrace(enable bit) returns bit as 'mysharedlib';

(Note that if the library name lacks a suffix, the server automatically appends it: on UNIX it becomes libxxx.so, and on Windows it becomes xxx.dll.)

Once registered, the UDF can be invoked via a SELECT statement:

    select toggleTrace(true);

Unlike statically linked functions, dynamically loaded UDFs retain internal metadata about their argument types. These types are validated by the SQL compiler. The SQL engine internally represents all integer types as 64-bit integers (int8) and floating-point types as doubles (real8). When a function argument is declared as a different scalar type, implicit conversion is applied. Thus, a function declared to accept a float will actually receive a double (represented as a RealValue object) and must return a RealValue as well (there is no way to return a native float in the SQL API).

Modifying Data Using Dynamically Loaded UDFs

UDFs can modify database data, execute SQL statements or queries, and work with sequence iterators. For example:

    McoSql::Value *load_cme_trades(McoSql::SqlEngine *engine,
                                   McoSql::Vector<McoSql::Value> *args)
    {
        McoSql::DataSource *res = engine->executeQuery(
            engine->getCurrentTransaction(),
            "SELECT TradeDateTime, SeqNum, GroupCode, ProductCode, "
            "InstrumentName, EntryPrice, EntryQuantity, AggressorSide, "
            "TickDirection FROM TOBSeq WHERE Book = %s AND "
            "SecurityID = %i AND EntryType = %s",
            Book.c_str(), SecurityID, EntryType.c_str());
        ...
    }

Subsequent operations run in the context of the transaction that called the UDF. If the UDF modifies data, the transaction must be READ_WRITE. For INSERT and UPDATE statements, the transaction upgrades automatically. However, if you need to modify sequence data using a sequence iterator, you must explicitly upgrade the transaction within the UDF code:

        ...
        McoSql::Cursor *cursor = res->records();
        McoSql::Record *rec = cursor->next();
        McoSequence<int8> *fldEntryPrice = dynamic_cast
            <McoSequence<int8>*>(rec->get(5));

        engine->getCurrentTransaction()->upgrade();
        EntryPrice->append(values, 1000);
        ...

where EntryPrice is a sequence field in the TOBSeq database object.

Notes on Using Sequences with UDFs

UDF code can access sequence iterators and perform operations on them. A sequence iterator is represented by an object of class McoGenericSequence or one of its descendants. Keep the following in mind:

Appending to a sequence

You can append values to a sequence using McoGenericSequence::append() only if the sequence is materialized. A materialized sequence is represented by an McoSequence<T> object, which provides the following method:

    virtual void append(T const* items, mco_size_t nItems);

Here, T is the actual sequence data type. You cannot append items to a non-materialized sequence. The transaction must be opened in READ_WRITE mode. If using automatic transactions with a SELECT statement to access sequence fields, use SELECT ... FOR UPDATE as shown in the previous examples.

Iterating over sequences

Sequences may be iterated in two ways:

  1. Using low-level iterators obtained via McoGenericSequence::getIterator().
  2. Using McoSql::Value* McoGenericSequence::next(), which returns an IntValue, RealValue, or String representing the next element, or NULL if no more elements exist.

In some scenarios, the iterator may not be initialized. It is best practice to call getIterator() before next() to ensure proper initialization:

    {
        McoGenericSequence *time_it = dynamic_cast
            <McoGenericSequence *>(args->get(0));
        if (time_it == NULL)
        {
            process_error();
        }
        time_it->getIterator();
        for (McoSql::Value *vt; vt != NULL; vt = time_it->next())
        {
            ...
        }
    }

Sequence classes

As noted above, sequences may be represented as either McoGenericSequence or McoSequence<T>, depending on the context. Use McoSequence<T> only when necessary, such as when updating or appending to a sequence.

NULL Arguments to UDFs

You can pass NULL as an argument value to a user-defined function. For example:

    create function sf(s string) returns string in 'lua' as 'return s end';
    create table t(s string);
    insert into t values(['hello', null]);
    select sf(s) from t;
    select sf(null);

    #1
    ------------------------------------------------------------------------------
    hello
    null

    Selected records: 2