-
Notifications
You must be signed in to change notification settings - Fork 5
The require function
The require
function allows you to load external javascript files. The require
method takes a single string argument, which identifies a loadable script file. The script file is read, compiled and executed immediately, and the result is returned. This is the signature:
variant require(string script[, boolean reload]);
The script
argument must identify a valid javascript file. Require will attempt to load the script from the directory identified by the value of the js_module_path
system variable. This is a security measure which allows DBA's to limit the scripts which may be loaded.
The value returned by running the script is cached. Subsequent calls to require
using the same script
argument will draw the result value from the cache and reuse them. Module writes should ensure their script is stateless so that it can be properly reused.
The require()
function optionally accepts a second boolean argument. When true
, the specified module will be cleared from the cache and reloaded from source. It's primarily useful in case the script file needs to be modified after the module was already loaded.
If require encounters an error, an exception is thrown.
The require()
function can be used to hide the implementation details of entire functional udfs or aggregate udfs. Consider the following example:
mysql> select jsagg('require("json_export.js");', category_id, name) json from sakila.category;
...with the following result:
[
{
"category_id": 1,
"name": "Action"
},
...
{
"category_id": 16,
"name": "Travel"
}
]
As you can see, the script passed to jsagg
consists only of a single call to require()
. But we already mentioned that jsagg
requires the script to define a clear()
, udf()
and an add()
function. The reason why this works is that the json_export.js
script actually creates these functions. These are the contents of json_export.js
:
(function json_export(){
var rows, row, i, args = this.arguments, n = args.length, arg;
this.clear = function(){
rows = [];
}
this.udf = function() {
rows.push(row = {});
for (i = 0; i < n; i++) {
arg = args[i];
row[arg.name] = arg.value;
}
}
this.agg = function(){
return JSON.stringify(rows, null, " ");
}
})();