-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[SPARK-19335][SPARK-38200][SQL] Add upserts for writing to JDBC #41518
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f2fdaac
Implement upsert for MySQL
EnricoMi 781c713
Implement upsert for Postgres
EnricoMi adedde7
Code cleanup
EnricoMi 6aa37b4
Move upsert tests into trait
EnricoMi 5ce43da
Implement upsert for MsSqlServer
EnricoMi 9d9a8fe
Fix non-existing upsert test for Postgres
EnricoMi 7fd80b5
Add upsert concurrency integration test
EnricoMi 7602df4
Add tests with varying column order
EnricoMi 1b24644
Add test with varying column order, sketch more tests
EnricoMi e0e65d3
Revert empty line removal, fix scalastyle error
EnricoMi fc707f1
Refactor tableDoesNotSupportError to reuse in tableDoesNotSupportUpse…
EnricoMi 803e5de
Fix after merge master
EnricoMi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
137 changes: 137 additions & 0 deletions
137
...ector/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/UpsertTests.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| /* | ||
| * 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.jdbc | ||
|
|
||
| import java.sql.Timestamp | ||
| import java.util.Properties | ||
|
|
||
| import org.apache.spark.sql.{Row, SaveMode} | ||
| import org.apache.spark.sql.functions.{col, lit, rand, when} | ||
|
|
||
| trait UpsertTests { | ||
| self: DockerJDBCIntegrationSuite => | ||
|
|
||
| import testImplicits._ | ||
|
|
||
| def createTableOption: String | ||
| def upsertTestOptions: Map[String, String] = Map("createTableOptions" -> createTableOption) | ||
|
|
||
| test(s"Upsert existing table") { doTestUpsert(tableExists = true) } | ||
| test(s"Upsert non-existing table") { doTestUpsert(tableExists = false) } | ||
|
|
||
| Seq( | ||
| Seq("ts", "id", "v1", "v2"), | ||
| Seq("ts", "v1", "id", "v2"), | ||
| Seq("ts", "v1", "v2", "id"), | ||
| Seq("v2", "v1", "ts", "id") | ||
| ).foreach { columns => | ||
| test(s"Upsert with varying column order - ${columns.mkString(",")}") { | ||
| doTestUpsert(tableExists = true, Some(columns)) | ||
| } | ||
| } | ||
|
|
||
| def doTestUpsert(tableExists: Boolean, project: Option[Seq[String]] = None): Unit = { | ||
| val df = Seq( | ||
| (1, Timestamp.valueOf("1996-01-01 01:23:46"), 1.235, 1.234568), // row unchanged | ||
| (2, Timestamp.valueOf("1996-01-01 01:23:45"), 2.346, 2.345678), // updates v1 | ||
| (2, Timestamp.valueOf("1996-01-01 01:23:46"), 2.347, 2.345680), // updates v1 and v2 | ||
| (3, Timestamp.valueOf("1996-01-01 01:23:45"), 3.456, 3.456789) // inserts new row | ||
| ).toDF("id", "ts", "v1", "v2").repartition(1) // .repartition(10) | ||
|
|
||
| val table = if (tableExists) "upsert" else "new_upsert_table" | ||
| val options = upsertTestOptions ++ Map( | ||
| "numPartitions" -> "10", | ||
| "upsert" -> "true", | ||
| "upsertKeyColumns" -> "id, ts" | ||
| ) | ||
| project.map(columns => df.select(columns.map(col): _*)).getOrElse(df) | ||
| .write.mode(SaveMode.Append).options(options).jdbc(jdbcUrl, table, new Properties) | ||
|
|
||
| val actual = spark.read.jdbc(jdbcUrl, table, new Properties).collect().toSet | ||
| val existing = if (tableExists) { | ||
| Set((1, Timestamp.valueOf("1996-01-01 01:23:45"), 1.234, 1.234567)) | ||
| } else { | ||
| Set.empty | ||
| } | ||
| val upsertedRows = Set( | ||
| (1, Timestamp.valueOf("1996-01-01 01:23:46"), 1.235, 1.234568), | ||
| (2, Timestamp.valueOf("1996-01-01 01:23:45"), 2.346, 2.345678), | ||
| (2, Timestamp.valueOf("1996-01-01 01:23:46"), 2.347, 2.345680), | ||
| (3, Timestamp.valueOf("1996-01-01 01:23:45"), 3.456, 3.456789) | ||
| ) | ||
| val expected = (existing ++ upsertedRows).map { case (id, ts, v1, v2) => | ||
| Row(Integer.valueOf(id), ts, v1.doubleValue(), v2.doubleValue()) | ||
| } | ||
| assert(actual === expected) | ||
| } | ||
|
|
||
| test(s"Upsert concurrency") { | ||
| // create a table with 100k rows | ||
| val init = | ||
| spark.range(100000) | ||
| .withColumn("ts", lit(Timestamp.valueOf("2023-06-07 12:34:56"))) | ||
| .withColumn("v", rand()) | ||
|
|
||
| // upsert 100 batches of 100 rows each | ||
| // run in 32 tasks | ||
| val patch = | ||
| spark.range(100) | ||
| .join(spark.range(100).select(($"id" * 1000).as("offset"))) | ||
| .repartition(32) | ||
| .select( | ||
| ($"id" + $"offset").as("id"), | ||
| lit(Timestamp.valueOf("2023-06-07 12:34:56")).as("ts"), | ||
| lit(-1.0).as("v") | ||
| ) | ||
|
|
||
| spark.sparkContext.setJobDescription("init") | ||
| init | ||
| .write | ||
| .mode(SaveMode.Overwrite) | ||
| .option("createTableOptions", createTableOption) | ||
| .jdbc(jdbcUrl, "new_upsert_table", new Properties) | ||
|
|
||
| spark.sparkContext.setJobDescription("patch") | ||
| patch | ||
| .write | ||
| .mode(SaveMode.Append) | ||
| .option("upsert", value = true) | ||
| .option("upsertKeyColumns", "id, ts") | ||
| .options(upsertTestOptions) | ||
| .jdbc(jdbcUrl, "new_upsert_table", new Properties) | ||
|
|
||
| // check result table has 100*100 updated rows | ||
| val result = spark.read.jdbc(jdbcUrl, "new_upsert_table", new Properties) | ||
| .select($"id", when($"v" === -1.0, true).otherwise(false).as("patched")) | ||
| .groupBy($"patched") | ||
| .count() | ||
| .sort($"patched") | ||
| .as[(Boolean, Long)] | ||
| .collect() | ||
| assert(result === Seq((false, 90000), (true, 10000))) | ||
| } | ||
|
|
||
| test("Upsert with columns that require quotes") {} | ||
| test("Upsert with table name that requires quotes") {} | ||
| test("Upsert null values") {} | ||
|
|
||
| test("Write with unspecified mode with upsert") {} | ||
| test("Write with overwrite mode with upsert") {} | ||
| test("Write with error-if-exists mode with upsert") {} | ||
| test("Write with ignore mode with upsert") {} | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -162,6 +162,11 @@ class JDBCOptions( | |
| val isTruncate = parameters.getOrElse(JDBC_TRUNCATE, "false").toBoolean | ||
|
|
||
| val isCascadeTruncate: Option[Boolean] = parameters.get(JDBC_CASCADE_TRUNCATE).map(_.toBoolean) | ||
| // if to upsert the table in the JDBC database | ||
| val isUpsert = parameters.getOrElse(JDBC_UPSERT, "false").toBoolean | ||
| // the columns used to identify update and insert rows in upsert mode | ||
| val upsertKeyColumns = parameters.getOrElse(JDBC_UPSERT_KEY_COLUMNS, "").split(",").map(_.trim) | ||
|
|
||
| // the create table option , which can be table_options or partition_options. | ||
| // E.g., "CREATE TABLE t (name string) ENGINE=InnoDB DEFAULT CHARSET=utf8" | ||
| // TODO: to reuse the existing partition parameters for those partition specific options | ||
|
|
@@ -296,6 +301,8 @@ object JDBCOptions { | |
| val JDBC_BATCH_FETCH_SIZE = newOption("fetchsize") | ||
| val JDBC_TRUNCATE = newOption("truncate") | ||
| val JDBC_CASCADE_TRUNCATE = newOption("cascadeTruncate") | ||
| val JDBC_UPSERT = newOption("upsert") | ||
|
||
| val JDBC_UPSERT_KEY_COLUMNS = newOption("upsertKeyColumns") | ||
| val JDBC_CREATE_TABLE_OPTIONS = newOption("createTableOptions") | ||
| val JDBC_CREATE_TABLE_COLUMN_TYPES = newOption("createTableColumnTypes") | ||
| val JDBC_CUSTOM_DATAFRAME_COLUMN_TYPES = newOption("customSchema") | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems not necessary!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed