# Is it hard to support Julia UDFs in DuckDB?

**URL:** https://discourse.julialang.org/t/is-it-hard-to-support-julia-udfs-in-duckdb/118509
**Category:** Data
**Created:** [August 23, 2024, 12:11am UTC](https://discourse.julialang.org/t/is-it-hard-to-support-julia-udfs-in-duckdb/118509 "2024-08-23T00:11:59Z")
**Posts on this page:** 1
**Showing post:** 23

<div class="post-metadata">

### Author: ![tqml](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tqml/32/22710_2.png) [@tqml](https://discourse.julialang.org/u/tqml)
#### Post date: [December 19, 2024, 6:20pm UTC](https://discourse.julialang.org/t/is-it-hard-to-support-julia-udfs-in-duckdb/118509/23 "2024-12-19T18:20:11Z")

</div>

Update: I opened a thread to gather ideas how this can be implemented properly. The main problem seems to be that `@cfunction` only accepts objects in global scope (at leat to my understanding).

Not sure if a simple API like

```julia
fun = @create_scalar_function my_sum(::Int64, ::Int64)::Int64

```

is possible due to this limitation (which might be a bummer 😕 )

> [@Generate a function via macro and pass to @cfunction. Possible?](https://discourse.julialang.org/t/generate-a-function-via-macro-and-pass-to-cfunction-possible/123988/3):
>
> Thanks for the reply and the explanation. Is there any way to automatically define the wrapper function before @cfunction is evaluated? I want to have the implementation as user-friendly as possible and avoid that the user needs to first define a wrapper in global scope. It would be convenient if all of this could happen within one macro or function call.

```julia
macro _create_scalar_function_new(func_expr)

    func, parameters, return_type = _udf_parse_function_expr(func_expr)
    func_esc = esc(func)
    func_name = string(func)
    parameter_names = [p[1] for p in parameters]
    parameter_types = [p[2] for p in parameters]
    parameter_types_vec = Expr(:vect, parameter_types...) # create a vector expression, e.g. [Int, Int]
    wrapper_expr = _udf_generate_wrapper(func_expr)

    quote
        local wrapper = $(wrapper_expr)
        local fun = ScalarFunction($func_name, $parameter_types_vec, $return_type, $func_esc, wrapper)

        wrapper(C_NULL, C_NULL, C_NULL) # works
        fun.wrapper(C_NULL, C_NULL, C_NULL) # works

        # Everything below only works in GLOBAL scope in the REPL
        # ptr = @cfunction(fun.wrapper, Cvoid, (duckdb_function_info, duckdb_data_chunk, duckdb_vector))
        # ccall(ptr, Cvoid, (duckdb_function_info, duckdb_data_chunk, duckdb_vector), C_NULL, C_NULL, C_NULL) # doesnt work
        # duckdb_scalar_function_set_function(fun.handle, ptr)
        
        fun
    end

end

```

---

_[View the full topic](https://discourse.julialang.org/t/is-it-hard-to-support-julia-udfs-in-duckdb/118509)._
