Skip to content
Merged
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 @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Comment thread
apurtell marked this conversation as resolved.
Resolved
dataColumns.append(dataColName).append(",");
indexColumns.append('"').append(indexColName).append("\",");
indexColumnNames.add(indexColName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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("'");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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("'");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,15 +228,20 @@ 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
*/
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -38,4 +50,58 @@ public static synchronized Collection<Object[]> 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());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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());
}
}
}
Loading