{"action":"created","comment":{"url":"https://api.github.com/repos/apache/spark/pulls/comments/93720313","pull_request_review_id":14254102,"id":93720313,"diff_hunk":"@@ -363,48 +365,125 @@ final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {\n       throw new AnalysisException(\"Cannot create hive serde table with saveAsTable API\")\n     }\n \n-    val tableExists = df.sparkSession.sessionState.catalog.tableExists(tableIdent)\n-\n-    (tableExists, mode) match {\n-      case (true, SaveMode.Ignore) =>\n-        // Do nothing\n-\n-      case (true, SaveMode.ErrorIfExists) =>\n-        throw new AnalysisException(s\"Table $tableIdent already exists.\")\n-\n-      case _ =>\n-        val existingTable = if (tableExists) {\n-          Some(df.sparkSession.sessionState.catalog.getTableMetadata(tableIdent))\n-        } else {\n-          None\n-        }\n-        val storage = if (tableExists) {\n-          existingTable.get.storage\n-        } else {\n-          DataSource.buildStorageFormatFromOptions(extraOptions.toMap)\n-        }\n-        val tableType = if (tableExists) {\n-          existingTable.get.tableType\n-        } else if (storage.locationUri.isDefined) {\n-          CatalogTableType.EXTERNAL\n-        } else {\n-          CatalogTableType.MANAGED\n+    val catalog = df.sparkSession.sessionState.catalog\n+    val db = tableIdent.database.getOrElse(catalog.getCurrentDatabase)\n+    val tableIdentWithDB = tableIdent.copy(database = Some(db))\n+    val tableName = tableIdent.unquotedString\n+\n+    catalog.getTableMetadataOption(tableIdent) match {\n+      // If the table already exists...\n+      case Some(tableMeta) =>\n+        mode match {\n+          case SaveMode.Ignore => // Do nothing\n+\n+          case SaveMode.ErrorIfExists =>\n+            throw new AnalysisException(s\"Table $tableName already exists. You can set SaveMode \" +\n+              \"to SaveMode.Append to insert data into the table or set SaveMode to \" +\n+              \"SaveMode.Overwrite to overwrite the existing data.\")\n+\n+          case SaveMode.Append =>\n+            // Check if the specified data source match the data source of the existing table.\n+            val specifiedProvider = DataSource.lookupDataSource(source)\n+            // TODO: Check that options from the resolved relation match the relation that we are\n+            // inserting into (i.e. using the same compression).\n+\n+            // Pass a table identifier with database part, so that `lookupRelation` won't get temp\n+            // views unexpectedly.\n+            EliminateSubqueryAliases(catalog.lookupRelation(tableIdentWithDB)) match {\n+              case l @ LogicalRelation(_: InsertableRelation | _: HadoopFsRelation, _, _) =>\n+                // check if the file formats match\n+                l.relation match {\n+                  case r: HadoopFsRelation if r.fileFormat.getClass != specifiedProvider =>\n+                    throw new AnalysisException(\n+                      s\"The file format of the existing table $tableName is \" +\n+                        s\"`${r.fileFormat.getClass.getName}`. It doesn't match the specified \" +\n+                        s\"format `$source`\")\n+                  case _ =>\n+                }\n+              case s: SimpleCatalogRelation if DDLUtils.isDatasourceTable(s.metadata) => // OK.\n+              case c: CatalogRelation if c.catalogTable.provider == Some(DDLUtils.HIVE_PROVIDER) =>\n+                throw new AnalysisException(s\"Saving data in the Hive serde table $tableName \" +\n+                  s\"is not supported yet. Please use the insertInto() API as an alternative.\")\n+              case o =>\n+                throw new AnalysisException(s\"Saving data in ${o.toString} is not supported.\")\n+            }\n+\n+            val existingSchema = tableMeta.schema\n+            if (df.logicalPlan.schema.size != existingSchema.size) {\n+              throw new AnalysisException(\n+                s\"The column number of the existing table $tableName\" +\n+                  s\"(${existingSchema.catalogString}) doesn't match the data schema\" +\n+                  s\"(${df.logicalPlan.schema.catalogString})\")\n+            }\n+\n+            if (partitioningColumns.isDefined) {\n+              logWarning(\"append to an existing table, the specified partition columns \" +\n+                s\"[${partitioningColumns.get.mkString(\", \")}] will be ignored.\")\n+            }\n+\n+            val specifiedBucketSpec = getBucketSpec\n+            if (specifiedBucketSpec.isDefined) {\n+              logWarning(\"append to an existing table, the specified bucketing \" +\n+                s\"(${specifiedBucketSpec.get}) will be ignored.\")\n+            }\n+\n+            // Because we are inserting into an existing table, we should respect the existing\n+            // schema and adjust columns order of the given dataframe according to it.\n+            val adjustedColumns = existingSchema.map(f => Column(df.resolve(f.name)))\n+            df.select(adjustedColumns: _*).write.insertInto(tableIdentWithDB)\n+\n+          case SaveMode.Overwrite =>\n+            EliminateSubqueryAliases(catalog.lookupRelation(tableIdentWithDB)) match {\n+              // Only do the check if the table is a data source table\n+              // (the relation is a BaseRelation).\n+              case LogicalRelation(dest: BaseRelation, _, _) =>\n+                // Get all input data source relations of the query.\n+                val srcRelations = df.logicalPlan.collect {\n+                  case LogicalRelation(src: BaseRelation, _, _) => src\n+                }\n+                if (srcRelations.contains(dest)) {\n+                  throw new AnalysisException(\n+                    s\"Cannot overwrite table $tableName that is also being read from\")\n+                }\n+              case _ => // OK\n+            }\n+\n+            // Drop the existing table and create it again.\n+            catalog.dropTable(tableIdentWithDB, ignoreIfNotExists = true, purge = false)\n+            createTable(tableIdentWithDB)\n+\n+            // Refresh the cache of the table in the catalog.\n+            catalog.refreshTable(tableIdentWithDB)\n         }\n \n-        val tableDesc = CatalogTable(\n-          identifier = tableIdent,\n-          tableType = tableType,\n-          storage = storage,\n-          schema = new StructType,\n-          provider = Some(source),\n-          partitionColumnNames = partitioningColumns.getOrElse(Nil),\n-          bucketSpec = getBucketSpec\n-        )\n-        df.sparkSession.sessionState.executePlan(\n-          CreateTable(tableDesc, mode, Some(df.logicalPlan))).toRdd\n+      // If the table doesn't exist...\n+      case None => createTable(tableIdentWithDB)\n     }\n   }\n \n+  private def createTable(tableIdent: TableIdentifier): Unit = {\n+    val storage = DataSource.buildStorageFormatFromOptions(extraOptions.toMap)\n+    val tableType = if (storage.locationUri.isDefined) {","path":"sql/core/src/main/scala/org/apache/spark/sql/DataFrameWriter.scala","position":193,"original_position":167,"commit_id":"59f06ce86338b11b74164de632cee518bf513697","original_commit_id":"6c64007967a7d34296367ef53f24a5a73c03dbab","user":{"login":"yhuai","id":2072857,"avatar_url":"https://avatars.githubusercontent.com/u/2072857?v=3","gravatar_id":"","url":"https://api.github.com/users/yhuai","html_url":"https://github.com/yhuai","followers_url":"https://api.github.com/users/yhuai/followers","following_url":"https://api.github.com/users/yhuai/following{/other_user}","gists_url":"https://api.github.com/users/yhuai/gists{/gist_id}","starred_url":"https://api.github.com/users/yhuai/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/yhuai/subscriptions","organizations_url":"https://api.github.com/users/yhuai/orgs","repos_url":"https://api.github.com/users/yhuai/repos","events_url":"https://api.github.com/users/yhuai/events{/privacy}","received_events_url":"https://api.github.com/users/yhuai/received_events","type":"User","site_admin":false},"body":"Which part of that pr is reverted?","created_at":"2016-12-23T00:57:00Z","updated_at":"2016-12-23T00:57:00Z","html_url":"https://github.com/apache/spark/pull/15996#discussion_r93720313","pull_request_url":"https://api.github.com/repos/apache/spark/pulls/15996","_links":{"self":{"href":"https://api.github.com/repos/apache/spark/pulls/comments/93720313"},"html":{"href":"https://github.com/apache/spark/pull/15996#discussion_r93720313"},"pull_request":{"href":"https://api.github.com/repos/apache/spark/pulls/15996"}}},"pull_request":{"url":"https://api.github.com/repos/apache/spark/pulls/15996","id":95053637,"html_url":"https://github.com/apache/spark/pull/15996","diff_url":"https://github.com/apache/spark/pull/15996.diff","patch_url":"https://github.com/apache/spark/pull/15996.patch","issue_url":"https://api.github.com/repos/apache/spark/issues/15996","number":15996,"state":"open","locked":false,"title":"[SPARK-18567][SQL] Simplify CreateDataSourceTableAsSelectCommand","user":{"login":"cloud-fan","id":3182036,"avatar_url":"https://avatars.githubusercontent.com/u/3182036?v=3","gravatar_id":"","url":"https://api.github.com/users/cloud-fan","html_url":"https://github.com/cloud-fan","followers_url":"https://api.github.com/users/cloud-fan/followers","following_url":"https://api.github.com/users/cloud-fan/following{/other_user}","gists_url":"https://api.github.com/users/cloud-fan/gists{/gist_id}","starred_url":"https://api.github.com/users/cloud-fan/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/cloud-fan/subscriptions","organizations_url":"https://api.github.com/users/cloud-fan/orgs","repos_url":"https://api.github.com/users/cloud-fan/repos","events_url":"https://api.github.com/users/cloud-fan/events{/privacy}","received_events_url":"https://api.github.com/users/cloud-fan/received_events","type":"User","site_admin":false},"body":"## What changes were proposed in this pull request?\r\n\r\nThe `CreateDataSourceTableAsSelectCommand` is quite complex now, as it has a lot of work to do if the table already exists:\r\n\r\n1. throw exception if we don't want to ignore it.\r\n2. do some check and adjust the schema if we want to append data.\r\n3. drop the table and create it again if we want to overwrite.\r\n\r\nThe work 2 and 3 are required by `DataFrameWriter` only, I think it's more reasonable to put them in `DataFrameWriter`, to simplify `CreateDataSourceTableAsSelectCommand`.\r\n\r\nThis PR also fix a confusing partition related behavior: if we create an external partitioned data source table without calling `REPAIR TABLE`, and then use `DataFrameWriter.saveAsTable` to append data to this table, all partitions will be visible, while the expected behavior should be: only the updated partitions should be visible.\r\n\r\n## How was this patch tested?\r\n\r\nexisting tests.","created_at":"2016-11-23T18:04:50Z","updated_at":"2016-12-23T00:57:00Z","closed_at":null,"merged_at":null,"merge_commit_sha":"b63b4af96309d0fccf165903a8fa6b224c7db10a","assignee":null,"assignees":[],"milestone":null,"commits_url":"https://api.github.com/repos/apache/spark/pulls/15996/commits","review_comments_url":"https://api.github.com/repos/apache/spark/pulls/15996/comments","review_comment_url":"https://api.github.com/repos/apache/spark/pulls/comments{/number}","comments_url":"https://api.github.com/repos/apache/spark/issues/15996/comments","statuses_url":"https://api.github.com/repos/apache/spark/statuses/59f06ce86338b11b74164de632cee518bf513697","head":{"label":"cloud-fan:append","ref":"append","sha":"59f06ce86338b11b74164de632cee518bf513697","user":{"login":"cloud-fan","id":3182036,"avatar_url":"https://avatars.githubusercontent.com/u/3182036?v=3","gravatar_id":"","url":"https://api.github.com/users/cloud-fan","html_url":"https://github.com/cloud-fan","followers_url":"https://api.github.com/users/cloud-fan/followers","following_url":"https://api.github.com/users/cloud-fan/following{/other_user}","gists_url":"https://api.github.com/users/cloud-fan/gists{/gist_id}","starred_url":"https://api.github.com/users/cloud-fan/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/cloud-fan/subscriptions","organizations_url":"https://api.github.com/users/cloud-fan/orgs","repos_url":"https://api.github.com/users/cloud-fan/repos","events_url":"https://api.github.com/users/cloud-fan/events{/privacy}","received_events_url":"https://api.github.com/users/cloud-fan/received_events","type":"User","site_admin":false},"repo":{"id":19689699,"name":"spark","full_name":"cloud-fan/spark","owner":{"login":"cloud-fan","id":3182036,"avatar_url":"https://avatars.githubusercontent.com/u/3182036?v=3","gravatar_id":"","url":"https://api.github.com/users/cloud-fan","html_url":"https://github.com/cloud-fan","followers_url":"https://api.github.com/users/cloud-fan/followers","following_url":"https://api.github.com/users/cloud-fan/following{/other_user}","gists_url":"https://api.github.com/users/cloud-fan/gists{/gist_id}","starred_url":"https://api.github.com/users/cloud-fan/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/cloud-fan/subscriptions","organizations_url":"https://api.github.com/users/cloud-fan/orgs","repos_url":"https://api.github.com/users/cloud-fan/repos","events_url":"https://api.github.com/users/cloud-fan/events{/privacy}","received_events_url":"https://api.github.com/users/cloud-fan/received_events","type":"User","site_admin":false},"private":false,"html_url":"https://github.com/cloud-fan/spark","description":"Mirror of Apache Spark","fork":true,"url":"https://api.github.com/repos/cloud-fan/spark","forks_url":"https://api.github.com/repos/cloud-fan/spark/forks","keys_url":"https://api.github.com/repos/cloud-fan/spark/keys{/key_id}","collaborators_url":"https://api.github.com/repos/cloud-fan/spark/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/cloud-fan/spark/teams","hooks_url":"https://api.github.com/repos/cloud-fan/spark/hooks","issue_events_url":"https://api.github.com/repos/cloud-fan/spark/issues/events{/number}","events_url":"https://api.github.com/repos/cloud-fan/spark/events","assignees_url":"https://api.github.com/repos/cloud-fan/spark/assignees{/user}","branches_url":"https://api.github.com/repos/cloud-fan/spark/branches{/branch}","tags_url":"https://api.github.com/repos/cloud-fan/spark/tags","blobs_url":"https://api.github.com/repos/cloud-fan/spark/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/cloud-fan/spark/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/cloud-fan/spark/git/refs{/sha}","trees_url":"https://api.github.com/repos/cloud-fan/spark/git/trees{/sha}","statuses_url":"https://api.github.com/repos/cloud-fan/spark/statuses/{sha}","languages_url":"https://api.github.com/repos/cloud-fan/spark/languages","stargazers_url":"https://api.github.com/repos/cloud-fan/spark/stargazers","contributors_url":"https://api.github.com/repos/cloud-fan/spark/contributors","subscribers_url":"https://api.github.com/repos/cloud-fan/spark/subscribers","subscription_url":"https://api.github.com/repos/cloud-fan/spark/subscription","commits_url":"https://api.github.com/repos/cloud-fan/spark/commits{/sha}","git_commits_url":"https://api.github.com/repos/cloud-fan/spark/git/commits{/sha}","comments_url":"https://api.github.com/repos/cloud-fan/spark/comments{/number}","issue_comment_url":"https://api.github.com/repos/cloud-fan/spark/issues/comments{/number}","contents_url":"https://api.github.com/repos/cloud-fan/spark/contents/{+path}","compare_url":"https://api.github.com/repos/cloud-fan/spark/compare/{base}...{head}","merges_url":"https://api.github.com/repos/cloud-fan/spark/merges","archive_url":"https://api.github.com/repos/cloud-fan/spark/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/cloud-fan/spark/downloads","issues_url":"https://api.github.com/repos/cloud-fan/spark/issues{/number}","pulls_url":"https://api.github.com/repos/cloud-fan/spark/pulls{/number}","milestones_url":"https://api.github.com/repos/cloud-fan/spark/milestones{/number}","notifications_url":"https://api.github.com/repos/cloud-fan/spark/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/cloud-fan/spark/labels{/name}","releases_url":"https://api.github.com/repos/cloud-fan/spark/releases{/id}","deployments_url":"https://api.github.com/repos/cloud-fan/spark/deployments","created_at":"2014-05-12T07:32:26Z","updated_at":"2016-05-26T10:38:18Z","pushed_at":"2016-12-22T12:08:15Z","git_url":"git://github.com/cloud-fan/spark.git","ssh_url":"git@github.com:cloud-fan/spark.git","clone_url":"https://github.com/cloud-fan/spark.git","svn_url":"https://github.com/cloud-fan/spark","homepage":null,"size":253754,"stargazers_count":1,"watchers_count":1,"language":"Scala","has_issues":false,"has_downloads":true,"has_wiki":false,"has_pages":false,"forks_count":1,"mirror_url":null,"open_issues_count":0,"forks":1,"open_issues":0,"watchers":1,"default_branch":"master"}},"base":{"label":"apache:master","ref":"master","sha":"24c0c94128770be9034fb69518713d7f6aa1e041","user":{"login":"apache","id":47359,"avatar_url":"https://avatars.githubusercontent.com/u/47359?v=3","gravatar_id":"","url":"https://api.github.com/users/apache","html_url":"https://github.com/apache","followers_url":"https://api.github.com/users/apache/followers","following_url":"https://api.github.com/users/apache/following{/other_user}","gists_url":"https://api.github.com/users/apache/gists{/gist_id}","starred_url":"https://api.github.com/users/apache/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/apache/subscriptions","organizations_url":"https://api.github.com/users/apache/orgs","repos_url":"https://api.github.com/users/apache/repos","events_url":"https://api.github.com/users/apache/events{/privacy}","received_events_url":"https://api.github.com/users/apache/received_events","type":"Organization","site_admin":false},"repo":{"id":17165658,"name":"spark","full_name":"apache/spark","owner":{"login":"apache","id":47359,"avatar_url":"https://avatars.githubusercontent.com/u/47359?v=3","gravatar_id":"","url":"https://api.github.com/users/apache","html_url":"https://github.com/apache","followers_url":"https://api.github.com/users/apache/followers","following_url":"https://api.github.com/users/apache/following{/other_user}","gists_url":"https://api.github.com/users/apache/gists{/gist_id}","starred_url":"https://api.github.com/users/apache/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/apache/subscriptions","organizations_url":"https://api.github.com/users/apache/orgs","repos_url":"https://api.github.com/users/apache/repos","events_url":"https://api.github.com/users/apache/events{/privacy}","received_events_url":"https://api.github.com/users/apache/received_events","type":"Organization","site_admin":false},"private":false,"html_url":"https://github.com/apache/spark","description":"Mirror of Apache Spark","fork":false,"url":"https://api.github.com/repos/apache/spark","forks_url":"https://api.github.com/repos/apache/spark/forks","keys_url":"https://api.github.com/repos/apache/spark/keys{/key_id}","collaborators_url":"https://api.github.com/repos/apache/spark/collaborators{/collaborator}","teams_url":"https://api.github.com/repos/apache/spark/teams","hooks_url":"https://api.github.com/repos/apache/spark/hooks","issue_events_url":"https://api.github.com/repos/apache/spark/issues/events{/number}","events_url":"https://api.github.com/repos/apache/spark/events","assignees_url":"https://api.github.com/repos/apache/spark/assignees{/user}","branches_url":"https://api.github.com/repos/apache/spark/branches{/branch}","tags_url":"https://api.github.com/repos/apache/spark/tags","blobs_url":"https://api.github.com/repos/apache/spark/git/blobs{/sha}","git_tags_url":"https://api.github.com/repos/apache/spark/git/tags{/sha}","git_refs_url":"https://api.github.com/repos/apache/spark/git/refs{/sha}","trees_url":"https://api.github.com/repos/apache/spark/git/trees{/sha}","statuses_url":"https://api.github.com/repos/apache/spark/statuses/{sha}","languages_url":"https://api.github.com/repos/apache/spark/languages","stargazers_url":"https://api.github.com/repos/apache/spark/stargazers","contributors_url":"https://api.github.com/repos/apache/spark/contributors","subscribers_url":"https://api.github.com/repos/apache/spark/subscribers","subscription_url":"https://api.github.com/repos/apache/spark/subscription","commits_url":"https://api.github.com/repos/apache/spark/commits{/sha}","git_commits_url":"https://api.github.com/repos/apache/spark/git/commits{/sha}","comments_url":"https://api.github.com/repos/apache/spark/comments{/number}","issue_comment_url":"https://api.github.com/repos/apache/spark/issues/comments{/number}","contents_url":"https://api.github.com/repos/apache/spark/contents/{+path}","compare_url":"https://api.github.com/repos/apache/spark/compare/{base}...{head}","merges_url":"https://api.github.com/repos/apache/spark/merges","archive_url":"https://api.github.com/repos/apache/spark/{archive_format}{/ref}","downloads_url":"https://api.github.com/repos/apache/spark/downloads","issues_url":"https://api.github.com/repos/apache/spark/issues{/number}","pulls_url":"https://api.github.com/repos/apache/spark/pulls{/number}","milestones_url":"https://api.github.com/repos/apache/spark/milestones{/number}","notifications_url":"https://api.github.com/repos/apache/spark/notifications{?since,all,participating}","labels_url":"https://api.github.com/repos/apache/spark/labels{/name}","releases_url":"https://api.github.com/repos/apache/spark/releases{/id}","deployments_url":"https://api.github.com/repos/apache/spark/deployments","created_at":"2014-02-25T08:00:08Z","updated_at":"2016-12-23T00:32:57Z","pushed_at":"2016-12-23T00:23:41Z","git_url":"git://github.com/apache/spark.git","ssh_url":"git@github.com:apache/spark.git","clone_url":"https://github.com/apache/spark.git","svn_url":"https://github.com/apache/spark","homepage":null,"size":258969,"stargazers_count":11172,"watchers_count":11172,"language":"Scala","has_issues":false,"has_downloads":true,"has_wiki":false,"has_pages":false,"forks_count":10480,"mirror_url":"git://git.apache.org/spark.git","open_issues_count":441,"forks":10480,"open_issues":441,"watchers":11172,"default_branch":"master"}},"_links":{"self":{"href":"https://api.github.com/repos/apache/spark/pulls/15996"},"html":{"href":"https://github.com/apache/spark/pull/15996"},"issue":{"href":"https://api.github.com/repos/apache/spark/issues/15996"},"comments":{"href":"https://api.github.com/repos/apache/spark/issues/15996/comments"},"review_comments":{"href":"https://api.github.com/repos/apache/spark/pulls/15996/comments"},"review_comment":{"href":"https://api.github.com/repos/apache/spark/pulls/comments{/number}"},"commits":{"href":"https://api.github.com/repos/apache/spark/pulls/15996/commits"},"statuses":{"href":"https://api.github.com/repos/apache/spark/statuses/59f06ce86338b11b74164de632cee518bf513697"}}}}
{"actor":{"display_login":"yhuai"}}