-
Notifications
You must be signed in to change notification settings - Fork 29k
[SPARK-20427][SQL] Read JDBC table use custom schema #18266
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
Changes from 19 commits
871c303
0444c4d
06881e8
ffaee42
a984f3b
e0fc6b4
9e6f7cf
5fdd2bb
87df014
63d3244
e08ccbb
247fc78
b8b03e2
b040c72
2ea56fc
1e2c1d9
b38a1a8
0b67f0f
7fc97b4
1fdf002
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -177,6 +177,16 @@ def jdbc_dataset_example(spark): | |
| .jdbc("jdbc:postgresql:dbserver", "schema.tablename", | ||
| properties={"user": "username", "password": "password"}) | ||
|
|
||
| # Specifying dataframe column data types on read | ||
| jdbcDF3 = spark.read \ | ||
| .format("jdbc") \ | ||
| .option("url", "jdbc:postgresql:dbserver") \ | ||
| .option("dbtable", "schema.tablename") \ | ||
| .option("user", "username") \ | ||
| .option("password", "password") \ | ||
| .option("customDataFrameColumnTypes", "id DECIMAL(38, 0), name STRING") \ | ||
|
||
| .load() | ||
|
|
||
| # Saving data to a JDBC source | ||
| jdbcDF.write \ | ||
| .format("jdbc") \ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,7 +21,7 @@ import java.sql.{Connection, Date, Timestamp} | |
| import java.util.Properties | ||
| import java.math.BigDecimal | ||
|
|
||
| import org.apache.spark.sql.Row | ||
| import org.apache.spark.sql.{DataFrame, Row} | ||
| import org.apache.spark.sql.execution.{WholeStageCodegenExec, RowDataSourceScanExec} | ||
| import org.apache.spark.sql.test.SharedSQLContext | ||
| import org.apache.spark.sql.types._ | ||
|
|
@@ -72,10 +72,17 @@ class OracleIntegrationSuite extends DockerJDBCIntegrationSuite with SharedSQLCo | |
| """.stripMargin.replaceAll("\n", " ")).executeUpdate() | ||
| conn.commit() | ||
|
|
||
| conn.prepareStatement("CREATE TABLE ts_with_timezone (id NUMBER(10), t TIMESTAMP WITH TIME ZONE)") | ||
| .executeUpdate() | ||
| conn.prepareStatement("INSERT INTO ts_with_timezone VALUES (1, to_timestamp_tz('1999-12-01 11:00:00 UTC','YYYY-MM-DD HH:MI:SS TZR'))") | ||
| .executeUpdate() | ||
| conn.prepareStatement( | ||
| "CREATE TABLE ts_with_timezone (id NUMBER(10), t TIMESTAMP WITH TIME ZONE)").executeUpdate() | ||
| conn.prepareStatement( | ||
| "INSERT INTO ts_with_timezone VALUES " + | ||
| "(1, to_timestamp_tz('1999-12-01 11:00:00 UTC','YYYY-MM-DD HH:MI:SS TZR'))").executeUpdate() | ||
| conn.commit() | ||
|
|
||
| conn.prepareStatement( | ||
| "CREATE TABLE tableWithCustomSchema (id NUMBER, n1 NUMBER(1), n2 NUMBER(1))").executeUpdate() | ||
| conn.prepareStatement( | ||
| "INSERT INTO tableWithCustomSchema values(12312321321321312312312312123, 1, 0)").executeUpdate() | ||
| conn.commit() | ||
|
|
||
| sql( | ||
|
|
@@ -104,7 +111,7 @@ class OracleIntegrationSuite extends DockerJDBCIntegrationSuite with SharedSQLCo | |
| } | ||
|
|
||
|
|
||
| test("SPARK-16625 : Importing Oracle numeric types") { | ||
| test("SPARK-16625 : Importing Oracle numeric types") { | ||
| val df = sqlContext.read.jdbc(jdbcUrl, "numerics", new Properties); | ||
| val rows = df.collect() | ||
| assert(rows.size == 1) | ||
|
|
@@ -272,4 +279,32 @@ class OracleIntegrationSuite extends DockerJDBCIntegrationSuite with SharedSQLCo | |
| assert(row.getDate(0).equals(dateVal)) | ||
| assert(row.getTimestamp(1).equals(timestampVal)) | ||
| } | ||
|
|
||
| test("SPARK-20427/SPARK-20921: read table use custom schema by jdbc api") { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Move these newly added test cases to JDBCSuite.scala. Only add a single test case for Oracle data type mappings requested in the JIRA tickets. |
||
| // default will throw IllegalArgumentException | ||
| val e = intercept[org.apache.spark.SparkException] { | ||
| spark.read.jdbc(jdbcUrl, "tableWithCustomSchema", new Properties()).collect() | ||
| } | ||
| assert(e.getMessage.contains( | ||
| "requirement failed: Decimal precision 39 exceeds max precision 38")) | ||
|
|
||
| // custom schema can read data | ||
| val props = new Properties() | ||
| props.put("customSchema", | ||
| s"ID DECIMAL(${DecimalType.MAX_PRECISION}, 0), N1 INT, N2 BOOLEAN") | ||
| val dfRead = spark.read.jdbc(jdbcUrl, "tableWithCustomSchema", props) | ||
|
|
||
| val rows = dfRead.collect() | ||
| // verify the data type | ||
| val types = rows(0).toSeq.map(x => x.getClass.toString) | ||
| assert(types(0).equals("class java.math.BigDecimal")) | ||
| assert(types(1).equals("class java.lang.Integer")) | ||
| assert(types(2).equals("class java.lang.Boolean")) | ||
|
|
||
| // verify the value | ||
| val values = rows(0) | ||
| assert(values.getDecimal(0).equals(new java.math.BigDecimal("12312321321321312312312312123"))) | ||
| assert(values.getInt(1).equals(1)) | ||
| assert(values.getBoolean(2).equals(false)) | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -80,7 +80,7 @@ object JDBCRDD extends Logging { | |
| * @return A Catalyst schema corresponding to columns in the given order. | ||
| */ | ||
| private def pruneSchema(schema: StructType, columns: Array[String]): StructType = { | ||
| val fieldMap = Map(schema.fields.map(x => x.metadata.getString("name") -> x): _*) | ||
| val fieldMap = Map(schema.fields.map(x => x.name -> x): _*) | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is not a related change. Could you revert it back?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorry, I did not get your point. Could you show me an example? Is it a behavior breaking change?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see. Could we just get rid of the line where we put
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It seems safe to remove this line. |
||
| new StructType(columns.map(name => fieldMap(name))) | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -111,7 +111,16 @@ private[sql] case class JDBCRelation( | |
|
|
||
| override val needConversion: Boolean = false | ||
|
|
||
| override val schema: StructType = JDBCRDD.resolveTable(jdbcOptions) | ||
| override val schema: StructType = { | ||
| val schema = JDBCRDD.resolveTable(jdbcOptions) | ||
| val customSchema = jdbcOptions.customSchema | ||
| if (customSchema.isDefined) { | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, customSchema.get, | ||
| sqlContext.sessionState.conf.resolver) | ||
| } else { | ||
| schema | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. val tableSchema = JDBCRDD.resolveTable(jdbcOptions)
jdbcOptions.customSchema match {
case Some(customSchema) => JdbcUtils.parseUserSpecifiedColumnTypes(
tableSchema, customSchema, sparkSession.sessionState.conf.resolver)
case None => tableSchema
} |
||
| } | ||
|
|
||
| // Check if JDBCRDD.compileFilter can accept input filters | ||
| override def unhandledFilters(filters: Array[Filter]): Array[Filter] = { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,6 +29,7 @@ import org.apache.spark.executor.InputMetrics | |
| import org.apache.spark.internal.Logging | ||
| import org.apache.spark.sql.{AnalysisException, DataFrame, Row} | ||
| import org.apache.spark.sql.catalyst.InternalRow | ||
| import org.apache.spark.sql.catalyst.analysis.Resolver | ||
| import org.apache.spark.sql.catalyst.encoders.RowEncoder | ||
| import org.apache.spark.sql.catalyst.expressions.SpecificInternalRow | ||
| import org.apache.spark.sql.catalyst.parser.CatalystSqlParser | ||
|
|
@@ -767,6 +768,35 @@ object JdbcUtils extends Logging { | |
| if (isCaseSensitive) userSchemaMap else CaseInsensitiveMap(userSchemaMap) | ||
| } | ||
|
|
||
| /** | ||
| * Parses the user specified customSchema option value to DataFrame schema, | ||
| * and returns it if it's all columns are equals to default schema's. | ||
| */ | ||
| def parseUserSpecifiedColumnTypes( | ||
| schema: StructType, | ||
| columnTypes: String, | ||
| nameEquality: Resolver): StructType = { | ||
|
||
| val userSchema = CatalystSqlParser.parseTableSchema(columnTypes) | ||
|
|
||
| SchemaUtils.checkColumnNameDuplication( | ||
| userSchema.map(_.name), "in the customSchema option value", nameEquality) | ||
|
|
||
| if (userSchema.size != schema.size) { | ||
| throw new AnalysisException("Please provide all the columns, " + | ||
| s"all columns are: ${schema.fields.map(_.name).mkString(",")}") | ||
| } | ||
|
|
||
| // This is resolved by names, only check the column names. | ||
| userSchema.fieldNames.foreach { col => | ||
| schema.find(f => nameEquality(f.name, col)).getOrElse { | ||
| throw new AnalysisException( | ||
| s"${JDBCOptions.JDBC_CUSTOM_DATAFRAME_COLUMN_TYPES} option column $col not found in " + | ||
| s"schema ${schema.catalogString}") | ||
|
||
| } | ||
| } | ||
| userSchema | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is your expected behaviors when users-specified schema does not include all the columns of the underlying table schema?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. OK, I'll ask user to specified all the columns. |
||
| } | ||
|
|
||
| /** | ||
| * Saves the RDD to the database in a single transaction. | ||
| */ | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| /* | ||
| * 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.execution.datasources.jdbc | ||
|
|
||
| import org.apache.spark.SparkFunSuite | ||
| import org.apache.spark.sql.AnalysisException | ||
| import org.apache.spark.sql.catalyst.parser.ParseException | ||
| import org.apache.spark.sql.types._ | ||
|
|
||
| class JdbcUtilsSuite extends SparkFunSuite { | ||
|
|
||
| val schema = StructType(Seq( | ||
| StructField("C1", StringType, false), StructField("C2", IntegerType, false))) | ||
| val caseSensitive = org.apache.spark.sql.catalyst.analysis.caseSensitiveResolution | ||
| val caseInsensitive = org.apache.spark.sql.catalyst.analysis.caseInsensitiveResolution | ||
|
|
||
| test("Parse user specified column types") { | ||
| assert( | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "C1 DATE, C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("C1", DateType, true), StructField("C2", StringType, true)))) | ||
| assert(JdbcUtils.parseUserSpecifiedColumnTypes(schema, "C1 DATE, C2 STRING", caseSensitive) === | ||
| StructType(Seq(StructField("C1", DateType, true), StructField("C2", StringType, true)))) | ||
| assert( | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c1 DATE, C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c1", DateType, true), StructField("C2", StringType, true)))) | ||
| assert(JdbcUtils.parseUserSpecifiedColumnTypes( | ||
| schema, "c1 DECIMAL(38, 0), C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c1", DecimalType(38, 0), true), | ||
| StructField("C2", StringType, true)))) | ||
|
|
||
| // Throw AnalysisException | ||
| val duplicate = intercept[AnalysisException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c1 DATE, c1 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c1", DateType, true), StructField("c1", StringType, true))) | ||
| } | ||
| assert(duplicate.getMessage.contains( | ||
| "Found duplicate column(s) in the customSchema option value")) | ||
|
|
||
| val allColumns = intercept[AnalysisException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "C1 STRING", caseSensitive) === | ||
| StructType(Seq(StructField("C1", DateType, true))) | ||
| } | ||
| assert(allColumns.getMessage.contains("Please provide all the columns,")) | ||
|
|
||
| val caseSensitiveColumnNotFound = intercept[AnalysisException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c1 DATE, C2 STRING", caseSensitive) === | ||
| StructType(Seq(StructField("c1", DateType, true), StructField("C2", StringType, true))) | ||
| } | ||
| assert(caseSensitiveColumnNotFound.getMessage.contains( | ||
| s"${JDBCOptions.JDBC_CUSTOM_DATAFRAME_COLUMN_TYPES} option column c1 not found in schema")) | ||
|
|
||
| val caseInsensitiveColumnNotFound = intercept[AnalysisException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c3 DATE, C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c3", DateType, true), StructField("C2", StringType, true))) | ||
| } | ||
| assert(caseInsensitiveColumnNotFound.getMessage.contains( | ||
| s"${JDBCOptions.JDBC_CUSTOM_DATAFRAME_COLUMN_TYPES} option column c3 not found in schema")) | ||
|
|
||
| // Throw ParseException | ||
| val dataTypeNotSupported = intercept[ParseException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c3 DATEE, C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c3", DateType, true), StructField("C2", StringType, true))) | ||
| } | ||
| assert(dataTypeNotSupported.getMessage.contains("DataType datee is not supported")) | ||
|
|
||
| val mismatchedInput = intercept[ParseException]{ | ||
| JdbcUtils.parseUserSpecifiedColumnTypes(schema, "c3 DATE. C2 STRING", caseInsensitive) === | ||
| StructType(Seq(StructField("c3", DateType, true), StructField("C2", StringType, true))) | ||
| } | ||
| assert(mismatchedInput.getMessage.contains("mismatched input '.' expecting")) | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
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.
customSchema