H2用户定义的聚合函数ListAgg,不能在第一个参数上使用DISTINCT或TRIM()

时间:2015-10-09 21:01:52

标签: java sql h2

所以我有一个DB2生产数据库,我需要使用可用的函数ListAgg。我希望我的单元测试(使用H2)正确测试此功能。不幸的是H2不直接支持ListAgg。但是,我可以创建一个用户定义的聚合函数...

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.h2.api.AggregateFunction;

import com.google.common.base.Joiner;

public class ListAgg implements AggregateFunction
{

private List<String> values = new ArrayList<String>();
private String delimiter = ",";

@Override
public void init(Connection conn) throws SQLException
{
}

@Override
public int getType(int[] inputTypes) throws SQLException
{
    if (inputTypes.length != 2) {
        throw new java.sql.SQLException("The aggregate function ListAgg must have 2 arguments.");
    }
    return java.sql.Types.VARCHAR;
}

@Override
public void add(Object sqlValues) throws SQLException
{
    Object[] objects = (Object[]) sqlValues;
    this.delimiter = (String) objects[1];
    String value = (String) objects[0];
    values.add(value);
}

@Override
public Object getResult() throws SQLException
{
    return Joiner.on(delimiter).join(values);
}

}

我做过的。这适用于

ListAgg(columnName, ',')

失败了
ListAgg(DISTINCT TRIM(columnName), ',')

我错过了什么?

编辑: 我收到以下错误消息:

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback;
bad SQL grammar [select ..., LISTAGG(DISTINCT TRIM(columnName), ',') as 
columnName_LIST, from ... group by ...]; nested exception is 
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT ... "; 
expected "NOT, EXISTS, INTERSECTS, SELECT, FROM"; SQL statement:
select ... from ... group by ... [42001-174]    
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) 
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)

EDIT2:

COUNT()是否也实现了AggregateFunction,还是内部使用了其他东西?因为H2能够处理COUNT(DISTINCT columnName)

1 个答案:

答案 0 :(得分:1)

我认为H2不允许您在自定义聚合函数上使用DISTINCT关键字。但您可以轻松定义自己的ListAgg“不同”版本:

public class DistinctListAgg implements AggregateFunction {
    private Set<String> values = new LinkedHashSet<String>();
    // The rest is the same
}