H2 how to call a User Defined Function with parameters in a Join query?

Viewed 130

H2 how to call a User Defined Function with parameters in a Join query?

Hi!

I'm getting a problem when calling a User Defined Function with parameters in a Join query.

This is the query I try to run in my unit tests using a H2 datasource:

select 
    e.entry_id,
    debts.amount
from 
    my_schema."Entry" e 
left 
    join my_schema.get_children_summary(e.entry_id, e.customer_id) debts on debts.id_entry = e.entry_id 

This is the error message a get during the execution:

Column "e.entry_id" not found; SQL statement:
select
 e.entry_id from my_schema."Entry" e
left join my_schema.get_children_summary(e.entry_id, e.customer_id) debts on debts.id_entry = e.entry_id [42122-200] 42S22/42122 (Help)

This is class used to create the H2 function alias:

public class UserDefinedFunctions {

    public static ResultSet getChildrenSummary(Connection connection, Integer entryId, Integer customerId)
            throws SQLException {
        SimpleResultSet rs = new SimpleResultSet();
        rs.addColumn("id_entry", Types.INTEGER, 15, 4);
        rs.addColumn("amount", Types.NUMERIC, 15, 4);

        if (isColumnlist(connection)) {
            return rs;
        }

        Optional<Entry> entry = ...;
        rs.addRow(entry.get().getEntryId(), entry.get().getAmount());

        return rs;
    }

    private static boolean isColumnlist(Connection connection) throws SQLException {
        String url = connection.getMetaData().getURL();
        return url.equals("jdbc:columnlist:connection");
    }

}

Create alias script:

DROP ALIAS IF EXISTS libra_schema.get_children_summary;
CREATE ALIAS IF NOT EXISTS libra_schema.get_children_summary FOR "com.package.UserDefinedFunctions.getChildrenSummary";

Can anyone tell me if it is possible to call a function passing the fields of a table in a join?

1 Answers

This will not work in h2 and is not planned to be supported.

The reason for this behaviour is, that the function is only executed once during the execution of the query, and the results will be joined afterwards. The function is not executed for each table row resulting from prior selects.

Read Evgenij Ryazanov's original answer at https://github.com/h2database/h2database/issues/3546

Related