/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.calcite.test;

import org.apache.calcite.plan.hep.HepPlanner;
import org.apache.calcite.plan.hep.HepProgram;
import org.apache.calcite.plan.hep.HepProgramBuilder;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.rules.CoreRules;
import org.apache.calcite.tools.RelBuilder;

import org.junit.jupiter.api.Test;

/**
 * Test cases for {@link org.apache.calcite.rel.metadata.RelMdSelectivity}.
 */
class RelMdSelectivityTest {

  /** Test case for
   * <a href="https://issues.apache.org/jira/browse/CALCITE-4414">[CALCITE-4414]
   * RelMdSelectivity#getSelectivity for Calc can propagate a predicate with wrong reference</a>. */
  @Test void testCalcSelectivityWithPredicate() {
    final RelBuilder builder = RelBuilder.create(RelBuilderTest.config().build());
    final RelNode relNode = builder
        .scan("EMP")
        .project(
            builder.field("DEPTNO"))
        .scan("EMP")
        .project(
            builder.field("DEPTNO"))
        .union(true)
        .projectPlus(builder.field("DEPTNO"))
        .filter(
            builder.equals(
                builder.field(0),
                builder.literal(0)))
        .build();

    // Program to convert Project + Filter into a single Calc
    final HepProgram program = new HepProgramBuilder()
        .addRuleInstance(CoreRules.FILTER_TO_CALC)
        .addRuleInstance(CoreRules.PROJECT_TO_CALC)
        .addRuleInstance(CoreRules.CALC_MERGE)
        .build();
    final HepPlanner hepPlanner = new HepPlanner(program);
    hepPlanner.setRoot(relNode);
    RelNode output = hepPlanner.findBestExp();

    // Add filter on the extra field generated by projectPlus (now a Calc after hepPlanner)
    output = builder
        .push(output)
        .filter(
            builder.equals(
                builder.field(1),
                builder.literal(0)))
        .build();

    // Should not fail
    output.estimateRowCount(output.getCluster().getMetadataQuery());
  }
}
