Skip to main content
JavaScript code is inlined in CREATE FUNCTION statement and then run on the embedded QuickJS virtual machine in RisingWave. It does not support access to external networks and is limited to computational tasks only. Compared to other languages, JavaScript UDFs offer the easiest way to define UDFs in RisingWave.

Define your functions

You can use the CREATE FUNCTION command to create JavaScript UDFs.

Basic JavaScript UDFs

Syntax
The argument names you defined can be used in the function body. For example:
See the correspondence between SQL types and JavaScript types in the Data type mapping. You need to ensure that the type of the return value is either null or consistent with the type in the RETURNS clause. If the function you defined returns a table, you need to use the yield statement to return the data of each row. For example:

Async and batched JavaScript UDFs

Added in v2.3.0.
You can create JavaScript UDFs with asynchronous execution and batch processing using the following syntax.
Syntax
  • async: Set to true to enable async functions like await fetch().
  • batch: Set to true to process multiple batches. Make sure each argument of the function accepts an array of arg_type.
Example

Use your functions

Once the UDFs are created in RisingWave, you can use them in SQL queries just like any built-in functions. For example:

Define your aggregate functions

You can create aggregate functions using the CREATE AGGREGATE command. Refer to the syntax below:
In the function_body, the code should define several exported functions to implement the aggregate function. Required functions:
  • create_state() -> state: Create a new state.
  • accumulate(state, *args) -> state: Accumulate a new value into the state, returning the updated state.
Optional functions:
  • finish(state) -> value: Get the result of the aggregate function. If not defined, the state is returned as the result.
  • retract(state, *args) -> state: Retract a value from the state, returning the updated state. If not defined, the state can not be updated incrementally in materialized views and performance may be affected.
The following command creates an aggregate function named weighted_avg to calculate the weighted average.
JavaScript UDAF

Data type mapping

The following table shows the data type mapping between SQL and JavaScript: