Skip to content

Commit

Permalink
[SPARK-46602][SQL] Propagate allowExisting in view creation when th…
Browse files Browse the repository at this point in the history
…e view/table does not exists

### What changes were proposed in this pull request?
This PR fixes the undesired behavior that concurrent `CREATE VIEW IF NOT EXISTS` queries could throw `TABLE_OR_VIEW_ALREADY_EXISTS` exceptions. It's because the current implementation did not propagate the 'IF NOT EXISTS' when the detecting view/table does not exists.

### Why are the changes needed?
Fix the above issue.

### Does this PR introduce _any_ user-facing change?
Yes in the sense that if fixes an issue in concurrent case.

### How was this patch tested?
Without the fix the following test failed while with this PR if passed. But following the [comment](apache#44603 (comment)), I removed the test from this PR.
```scala
  test("CREATE VIEW IF NOT EXISTS never throws TABLE_OR_VIEW_ALREADY_EXISTS") {
    // Concurrently create a view with the same name, so that some of the queries may all
    // get that the view does not exist and try to create it. But with IF NOT EXISTS, the
    // queries should not fail.
    import ExecutionContext.Implicits.global
    val concurrency = 10
    val tableName = "table_name"
    val viewName = "view_name"
    withTable(tableName) {
      sql(s"CREATE TABLE $tableName (id int) USING parquet")
      withView("view_name") {
        val futures = (0 to concurrency).map { _ =>
          Future {
            Try {
              sql(s"CREATE VIEW IF NOT EXISTS $viewName AS SELECT * FROM $tableName")
            }
          }
        }
        futures.map { future =>
           val res = ThreadUtils.awaitResult(future, 5.seconds)
           assert(
             res.isSuccess,
             s"Failed to create view: ${if (res.isFailure) res.failed.get.getMessage}"
           )
        }
      }
    }
  }
```

### Was this patch authored or co-authored using generative AI tooling?
No.

Closes apache#44603 from anchovYu/create-view-if-not-exist-fix.

Authored-by: Xinyi Yu <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
  • Loading branch information
anchovYu authored and cloud-fan committed Jan 5, 2024
1 parent 70b90c8 commit 9b3c70f
Showing 1 changed file with 1 addition and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ case class CreateViewCommand(
}
} else {
// Create the view if it doesn't exist.
catalog.createTable(prepareTable(sparkSession, analyzedPlan), ignoreIfExists = false)
catalog.createTable(prepareTable(sparkSession, analyzedPlan), ignoreIfExists = allowExisting)
}
Seq.empty[Row]
}
Expand Down

0 comments on commit 9b3c70f

Please sign in to comment.