Database.createFunction

Creates and registers a new function in the database.

If a function with the same name and the same arguments already exists, it is replaced by the new one.

The memory associated with the function will be released when the database connection is closed.

  1. void createFunction(string name, T fun, Deterministic det)
  2. void createFunction(string name, T fun)
    struct Database
    private public
    void
    createFunction
    (
    T
    )
    (
    string name
    ,
    T fun = null
    )
    if (
    is(T == typeof(null))
    )

Parameters

name string

The name that the function will have in the database.

fun T

a delegate or function that implements the function. fun must satisfy the following criteria:

  • It must not be variadic.
  • Its arguments must all have a type that is compatible with SQLite types: it must be a boolean or numeric type, a string, an array, null, or a Nullable!T where T is any of the previous types.
  • Its return value must also be of a compatible type.

or

  • It must be a normal or type-safe variadic function where the arguments are of type ColumnData. In other terms, the signature of the function must be: function(ColumnData[] args) or function(ColumnData[] args...)
  • Its return value must be a boolean or numeric type, a string, an array, null, or a Nullable!T where T is any of the previous types.

Pass a null function pointer to delete the function from the database connection.

Examples

string star(int count, string starSymbol = "*")
{
    import std.range : repeat;
    import std.array : join;

    return starSymbol.repeat(count).join;
}

auto db = Database(":memory:");
db.createFunction("star", &star);
assert(db.execute("SELECT star(5)").oneValue!string == "*****");
assert(db.execute("SELECT star(3, '♥')").oneValue!string == "♥♥♥");
// The implementation of the new function
string myList(ColumnData[] args)
{
    import std.array : appender;
    import std.string : format, join;

    auto app = appender!(string[]);
    foreach (arg; args)
    {
        if (arg.type == SqliteType.TEXT)
            app.put(`"%s"`.format(arg));
        else
            app.put("%s".format(arg));
    }
    return app.data.join(", ");
}

auto db = Database(":memory:");
db.createFunction("my_list", &myList);
auto list = db.execute("SELECT my_list(42, 3.14, 'text', NULL)").oneValue!string;
assert(list == `42, 3.14, "text", null`);

See Also

Meta