Skip to content

Commit 6d3cd42

Browse files
[AMORO-4423][Common] Escape Spark SQL literals in table-operation history (#4424)
Escape Spark SQL literals in table-operation history Co-authored-by: Jiwon Park <jiwonpark@apache.org>
1 parent 28c0a57 commit 6d3cd42

2 files changed

Lines changed: 211 additions & 3 deletions

File tree

‎amoro-common/src/main/java/org/apache/amoro/table/descriptor/SparkMetadataChangeHandler.java‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,20 @@ public class SparkMetadataChangeHandler implements MetadataChangeHandler {
3939

4040
private final String tableName;
4141

42+
/**
43+
* Escapes a raw value so it can be spliced between single quotes in a Spark SQL literal. Spark
44+
* uses backslash escapes rather than the SQL-standard doubled apostrophe, so backslashes are
45+
* doubled first and apostrophes escaped second.
46+
*/
47+
private static String escapeLiteral(String value) {
48+
return value
49+
.replace("\\", "\\\\")
50+
.replace("'", "\\'")
51+
.replace("\n", "\\n")
52+
.replace("\r", "\\r")
53+
.replace("\t", "\\t");
54+
}
55+
4256
public SparkMetadataChangeHandler(String tableName) {
4357
this.tableName = tableName;
4458
}
@@ -48,7 +62,11 @@ public String changeAndAddProperties(Map<String, String> diffProperties) {
4862
String template = ALTER_TABLE + SET_PROPERTIES;
4963
String properties =
5064
diffProperties.entrySet().stream()
51-
.map(entry -> String.format("'%s' = '%s'", entry.getKey(), entry.getValue()))
65+
.map(
66+
entry ->
67+
String.format(
68+
"'%s' = '%s'",
69+
escapeLiteral(entry.getKey()), escapeLiteral(entry.getValue())))
5270
.collect(Collectors.joining(","));
5371
return String.format(template, tableName, properties);
5472
}
@@ -57,7 +75,9 @@ public String changeAndAddProperties(Map<String, String> diffProperties) {
5775
public String removeProperties(Set<String> removeKeys) {
5876
String template = ALTER_TABLE + UNSET_PROPERTIES;
5977
String properties =
60-
removeKeys.stream().map(key -> String.format("'%s'", key)).collect(Collectors.joining(","));
78+
removeKeys.stream()
79+
.map(key -> String.format("'%s'", escapeLiteral(key)))
80+
.collect(Collectors.joining(","));
6181
return String.format(template, tableName, properties);
6282
}
6383

@@ -93,7 +113,9 @@ public String changeColumnsRequire(String columnName, boolean required) {
93113
@Override
94114
public String changeColumnsComment(String columnName, String comment) {
95115
String template = ALTER_TABLE + ALTER_COLUMN + DOC;
96-
return String.format(template, tableName, columnName, comment);
116+
// A null comment means the comment is being removed, which Spark spells as an empty literal.
117+
return String.format(
118+
template, tableName, columnName, escapeLiteral(comment == null ? "" : comment));
97119
}
98120

99121
@Override
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
package org.apache.amoro.table.descriptor;
20+
21+
import org.apache.amoro.table.TableIdentifier;
22+
import org.junit.jupiter.api.Assertions;
23+
import org.junit.jupiter.api.Test;
24+
25+
import java.util.Arrays;
26+
import java.util.Collections;
27+
import java.util.LinkedHashMap;
28+
import java.util.List;
29+
import java.util.Map;
30+
31+
/**
32+
* Guards single-quoted Spark SQL literal escaping. Spark uses backslash escapes inside regular
33+
* string literals, not the SQL-standard doubled apostrophe, so a raw backslash must be doubled and
34+
* a raw apostrophe backslash-escaped wherever a key, value or comment is spliced between single
35+
* quotes.
36+
*/
37+
public class TestSparkMetadataChangeHandlerLiterals {
38+
39+
private static final String TABLE_NAME = "tbl";
40+
41+
/**
42+
* Plain ASCII keys, values and comments must keep producing exactly the same DDL as before: the
43+
* escaping must be a no-op when there is nothing to escape.
44+
*/
45+
@Test
46+
public void simpleLiteralsAreUnchanged() {
47+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
48+
49+
Assertions.assertEquals(
50+
"ALTER TABLE tbl SET TBLPROPERTIES ('k1' = 'v1')",
51+
handler.changeAndAddProperties(Collections.singletonMap("k1", "v1")));
52+
Assertions.assertEquals(
53+
"ALTER TABLE tbl UNSET TBLPROPERTIES ('k1')",
54+
handler.removeProperties(Collections.singleton("k1")));
55+
Assertions.assertEquals(
56+
"ALTER TABLE tbl ALTER COLUMN c COMMENT 'new comment'",
57+
handler.changeColumnsComment("c", "new comment"));
58+
}
59+
60+
/** {@code '} must be escaped in both the property key and the property value. */
61+
@Test
62+
public void changeAndAddPropertiesEscapesApostropheInKeyAndValue() {
63+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
64+
String ddl = handler.changeAndAddProperties(Collections.singletonMap("user's", "O'Reilly"));
65+
66+
Assertions.assertEquals("ALTER TABLE tbl SET TBLPROPERTIES ('user\\'s' = 'O\\'Reilly')", ddl);
67+
Assertions.assertFalse(ddl.contains("''"), "apostrophe must be backslash-escaped, not doubled");
68+
}
69+
70+
/** {@code \} must be doubled in both the property key and the property value. */
71+
@Test
72+
public void changeAndAddPropertiesEscapesBackslashInKeyAndValue() {
73+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
74+
String ddl = handler.changeAndAddProperties(Collections.singletonMap("a\\b", "C:\\tmp"));
75+
76+
Assertions.assertEquals("ALTER TABLE tbl SET TBLPROPERTIES ('a\\\\b' = 'C:\\\\tmp')", ddl);
77+
}
78+
79+
/** {@code \} must be doubled in a removed property key as well. */
80+
@Test
81+
public void removePropertiesEscapesBackslashInKey() {
82+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
83+
Assertions.assertEquals(
84+
"ALTER TABLE tbl UNSET TBLPROPERTIES ('a\\\\b')",
85+
handler.removeProperties(Collections.singleton("a\\b")));
86+
}
87+
88+
/** A column comment containing both an apostrophe and a backslash. */
89+
@Test
90+
public void changeColumnsCommentEscapesApostropheAndBackslash() {
91+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
92+
Assertions.assertEquals(
93+
"ALTER TABLE tbl ALTER COLUMN c COMMENT 'O\\'Reilly\\'s C:\\\\tmp'",
94+
handler.changeColumnsComment("c", "O'Reilly's C:\\tmp"));
95+
}
96+
97+
/**
98+
* A backslash immediately before an apostrophe must be escaped backslash-first, leaving the quote
99+
* unambiguous instead of a stray unterminated quote.
100+
*/
101+
@Test
102+
public void backslashImmediatelyBeforeQuoteIsEscapedInOrder() {
103+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
104+
Assertions.assertEquals(
105+
"ALTER TABLE tbl ALTER COLUMN c COMMENT 'a\\\\\\'b'",
106+
handler.changeColumnsComment("c", "a\\'b"));
107+
}
108+
109+
/** A raw newline or tab must be emitted escaped so the comment value survives. */
110+
@Test
111+
public void changeColumnsCommentEscapesNewlineAndTab() {
112+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
113+
Assertions.assertEquals(
114+
"ALTER TABLE tbl ALTER COLUMN c COMMENT 'line1\\nline2\\tend'",
115+
handler.changeColumnsComment("c", "line1\nline2\tend"));
116+
}
117+
118+
/** A null comment removes the comment, which Spark spells as an empty literal. */
119+
@Test
120+
public void changeColumnsCommentNullBecomesEmptyLiteral() {
121+
SparkMetadataChangeHandler handler = new SparkMetadataChangeHandler(TABLE_NAME);
122+
Assertions.assertEquals(
123+
"ALTER TABLE tbl ALTER COLUMN c COMMENT ''", handler.changeColumnsComment("c", null));
124+
}
125+
126+
/**
127+
* A comment removal arriving through the real {@link DDLReverser} history path must also emit an
128+
* empty literal rather than the text {@code null}.
129+
*/
130+
@Test
131+
public void ddlReverserRemovingCommentEmitsEmptyLiteral() {
132+
List<DDLInfo> ddls =
133+
reverse(
134+
meta(0L, "old comment", Collections.emptyMap()),
135+
meta(1L, null, Collections.emptyMap()));
136+
137+
Assertions.assertEquals(1, ddls.size());
138+
Assertions.assertEquals("ALTER TABLE tbl ALTER COLUMN c COMMENT ''", ddls.get(0).getDdl());
139+
Assertions.assertEquals(DDLInfo.DDLType.UPDATE_SCHEMA, ddls.get(0).getDdlType());
140+
}
141+
142+
/** Drives the {@link DDLReverser} property history (removed key, changed value) and comment. */
143+
@Test
144+
public void ddlReverserEscapesPropertyAndCommentHistory() {
145+
Map<String, String> preProperties = new LinkedHashMap<>();
146+
preProperties.put("d\\rop", "x");
147+
preProperties.put("k", "old");
148+
149+
List<DDLInfo> ddls =
150+
reverse(
151+
meta(0L, "old comment", preProperties),
152+
meta(1L, "it's", Collections.singletonMap("k", "O'Reilly")));
153+
154+
Assertions.assertEquals(3, ddls.size());
155+
156+
Assertions.assertEquals(
157+
"ALTER TABLE tbl UNSET TBLPROPERTIES ('d\\\\rop')", ddls.get(0).getDdl());
158+
Assertions.assertEquals(DDLInfo.DDLType.UPDATE_PROPERTIES, ddls.get(0).getDdlType());
159+
160+
Assertions.assertEquals(
161+
"ALTER TABLE tbl SET TBLPROPERTIES ('k' = 'O\\'Reilly')", ddls.get(1).getDdl());
162+
Assertions.assertEquals(DDLInfo.DDLType.UPDATE_PROPERTIES, ddls.get(1).getDdlType());
163+
164+
Assertions.assertEquals(
165+
"ALTER TABLE tbl ALTER COLUMN c COMMENT 'it\\'s'", ddls.get(2).getDdl());
166+
Assertions.assertEquals(DDLInfo.DDLType.UPDATE_SCHEMA, ddls.get(2).getDdlType());
167+
}
168+
169+
/** Drives {@link DDLReverser} with two fake metadata snapshots. */
170+
private static List<DDLInfo> reverse(
171+
TableMetaExtract.InternalTableMeta pre, TableMetaExtract.InternalTableMeta current) {
172+
TableMetaExtract<String> extractor = table -> Arrays.asList(pre, current);
173+
return new DDLReverser<>(extractor)
174+
.reverse("table", TableIdentifier.of("catalog", "db", TABLE_NAME));
175+
}
176+
177+
private static TableMetaExtract.InternalTableMeta meta(
178+
long time, String comment, Map<String, String> properties) {
179+
return new TableMetaExtract.InternalTableMeta(
180+
time, Collections.singletonList(schema(0, comment, false)), properties);
181+
}
182+
183+
private static TableMetaExtract.InternalSchema schema(int id, String comment, boolean required) {
184+
return new TableMetaExtract.InternalSchema(id, null, "c", "int", comment, required);
185+
}
186+
}

0 commit comments

Comments
 (0)