Function API#
Python関数からDuckDBユーザー定義関数(UDF)を作成
SQLクエリで利用できる
import duckdb
function_oid = duckdb.sql("SELECT function_oid FROM duckdb_functions() LIMIT 5")
function_oid.show()
┌──────────────┐
│ function_oid │
│ int64 │
├──────────────┤
│ 8 │
│ 1222 │
│ 1824 │
│ 1818 │
│ 1818 │
└──────────────┘
関数を定義
def pow_plus_one(x):
return x**2 + 1
create_function#
name: DuckDBに定義する関数の名前
function: 登録する関数
parameters: 関数に渡す引数の型のリスト
return_type: 返り値の型
type (Optional): 関数の種類、組込みのPython
native(デフォルト)、PyArrowテーブルarrownull_handling (Optional): null値の扱い、デフォルト(
None)ではNull-In Null-Out 、specialでnull値の扱いを指定exception_handling (Optional): 例外の扱い、デフォルト(
None)ではPythonの例外が送出、return_nullでnullを返すside_effects (Optional): デフォルト(
False)では同じ入力に同じ結果を返し、関数の結果がランダム性などの影響を受ける場合はTrueにする
duckdb.create_function("pow_plus_one", pow_plus_one, [float], float)
/tmp/ipykernel_154855/610389414.py:1: DeprecationWarning: numpy.core is deprecated and has been renamed to numpy._core. The numpy._core namespace contains private NumPy internals and its use is discouraged, as NumPy internals can change without warning in any release. In practice, most real-world usage of numpy.core is to access functionality in the public NumPy API. If that is the case, use the public NumPy API. If not, you are using NumPy internals. If you would still like to access an internal attribute, use numpy._core.multiarray.
duckdb.create_function("pow_plus_one", pow_plus_one, [float], float)
<duckdb.duckdb.DuckDBPyConnection at 0x7f035434b470>
duckdb.sql("SELECT pow_plus_one(function_oid) FROM function_oid")
┌────────────────────────────┐
│ pow_plus_one(function_oid) │
│ double │
├────────────────────────────┤
│ 65.0 │
│ 1493285.0 │
│ 3326977.0 │
│ 3305125.0 │
│ 3305125.0 │
└────────────────────────────┘
関数の定義を削除
duckdb.remove_function("pow_plus_one")
<duckdb.duckdb.DuckDBPyConnection at 0x7f035434b470>
関数に型ヒントを定義することで、オプションのパラメータを省略できる
def pow_plus_two(x: float) -> float:
return x**2 + 2
duckdb.create_function("pow_plus_two", pow_plus_two)
duckdb.sql("SELECT pow_plus_two(function_oid) FROM function_oid")
┌────────────────────────────┐
│ pow_plus_two(function_oid) │
│ double │
├────────────────────────────┤
│ 66.0 │
│ 1493286.0 │
│ 3326978.0 │
│ 3305126.0 │
│ 3305126.0 │
└────────────────────────────┘
DuckDBのデータ型を明示する場合、DuckDBPyTypeオブジェクトを指定する
import datetime
from duckdb.typing import DATE
def nice_day() -> str:
return str(datetime.date.today())
duckdb.create_function("nice_day", nice_day, return_type=DATE)
duckdb.sql("SELECT nice_day()")
┌────────────┐
│ nice_day() │
│ date │
├────────────┤
│ 2024-10-15 │
└────────────┘