diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/CreateIndexCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/CreateIndexCompiler.java index f6e3b6eded6..ccb3d234791 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/CreateIndexCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/CreateIndexCompiler.java @@ -56,6 +56,7 @@ import org.apache.phoenix.schema.types.PBoolean; import org.apache.phoenix.schema.types.PBson; import org.apache.phoenix.schema.types.PChar; +import org.apache.phoenix.schema.types.PCharArray; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PDate; import org.apache.phoenix.schema.types.PDateArray; @@ -72,6 +73,7 @@ import org.apache.phoenix.schema.types.PUnsignedTimestamp; import org.apache.phoenix.schema.types.PUnsignedTimestampArray; import org.apache.phoenix.schema.types.PVarchar; +import org.apache.phoenix.schema.types.PVarcharArray; import org.apache.phoenix.util.ByteUtil; import org.apache.phoenix.util.EnvironmentEdgeManager; import org.apache.phoenix.util.PhoenixRuntime; @@ -119,6 +121,10 @@ private String getValue(PDataType type) { || type instanceof PUnsignedTimestampArray ) { return "ARRAY[" + getValue(PDate.INSTANCE) + "]"; + } else if (type instanceof PCharArray || type instanceof PVarcharArray) { + // A fixed element keeps the probe row deterministic. The scalar VARCHAR and CHAR cases use + // the same value. + return "ARRAY[" + getValue(PVarchar.INSTANCE) + "]"; } else if (type instanceof PArrayDataType) { return "ARRAY" + type.getSampleValue().toString(); } else if (type instanceof PJson || type instanceof PBson) { diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/PostIndexDDLCompiler.java b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/PostIndexDDLCompiler.java index 4441c71d8bc..fb15e77e22f 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/compile/PostIndexDDLCompiler.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/compile/PostIndexDDLCompiler.java @@ -29,7 +29,6 @@ import org.apache.phoenix.schema.PTable; import org.apache.phoenix.schema.TableRef; import org.apache.phoenix.util.IndexUtil; -import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.thirdparty.com.google.common.collect.Lists; @@ -74,10 +73,9 @@ public MutationPlan compile(final PTable indexTable) throws SQLException { for (int i = posOffset; i < nIndexPKColumns; i++) { PColumn col = indexPKColumns.get(i); String indexColName = col.getName().getString(); - // need to escape backslash as this used in the SELECT statement - String dataColName = col.getExpressionStr() == null - ? col.getName().getString() - : StringUtil.escapeBackslash(col.getExpressionStr()); + // The stored expression is valid SQL text. Do not escape it again. + String dataColName = + col.getExpressionStr() == null ? col.getName().getString() : col.getExpressionStr(); dataColumns.append(dataColName).append(","); indexColumns.append('"').append(indexColName).append("\","); indexColumnNames.add(indexColName); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowSchemasStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowSchemasStatement.java index 596b02bf229..ba10d4718af 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowSchemasStatement.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowSchemasStatement.java @@ -20,6 +20,7 @@ import java.util.Objects; import javax.annotation.Nullable; import org.apache.phoenix.compile.ColumnResolver; +import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions; @@ -44,7 +45,7 @@ public void toSQL(ColumnResolver resolver, StringBuilder buf) { buf.append("SHOW SCHEMAS"); if (schemaPattern != null) { buf.append(" LIKE "); - buf.append("'").append(schemaPattern).append("'"); + buf.append("'").append(StringUtil.escapeStringConstant(schemaPattern)).append("'"); } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowTablesStatement.java b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowTablesStatement.java index f3ee7ff7fbd..acc2bee5322 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowTablesStatement.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/parse/ShowTablesStatement.java @@ -20,6 +20,7 @@ import java.util.Objects; import javax.annotation.Nullable; import org.apache.phoenix.compile.ColumnResolver; +import org.apache.phoenix.util.StringUtil; import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions; @@ -65,7 +66,7 @@ public void toSQL(ColumnResolver resolver, StringBuilder buf) { } if (dbPattern != null) { buf.append(" LIKE "); - buf.append("'").append(dbPattern).append("'"); + buf.append("'").append(StringUtil.escapeStringConstant(dbPattern)).append("'"); } } diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java index cdad48aa0b7..5889146f814 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/schema/MetaDataClient.java @@ -1762,8 +1762,9 @@ public MutationState createIndex(CreateIndexStatement statement, byte[][] splits // functional index column name. Otherwise the leading space would be baked into the // PColumn name and would later show up inside the double quotes of the case-sensitive // display name (e.g. PROJECT " JSON_VALUE(DOC,'$.type')"). - // need to escape backslash as this expression will be re-parsed later - String expressionStr = StringUtil.escapeBackslash(buf.toString().trim()); + // ParseNode.toSQL already escapes backslashes and quotes in string literals. Do not escape + // the text again. + String expressionStr = buf.toString().trim(); ColumnName colName = null; ColumnRef colRef = expressionIndexCompiler.getColumnRef(); diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java index 81057f305f4..6f06bc38d71 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/SchemaUtil.java @@ -228,8 +228,8 @@ public static String normalizeIdentifier(String name) { } /** - * Normalize a Literal. If literal is surrounded by single quotes, the quotes are trimmed, else - * full string is returned + * Normalize a Literal. A string literal gives its parsed value. Any other literal gives its SQL + * text, without the enclosing single quotes. * @param literal the parsed LiteralParseNode * @return the normalized literal string */ @@ -237,6 +237,11 @@ public static String normalizeLiteral(LiteralParseNode literal) { if (literal == null) { return null; } + // The SQL text of a string literal holds escape sequences. The parsed value does not. To get + // a value with a quote or a backslash, the SQL statement escapes that character. + if (literal.getValue() instanceof String) { + return (String) literal.getValue(); + } String literalString = literal.toString(); if (isEnclosedInSingleQuotes(literalString)) { // Trim the single quotes diff --git a/phoenix-core-client/src/main/java/org/apache/phoenix/util/StringUtil.java b/phoenix-core-client/src/main/java/org/apache/phoenix/util/StringUtil.java index 25850ce9454..0bfc0d46503 100644 --- a/phoenix-core-client/src/main/java/org/apache/phoenix/util/StringUtil.java +++ b/phoenix-core-client/src/main/java/org/apache/phoenix/util/StringUtil.java @@ -358,15 +358,18 @@ private static void rangeCheck(int length, int fromIndex, int toIndex) { } } + /** + * Escapes a string for use as the body of a Phoenix SQL string literal. The SQL lexer reads a + * backslash as the start of an escape sequence. It reads a doubled quote as one quote. This + * method doubles each backslash and each single quote. The parser then reads the quoted result + * back as the original string. + */ public static String escapeStringConstant(String pattern) { - // commons-lang3 dropped StringEscapeUtils.escapeSql because it was - // extremely naive in its implementation. Copying that implementation - // here as a stop-gap. - // https://stackoverflow.com/questions/32096614/migrating-stringescapeutils-escapesql-from-commons-lang if (pattern == null) { return null; } - return org.apache.commons.lang3.StringUtils.replace(pattern, "'", "''"); + String escaped = org.apache.commons.lang3.StringUtils.replace(pattern, "\\", "\\\\"); + return org.apache.commons.lang3.StringUtils.replace(escaped, "'", "''"); } public static String escapeBackslash(String input) { diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalMutableTxIndexIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalMutableTxIndexIT.java index a0d432a89a4..78abd8d43b6 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalMutableTxIndexIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/index/GlobalMutableTxIndexIT.java @@ -17,9 +17,21 @@ */ package org.apache.phoenix.end2end.index; +import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.util.Arrays; import java.util.Collection; +import java.util.Properties; import org.apache.phoenix.end2end.ParallelStatsDisabledTest; +import org.apache.phoenix.util.PropertiesUtil; +import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runners.Parameterized.Parameters; @@ -38,4 +50,58 @@ public static synchronized Collection data() { { "OMID", false }, }); } + /** + * The index build for a transactional table and the index maintenance compile the stored index + * expression separately. Both must give the same value for a string literal with a backslash. + */ + @Test + public void testFunctionalIndexBackslashLiteralBuildAndMaintenance() throws Exception { + Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); + String tableName = generateUniqueName(); + String indexName = generateUniqueName(); + try (Connection conn = DriverManager.getConnection(getUrl(), props)) { + conn.setAutoCommit(false); + conn.createStatement() + .execute("CREATE TABLE " + tableName + " (k VARCHAR NOT NULL PRIMARY KEY, v VARCHAR)" + + " COLUMN_ENCODED_BYTES=0, TRANSACTIONAL=true, TRANSACTION_PROVIDER='OMID'"); + PreparedStatement upsert = conn.prepareStatement("UPSERT INTO " + tableName + " VALUES(?,?)"); + // The index build reads these rows. + upsert.setString(1, "k1"); + upsert.setString(2, "a1b2"); + upsert.execute(); + upsert.setString(1, "k2"); + upsert.setString(2, "x\\d"); + upsert.execute(); + conn.commit(); + + // The SQL literal '\\d' gives the regular expression \d, which matches one digit. + conn.createStatement().execute( + "CREATE INDEX " + indexName + " ON " + tableName + " (REGEXP_REPLACE(v, '\\\\d', 'X'))"); + + // Index maintenance writes the index rows for these rows. + upsert.setString(1, "k3"); + upsert.setString(2, "c3"); + upsert.execute(); + upsert.setString(1, "k4"); + upsert.setString(2, "y\\d"); + upsert.execute(); + conn.commit(); + + ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM " + indexName); + assertTrue(rs.next()); + assertEquals("aXbX", rs.getString(1)); + assertEquals("k1", rs.getString(2)); + assertTrue(rs.next()); + assertEquals("cX", rs.getString(1)); + assertEquals("k3", rs.getString(2)); + assertTrue(rs.next()); + assertEquals("x\\d", rs.getString(1)); + assertEquals("k2", rs.getString(2)); + assertTrue(rs.next()); + assertEquals("y\\d", rs.getString(1)); + assertEquals("k4", rs.getString(2)); + assertFalse(rs.next()); + } + } + } diff --git a/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java b/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java index a0bfb49d311..3837a0e09be 100644 --- a/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java +++ b/phoenix-core/src/test/java/org/apache/phoenix/parse/QueryParserTest.java @@ -1006,6 +1006,11 @@ public void testShowStmt() throws Exception { parseQuery("show tables in foo"); parseQuery("show tables in foo like 'bar%'"); parseQuery("show tables like 'bar%'"); + for (String sql : new String[] { "show schemas like 'it''s\\_x'", + "show tables like 'it''s\\_x'", "show tables like 'a\\\\b'" }) { + BindableStatement stmt = new SQLParser(sql).parseStatement(); + assertEquals(stmt, new SQLParser(stmt.toString()).parseStatement()); + } // Expected failures. parseQueryThatShouldFail("show schemas like foo"); diff --git a/phoenix-core/src/test/java/org/apache/phoenix/schema/SchemaUtilTest.java b/phoenix-core/src/test/java/org/apache/phoenix/schema/SchemaUtilTest.java index d03a588b707..08172fc17e4 100644 --- a/phoenix-core/src/test/java/org/apache/phoenix/schema/SchemaUtilTest.java +++ b/phoenix-core/src/test/java/org/apache/phoenix/schema/SchemaUtilTest.java @@ -21,6 +21,8 @@ import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.exception.SQLExceptionCode; +import org.apache.phoenix.parse.LiteralParseNode; +import org.apache.phoenix.parse.SQLParser; import org.apache.phoenix.util.SchemaUtil; import org.junit.Test; @@ -78,4 +80,18 @@ public void testGetTableNameFromFullName() { String tableDisplayName = SchemaUtil.getTableNameFromFullName("schemaName.tableName"); assertEquals(tableDisplayName, "tableName"); } + + @Test + public void testNormalizeLiteralReturnsParsedValue() throws Exception { + assertEquals("T\\_X", normalizeLiteral("'T\\_X'")); + assertEquals("a\\b", normalizeLiteral("'a\\\\b'")); + assertEquals("it's", normalizeLiteral("'it''s'")); + // An escaped literal can give any value, also a value with doubled quotes. + assertEquals("O''Brien", normalizeLiteral("'O''''Brien'")); + assertEquals("1", SchemaUtil.normalizeLiteral(new LiteralParseNode(1))); + } + + private static String normalizeLiteral(String sql) throws Exception { + return SchemaUtil.normalizeLiteral(new SQLParser(sql).parseLiteral()); + } } diff --git a/phoenix-core/src/test/java/org/apache/phoenix/util/StringUtilTest.java b/phoenix-core/src/test/java/org/apache/phoenix/util/StringUtilTest.java index 1ae9e880c9b..41c90494d10 100644 --- a/phoenix-core/src/test/java/org/apache/phoenix/util/StringUtilTest.java +++ b/phoenix-core/src/test/java/org/apache/phoenix/util/StringUtilTest.java @@ -20,7 +20,9 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import org.apache.phoenix.parse.SQLParser; import org.apache.phoenix.schema.SortOrder; +import org.apache.phoenix.schema.types.PVarchar; import org.junit.Test; public class StringUtilTest { @@ -81,4 +83,14 @@ public void testCalculateUTF8Offset() throws Exception { tmp = tmp + data.charAt(i + data.length()); } } + + @Test + public void testEscapeStringConstantRoundTrip() throws Exception { + String[] values = { "a\\b", "\\", "a\\", "\\\\", "it's", "\\'", "''", "a\\nb", "a\\_b\\%", + "x\\\"y", "line\nbreak", "a\\Nb", "end'" }; + for (String value : values) { + String literal = PVarchar.INSTANCE.toStringLiteral(value, null); + assertEquals(literal, value, new SQLParser(literal).parseLiteral().getValue()); + } + } }