Pat Buxton
Pat Buxton

Reputation: 368

Is it possible to use nested custom functions in SQLAlchemy?

If I declare two custom functions in SQLAlchemy, should it be possible for one to call the other? If a "built-in" function is used in a custom function, the output is resolved correctly. I am declaring my functions like this

import sqlalchemy
from sqlalchemy import func, column
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.functions import FunctionElement
 
 
class my_func_1(FunctionElement):
    name = 'my_func_1'
 
 
@compiles(my_func_1)
def compile_my_func_1(element, compiler, **kw):
    col, = list(element.clauses)
    return compiler.process(func.to_date(col, 'dd-mm-yyyy'), **kw)
 
 
class my_func_2(FunctionElement):
    name = 'my_func_2'
 
 
@compiles(my_func_2)
def compile_my_func_2(element, compiler, **kw):
    col, = list(element.clauses)
    return compiler.process(func.my_func_1(col), **kw)
 
 
print(sqlalchemy.select([(my_func_1(column("Start")))]))
print(sqlalchemy.select([(my_func_2(column("Start")))]))

The output of this is:

SELECT to_date("Start", :to_date_1)
SELECT my_func_1("Start")

But I was hoping for:

SELECT to_date("Start", :to_date_1)
SELECT to_date("Start", :to_date_1)

As this simple example is effectively just a redirection.
Perhaps this is not even supported, but I can't spot anything specific in the docs that suggest that it is not.

Upvotes: 0

Views: 230

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52949

Base your functions on GenericFunction instead of FunctionElement, the former registers your functions to be available under func, or use my_func_1 instead of func.my_func_1 in the compiler function.

Upvotes: 1

Related Questions