Creating a Java UDF handler (original) (raw)

This topic describes how to write the Java handler for a user-defined function (UDF). When you write a Java UDF, you write Java code for Snowflake to execute as UDF logic. This Java code is the UDF’s handler.

You deploy the UDF with CREATE FUNCTION, giving the UDF a name and specifying the Java method as the handler to use when the UDF is called. For more information about creating a UDF with SQL, see Creating a user-defined function.

For more example code, see Java UDF handler examples.

Writing the UDF handler in Java

Use the following requirements and guidelines when writing your Java UDF handler.

Adding dependencies to the classpath

When your handler code requires classes packaged in external JAR files, you can add these dependencies to the Snowflake-managed classpath available to your handler. The following describes how to add JAR files to the classpath visible to a Java UDF handler. For more information, see Making dependencies available to your code.

Organizing your files

If you plan to compile the Java code to create the JAR file yourself, you can organize the files as shown below. This example assumes that you plan to use Java’s package mechanism.

_developmentDirectory_

This directory contains the project-specific files required to create your Java UDF.

_packageDirectory_

This directory contains the .java files to compile and include in the package.

_classfile#.java_

These files contain the Java source code of the UDF.

_classfile#.class_

These are the .class file(s) created by compiling the .java files.

_manifestfile.manifest_

The optional manifest file used when combining the .class files (and optionally, dependency JAR files) into the JAR file.

_jarfile.jar_

The JAR file that contains the UDF code.

_putcommand.sql_

This file contains the SQL PUT command to copy the JAR file to a Snowflakestage.

Compiling the Java code and creating the JAR file

To create a JAR file that contains the compiled Java code:

Copying the JAR file to your stage

In order for Snowflake to read from the JAR containing your handler method, you need to copy the JAR to one of the following kinds of stage:

The stage hosting the JAR file must be readable by the owner of the UDF.

Typically, you upload the JAR to a named internal stage using the PUT command. Note that you can’t execute the PUT command through the Snowflake GUI; you can use SnowSQL to execute PUT. See theJava UDF handler examples section for an example PUT command to copy a .jar file to a stage.

For more about creating stages, see CREATE STAGE.

Caveats and Best Practices

If you delete or rename the JAR file, you can no longer call the UDF.

If you need to update your JAR file, then: