Skip to content

Commit 1135430

Browse files
Huaxin Gaoyhuai
authored andcommitted
[SPARK-11788][SQL] surround timestamp/date value with quotes in JDBC data source
When query the Timestamp or Date column like the following val filtered = jdbcdf.where($"TIMESTAMP_COLUMN" >= beg && $"TIMESTAMP_COLUMN" < end) The generated SQL query is "TIMESTAMP_COLUMN >= 2015-01-01 00:00:00.0" It should have quote around the Timestamp/Date value such as "TIMESTAMP_COLUMN >= '2015-01-01 00:00:00.0'" Author: Huaxin Gao <huaxing@oc0558782468.ibm.com> Closes apache#9872 from huaxingao/spark-11788. (cherry picked from commit 5a8b5fd) Signed-off-by: Yin Huai <yhuai@databricks.com>
1 parent f1122dd commit 1135430

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JDBCRDD.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
package org.apache.spark.sql.execution.datasources.jdbc
1919

20-
import java.sql.{Connection, DriverManager, ResultSet, ResultSetMetaData, SQLException}
20+
import java.sql.{Connection, Date, DriverManager, ResultSet, ResultSetMetaData, SQLException, Timestamp}
2121
import java.util.Properties
2222

2323
import org.apache.commons.lang3.StringUtils
@@ -265,6 +265,8 @@ private[sql] class JDBCRDD(
265265
*/
266266
private def compileValue(value: Any): Any = value match {
267267
case stringValue: String => s"'${escapeSql(stringValue)}'"
268+
case timestampValue: Timestamp => "'" + timestampValue + "'"
269+
case dateValue: Date => "'" + dateValue + "'"
268270
case _ => value
269271
}
270272

sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCSuite.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,4 +484,15 @@ class JDBCSuite extends SparkFunSuite with BeforeAndAfter with SharedSQLContext
484484
assert(h2.getTableExistsQuery(table) == defaultQuery)
485485
assert(derby.getTableExistsQuery(table) == defaultQuery)
486486
}
487+
488+
test("Test DataFrame.where for Date and Timestamp") {
489+
// Regression test for bug SPARK-11788
490+
val timestamp = java.sql.Timestamp.valueOf("2001-02-20 11:22:33.543543");
491+
val date = java.sql.Date.valueOf("1995-01-01")
492+
val jdbcDf = sqlContext.read.jdbc(urlWithUserAndPass, "TEST.TIMETYPES", new Properties)
493+
val rows = jdbcDf.where($"B" > date && $"C" > timestamp).collect()
494+
assert(rows(0).getAs[java.sql.Date](1) === java.sql.Date.valueOf("1996-01-01"))
495+
assert(rows(0).getAs[java.sql.Timestamp](2)
496+
=== java.sql.Timestamp.valueOf("2002-02-20 11:22:33.543543"))
497+
}
487498
}

0 commit comments

Comments
 (0)