[Apache Calcite] 添加自定义运算符

384 阅读1分钟

 

   /** "MYAGG" user-defined aggregate function. This agg function accept two numeric arguments
     * in order to reproduce the throws of CALCITE-2744. */
    public static class MyAvgAggFunction extends SqlAggFunction {
        public MyAvgAggFunction() {
            super("MYAGG", null, SqlKind.AVG, ReturnTypes.AVG_AGG_FUNCTION,
                    null, OperandTypes.family(SqlTypeFamily.NUMERIC, SqlTypeFamily.NUMERIC),
                    SqlFunctionCategory.NUMERIC, false, false, Optionality.FORBIDDEN);
        }

        @Override public boolean isDeterministic() {
            return false;
        }
    }

 

Frameworks.ConfigBuilder configBuilder = Frameworks.newConfigBuilder();
SqlOperatorTable opTab =
        ChainedSqlOperatorTable.of( SqlStdOperatorTable.instance(),
                new ListSqlOperatorTable(
                        ImmutableList.of(new MycatAggFunctions.MyAvgAggFunction())));
configBuilder.operatorTable(opTab);
    public static class MyAvgAggFunction extends SqlAggFunction {
        static final List<RelDataType> apply = Collections.singletonList(RelDataTypeFactoryImpl.JavaType.proto(SqlTypeName.DOUBLE, true).apply(new JavaTypeFactoryImpl()));

        public MyAvgAggFunction() {
            super(SqlKind.AVG.name(), null, SqlKind.AVG, opBinding -> {
                        final RelDataTypeFactory typeFactory = opBinding.getTypeFactory();
                        final RelDataType relDataType = typeFactory.createJavaType(Double.class);
                        if (opBinding.getGroupCount() == 0 || opBinding.hasFilter()) {
                            return typeFactory.createTypeWithNullability(relDataType, true);
                        } else {
                            return relDataType;
                        }
                    },
                    null, OperandTypes.NUMERIC,
                    SqlFunctionCategory.NUMERIC, false, false, Optionality.FORBIDDEN);
        }

        @Override
        public List<RelDataType> getParamTypes() {
            return apply;
            // return Arrays.asList(apply);
        }

        @Override
        public boolean isDeterministic() {
            return false;
        }
    }
}

 

    /**
     * Arithmetic division operator, '<code>/</code>'.
     */
    public static final SqlBinaryOperator DIVIDE
            ;

    static {
        DIVIDE = new SqlBinaryOperator(
                "/",
                SqlKind.DIVIDE,
                60,
                true,
                chain(DECIMAL_QUOTIENT_NULLABLE, ARG0_INTERVAL_NULLABLE,
                        opBinding -> opBinding.getTypeFactory().createJavaType(Double.class)),
                InferTypes.FIRST_KNOWN,
                OperandTypes.DIVISION_OPERATOR);
    }