/*
 * 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.spark.sql.analysis.resolver

import org.apache.spark.sql.{Column, Row}
import org.apache.spark.sql.test.SharedSparkSession

/**
 * Test cases that cover dataframe analyzer test gaps discovered during single-pass analyzer
 * development.
 */
class DataFrameAnalyzerTestGapsSuite extends SharedSparkSession {
  import testImplicits._

  test("Implicit alias resolution") {
    val table = Seq((1), (2), (3)).toDF("a")
    val query = table.select($"a" + 1)
    assert(query.schema.head.name === "(a + 1)")
    checkAnswer(
      query,
      Seq(Row(2), Row(3), Row(4))
    )
  }

  test("Nested aliases collapsed") {
    val table = Seq((1), (2), (3)).toDF("a")
    val query = table.select($"a".as("innerAlias").as("outerAlias"))
    assert(query.schema.head.name === "outerAlias")
    checkAnswer(
      query,
      Seq(Row(1), Row(2), Row(3))
    )
  }

  test("Arbitrary number of nested aliases") {
    val table = Seq((1), (2), (3)).toDF("a")
    var projectList: Column = $"a"
    for (index <- 0 until 100) {
      projectList = projectList.as("alias_" + index)
    }
    val query = table.select(projectList)
    assert(query.schema.head.name === "alias_99")
    checkAnswer(
      query,
      Seq(Row(1), Row(2), Row(3))
    )
  }

  test("Nested aliases with autogenerated names") {
    val table = Seq((1), (2), (3)).toDF("a")
    val query = table.select($"a".as("innerAlias").as("outerAlias") + 1)
    assert(query.schema.head.name === "(a AS innerAlias AS outerAlias + 1)")
    checkAnswer(
      query,
      Seq(Row(2), Row(3), Row(4))
    )
    val finalQuery = query.select($"(a AS innerAlias AS outerAlias + 1)" * 2)
    checkAnswer(
      finalQuery,
      Seq(Row(4), Row(6), Row(8))
    )
  }
}
