Search code examples
user-defined-functionsarangodbaql

How to specify database name in UDF?


I wrote small UDF (based on docs page):

function greeting() {
    const db = require('@arangodb').db; 
    let result = db._query('for d in docs FILTER p.id == "123" return d').toArray()[0]
    return result;
}

module.exports = greeting;

The problem that it work only with default _system db. How to specify another?

I found mention in docs:

Changing the database might be disallowed in some contexts, for example server-side actions (including Foxx).

So it's impossible?! it's absurd!


Solution

  • From the docs:

    Internally, UDFs are stored in a system collection named _aqlfunctions of the selected database. When an AQL statement refers to such a UDF, it is loaded from that collection. The UDFs will be exclusively available for queries in that particular database.

    If you have a database myDB, then make sure to register the UDF for that database:

    arangosh --server.database myDB ...
    

    or connect to the default database and switch to the right one:

    db._useDatabase("myDB");
    aqlfunctions.register(...);
    

    You cannot access different databases from within a UDF, it is restricted to the current database by design - it is an extension mechanism for AQL, which is executed in the context of a single database.