Wednesday, June 03, 2015

Javascript Inside the Database


Where there's a will, there's a way. Not sure on the best use of this off hand but here it is.

Javascript inside an Oracle Database.

Since Javascript is included in java via the ScriptEngine framework. It's fairly easy to add a java wrapper to call the javascript engine.
create or replace and compile java source named "EvalScript" as
import javax.script.*;
public class EvalScript {
    public static String eval(String argument) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("javascript");

        // set the param into the javascript context
        engine.put("s", argument);

        // evaluate JavaScript code from String
        return  engine.eval("var a='hi';  a + ', ' + s;").toString();
        //return "a";
    }
}
/

Then the standard plsql wrapper to call a java stored procedure.
create or replace function eval (argument in varchar2)
 return varchar2  as language java
name 'EvalScript.eval(java.lang.String) return java.lang.String';


Now you can simply call that function and the return is from javascript OR make a REST call via ORDS.

This is a simple REST call that takes in {name} and passes it to the function just created.






Then pass in the value to be passed in to the javascript engine and you now have ORDS + DB + Server Side javascript.




Disqus for Kris' Blog