10 Using External Functions
DataDirect XQuery supports two types of external functions: Java and SQL. External functions are implemented outside the query environment.
Java functions might be used to return system information, to invoke a web service call, or simply to make a function available that is not in the XQuery function library.
SQL functions might be used to invoke a stored procedure or to make a function available that is not in the XQuery function library.
All external functions are namespace qualified, and the namespace that is used tells DataDirect XQuery whether the external function is written in Java or in SQL. Before calling such a function, it must be declared in the query.
Example: Java Function (Static Method)
Suppose an application needs to return information about the Java environment in which a query runs. The following Java code defines a class that contains the function to retrieve this information in Java:
public class myClass extends Object { ... public static String myExternalFunction() { StringBuffer returnBuffer = new StringBuffer(); Properties systemProperties = System.getProperties(); returnBuffer.append("VM Version:" + systemProperties.get("java.vm.version") + "\n"); returnBuffer.append("VM Vendor:" + systemProperties.get("java.vm.vendor") + "\n"); returnBuffer.append("VM Name:" + systemProperties.get("java.vm.name")); return returnBuffer.toString(); } }Now, the function must be declared, as shown in the following query:
declare namespace ex="ddtekjava:myClass"; declare function ex:myExternalFunction() as xs:string external; let $infoString := ex:myExternalFunction() return let($infoString := ex:myExternalFunction() return <vm_info>{$infoString}</vm_info>)In the preceding XQuery expression, the XQuery binds a namespace prefix (
ex) to the fully qualified name of the class that defines the function.Example: SQL Function
A SQL function can be called in a similar way to calling a Java function. The namespace for a SQL function is the predefined namespace, http://www.datadirect.com/xquery/sql-function, which is bound to the predefined prefix ddtek-sql. The following example calls the SQL function rtrim().