|
| 1 | +--- |
| 2 | +title: CREATE EMBEDDED FUNCTION |
| 3 | +sidebar_position: 2 |
| 4 | +--- |
| 5 | +import FunctionDescription from '@site/src/components/FunctionDescription'; |
| 6 | + |
| 7 | +<FunctionDescription description="Introduced or updated: v1.2.339"/> |
| 8 | + |
| 9 | +Creates an Embedded UDF using programming languages (Python, JavaScript, WASM). Uses the same unified `$$` syntax as SQL functions for consistency. |
| 10 | + |
| 11 | +## Syntax |
| 12 | + |
| 13 | +```sql |
| 14 | +CREATE [ OR REPLACE ] FUNCTION [ IF NOT EXISTS ] <function_name> |
| 15 | + ( [<parameter_list>] ) |
| 16 | + RETURNS <return_type> |
| 17 | + LANGUAGE <language> |
| 18 | + [IMPORTS = ('<import_path>', ...)] |
| 19 | + [PACKAGES = ('<package_path>', ...)] |
| 20 | + HANDLER = '<handler_name>' |
| 21 | + AS $$ <function_code> $$ |
| 22 | + [ DESC='<description>' ] |
| 23 | +``` |
| 24 | + |
| 25 | +Where: |
| 26 | +- `<parameter_list>`: Comma-separated list of parameters with their types (e.g., `x INT, name VARCHAR`) |
| 27 | +- `<return_type>`: The data type of the function's return value |
| 28 | +- `<language>`: Programming language (`python`, `javascript`, `wasm`) |
| 29 | +- `<import_path>`: Stage files to import (e.g., `@s_udf/your_file.zip`) |
| 30 | +- `<package_path>`: Packages to install from pypi (Python only) |
| 31 | +- `<handler_name>`: Name of the function in the code to call |
| 32 | +- `<function_code>`: The implementation code in the specified language |
| 33 | + |
| 34 | +## Supported Languages |
| 35 | + |
| 36 | +| Language | Description | Enterprise Required | Package Support | |
| 37 | +|----------|-------------|-------------------|-----------------| |
| 38 | +| `python` | Python 3 with standard library | Yes | PyPI packages via PACKAGES | |
| 39 | +| `javascript` | Modern JavaScript (ES6+) | No | No | |
| 40 | +| `wasm` | WebAssembly (Rust compiled) | No | No | |
| 41 | + |
| 42 | +## Data Type Mappings |
| 43 | + |
| 44 | +### Python |
| 45 | +| Databend Type | Python Type | |
| 46 | +|--------------|-------------| |
| 47 | +| NULL | None | |
| 48 | +| BOOLEAN | bool | |
| 49 | +| INT | int | |
| 50 | +| FLOAT/DOUBLE | float | |
| 51 | +| DECIMAL | decimal.Decimal | |
| 52 | +| VARCHAR | str | |
| 53 | +| BINARY | bytes | |
| 54 | +| LIST | list | |
| 55 | +| MAP | dict | |
| 56 | +| STRUCT | object | |
| 57 | +| JSON | dict/list | |
| 58 | + |
| 59 | +### JavaScript |
| 60 | +| Databend Type | JavaScript Type | |
| 61 | +|--------------|----------------| |
| 62 | +| NULL | null | |
| 63 | +| BOOLEAN | Boolean | |
| 64 | +| INT | Number | |
| 65 | +| FLOAT/DOUBLE | Number | |
| 66 | +| DECIMAL | BigDecimal | |
| 67 | +| VARCHAR | String | |
| 68 | +| BINARY | Uint8Array | |
| 69 | +| DATE/TIMESTAMP | Date | |
| 70 | +| ARRAY | Array | |
| 71 | +| MAP | Object | |
| 72 | +| STRUCT | Object | |
| 73 | +| JSON | Object/Array | |
| 74 | + |
| 75 | +## Access Control Requirements |
| 76 | + |
| 77 | +| Privilege | Object Type | Description | |
| 78 | +|:----------|:--------------|:---------------| |
| 79 | +| SUPER | Global, Table | Operates a UDF | |
| 80 | + |
| 81 | +To create an embedded function, the user performing the operation or the [current_role](/guides/security/access-control/roles) must have the SUPER [privilege](/guides/security/access-control/privileges). |
| 82 | + |
| 83 | +## Examples |
| 84 | + |
| 85 | +### Python Function |
| 86 | + |
| 87 | +```sql |
| 88 | +-- Simple Python function |
| 89 | +CREATE FUNCTION calculate_age_py(VARCHAR) |
| 90 | +RETURNS INT |
| 91 | +LANGUAGE python HANDLER = 'calculate_age' |
| 92 | +AS $$ |
| 93 | +from datetime import datetime |
| 94 | + |
| 95 | +def calculate_age(birth_date_str): |
| 96 | + birth_date = datetime.strptime(birth_date_str, '%Y-%m-%d') |
| 97 | + today = datetime.now() |
| 98 | + age = today.year - birth_date.year |
| 99 | + if (today.month, today.day) < (birth_date.month, birth_date.day): |
| 100 | + age -= 1 |
| 101 | + return age |
| 102 | +$$; |
| 103 | + |
| 104 | +-- Use the function |
| 105 | +SELECT calculate_age_py('1990-05-15') AS age; |
| 106 | +``` |
| 107 | + |
| 108 | +### JavaScript Function |
| 109 | + |
| 110 | +```sql |
| 111 | +-- JavaScript function for age calculation |
| 112 | +CREATE FUNCTION calculate_age_js(VARCHAR) |
| 113 | +RETURNS INT |
| 114 | +LANGUAGE javascript HANDLER = 'calculateAge' |
| 115 | +AS $$ |
| 116 | +export function calculateAge(birthDateStr) { |
| 117 | + const birthDate = new Date(birthDateStr); |
| 118 | + const today = new Date(); |
| 119 | + |
| 120 | + let age = today.getFullYear() - birthDate.getFullYear(); |
| 121 | + const monthDiff = today.getMonth() - birthDate.getMonth(); |
| 122 | + |
| 123 | + if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { |
| 124 | + age--; |
| 125 | + } |
| 126 | + |
| 127 | + return age; |
| 128 | +} |
| 129 | +$$; |
| 130 | + |
| 131 | +-- Use the function |
| 132 | +SELECT calculate_age_js('1990-05-15') AS age; |
| 133 | +``` |
| 134 | + |
| 135 | +### Python Function with Packages |
| 136 | + |
| 137 | +```sql |
| 138 | +CREATE FUNCTION ml_model_score() |
| 139 | +RETURNS FLOAT |
| 140 | +LANGUAGE python IMPORTS = ('@s1/model.zip') PACKAGES = ('scikit-learn') HANDLER = 'model_score' |
| 141 | +AS $$ |
| 142 | +from sklearn.datasets import load_iris |
| 143 | +from sklearn.model_selection import train_test_split |
| 144 | +from sklearn.ensemble import RandomForestClassifier |
| 145 | + |
| 146 | +def model_score(): |
| 147 | + X, y = load_iris(return_X_y=True) |
| 148 | + X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) |
| 149 | + |
| 150 | + model = RandomForestClassifier() |
| 151 | + model.fit(X_train, y_train) |
| 152 | + return model.score(X_test, y_test) |
| 153 | +$$; |
| 154 | + |
| 155 | +-- Use the function |
| 156 | +SELECT ml_model_score() AS accuracy; |
| 157 | +``` |
| 158 | + |
| 159 | +### WASM Function |
| 160 | + |
| 161 | +First, create a Rust project and compile to WASM: |
| 162 | + |
| 163 | +```toml |
| 164 | +# Cargo.toml |
| 165 | +[package] |
| 166 | +name = "arrow-udf-example" |
| 167 | +version = "0.1.0" |
| 168 | + |
| 169 | +[lib] |
| 170 | +crate-type = ["cdylib"] |
| 171 | + |
| 172 | +[dependencies] |
| 173 | +arrow-udf = "0.8" |
| 174 | +``` |
| 175 | + |
| 176 | +```rust |
| 177 | +// src/lib.rs |
| 178 | +use arrow_udf::function; |
| 179 | + |
| 180 | +#[function("fib(int) -> int")] |
| 181 | +fn fib(n: i32) -> i32 { |
| 182 | + let (mut a, mut b) = (0, 1); |
| 183 | + for _ in 0..n { |
| 184 | + let c = a + b; |
| 185 | + a = b; |
| 186 | + b = c; |
| 187 | + } |
| 188 | + a |
| 189 | +} |
| 190 | +``` |
| 191 | + |
| 192 | +Build and deploy: |
| 193 | + |
| 194 | +```bash |
| 195 | +cargo build --release --target wasm32-wasip1 |
| 196 | +# Upload to stage |
| 197 | +CREATE STAGE s_udf; |
| 198 | +PUT fs:///target/wasm32-wasip1/release/arrow_udf_example.wasm @s_udf/; |
| 199 | +``` |
| 200 | + |
| 201 | +```sql |
| 202 | +-- Create WASM function |
| 203 | +CREATE FUNCTION fib_wasm(INT) |
| 204 | +RETURNS INT |
| 205 | +LANGUAGE wasm HANDLER = 'fib' |
| 206 | +AS $$@s_udf/arrow_udf_example.wasm$$; |
| 207 | + |
| 208 | +-- Use the function |
| 209 | +SELECT fib_wasm(10) AS fibonacci_result; |
| 210 | +``` |
| 211 | + |
0 commit comments