Search code examples
sqlalchemytrino

Invoking Trino's try_cast() using SQLAlchemy


I am using SQLAlchemy to execute SQL queries on Trino. I want to use Trino's try_cast() function, so I tried the following:

from sqlalchemy.sql import try_cast

# other stuff...

try_cast(col, data_type)

This throws the following error:

Exception: Compiler <trino.sqlalchemy.compiler.TrinoSQLCompiler object at 0x13fe19c00> can't render element of type <class 'sqlalchemy.sql.elements.TryCast'> (Background on this error at: https://sqlalche.me/e/20/l7de)

It seems that SQLAlchemy does not know how to implement try_cast for the Trino dialect. (Note that this is not a problem for sqlalchemy.sql.cast.) The link in the error message suggests using ClauseElement.compile(), but I can't see how to specify the Trino dialect, since there is no module sqlalchemy.dialects.trino (or have I missed something?). Is there a succinct way to solve this problem?


Solution

  • I fixed this by adding a visit_try_cast() method to trino.sqlalchemy.compiler.TrinoSQLCompiler:

    def visit_try_cast(self, element, **kw):
        return f"try_cast({self.process(element.clause, **kw)} as {self.process(element.typeclause, **kw)})"
    
    

    I have created a PR.