Introduction to Java UDFs | Snowflake Documentation (original) (raw)

You can write the handler for a user-defined function (UDF) in Java. Topics in this section describe how to design and write a Java handler. You’ll also find examples.

For an introduction to UDFs, including a list of languages in which you can write a UDF handler, refer to User-defined functions overview.

Once you have a handler, you create the UDF with SQL. For information on using SQL to create or call a UDF, refer toCreating a user-defined function or Executing a UDF.

Snowflake currently supports writing UDFs in the following versions of Java:

How a Java handler works

When a user calls a UDF, the user passes UDF’s name and arguments to Snowflake. Snowflake calls the associated handler code (with arguments, if any) to execute the UDF’s logic. The handler method then returns the output to Snowflake, which passes it back to the client.

For each row passed to a UDF, the UDF returns either a scalar (i.e. single) value or, if defined as a table function, a set of rows.

Java UDFs can contain both new code and calls to existing libraries, allowing you both flexibility and code reuse. For example, if you already have data analysis code in Java, then you can probably incorporate that into a Java UDF.

Below is a simplified illustration of the data flow:

UDF Data Flow

Example

Code in the following example creates a UDF called echo_varchar with a handler method TestFunc.echoVarchar. The Java argument and return types are converted to and from SQL by Snowflake according to mappings described inSQL-Java Data Type Mappings.

CREATE OR REPLACE FUNCTION echo_varchar(x VARCHAR) RETURNS VARCHAR LANGUAGE JAVA CALLED ON NULL INPUT HANDLER = 'TestFunc.echoVarchar' TARGET_PATH = '@~/testfunc.jar' AS 'class TestFunc { public static String echoVarchar(String x) { return x; } }';

Design considerations

Keep in mind the following for designing a useful handler.

Handler coding

From basics to detailed examples, the following topics describe how to write a UDF handler in Java.