Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -716,11 +716,11 @@ abstract class JdbcDialect extends Serializable with Logging {
}

def getTableCommentQuery(table: String, comment: String): String = {
s"COMMENT ON TABLE $table IS '$comment'"
s"COMMENT ON TABLE $table IS '${escapeSql(comment)}'"
}

def getSchemaCommentQuery(schema: String, comment: String): String = {
s"COMMENT ON SCHEMA ${quoteIdentifier(schema)} IS '$comment'"
s"COMMENT ON SCHEMA ${quoteIdentifier(schema)} IS '${escapeSql(comment)}'"
}

def removeSchemaCommentQuery(schema: String): String = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ private case class MySQLDialect() extends JdbcDialect with SQLConfHelper with No

// See https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
override def getTableCommentQuery(table: String, comment: String): String = {
s"ALTER TABLE $table COMMENT = '$comment'"
s"ALTER TABLE $table COMMENT = '${escapeSql(comment)}'"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking, out of scope — just flagging for completeness: escapeSql doubles ' but doesn't escape \. MySQL treats backslash as an escape character by default (NO_BACKSLASH_ESCAPES unset), so a comment containing a backslash can still be mangled (or break the statement if trailing) here. This is pre-existing and shared with compileValue's MySQL string-predicate handling, and this PR is a strict improvement for the single-quote case, so nothing to change here.

}

override def getJDBCType(dt: DataType): Option[JdbcType] = dt match {
Expand Down
13 changes: 13 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,19 @@ class JDBCSuite extends SharedSparkSession {
assert(mySQLSQL(StringStartsWith("c", "a%b_")) === """`c` LIKE 'a\\%b\\_%' ESCAPE '\\'""")
}

test("SPARK-57446: escape single quotes in JDBC comment queries") {
val defaultDialect = JdbcDialects.get("jdbc:")
assert(defaultDialect.getTableCommentQuery("t", "a'b") ===
"COMMENT ON TABLE t IS 'a''b'")
assert(defaultDialect.getSchemaCommentQuery("s", "a'b") ===
"""COMMENT ON SCHEMA "s" IS 'a''b'""")

// MySQL overrides getTableCommentQuery with its own ALTER TABLE syntax.
val mySQLDialect = JdbcDialects.get("jdbc:mysql://127.0.0.1/db")
assert(mySQLDialect.getTableCommentQuery("t", "a'b") ===
"ALTER TABLE t COMMENT = 'a''b'")
}

test("Dialect unregister") {
JdbcDialects.unregisterDialect(H2Dialect())
try {
Expand Down