Elffuss BraidHub

kikocis/java-driver public

JAVA-1064: getTable create statement doesn't properly handle quotes in primary key.

(cherry picked from 2.1)
Changesetec028a844b590beed64dd852903331b89f44daf2e8c6bc0dd75253c495141223
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-03 11:50 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-04-01 10:41 +02:00
Parents66cf8d328fd5

Browse the files at this changeset

8 files changed

modified changelog/README.md +1 −0
@@ -12,6 +12,7 @@
1212 - [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name.
1313 - [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries.
1414 - [bug] JAVA-1100: Exception when connecting with shaded java driver in OSGI
15+- [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key.
1516
1617
1718 ### 3.0.0
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +39 −3
@@ -48,6 +48,15 @@
4848 private static final Pattern alphanumeric = Pattern.compile("\\w+"); // this includes _
4949 private static final Pattern lowercaseAlphanumeric = Pattern.compile("[a-z][a-z0-9_]*");
5050
51+ private static final Set<String> RESERVED_KEYWORDS = ImmutableSet.of(
52+ "add", "allow", "alter", "and", "any", "apply", "asc", "authorize", "batch", "begin", "by",
53+ "columnfamily", "create", "delete", "desc", "drop", "each_quorum", "from", "grant", "in",
54+ "index", "inet", "infinity", "insert", "into", "keyspace", "keyspaces", "limit", "local_one",
55+ "local_quorum", "modify", "nan", "norecursive", "of", "on", "one", "order", "password",
56+ "primary", "quorum", "rename", "revoke", "schema", "select", "set", "table", "to",
57+ "token", "three", "truncate", "two", "unlogged", "update", "use", "using", "where", "with"
58+ );
59+
5160 Metadata(Cluster.Manager cluster) {
5261 this.cluster = cluster;
5362 }
@@ -129,8 +138,11 @@
129138 // tables. Because it comes from Cassandra, we could just always quote it,
130139 // but to get a nicer output we don't do it if it's not necessary.
131140 static String escapeId(String ident) {
132- // we don't need to escape if it's lowercase and match non-quoted CQL3 ids.
133- return lowercaseAlphanumeric.matcher(ident).matches() ? ident : quote(ident);
141+ // we don't need to escape if it's lowercase and match non-quoted CQL3 ids,
142+ // and if it's not a CQL reserved keyword
143+ return lowercaseAlphanumeric.matcher(ident).matches()
144+ && !isReservedCqlKeyword(ident) ?
145+ ident : quote(ident);
134146 }
135147
136148 /**
@@ -180,8 +192,13 @@
180192 * the identifier in double quotes (see the
181193 * <a href="http://cassandra.apache.org/doc/cql3/CQL.html#identifiers">CQL documentation</a>
182194 * for details). If you are using case sensitive identifiers, this method
183- * can be used to enclose such identifier in double quotes, making it case
195+ * can be used to enclose such identifiers in double quotes, making them case
184196 * sensitive.
197+ * <p/>
198+ * Note that
199+ * <a href="https://docs.datastax.com/en/cql/3.0/cql/cql_reference/keywords_r.html">reserved CQL keywords</a>
200+ * should also be quoted. You can check if a given identifier is a reserved keyword
201+ * by calling {@link #isReservedCqlKeyword(String)}.
185202 *
186203 * @param id the keyspace or table identifier.
187204 * @return {@code id} enclosed in double-quotes, for use in methods like
@@ -192,6 +209,25 @@
192209 return '"' + id.replace("\"", "\"\"") + '"';
193210 }
194211
212+ /**
213+ * Checks whether an identifier is a known reserved CQL keyword or not.
214+ * <p/>
215+ * The check is case-insensitive, i.e., the word "{@code KeYsPaCe}"
216+ * would be considered as a reserved CQL keyword just as "{@code keyspace}".
217+ * <p/>
218+ * Note: The list of reserved CQL keywords is subject to change in future
219+ * versions of Cassandra. As a consequence, this method is provided solely as a
220+ * convenience utility and should not be considered as an authoritative
221+ * source of truth for checking reserved CQL keywords.
222+ *
223+ * @param id the identifier to check; should not be {@code null}.
224+ * @return {@code true} if the given identifier is a known reserved
225+ * CQL keyword, {@code false} otherwise.
226+ */
227+ public static boolean isReservedCqlKeyword(String id) {
228+ return id != null && RESERVED_KEYWORDS.contains(id.toLowerCase());
229+ }
230+
195231 /**
196232 * Returns the token ranges that define data distribution in the ring.
197233 * <p/>
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +2 −2
@@ -401,12 +401,12 @@
401401 sb.append("CREATE TABLE ").append(Metadata.escapeId(keyspace.getName())).append('.').append(Metadata.escapeId(name)).append(" (");
402402 newLine(sb, formatted);
403403 for (ColumnMetadata cm : columns.values())
404- newLine(sb.append(spaces(4, formatted)).append(cm).append(','), formatted);
404+ newLine(sb.append(spaces(4, formatted)).append(cm).append(',').append(spaces(1, !formatted)), formatted);
405405
406406 // PK
407407 sb.append(spaces(4, formatted)).append("PRIMARY KEY (");
408408 if (partitionKey.size() == 1) {
409- sb.append(partitionKey.get(0).getName());
409+ sb.append(Metadata.escapeId(partitionKey.get(0).getName()));
410410 } else {
411411 sb.append('(');
412412 boolean first = true;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +3 −1
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core.querybuilder;
1717
18+import com.datastax.driver.core.Metadata;
1819 import com.datastax.driver.core.RegularStatement;
1920 import com.datastax.driver.core.TableMetadata;
2021 import com.datastax.driver.core.exceptions.InvalidQueryException;
@@ -227,9 +228,10 @@
227228 *
228229 * @param columnName the column name to quote.
229230 * @return the quoted column name.
231+ * @see Metadata#quote(String)
230232 */
231233 public static String quote(String columnName) {
232- return '"' + columnName + '"';
234+ return Metadata.quote(columnName);
233235 }
234236
235237 /**
modified driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +2 −9
@@ -16,13 +16,12 @@
1616 package com.datastax.driver.core.schemabuilder;
1717
1818 import com.datastax.driver.core.CodecRegistry;
19+import com.datastax.driver.core.Metadata;
1920 import com.datastax.driver.core.ProtocolVersion;
2021 import com.datastax.driver.core.RegularStatement;
2122 import com.google.common.base.Strings;
2223
2324 import java.nio.ByteBuffer;
24-import java.util.Arrays;
25-import java.util.List;
2625 import java.util.Map;
2726
2827 /**
@@ -33,12 +32,6 @@
3332 static final String STATEMENT_START = "\n\t";
3433 static final String COLUMN_FORMATTING = "\n\t\t";
3534
36- static final List<String> RESERVED_KEYWORDS = Arrays.asList(
37- ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
38- "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
39- "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
40- .split(","));
41-
4235 private volatile String cache;
4336
4437 abstract String buildInternal();
@@ -104,7 +97,7 @@
10497 }
10598
10699 static void validateNotKeyWord(String label, String message) {
107- if (RESERVED_KEYWORDS.contains(label)) {
100+ if (Metadata.isReservedCqlKeyword(label)) {
108101 throw new IllegalArgumentException(message);
109102 }
110103 }
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +72 −0
@@ -497,4 +497,76 @@
497497 // then the table's options should contain populated extensions.
498498 assertThat(table.getOptions().getExtensions()).isEqualTo(extensions);
499499 }
500+
501+ /**
502+ * Validates that a table with case-sensitive column names and column names
503+ * consisting of (quoted) reserved keywords is correctly parsed
504+ * and that the generated CQL is valid.
505+ *
506+ * @jira_ticket JAVA-1064
507+ * @test_category metadata
508+ */
509+ @Test(groups = "short")
510+ public void should_parse_table_with_case_sensitive_column_names_and_reserved_keywords() throws Exception {
511+ // given
512+ String c1 = Metadata.quote("quotes go \"\" here \"\" ");
513+ String c2 = Metadata.quote("\\x00\\x25");
514+ String c3 = Metadata.quote("columnfamily");
515+ String c4 = Metadata.quote("select");
516+ String c5 = Metadata.quote("who''s there'? ");
517+ String c6 = Metadata.quote("faux )");
518+ String c7 = Metadata.quote("COMPACT STORAGE");
519+ // single partition key
520+ String cql1 = String.format("CREATE TABLE %s.\"MyTable1\" ("
521+ + "%s text, "
522+ + "%s text, "
523+ + "%s text, "
524+ + "%s text, "
525+ + "%s text, "
526+ + "%s text, "
527+ + "%s text, "
528+ + "PRIMARY KEY (%s, %s, %s, %s, %s, %s)"
529+ + ")", keyspace, c1, c2, c3, c4, c5, c6, c7, c1, c2, c3, c4, c5, c6);
530+ // composite partition key
531+ String cql2 = String.format("CREATE TABLE %s.\"MyTable2\" ("
532+ + "%s text, "
533+ + "%s text, "
534+ + "%s text, "
535+ + "%s text, "
536+ + "%s text, "
537+ + "%s text, "
538+ + "%s text, "
539+ + "PRIMARY KEY ((%s, %s), %s, %s, %s, %s)"
540+ + ")", keyspace, c1, c2, c3, c4, c5, c6, c7, c1, c2, c3, c4, c5, c6);
541+ // when
542+ execute(cql1, cql2);
543+ TableMetadata table1 = cluster().getMetadata().getKeyspace(keyspace).getTable("\"MyTable1\"");
544+ TableMetadata table2 = cluster().getMetadata().getKeyspace(keyspace).getTable("\"MyTable2\"");
545+ // then
546+ assertThat(table1)
547+ .hasColumn(c1)
548+ .hasColumn(c2)
549+ .hasColumn(c3)
550+ .hasColumn(c4)
551+ .hasColumn(c5)
552+ .hasColumn(c6)
553+ .hasColumn(c7);
554+ assertThat(table1.asCQLQuery()).startsWith(cql1);
555+ assertThat(table2)
556+ .hasColumn(c1)
557+ .hasColumn(c2)
558+ .hasColumn(c3)
559+ .hasColumn(c4)
560+ .hasColumn(c5)
561+ .hasColumn(c6)
562+ .hasColumn(c7);
563+ assertThat(table2.asCQLQuery()).startsWith(cql2);
564+ execute(
565+ "DROP TABLE \"MyTable1\"",
566+ "DROP TABLE \"MyTable2\"",
567+ table1.asCQLQuery(),
568+ table2.asCQLQuery()
569+ );
570+ }
571+
500572 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +1 −1
@@ -850,7 +850,7 @@
850850 public void should_quote_column_names_with_escaped_quotes() {
851851 // A column name can include quotes as long as it is escaped with another set of quotes, so "foo""bar" is a valid name.
852852 String query = "SELECT * FROM foo WHERE \"foo \"\" bar\"=1;";
853- Statement statement = select().from("foo").where(eq(quote("foo \"\" bar"), 1));
853+ Statement statement = select().from("foo").where(eq(quote("foo \" bar"), 1));
854854
855855 assertThat(statement.toString()).isEqualTo(query);
856856 }
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java +12 −12
@@ -545,54 +545,54 @@
545545 }
546546
547547 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
548- expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
548+ expectedExceptionsMessageRegExp = "The keyspace name 'ADD' is not allowed because it is a reserved keyword")
549549 public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
550- createTable("add", "test")
550+ createTable("ADD", "test")
551551 .addPartitionKey("pk", DataType.bigint())
552552 .addColumn("col", DataType.text()).getQueryString();
553553 }
554554
555555 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
556- expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
556+ expectedExceptionsMessageRegExp = "The table name 'ADD' is not allowed because it is a reserved keyword")
557557 public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
558- createTable("add")
558+ createTable("ADD")
559559 .addPartitionKey("pk", DataType.bigint())
560560 .addColumn("col", DataType.text()).getQueryString();
561561 }
562562
563563 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
564- expectedExceptionsMessageRegExp = "The partition key name 'add' is not allowed because it is a reserved keyword")
564+ expectedExceptionsMessageRegExp = "The partition key name 'ADD' is not allowed because it is a reserved keyword")
565565 public void should_fail_if_partition_key_is_a_reserved_keyword() throws Exception {
566566 createTable("test")
567- .addPartitionKey("add", DataType.bigint())
567+ .addPartitionKey("ADD", DataType.bigint())
568568 .addColumn("col", DataType.text()).getQueryString();
569569 }
570570
571571 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
572- expectedExceptionsMessageRegExp = "The clustering column name 'add' is not allowed because it is a reserved keyword")
572+ expectedExceptionsMessageRegExp = "The clustering column name 'ADD' is not allowed because it is a reserved keyword")
573573 public void should_fail_if_clustering_key_is_a_reserved_keyword() throws Exception {
574574 createTable("test")
575575 .addPartitionKey("pk", DataType.bigint())
576- .addClusteringColumn("add", DataType.uuid())
576+ .addClusteringColumn("ADD", DataType.uuid())
577577 .addColumn("col", DataType.text()).getQueryString();
578578 }
579579
580580 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
581- expectedExceptionsMessageRegExp = "The column name 'add' is not allowed because it is a reserved keyword")
581+ expectedExceptionsMessageRegExp = "The column name 'ADD' is not allowed because it is a reserved keyword")
582582 public void should_fail_if_simple_column_is_a_reserved_keyword() throws Exception {
583583 createTable("test")
584584 .addPartitionKey("pk", DataType.bigint())
585585 .addClusteringColumn("cluster", DataType.uuid())
586- .addColumn("add", DataType.text()).getQueryString();
586+ .addColumn("ADD", DataType.text()).getQueryString();
587587 }
588588
589589 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
590- expectedExceptionsMessageRegExp = "The static column name 'add' is not allowed because it is a reserved keyword")
590+ expectedExceptionsMessageRegExp = "The static column name 'ADD' is not allowed because it is a reserved keyword")
591591 public void should_fail_if_static_column_is_a_reserved_keyword() throws Exception {
592592 createTable("test")
593593 .addPartitionKey("pk", DataType.bigint())
594594 .addClusteringColumn("cluster", DataType.uuid())
595- .addStaticColumn("add", DataType.text())
595+ .addStaticColumn("ADD", DataType.text())
596596 .addColumn("col", DataType.text()).getQueryString();
597597 }
598598