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 = Deterministic.yes)
  2. void createFunction(string name, T fun = null)
    struct Database
    void
    createFunction
    (
    T
    )
    (
    string name
    ,
    T fun = null
    )
    if (
    is(T == typeof(null))
    )

Parameters

name
Type: string

The name that the function will have in the database.

fun
Type: 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

1 string star(int count, string starSymbol = "*")
2 {
3     import std.range : repeat;
4     import std.array : join;
5 
6     return starSymbol.repeat(count).join;
7 }
8 
9 auto db = Database(":memory:");
10 db.createFunction("star", &star);
11 assert(db.execute("SELECT star(5)").oneValue!string == "*****");
12 assert(db.execute("SELECT star(3, '♥')").oneValue!string == "♥♥♥");
1 // The implementation of the new function
2 string myList(ColumnData[] args)
3 {
4     import std.array : appender;
5     import std.string : format, join;
6 
7     auto app = appender!(string[]);
8     foreach (arg; args)
9     {
10         if (arg.type == SqliteType.TEXT)
11             app.put(`"%s"`.format(arg));
12         else
13             app.put("%s".format(arg));
14     }
15     return app.data.join(", ");
16 }
17 
18 auto db = Database(":memory:");
19 db.createFunction("my_list", &myList);
20 auto list = db.execute("SELECT my_list(42, 3.14, 'text', NULL)").oneValue!string;
21 assert(list == `42, 3.14, "text", null`);

See Also

Meta