Elffuss BraidHub

kikocis/java-driver public

SchemaBuilder with UDT support (JAVA-70).

Includes changes by @olim7t.
Changeset2c8f595e480696c2ba606dad81c2582a19d73411b6b73af33ad7252209eea985
AuthorDuyHai DOAN <doanduyhai@gmail.com> · 2014-10-27 13:39 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-11-24 10:42 +01:00
Parentsef212454eccb

Browse the files at this changeset

21 files changed

modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +1 −1
@@ -29,7 +29,7 @@
2929 * It is thus advised to do so if a {@link com.datastax.driver.core.policies.TokenAwarePolicy}
3030 * is in use.
3131 * <p>
32- * The provider builders perform very little validation of the built query.
32+ * The provided builders perform very little validation of the built query.
3333 * There is thus no guarantee that a built query is valid, and it is
3434 * definitively possible to create invalid queries.
3535 * <p>
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/AbstractCreateStatement.java +191 −0
@@ -0,0 +1,191 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.util.LinkedHashMap;
19+import java.util.Map;
20+
21+import com.google.common.base.Optional;
22+
23+import com.datastax.driver.core.DataType;
24+
25+public abstract class AbstractCreateStatement<T extends AbstractCreateStatement<T>> extends SchemaStatement {
26+
27+ protected Optional<String> keyspaceName = Optional.absent();
28+ protected boolean ifNotExists;
29+ protected Map<String, ColumnType> simpleColumns = new LinkedHashMap<String, ColumnType>();
30+
31+ @SuppressWarnings("unchecked")
32+ private T self = (T)this;
33+
34+ /**
35+ * Add the 'IF NOT EXISTS' condition to this CREATE statement.
36+ *
37+ * @return this CREATE statement.
38+ */
39+ public T ifNotExists() {
40+ this.ifNotExists = true;
41+ return self;
42+ }
43+
44+ /**
45+ * Add a column definition to this CREATE statement.
46+ *
47+ * <p>
48+ * To add a list column:
49+ * <pre class="code"><code class="java">
50+ * addColumn("myList",DataType.list(DataType.text()))
51+ * </code></pre>
52+ *
53+ * To add a set column:
54+ * <pre class="code"><code class="java">
55+ * addColumn("mySet",DataType.set(DataType.text()))
56+ * </code></pre>
57+ *
58+ * To add a map column:
59+ * <pre class="code"><code class="java">
60+ * addColumn("myMap",DataType.map(DataType.cint(),DataType.text()))
61+ * </code></pre>
62+ *
63+ * @param columnName the name of the column to be added.
64+ * @param dataType the data type of the column to be added.
65+ * @return this CREATE statement.
66+ */
67+ public T addColumn(String columnName, DataType dataType) {
68+ validateNotEmpty(columnName, "Column name");
69+ validateNotNull(dataType, "Column type");
70+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
71+ simpleColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
72+ return self;
73+ }
74+
75+ /**
76+ * Add a column definition to this CREATE statement, when the type contains a UDT.
77+ *
78+ * @param columnName the name of the column to be added.
79+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
80+ * @return this CREATE statement.
81+ */
82+ public T addUDTColumn(String columnName, UDTType udtType) {
83+ validateNotEmpty(columnName, "Column name");
84+ validateNotNull(udtType, "Column type");
85+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
86+ simpleColumns.put(columnName, udtType);
87+ return self;
88+ }
89+
90+ /**
91+ * Shorthand to add a column definition to this CREATE statement, when the type is a list of UDT.
92+ *
93+ * @param columnName the name of the column to be added
94+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
95+ * @return this CREATE statement.
96+ */
97+ public T addUDTListColumn(String columnName, UDTType udtType) {
98+ validateNotEmpty(columnName, "Column name");
99+ validateNotNull(udtType, "Column element type");
100+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
101+ simpleColumns.put(columnName, UDTType.list(udtType));
102+ return self;
103+ }
104+
105+ /**
106+ * Shorthand to add a column definition to this CREATE statement, when the type is a set of UDT.
107+ *
108+ * @param columnName the name of the column to be added
109+ * @param udtType the udt type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
110+ * @return this CREATE statement.
111+ */
112+ public T addUDTSetColumn(String columnName, UDTType udtType) {
113+ validateNotEmpty(columnName, "Column name");
114+ validateNotNull(udtType, "Column element type");
115+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
116+ simpleColumns.put(columnName, UDTType.set(udtType));
117+ return self;
118+ }
119+
120+ /**
121+ * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT value type.
122+ * <p>
123+ * Example:
124+ * <pre>
125+ * addUDTMapColumn("addresses", DataType.text(), frozen("address"));
126+ * </pre>
127+ *
128+ * @param columnName the name of the column to be added.
129+ * @param keyType the key type of the column to be added.
130+ * @param valueUdtType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
131+ * @return this CREATE statement.
132+ */
133+ public T addUDTMapColumn(String columnName, DataType keyType, UDTType valueUdtType) {
134+ validateNotEmpty(columnName, "Column name");
135+ validateNotNull(keyType, "Map key type");
136+ validateNotNull(valueUdtType, "Map value UDT type");
137+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
138+ simpleColumns.put(columnName, UDTType.mapWithUDTValue(keyType, valueUdtType));
139+ return self;
140+ }
141+
142+ /**
143+ * Shorthand to add a column definition to this CREATE statement, when the type is a map with a UDT key type.
144+ * <p>
145+ * Example:
146+ * <pre>
147+ * addUDTMapColumn("roles", frozen("user"), DataType.text());
148+ * </pre>
149+ *
150+ * @param columnName the name of the column to be added.
151+ * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
152+ * @param valueType the value raw type of the column to be added.
153+ * @return this CREATE statement.
154+ */
155+ public T addUDTMapColumn(String columnName, UDTType udtKeyType, DataType valueType) {
156+ validateNotEmpty(columnName, "Column name");
157+ validateNotNull(udtKeyType, "Map key UDT type");
158+ validateNotNull(valueType, "Map value type");
159+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
160+ simpleColumns.put(columnName, UDTType.mapWithUDTKey(udtKeyType, valueType));
161+ return self;
162+ }
163+
164+ /**
165+ * Shorthand to add a column definition to this CREATE statement, when the type is a map with UDT key and value types.
166+ * <p>
167+ * Example:
168+ * <pre>
169+ * addUDTMapColumn("users", frozen("user"), frozen("address"));
170+ * </pre>
171+ *
172+ * @param columnName the name of the column to be added.
173+ * @param udtKeyType the key UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
174+ * @param udtValueType the value UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)}.
175+ * @return this CREATE statement.
176+ *
177+ */
178+ public T addUDTMapColumn(String columnName, UDTType udtKeyType, UDTType udtValueType) {
179+ validateNotEmpty(columnName, "Column name");
180+ validateNotNull(udtKeyType, "Map key UDT type");
181+ validateNotNull(udtValueType, "Map value UDT type");
182+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
183+ simpleColumns.put(columnName, UDTType.mapWithUDTKeyAndValue(udtKeyType, udtValueType));
184+ return self;
185+ }
186+
187+ protected String buildColumnType(Map.Entry<String, ColumnType> entry) {
188+ final ColumnType columnType = entry.getValue();
189+ return entry.getKey() + " " + columnType.asCQLString();
190+ }
191+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Alter.java +249 −0
@@ -0,0 +1,249 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.util.List;
19+
20+import com.google.common.base.Optional;
21+
22+import com.datastax.driver.core.DataType;
23+
24+import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
25+import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
26+
27+/**
28+ * An in-construction ALTER TABLE statement.
29+ */
30+public class Alter implements StatementStart {
31+
32+ private Optional<String> keyspaceName = Optional.absent();
33+ private String tableName;
34+
35+ Alter(String keyspaceName, String tableName) {
36+ validateNotEmpty(keyspaceName, "Keyspace name");
37+ validateNotEmpty(tableName, "Table name");
38+ validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName));
39+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
40+ this.tableName = tableName;
41+ this.keyspaceName = Optional.fromNullable(keyspaceName);
42+ }
43+
44+ Alter(String tableName) {
45+ validateNotEmpty(tableName, "Table name");
46+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
47+ this.tableName = tableName;
48+ }
49+
50+ /**
51+ * Add an ALTER column clause (to change the column type) to this ALTER TABLE statement.
52+
53+ * @param columnName the name of the column to be altered.
54+ * @return a new {@link Alter.AlterColumn} instance.
55+ */
56+ public AlterColumn alterColumn(String columnName) {
57+ validateNotEmpty(columnName, "Column to be altered");
58+ validateNotKeyWord(columnName, String.format("The altered column name '%s' is not allowed because it is a reserved keyword", columnName));
59+ return new AlterColumn(this, columnName);
60+ }
61+
62+ /**
63+ * Add a new ADD column clause to this ALTER TABLE statement.
64+ *
65+ * @param columnName the name of the column to be added.
66+ * @return a new {@link Alter.AddColumn} instance.
67+ */
68+ public AddColumn addColumn(String columnName) {
69+ validateNotEmpty(columnName, "Added column");
70+ validateNotKeyWord(columnName, String.format("The new column name '%s' is not allowed because it is a reserved keyword", columnName));
71+ return new AddColumn(this, columnName, false);
72+ }
73+
74+ /**
75+ * Add a new ADD column clause to this ALTER TABLE statement, to add a static column.
76+ *
77+ * @param columnName the name of the column to be added.
78+ * @return a new {@link Alter.AddColumn} instance.
79+ */
80+ public AddColumn addStaticColumn(String columnName) {
81+ validateNotEmpty(columnName, "Added static column");
82+ validateNotKeyWord(columnName, String.format("The new static column name '%s' is not allowed because it is a reserved keyword", columnName));
83+ return new AddColumn(this, columnName, true);
84+ }
85+
86+ /**
87+ * Add a new DROP column clause to this ALTER TABLE statement.
88+ * <p>
89+ * Note that you cannot drop a column that is part of the primary key.
90+
91+ * @param columnName the name of the column to be dropped.
92+ * @return the final ALTER TABLE DROP COLUMN statement.
93+ */
94+ public SchemaStatement dropColumn(String columnName) {
95+ validateNotEmpty(columnName, "Column to be dropped");
96+ validateNotKeyWord(columnName, String.format("The dropped column name '%s' is not allowed because it is a reserved keyword", columnName));
97+ return SchemaStatement.fromQueryString(buildInternal() + " DROP " + columnName);
98+ }
99+
100+ /**
101+ * Add a new RENAME column clause to this ALTER TABLE statement.
102+ * <p>
103+ * Note that you can only rename a column that is part of the primary key.
104+ *
105+ * @param columnName the name of the column to be renamed.
106+ * @return a new {@link Alter.RenameColumn} instance.
107+ */
108+ public RenameColumn renameColumn(String columnName) {
109+ validateNotEmpty(columnName, "Column to be renamed");
110+ validateNotKeyWord(columnName, String.format("The renamed column name '%s' is not allowed because it is a reserved keyword", columnName));
111+ return new RenameColumn(this, columnName);
112+ }
113+
114+ /**
115+ * Add options (WITH clause) to this ALTER TABLE statement.
116+ *
117+ * @return a new {@link Alter.Options} instance.
118+ */
119+ public Options withOptions() {
120+ return new Options(this);
121+ }
122+
123+ /**
124+ * An ALTER column clause.
125+ */
126+ public static class AlterColumn {
127+
128+ private final Alter alter;
129+ private final String columnName;
130+
131+ AlterColumn(Alter alter, String columnName) {
132+ this.alter = alter;
133+ this.columnName = columnName;
134+ }
135+
136+ /**
137+ * Define the new type of the altered column.
138+ *
139+ * @param type the new type of the altered column.
140+ * @return the final statement.
141+ */
142+ public SchemaStatement type(DataType type) {
143+ return SchemaStatement.fromQueryString(
144+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + type.toString());
145+ }
146+
147+ /**
148+ * Define the new type of the altered column, when that type contains a UDT.
149+ *
150+ * @param udtType the UDT type. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
151+ * @return the final statement.
152+ */
153+ public SchemaStatement udtType(UDTType udtType) {
154+ return SchemaStatement.fromQueryString(
155+ alter.buildInternal() + " ALTER " + columnName + " TYPE " + udtType.asCQLString());
156+ }
157+ }
158+
159+ /**
160+ * An ADD column clause.
161+ */
162+ public static class AddColumn {
163+
164+ private final Alter alter;
165+ private final String columnName;
166+ private final boolean staticColumn;
167+
168+ AddColumn(Alter alter, String columnName, boolean staticColumn) {
169+ this.alter = alter;
170+ this.columnName = columnName;
171+ this.staticColumn = staticColumn;
172+ }
173+
174+ /**
175+ * Define the type of the added column.
176+ *
177+ * @param type the type of the added column.
178+ * @return the final statement.
179+ */
180+ public SchemaStatement type(DataType type) {
181+ return SchemaStatement.fromQueryString(
182+ alter.buildInternal() + " ADD " + columnName + " " + type.toString()
183+ + (staticColumn ? " static" : ""));
184+ }
185+
186+ /**
187+ * Define the type of the added column, when that type contains a UDT.
188+ *
189+ * @param udtType the UDT type of the added column.
190+ * @return the final statement.
191+ */
192+ public SchemaStatement udtType(UDTType udtType) {
193+ return SchemaStatement.fromQueryString(
194+ alter.buildInternal() + " ADD " + columnName + " " + udtType.asCQLString()
195+ + (staticColumn ? " static" : ""));
196+ }
197+ }
198+
199+ /**
200+ * A RENAME column clause.
201+ */
202+ public static class RenameColumn {
203+
204+ private final Alter alter;
205+ private final String columnName;
206+
207+ RenameColumn(Alter alter, String columnName) {
208+ this.alter = alter;
209+ this.columnName = columnName;
210+ }
211+
212+ /**
213+ * Define the new name of the column.
214+ *
215+ * @param newColumnName the new name of the column.
216+ * @return the final statement.
217+ */
218+ public SchemaStatement to(String newColumnName) {
219+ validateNotEmpty(newColumnName, "New column name");
220+ validateNotKeyWord(newColumnName, String.format("The new column name '%s' is not allowed because it is a reserved keyword", newColumnName));
221+ return SchemaStatement.fromQueryString(
222+ alter.buildInternal() + " RENAME " + columnName + " TO " + newColumnName);
223+ }
224+ }
225+
226+ /**
227+ * The table options of an ALTER TABLE statement.
228+ */
229+ public static class Options extends TableOptions<Options> {
230+
231+ Options(Alter alter) {
232+ super(alter);
233+ }
234+
235+ @Override
236+ protected void addSpecificOptions(List<String> options) {
237+ // nothing to do (no specific options)
238+ }
239+ }
240+
241+ @Override
242+ public String buildInternal() {
243+ String tableSpec = keyspaceName.isPresent()
244+ ? keyspaceName.get() + "." + tableName
245+ : tableName;
246+
247+ return SchemaStatement.STATEMENT_START + "ALTER TABLE " + tableSpec;
248+ }
249+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/ColumnType.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import com.datastax.driver.core.DataType;
19+
20+/**
21+ * Wrapper around UDT and non-UDT types.
22+ * <p>
23+ * The reason for this interface is that the core API doesn't let us build {@link com.datastax.driver.core.DataType}s representing UDTs, we have to obtain
24+ * them from the cluster metadata. Since we want to use SchemaBuilder without a Cluster instance, UDT types will be provided via
25+ * {@link UDTType} instances.
26+ */
27+interface ColumnType {
28+ String asCQLString();
29+
30+ class NativeColumnType implements ColumnType {
31+ private final String asCQLString;
32+
33+ NativeColumnType(DataType nativeType) {
34+ asCQLString = nativeType.toString();
35+ }
36+
37+ @Override public String asCQLString() {
38+ return asCQLString;
39+ }
40+ }
41+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Create.java +373 −0
@@ -0,0 +1,373 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.util.*;
19+
20+import static java.util.Map.Entry;
21+
22+import com.google.common.base.Joiner;
23+import com.google.common.base.Objects;
24+import com.google.common.base.Optional;
25+import com.google.common.collect.Lists;
26+
27+import com.datastax.driver.core.DataType;
28+
29+/**
30+ * A built CREATE TABLE statement.
31+ */
32+public class Create extends AbstractCreateStatement<Create> {
33+
34+ private String tableName;
35+ private Map<String, ColumnType> partitionColumns = new LinkedHashMap<String, ColumnType>();
36+ private Map<String, ColumnType> clusteringColumns = new LinkedHashMap<String, ColumnType>();
37+ private Map<String, ColumnType> staticColumns = new LinkedHashMap<String, ColumnType>();
38+
39+ Create(String keyspaceName, String tableName) {
40+ validateNotEmpty(keyspaceName, "Keyspace name");
41+ validateNotEmpty(tableName, "Table name");
42+ validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName));
43+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
44+ this.tableName = tableName;
45+ this.keyspaceName = Optional.fromNullable(keyspaceName);
46+ }
47+
48+ Create(String tableName) {
49+ validateNotEmpty(tableName, "Table name");
50+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
51+ this.tableName = tableName;
52+ }
53+
54+ /**
55+ * Add a partition key column definition to this CREATE TABLE statement.
56+ * <p>
57+ * This includes the column declaration (you don't need an additional {@code addColumn} call).
58+ * <p>
59+ * Partition key columns are added in the order of their declaration.
60+ *
61+ * @param columnName the name of the partition key column to be added.
62+ * @param dataType the data type of the partition key column to be added.
63+ * @return this CREATE statement.
64+ */
65+ public Create addPartitionKey(String columnName, DataType dataType) {
66+ validateNotEmpty(columnName, "Partition key name");
67+ validateNotNull(dataType, "Partition key type");
68+ validateNotKeyWord(columnName, String.format("The partition key name '%s' is not allowed because it is a reserved keyword", columnName));
69+ partitionColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
70+ return this;
71+ }
72+
73+ /**
74+ * Add a partition key column definition to this CREATE TABLE statement, when its type contains a UDT.
75+ * <p>
76+ * This includes the column declaration (you don't need an additional {@code addColumn} call).
77+ * <p>
78+ * Partition key columns are added in the order of their declaration.
79+ *
80+ * @param columnName the name of the partition key column to be added.
81+ * @param udtType the UDT type of the partition key column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
82+ * @return this CREATE statement.
83+ */
84+ public Create addUDTPartitionKey(String columnName, UDTType udtType) {
85+ validateNotEmpty(columnName, "Clustering key name");
86+ validateNotNull(udtType, "UDT partition key type");
87+ validateNotKeyWord(columnName, String.format("The partition key name '%s' is not allowed because it is a reserved keyword", columnName));
88+ partitionColumns.put(columnName, udtType);
89+ return this;
90+ }
91+
92+ /**
93+ * Add a clustering column definition to this CREATE TABLE statement.
94+ * <p>
95+ * This includes the column declaration (you don't need an additional {@code addColumn} call).
96+ * <p>
97+ * Clustering columns are added in the order of their declaration.
98+ *
99+ * @param columnName the name of the clustering column to be added.
100+ * @param dataType the data type of the clustering column to be added.
101+ * @return this CREATE statement.
102+ */
103+ public Create addClusteringColumn(String columnName, DataType dataType) {
104+ validateNotEmpty(columnName, "Clustering column name");
105+ validateNotNull(dataType, "Clustering column type");
106+ validateNotKeyWord(columnName, String.format("The clustering column name '%s' is not allowed because it is a reserved keyword", columnName));
107+ clusteringColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
108+ return this;
109+ }
110+
111+ /**
112+ * Add a clustering column definition to this CREATE TABLE statement, when its type contains a UDT.
113+ * <p>
114+ * This includes the column declaration (you don't need an additional {@code addColumn} call).
115+ * <p>
116+ * Clustering columns are added in the order of their declaration.
117+ *
118+ * @param columnName the name of the clustering column to be added.
119+ * @param udtType the UDT type of the clustering column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
120+ * @return this CREATE statement.
121+ */
122+ public Create addUDTClusteringColumn(String columnName, UDTType udtType) {
123+ validateNotEmpty(columnName, "Clustering column name");
124+ validateNotNull(udtType, "UDT clustering column type");
125+ validateNotKeyWord(columnName, String.format("The clustering column name '%s' is not allowed because it is a reserved keyword", columnName));
126+ clusteringColumns.put(columnName, udtType);
127+ return this;
128+ }
129+
130+ /**
131+ * Add a static column definition to this CREATE TABLE statement.
132+ *
133+ * @param columnName the name of the column to be added.
134+ * @param dataType the data type of the column to be added.
135+ * @return this CREATE statement.
136+ */
137+ public Create addStaticColumn(String columnName, DataType dataType) {
138+ validateNotEmpty(columnName, "Column name");
139+ validateNotNull(dataType, "Column type");
140+ validateNotKeyWord(columnName, String.format("The static column name '%s' is not allowed because it is a reserved keyword", columnName));
141+ staticColumns.put(columnName, new ColumnType.NativeColumnType(dataType));
142+ return this;
143+ }
144+
145+ /**
146+ * Add a static column definition to this CREATE TABLE statement, when its type contains a UDT.
147+ *
148+ * @param columnName the name of the column to be added.
149+ * @param udtType the UDT type of the column to be added. Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)}.
150+ * @return this CREATE statement.
151+ */
152+ public Create addUDTStaticColumn(String columnName, UDTType udtType) {
153+ validateNotEmpty(tableName, "Column name");
154+ validateNotNull(udtType, "Column UDT type");
155+ validateNotKeyWord(columnName, String.format("The static column name '%s' is not allowed because it is a reserved keyword", columnName));
156+ staticColumns.put(columnName, udtType);
157+ return this;
158+ }
159+
160+ /**
161+ * Add options for this CREATE TABLE statement.
162+ *
163+ * @return the options of this CREATE TABLE statement.
164+ */
165+ public Options withOptions() {
166+ return new Options(this);
167+ }
168+
169+ /**
170+ * The table options of a CREATE TABLE statement.
171+ */
172+ public static class Options extends TableOptions<Options> {
173+
174+ private final Create create;
175+
176+ private Options(Create create) {
177+ super(create.asStatementStart());
178+ this.create = create;
179+ }
180+
181+ private List<ClusteringOrder> clusteringOrderKeys = Lists.newArrayList();
182+
183+ private boolean compactStorage;
184+
185+ /**
186+ * Add a clustering order for this table.
187+ * <p>
188+ * To define the order on multiple columns, call this method repeatedly. The columns will be declared in the call order.
189+ *
190+ * @param columnName the clustering column name.
191+ * @param direction the clustering direction (DESC/ASC).
192+ * @return this {@code Options} object.
193+ */
194+ public Options clusteringOrder(String columnName, SchemaBuilder.Direction direction) {
195+ if (!create.clusteringColumns.containsKey(columnName)) {
196+ throw new IllegalArgumentException(String.format("Clustering key '%s' is unknown. Did you forget to declare it first?", columnName));
197+ }
198+ clusteringOrderKeys.add(new ClusteringOrder(columnName, direction));
199+ return this;
200+ }
201+
202+ /**
203+ * Enable the compact storage option for the table.
204+ *
205+ * @return this {@code Options} object.
206+ */
207+ public Options compactStorage() {
208+ this.compactStorage = true;
209+ return this;
210+ }
211+
212+ private static class ClusteringOrder {
213+ private final String clusteringColumnName;
214+ private final SchemaBuilder.Direction direction;
215+
216+ ClusteringOrder(String clusteringColumnName, SchemaBuilder.Direction direction) {
217+ validateNotEmpty(clusteringColumnName, "Column name for clustering order");
218+ this.clusteringColumnName = clusteringColumnName;
219+ this.direction = direction;
220+ }
221+
222+ public String getClusteringColumnName() {
223+ return clusteringColumnName;
224+ }
225+
226+ public String toStatement() {
227+ return clusteringColumnName + " " + direction.name();
228+ }
229+
230+ @Override
231+ public String toString() {
232+ return toStatement();
233+ }
234+
235+ @Override
236+ public boolean equals(Object o) {
237+ if (this == o) {
238+ return true;
239+ }
240+ if (o instanceof ClusteringOrder) {
241+ ClusteringOrder that = (ClusteringOrder)o;
242+ return Objects.equal(this.clusteringColumnName, that.clusteringColumnName) && Objects.equal(this.direction, that.direction);
243+ }
244+ return false;
245+ }
246+
247+ @Override
248+ public int hashCode() {
249+ return Objects.hashCode(clusteringColumnName, direction);
250+ }
251+ }
252+
253+ @Override
254+ protected void addSpecificOptions(List<String> options) {
255+ if (!clusteringOrderKeys.isEmpty()) {
256+ options.add("CLUSTERING ORDER BY(" + Joiner.on(", ").join(clusteringOrderKeys) + ")");
257+ }
258+
259+ if (compactStorage) {
260+ if (!create.staticColumns.isEmpty()) {
261+ throw new IllegalStateException(String.format("Cannot create table '%s' with compact storage and static columns '%s'", create.tableName, create.staticColumns.keySet()));
262+ }
263+ options.add("COMPACT STORAGE");
264+ }
265+ }
266+ }
267+
268+ @Override
269+ public String buildInternal() {
270+ if (partitionColumns.size() < 1) {
271+ throw new IllegalStateException(String.format("There should be at least one partition key defined for the table '%s'", tableName));
272+ }
273+
274+ validateColumnsDeclaration();
275+
276+ StringBuilder createStatement = new StringBuilder(STATEMENT_START).append("CREATE TABLE");
277+ if (ifNotExists) {
278+ createStatement.append(" IF NOT EXISTS");
279+ }
280+ createStatement.append(" ");
281+ if (keyspaceName.isPresent()) {
282+ createStatement.append(keyspaceName.get()).append(".");
283+ }
284+ createStatement.append(tableName);
285+
286+ List<String> allColumns = new ArrayList<String>();
287+ List<String> partitionKeyColumns = new ArrayList<String>();
288+ List<String> clusteringKeyColumns = new ArrayList<String>();
289+
290+ for (Entry<String, ColumnType> entry : partitionColumns.entrySet()) {
291+ allColumns.add(entry.getKey() + " " + entry.getValue().asCQLString());
292+ partitionKeyColumns.add(entry.getKey());
293+ }
294+
295+ for (Entry<String, ColumnType> entry : clusteringColumns.entrySet()) {
296+ allColumns.add(entry.getKey() + " " + entry.getValue().asCQLString());
297+ clusteringKeyColumns.add(entry.getKey());
298+ }
299+
300+ for (Entry<String, ColumnType> entry : staticColumns.entrySet()) {
301+ allColumns.add(entry.getKey() + " " + entry.getValue().asCQLString() + " static");
302+ }
303+
304+ for (Entry<String, ColumnType> entry : simpleColumns.entrySet()) {
305+ allColumns.add(buildColumnType(entry));
306+ }
307+
308+ String partitionKeyPart = partitionKeyColumns.size() == 1 ?
309+ partitionKeyColumns.get(0)
310+ : "(" + Joiner.on(", ").join(partitionKeyColumns) + ")";
311+
312+ String primaryKeyPart = clusteringKeyColumns.size() == 0 ?
313+ partitionKeyPart
314+ : partitionKeyPart + ", " + Joiner.on(", ").join(clusteringKeyColumns);
315+
316+ createStatement.append("(").append(COLUMN_FORMATTING);
317+ createStatement.append(Joiner.on("," + COLUMN_FORMATTING).join(allColumns));
318+ createStatement.append("," + COLUMN_FORMATTING).append("PRIMARY KEY");
319+ createStatement.append("(").append(primaryKeyPart).append(")");
320+ createStatement.append(")");
321+
322+ return createStatement.toString();
323+ }
324+
325+ private void validateColumnsDeclaration() {
326+
327+ final Collection partitionAndClusteringColumns = this.intersection(partitionColumns.keySet(), clusteringColumns.keySet());
328+ final Collection partitionAndSimpleColumns = this.intersection(partitionColumns.keySet(), simpleColumns.keySet());
329+ final Collection clusteringAndSimpleColumns = this.intersection(clusteringColumns.keySet(), simpleColumns.keySet());
330+ final Collection partitionAndStaticColumns = this.intersection(partitionColumns.keySet(), staticColumns.keySet());
331+ final Collection clusteringAndStaticColumns = this.intersection(clusteringColumns.keySet(), staticColumns.keySet());
332+ final Collection simpleAndStaticColumns = this.intersection(simpleColumns.keySet(), staticColumns.keySet());
333+
334+ if (!partitionAndClusteringColumns.isEmpty()) {
335+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as partition keys and clustering keys at the same time", partitionAndClusteringColumns));
336+ }
337+
338+ if (!partitionAndSimpleColumns.isEmpty()) {
339+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as partition keys and simple columns at the same time", partitionAndSimpleColumns));
340+ }
341+
342+ if (!clusteringAndSimpleColumns.isEmpty()) {
343+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as clustering keys and simple columns at the same time", clusteringAndSimpleColumns));
344+ }
345+
346+ if (!partitionAndStaticColumns.isEmpty()) {
347+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as partition keys and static columns at the same time", partitionAndStaticColumns));
348+ }
349+
350+ if (!clusteringAndStaticColumns.isEmpty()) {
351+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as clustering keys and static columns at the same time", clusteringAndStaticColumns));
352+ }
353+
354+ if (!simpleAndStaticColumns.isEmpty()) {
355+ throw new IllegalStateException(String.format("The '%s' columns can not be declared as simple columns and static columns at the same time", simpleAndStaticColumns));
356+ }
357+
358+ if (!staticColumns.isEmpty() && clusteringColumns.isEmpty()) {
359+ throw new IllegalStateException(String.format("The table '%s' cannot declare static columns '%s' without clustering columns", tableName, staticColumns.keySet()));
360+ }
361+ }
362+
363+ private <T> Collection<T> intersection(Collection<T> col1, Collection<T> col2) {
364+ Set<T> set = new HashSet<T>();
365+
366+ for (T t : col1) {
367+ if (col2.contains(t)) {
368+ set.add(t);
369+ }
370+ }
371+ return set;
372+ }
373+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateIndex.java +139 −0
@@ -0,0 +1,139 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import com.google.common.base.Optional;
19+
20+import static com.datastax.driver.core.schemabuilder.SchemaStatement.STATEMENT_START;
21+import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotEmpty;
22+import static com.datastax.driver.core.schemabuilder.SchemaStatement.validateNotKeyWord;
23+
24+/**
25+ * A built CREATE INDEX statement.
26+ */
27+public class CreateIndex implements StatementStart {
28+
29+ private String indexName;
30+ private boolean ifNotExists = false;
31+ private Optional<String> keyspaceName = Optional.absent();
32+ private String tableName;
33+ private String columnName;
34+ private boolean keys;
35+
36+ CreateIndex(String indexName) {
37+ validateNotEmpty(indexName, "Index name");
38+ validateNotKeyWord(indexName, String.format("The index name '%s' is not allowed because it is a reserved keyword", indexName));
39+ this.indexName = indexName;
40+ }
41+
42+ /**
43+ * Add the 'IF NOT EXISTS' condition to this CREATE INDEX statement.
44+ *
45+ * @return this CREATE INDEX statement.
46+ */
47+ public CreateIndex ifNotExists() {
48+ this.ifNotExists = true;
49+ return this;
50+ }
51+
52+ /**
53+ * Specify the keyspace and table to create the index on.
54+ *
55+ * @param keyspaceName the keyspace name.
56+ * @param tableName the table name.
57+ * @return a {@link CreateIndexOn} that will allow the specification of the column.
58+ */
59+ public CreateIndexOn onTable(String keyspaceName, String tableName) {
60+ validateNotEmpty(keyspaceName, "Keyspace name");
61+ validateNotEmpty(tableName, "Table name");
62+ validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName));
63+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
64+ this.keyspaceName = Optional.fromNullable(keyspaceName);
65+ this.tableName = tableName;
66+ return new CreateIndexOn();
67+ }
68+
69+ /**
70+ * Specify the table to create the index on.
71+ *
72+ * @param tableName the table name.
73+ * @return a {@link CreateIndexOn} that will allow the specification of the column.
74+ */
75+ public CreateIndexOn onTable(String tableName) {
76+ validateNotEmpty(tableName, "Table name");
77+ validateNotKeyWord(tableName, String.format("The table name '%s' is not allowed because it is a reserved keyword", tableName));
78+ this.tableName = tableName;
79+ return new CreateIndexOn();
80+ }
81+
82+ public class CreateIndexOn {
83+ /**
84+ * Specify the column to create the index on.
85+ *
86+ * @param columnName the column name.
87+ * @return the final CREATE INDEX statement.
88+ */
89+ public SchemaStatement andColumn(String columnName) {
90+ validateNotEmpty(columnName, "Column name");
91+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
92+ CreateIndex.this.columnName = columnName;
93+ return SchemaStatement.fromQueryString(buildInternal());
94+ }
95+
96+ /**
97+ * Create an index on the keys of the given map column.
98+ * @param columnName the column name.
99+ * @return the final CREATE INDEX statement.
100+ */
101+ public SchemaStatement andKeysOfColumn(String columnName) {
102+ validateNotEmpty(columnName, "Column name");
103+ validateNotKeyWord(columnName, String.format("The column name '%s' is not allowed because it is a reserved keyword", columnName));
104+ CreateIndex.this.columnName = columnName;
105+ CreateIndex.this.keys = true;
106+ return SchemaStatement.fromQueryString(buildInternal());
107+ }
108+ }
109+
110+ @Override
111+ public String buildInternal() {
112+ StringBuilder createStatement = new StringBuilder(STATEMENT_START).append("CREATE INDEX ");
113+
114+ if (ifNotExists) {
115+ createStatement.append("IF NOT EXISTS ");
116+ }
117+
118+ createStatement.append(indexName).append(" ON ");
119+
120+ if (keyspaceName.isPresent()) {
121+ createStatement.append(keyspaceName.get()).append(".");
122+ }
123+ createStatement.append(tableName);
124+
125+ createStatement.append("(");
126+ if (keys) {
127+ createStatement.append("KEYS(");
128+ }
129+
130+ createStatement.append(columnName);
131+
132+ if (keys) {
133+ createStatement.append(")");
134+ }
135+ createStatement.append(")");
136+
137+ return createStatement.toString();
138+ }
139+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/CreateType.java +78 −0
@@ -0,0 +1,78 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.util.ArrayList;
19+import java.util.List;
20+import java.util.Map;
21+
22+import com.google.common.base.Joiner;
23+import com.google.common.base.Optional;
24+
25+/**
26+ * A built CREATE TYPE statement.
27+ */
28+public class CreateType extends AbstractCreateStatement<CreateType> {
29+
30+ private String typeName;
31+
32+ CreateType(String keyspaceName, String typeName) {
33+ validateNotEmpty(keyspaceName, "Keyspace name");
34+ validateNotEmpty(typeName, "Custom type name");
35+ validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName));
36+ validateNotKeyWord(typeName, String.format("The custom type name '%s' is not allowed because it is a reserved keyword", typeName));
37+ this.typeName = typeName;
38+ this.keyspaceName = Optional.fromNullable(keyspaceName);
39+ }
40+
41+ CreateType(String typeName) {
42+ validateNotEmpty(typeName, "Custom type name");
43+ validateNotKeyWord(typeName, String.format("The custom type name '%s' is not allowed because it is a reserved keyword", typeName));
44+ this.typeName = typeName;
45+ }
46+
47+ /**
48+ * Generate the script for custom type creation
49+ * @return a CREATE TYPE statement
50+ */
51+ public String build() {
52+ return buildInternal();
53+ }
54+
55+ @Override
56+ public String buildInternal() {
57+
58+ StringBuilder createStatement = new StringBuilder(STATEMENT_START).append("CREATE TYPE ");
59+ if (ifNotExists) {
60+ createStatement.append("IF NOT EXISTS ");
61+ }
62+ if (keyspaceName.isPresent()) {
63+ createStatement.append(keyspaceName.get()).append(".");
64+ }
65+ createStatement.append(typeName);
66+
67+ List<String> allColumns = new ArrayList<String>();
68+ for (Map.Entry<String, ColumnType> entry : simpleColumns.entrySet()) {
69+ allColumns.add(buildColumnType(entry));
70+ }
71+
72+ createStatement.append("(").append(COLUMN_FORMATTING);
73+ createStatement.append(Joiner.on("," + COLUMN_FORMATTING).join(allColumns));
74+ createStatement.append(")");
75+
76+ return createStatement.toString();
77+ }
78+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/Drop.java +80 −0
@@ -0,0 +1,80 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import com.google.common.base.Optional;
19+
20+/**
21+ * A built DROP statement.
22+ */
23+public class Drop extends SchemaStatement {
24+
25+ enum DroppedItem {TABLE, TYPE, INDEX}
26+
27+ private Optional<String> keyspaceName = Optional.absent();
28+ private String itemName;
29+ private boolean ifExists;
30+ private final String itemType;
31+
32+ Drop(String keyspaceName, String itemName, DroppedItem itemType) {
33+ this.itemType = itemType.name();
34+ validateNotEmpty(keyspaceName, "Keyspace name");
35+ validateNotEmpty(itemName, this.itemType.toLowerCase() + " name");
36+ validateNotKeyWord(keyspaceName, String.format("The keyspace name '%s' is not allowed because it is a reserved keyword", keyspaceName));
37+ validateNotKeyWord(itemName, String.format("The " + this.itemType.toLowerCase() + " name '%s' is not allowed because it is a reserved keyword", itemName));
38+ this.itemName = itemName;
39+ this.keyspaceName = Optional.fromNullable(keyspaceName);
40+ }
41+
42+ Drop(String itemName, DroppedItem itemType) {
43+ this.itemType = itemType.name();
44+ validateNotEmpty(itemName, this.itemType.toLowerCase() + " name");
45+ validateNotKeyWord(itemName, String.format("The " + this.itemType.toLowerCase() + " name '%s' is not allowed because it is a reserved keyword", itemName));
46+ this.itemName = itemName;
47+ }
48+
49+ /**
50+ * Add the 'IF EXISTS' condition to this DROP statement.
51+ *
52+ * @return this statement.
53+ */
54+ public Drop ifExists() {
55+ this.ifExists = true;
56+ return this;
57+ }
58+
59+ @Override
60+ public String buildInternal() {
61+ StringBuilder dropStatement = new StringBuilder("DROP " + itemType + " ");
62+ if (ifExists) {
63+ dropStatement.append("IF EXISTS ");
64+ }
65+ if (keyspaceName.isPresent()) {
66+ dropStatement.append(keyspaceName.get()).append(".");
67+ }
68+
69+ dropStatement.append(itemName);
70+ return dropStatement.toString();
71+ }
72+
73+ /**
74+ * Generate a DROP TABLE statement
75+ * @return the final DROP TABLE statement
76+ */
77+ public String build() {
78+ return this.buildInternal();
79+ }
80+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaBuilder.java +381 −0
@@ -0,0 +1,381 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import static com.datastax.driver.core.schemabuilder.Drop.DroppedItem;
19+
20+/**
21+ * Static methods to build a CQL3 DDL statement.
22+ * <p>
23+ * The provided builders perform very little validation of the built query.
24+ * There is thus no guarantee that a built query is valid, and it is
25+ * definitively possible to create invalid queries.
26+ * <p>
27+ * Note that it could be convenient to use an 'import static' to use the methods of this class.
28+ */
29+public final class SchemaBuilder {
30+
31+ private SchemaBuilder() {}
32+
33+ /**
34+ * Start building a new CREATE TABLE statement.
35+ *
36+ * @param tableName the name of the table to create.
37+ * @return an in-construction CREATE TABLE statement.
38+ */
39+ public static Create createTable(String tableName) {
40+ return new Create(tableName);
41+ }
42+
43+ /**
44+ * Start building a new CREATE TABLE statement.
45+ *
46+ * @param keyspaceName the name of the keyspace to be used.
47+ * @param tableName the name of the table to create.
48+ * @return an in-construction CREATE TABLE statement.
49+ */
50+ public static Create createTable(String keyspaceName, String tableName) {
51+ return new Create(keyspaceName, tableName);
52+ }
53+
54+ /**
55+ * Start building a new ALTER TABLE statement.
56+ *
57+ * @param tableName the name of the table to be altered.
58+ * @return an in-construction ALTER TABLE statement.
59+ */
60+ public static Alter alterTable(String tableName) {
61+ return new Alter(tableName);
62+ }
63+
64+ /**
65+ * Start building a new ALTER TABLE statement.
66+ *
67+ * @param keyspaceName the name of the keyspace to be used.
68+ * @param tableName the name of the table to be altered.
69+ * @return an in-construction ALTER TABLE statement.
70+ */
71+ public static Alter alterTable(String keyspaceName, String tableName) {
72+ return new Alter(keyspaceName, tableName);
73+ }
74+
75+ /**
76+ * Start building a new DROP TABLE statement.
77+ *
78+ * @param tableName the name of the table to be dropped.
79+ * @return an in-construction DROP TABLE statement.
80+ */
81+ public static Drop dropTable(String tableName) {
82+ return new Drop(tableName, DroppedItem.TABLE);
83+ }
84+
85+ /**
86+ * Start building a new DROP TABLE statement.
87+ *
88+ * @param keyspaceName the name of the keyspace to be used.
89+ * @param tableName the name of the table to be dropped.
90+ * @return an in-construction DROP TABLE statement.
91+ */
92+ public static Drop dropTable(String keyspaceName, String tableName) {
93+ return new Drop(keyspaceName, tableName, DroppedItem.TABLE);
94+ }
95+
96+ /**
97+ * Start building a new CREATE INDEX statement.
98+ *
99+ * @param indexName the name of the table to create.
100+ * @return an in-construction CREATE INDEX statement.
101+ */
102+ public static CreateIndex createIndex(String indexName) {
103+ return new CreateIndex(indexName);
104+ }
105+
106+ /**
107+ * Start building a new DROP INDEX statement.
108+ *
109+ * @param indexName the name of the index to be dropped.
110+ * @return an in-construction DROP INDEX statement.
111+ */
112+ public static Drop dropIndex(String indexName) {
113+ return new Drop(indexName, DroppedItem.INDEX);
114+ }
115+
116+ /**
117+ * Start building a new DROP INDEX statement.
118+ *
119+ * @param keyspaceName the name of the keyspace to be used.
120+ * @param indexName the name of the index to be dropped.
121+ * @return an in-construction DROP INDEX statement.
122+ */
123+ public static Drop dropIndex(String keyspaceName, String indexName) {
124+ return new Drop(keyspaceName, indexName, DroppedItem.INDEX);
125+ }
126+
127+ /**
128+ * Start building a new CREATE TYPE statement.
129+ *
130+ * @param typeName the name of the custom type to create.
131+ * @return an in-construction CREATE TYPE statement.
132+ */
133+ public static CreateType createType(String typeName) {
134+ return new CreateType(typeName);
135+ }
136+
137+ /**
138+ * Start building a new CREATE TYPE statement.
139+ *
140+ * @param keyspaceName the name of the keyspace to be used.
141+ * @param typeName the name of the custom type to create.
142+ * @return an in-construction CREATE TYPE statement.
143+ */
144+ public static CreateType createType(String keyspaceName, String typeName) {
145+ return new CreateType(keyspaceName, typeName);
146+ }
147+
148+ /**
149+ * Start building a new DROP TYPE statement.
150+ *
151+ * @param typeName the name of the type to be dropped.
152+ * @return an in-construction DROP TYPE statement.
153+ */
154+ public static Drop dropType(String typeName) {
155+ return new Drop(typeName, DroppedItem.TYPE);
156+ }
157+
158+ /**
159+ * Start building a new DROP TYPE statement.
160+ *
161+ * @param keyspaceName the name of the keyspace to be used.
162+ * @param typeName the name of the type to be dropped.
163+ * @return an in-construction DROP TYPE statement.
164+ */
165+ public static Drop dropType(String keyspaceName, String typeName) {
166+ return new Drop(keyspaceName, typeName, DroppedItem.TYPE);
167+ }
168+
169+
170+ // Utility methods and types: these are not method starters, but they are exposed here in order to
171+ // have a single entry point to all schema builder features.
172+
173+ /**
174+ * Build the datatype representation of a frozen UDT, to include in a schema builder statement.
175+ * <p>
176+ * <code>frozen("foo")</code> will produce <code>frozen&lt;foo&gt;</code>.
177+ *
178+ * @param udtName the name of the UDT.
179+ * @return the type.
180+ */
181+ public static UDTType frozen(String udtName) {
182+ return UDTType.frozen(udtName);
183+ }
184+
185+ /**
186+ * Build the datatype representation of a complex UDT type, to include in a schema builder statement.
187+ * <p>
188+ * As of Cassandra 2.1, this method is not strictly necessary because {@link Create} and {@link Alter}
189+ * provide specialized methods to express simple collections of UDTs, but future versions will make it
190+ * possible to use types such as <code>map&lt;text, map&lt;text, frozen&lt;user&gt;&gt;&gt;</code>.
191+ *
192+ * @param literal the type literal as it will appear in the final CQL statement.
193+ * @return the type.
194+ */
195+ public static UDTType udtLiteral(String literal) {
196+ return UDTType.literal(literal);
197+ }
198+
199+ /**
200+ * Create options for the size-tiered compaction strategy, for use in a CREATE or ALTER TABLE statement.
201+ *
202+ * @return the options.
203+ */
204+ public static TableOptions.CompactionOptions.SizeTieredCompactionStrategyOptions sizedTieredStategy() {
205+ return new TableOptions.CompactionOptions.SizeTieredCompactionStrategyOptions();
206+ }
207+
208+ /**
209+ * Create options for the leveled compaction strategy, to use in a CREATE or ALTER TABLE statement.
210+ *
211+ * @return the options.
212+ */
213+ public static TableOptions.CompactionOptions.LeveledCompactionStrategyOptions leveledStrategy() {
214+ return new TableOptions.CompactionOptions.LeveledCompactionStrategyOptions();
215+ }
216+
217+ /**
218+ * Create options for the date-tiered compaction strategy, to use in a CREATE or ALTER TABLE statement.
219+ * <p>
220+ * This strategy was introduced in Cassandra 2.1.1.
221+ *
222+ * @return the options.
223+ */
224+ public static TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions dateTieredStrategy() {
225+ return new TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions();
226+ }
227+
228+ /**
229+ * Create options for the {@code NONE} compression strategy, to use in a CREATE or ALTER TABLE statement.
230+ *
231+ * @return the options.
232+ */
233+ public static TableOptions.CompressionOptions noCompression() {
234+ return new TableOptions.CompressionOptions.NoCompression();
235+ }
236+
237+ /**
238+ * Create options for the LZ4 compression strategy, to use in a CREATE or ALTER TABLE statement.
239+ *
240+ * @return the options.
241+ */
242+ public static TableOptions.CompressionOptions lz4() {
243+ return new TableOptions.CompressionOptions(TableOptions.CompressionOptions.Algorithm.LZ4);
244+ }
245+
246+ /**
247+ * Create options for the Snappy compression strategy, to use in a CREATE or ALTER TABLE statement.
248+ *
249+ * @return the options.
250+ */
251+ public static TableOptions.CompressionOptions snappy() {
252+ return new TableOptions.CompressionOptions(TableOptions.CompressionOptions.Algorithm.SNAPPY);
253+ }
254+
255+ /**
256+ * Create options for the Deflate compression strategy, to use in a CREATE or ALTER TABLE statement.
257+ *
258+ * @return the options.
259+ */
260+ public static TableOptions.CompressionOptions deflate() {
261+ return new TableOptions.CompressionOptions(TableOptions.CompressionOptions.Algorithm.DEFLATE);
262+ }
263+
264+ /**
265+ * Create the speculative retry strategy that never retries reads, to use in a CREATE or ALTER TABLE statement.
266+ *
267+ * @return the strategy.
268+ */
269+ public static TableOptions.SpeculativeRetryValue noSpeculativeRetry() {
270+ return new TableOptions.SpeculativeRetryValue("'NONE'");
271+ }
272+
273+ /**
274+ * Create the speculative retry strategy that retries reads of all replicas, to use in a CREATE or ALTER TABLE statement.
275+ *
276+ * @return the strategy.
277+ */
278+ public static TableOptions.SpeculativeRetryValue always() {
279+ return new TableOptions.SpeculativeRetryValue("'ALWAYS'");
280+ }
281+
282+ /**
283+ * Create the speculative retry strategy that retries based on the effect on throughput and latency,
284+ * to use in a CREATE or ALTER TABLE statement.
285+ *
286+ * @return the strategy.
287+ */
288+ public static TableOptions.SpeculativeRetryValue percentile(int percentile) {
289+ if (percentile < 0 || percentile > 100) {
290+ throw new IllegalArgumentException("Percentile value for speculative retry should be between 0 and 100");
291+ }
292+ return new TableOptions.SpeculativeRetryValue("'" + percentile + "percentile'");
293+ }
294+
295+ /**
296+ * Create the speculative retry strategy that retries after a given delay, to use in a CREATE or ALTER TABLE statement.
297+ *
298+ * @return the strategy.
299+ */
300+ public static TableOptions.SpeculativeRetryValue millisecs(int millisecs) {
301+ if (millisecs < 0) {
302+ throw new IllegalArgumentException("Millisecond value for speculative retry should be positive");
303+ }
304+ return new TableOptions.SpeculativeRetryValue("'" + millisecs + "ms'");
305+ }
306+
307+ /**
308+ * The direction used in clustering order declarations.
309+ *
310+ * @see Create.Options#clusteringOrder(String, com.datastax.driver.core.schemabuilder.SchemaBuilder.Direction)
311+ */
312+ public enum Direction {
313+ ASC, DESC
314+ }
315+
316+ /**
317+ * Caching strategies, for use in a CREATE or ALTER TABLE statement.
318+ */
319+ public enum Caching {
320+ ALL("'all'"), KEYS_ONLY("'keys_only'"), ROWS_ONLY("'rows_only'"), NONE("'none'");
321+
322+ private String value;
323+
324+ Caching(String value) {
325+ this.value = value;
326+ }
327+
328+ String value() {
329+ return value;
330+ }
331+ }
332+
333+ /**
334+ * Key caching strategies for Cassandra 2.1, for use in a CREATE or ALTER TABLE statement.
335+ */
336+ public enum KeyCaching {
337+ ALL("'all'"), NONE("'none'");
338+ private String value;
339+
340+ KeyCaching(String value) {
341+ this.value = value;
342+ }
343+
344+ String value() {
345+ return value;
346+ }
347+ }
348+
349+ /**
350+ * Return the row caching strategy that never caches rows ({@code none}, to use in a CREATE or ALTER TABLE statement.
351+ *
352+ * @return the strategy.
353+ */
354+ public static TableOptions.CachingRowsPerPartition noRows() {
355+ return new TableOptions.CachingRowsPerPartition("'none'");
356+ }
357+
358+ /**
359+ * Return the row caching strategy that caches all rows ({@code all}), to use in a CREATE or ALTER TABLE statement.
360+ * <p>
361+ * <strong>Be careful when choosing this option, you can starve Cassandra memory quickly if your partition is very large.</strong>
362+ *
363+ * @return the strategy.
364+ */
365+ public static TableOptions.CachingRowsPerPartition allRows() {
366+ return new TableOptions.CachingRowsPerPartition("'all'");
367+ }
368+
369+ /**
370+ * Return the row caching strategy that caches a given number of rows, to use in a CREATE or ALTER TABLE statement.
371+ *
372+ * @param rowNumber the number of rows to cache.
373+ * @return the strategy.
374+ */
375+ public static TableOptions.CachingRowsPerPartition rows(int rowNumber) {
376+ if (rowNumber <= 0) {
377+ throw new IllegalArgumentException("rows number for caching should be strictly positive");
378+ }
379+ return new TableOptions.CachingRowsPerPartition(Integer.toString(rowNumber));
380+ }
381+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/SchemaStatement.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.nio.ByteBuffer;
19+import java.util.Arrays;
20+import java.util.List;
21+
22+import com.google.common.base.Strings;
23+
24+import com.datastax.driver.core.ProtocolVersion;
25+import com.datastax.driver.core.RegularStatement;
26+
27+/**
28+ * A DDL statement generated by {@link SchemaBuilder}.
29+ */
30+public abstract class SchemaStatement extends RegularStatement {
31+
32+ static final String STATEMENT_START = "\n\t";
33+ static final String COLUMN_FORMATTING = "\n\t\t";
34+
35+ static final List<String> RESERVED_KEYWORDS = Arrays.asList(
36+ ("add,allow,alter,and,any,apply,asc,authorize,batch,begin,by,columnfamily,create,delete,desc,drop,each_quorum,from,grant,in,index,inet,infinity," +
37+ "insert,into,keyspace,keyspaces,limit,local_one,local_quorum,modify,nan,norecursive,of,on,order,password,primary,quorum,rename,revoke,schema," +
38+ "select,set,table,three,to,token,truncate,two,unlogged,update,use,using,where,with")
39+ .split(","));
40+
41+ private volatile String cache;
42+
43+ abstract String buildInternal();
44+
45+ @Override
46+ public String getQueryString() {
47+ if (cache == null) {
48+ cache = buildInternal();
49+ }
50+ return cache;
51+ }
52+
53+ @Override
54+ public ByteBuffer[] getValues(ProtocolVersion protocolVersion) {
55+ // DDL statements never have values
56+ return new ByteBuffer[0];
57+ }
58+
59+ @Override
60+ public boolean hasValues() {
61+ return false;
62+ }
63+
64+ @Override
65+ public String getKeyspace() {
66+ // This is exposed for token-aware routing. Since there is no token awareness for DDL statements, we don't need to
67+ // return anything here (even if a keyspace has been explicitly set in the statement).
68+ return null;
69+ }
70+
71+ @Override
72+ public ByteBuffer getRoutingKey() {
73+ return null; // there is no token awareness for DDL statements
74+ }
75+
76+ static void validateNotEmpty(String columnName, String label) {
77+ if (Strings.isNullOrEmpty(columnName)) {
78+ throw new IllegalArgumentException(label + " should not be null or blank");
79+ }
80+ }
81+
82+ static void validateNotNull(Object value, String label) {
83+ if (value == null) {
84+ throw new IllegalArgumentException(label + " should not be null");
85+ }
86+ }
87+
88+ static void validateNotKeyWord(String label, String message) {
89+ if (RESERVED_KEYWORDS.contains(label)) {
90+ throw new IllegalArgumentException(message);
91+ }
92+ }
93+
94+ static SchemaStatement fromQueryString(final String queryString) {
95+ return new SchemaStatement() {
96+ @Override public String buildInternal() {
97+ return queryString;
98+ }
99+ };
100+ }
101+
102+ StatementStart asStatementStart() {
103+ return new StatementStart() {
104+ @Override public String buildInternal() {
105+ return SchemaStatement.this.buildInternal();
106+ }
107+ };
108+ }
109+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/StatementStart.java +23 −0
@@ -0,0 +1,23 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+/**
19+ * The start of a statement, that another class will append to, to build the final statement.
20+ */
21+interface StatementStart {
22+ String buildInternal();
23+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/TableOptions.java +1097 −0
@@ -0,0 +1,1097 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import java.util.ArrayList;
19+import java.util.List;
20+
21+import com.google.common.base.Joiner;
22+import com.google.common.base.Optional;
23+import com.google.common.base.Strings;
24+
25+/**
26+ * The table options used in a CREATE TABLE or ALTER TABLE statement.
27+ * <p>
28+ * Implementation notes: this class is abstract and not meant to use directly.
29+ * The type parameter {@code T} allows usage of <strong>covariant return type</strong> and makes the builder pattern work for different sub-classes.
30+ *
31+ * @param <T> the concrete sub-class of {@link com.datastax.driver.core.schemabuilder.TableOptions}
32+ *
33+ * @see <a href="http://www.datastax.com/documentation/cql/3.1/cql/cql_reference/tabProp.html" target="_blank">details on table options</a>
34+ */
35+public abstract class TableOptions<T extends TableOptions> extends SchemaStatement {
36+
37+ private StatementStart statementStart;
38+
39+ private Optional<SchemaBuilder.Caching> cassandra20Caching = Optional.absent();
40+ private Optional<SchemaBuilder.KeyCaching> cassandra21KeyCaching = Optional.absent();
41+ private Optional<CachingRowsPerPartition> cassandra21RowCaching = Optional.absent();
42+
43+ private Optional<Double> bloomFilterFPChance = Optional.absent();
44+
45+ private Optional<String> comment = Optional.absent();
46+
47+ private Optional<CompressionOptions> compressionOptions = Optional.absent();
48+
49+ private Optional<CompactionOptions> compactionOptions = Optional.absent();
50+
51+ private Optional<Double> dcLocalReadRepairChance = Optional.absent();
52+
53+ private Optional<Integer> defaultTTL = Optional.absent();
54+
55+ private Optional<Integer> gcGraceSeconds = Optional.absent();
56+
57+ private Optional<Integer> indexInterval = Optional.absent();
58+ private Optional<Integer> minIndexInterval = Optional.absent();
59+ private Optional<Integer> maxIndexInterval = Optional.absent();
60+
61+ private Optional<Integer> memtableFlushPeriodInMillis = Optional.absent();
62+
63+ private Optional<Boolean> populateIOOnCacheFlush = Optional.absent();
64+
65+ private Optional<Double> readRepairChance = Optional.absent();
66+
67+ private Optional<Boolean> replicateOnWrite = Optional.absent();
68+
69+ private Optional<SpeculativeRetryValue> speculativeRetry = Optional.absent();
70+
71+ private List<String> customOptions = new ArrayList<String>();
72+
73+ @SuppressWarnings("unchecked")
74+ private final T self = (T)this;
75+
76+ TableOptions(StatementStart statementStart) {
77+ this.statementStart = statementStart;
78+ }
79+
80+ /**
81+ * Define the caching type for Cassandra 2.0.x.
82+ * <p>
83+ * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder.Caching#KEYS_ONLY}.
84+ *
85+ * @param caching the caching type (all enum values are allowed).
86+ * @return this {@code TableOptions} object.
87+ */
88+ public T caching(SchemaBuilder.Caching caching) {
89+ this.cassandra20Caching = Optional.fromNullable(caching);
90+ return self;
91+ }
92+
93+ /**
94+ * Define the caching options for Cassandra 2.1.x.
95+ * <p>
96+ * If no call is made to this method, the default values set by Cassandra are keys = {@link SchemaBuilder.Caching#ALL} and
97+ * rows_per_partition = {@link com.datastax.driver.core.schemabuilder.SchemaBuilder#noRows()}.
98+
99+ * @param keys the key cache type.
100+ * @param rowsPerPartition defines the number of rows to be cached per partition when Row Caching is enabled.
101+ * To create instances, use
102+ * {@link SchemaBuilder#noRows()},
103+ * {@link SchemaBuilder#allRows()} or
104+ * {@link SchemaBuilder#rows(int)}.
105+ * @return this {@code TableOptions} object.
106+ */
107+ public T caching(SchemaBuilder.KeyCaching keys, CachingRowsPerPartition rowsPerPartition) {
108+ this.cassandra21KeyCaching = Optional.fromNullable(keys);
109+ this.cassandra21RowCaching = Optional.fromNullable(rowsPerPartition);
110+ return self;
111+ }
112+
113+ /**
114+ * Define the desired false-positive probability for SSTable Bloom filters.
115+ * <p>
116+ * If no call is made to this method, the default value set by Cassandra is:
117+ * <ul>
118+ * <li><strong>0.01</strong> for the size-tiered compaction strategy;</li>
119+ * <li><strong>0.1</strong> for the leveled compaction strategy.</li>
120+ * </ul>
121+ *
122+ * @param fpChance the false positive change. This value should be between 0 and 1.0.
123+ * @return this {@code TableOptions} object.
124+ */
125+ public T bloomFilterFPChance(Double fpChance) {
126+ validateRateValue(fpChance, "Bloom filter false positive change");
127+ this.bloomFilterFPChance = Optional.fromNullable(fpChance);
128+ return self;
129+ }
130+
131+ /**
132+ * Define a human readable comment describing the table.
133+ *
134+ * @param comment the comment.
135+ * @return this {@code TableOptions} object.
136+ */
137+ public T comment(String comment) {
138+ this.comment = Optional.fromNullable(comment);
139+ return self;
140+ }
141+
142+ /**
143+ * Define the compression options.
144+ * <p>
145+ * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#lz4()}.
146+ *
147+ * @param compressionOptions the compression options. To create instances, use
148+ * {@link SchemaBuilder#noCompression()},
149+ * {@link SchemaBuilder#lz4()},
150+ * {@link SchemaBuilder#snappy()} or
151+ * {@link SchemaBuilder#deflate()}.
152+ * @return this {@code TableOptions} object.
153+ */
154+ public T compressionOptions(CompressionOptions compressionOptions) {
155+ this.compressionOptions = Optional.fromNullable(compressionOptions);
156+ return self;
157+ }
158+
159+ /**
160+ * Define the compaction options.
161+ * <p>
162+ * If no call is made to this method, the default value set by Cassandra is {@link SchemaBuilder#sizedTieredStategy()}.
163+ *
164+ * @param compactionOptions the compaction options. To create instances, use
165+ * {@link SchemaBuilder#sizedTieredStategy()},
166+ * {@link SchemaBuilder#leveledStrategy()} or
167+ * {@link SchemaBuilder#dateTieredStrategy()}
168+ * @return this {@code TableOptions} object.
169+ */
170+ public T compactionOptions(CompactionOptions compactionOptions) {
171+ this.compactionOptions = Optional.fromNullable(compactionOptions);
172+ return self;
173+ }
174+
175+ /**
176+ * Define the probability of read repairs being invoked over all replicas in the current data center.
177+ * <p>
178+ * If no call is made to this method, the default value set by Cassandra is 0.0.
179+ *
180+ * @param dcLocalReadRepairChance the probability.
181+ * @return this {@code TableOptions} object.
182+ */
183+ public T dcLocalReadRepairChance(Double dcLocalReadRepairChance) {
184+ validateRateValue(dcLocalReadRepairChance, "DC local read repair chance");
185+ this.dcLocalReadRepairChance = Optional.fromNullable(dcLocalReadRepairChance);
186+ return self;
187+ }
188+
189+ /**
190+ * Define the default expiration time in seconds for a table.
191+ *
192+ * <p>
193+ * Used in MapReduce/Hive scenarios when you have no control of TTL.
194+ * <p>
195+ * If no call is made to this method, the default value set by Cassandra is 0.
196+ *
197+ * @param defaultTimeToLive the default time to live in seconds for a table.
198+ * @return this {@code TableOptions} object.
199+ */
200+ public T defaultTimeToLive(Integer defaultTimeToLive) {
201+ this.defaultTTL = Optional.fromNullable(defaultTimeToLive);
202+ return self;
203+ }
204+
205+ /**
206+ * Define the time to wait before garbage collecting tombstones (deletion markers).
207+ *
208+ * The default value allows a great deal of time for consistency to be achieved prior to deletion.
209+ * In many deployments this interval can be reduced, and in a single-node cluster it can be safely set to zero.
210+ * <p>
211+ * If no call is made to this method, the default value set by Cassandra is 864000 secs (10 days).
212+ *
213+ * @param gcGraceSeconds the grace period.
214+ * @return this {@code TableOptions} object.
215+ */
216+ public T gcGraceSeconds(Integer gcGraceSeconds) {
217+ this.gcGraceSeconds = Optional.fromNullable(gcGraceSeconds);
218+ return self;
219+ }
220+
221+ /**
222+ * Define the index interval for Cassandra 2.0.
223+ *
224+ * To control the sampling of entries from the primary row index, configure sample frequency of the partition summary by changing the index interval.
225+ * After changing the index interval, SSTables are written to disk with new information. The interval corresponds to the number of index entries that
226+ * are skipped between taking each sample. By default, Cassandra samples one row key out of every 128. The larger the interval, the smaller and less
227+ * effective the sampling. The larger the sampling, the more effective the index, but with increased memory usage. In Cassandra 2.0.x, generally, the
228+ * best trade off between memory usage and performance is a value between 128 and 512 in combination with a large table key cache. However, if you have
229+ * small rows (many to an OS page), you may want to increase the sample size, which often lowers memory usage without an impact on performance. For
230+ * large rows, decreasing the sample size may improve read performance.
231+ * <p>
232+ * If no call is made to this method, the default value set by Cassandra is 128.
233+ *
234+ * @param indexInterval the index interval.
235+ * @return this {@code TableOptions} object.
236+ */
237+ public T indexInterval(Integer indexInterval) {
238+ this.indexInterval = Optional.fromNullable(indexInterval);
239+ return self;
240+ }
241+
242+ /**
243+ * Define the minimum index interval for Cassandra 2.1.
244+ * <p>
245+ * If no call is made to this method, the default value set by Cassandra is 128.
246+ *
247+ * @param minIndexInterval the minimum index interval.
248+ * @return this {@code TableOptions} object.
249+ *
250+ * @see #indexInterval(Integer)
251+ */
252+ public T minIndexInterval(Integer minIndexInterval) {
253+ this.minIndexInterval = Optional.fromNullable(minIndexInterval);
254+ return self;
255+ }
256+
257+ /**
258+ * Define the maximum index interval for Cassandra 2.1.
259+ * <p>
260+ * If no call is made to this method, the default value set by Cassandra is 2048.
261+ *
262+ * @param maxIndexInterval the maximum index interval.
263+ * @return this {@code TableOptions} object.
264+ *
265+ * @see #indexInterval(Integer)
266+ */
267+ public T maxIndexInterval(Integer maxIndexInterval) {
268+ this.maxIndexInterval = Optional.fromNullable(maxIndexInterval);
269+ return self;
270+ }
271+
272+ /**
273+ * Define the memtable flush period.
274+ *
275+ * If set, this forces flushing of the memtable after the specified time elapses.
276+ * <p>
277+ * If no call is made to this method, the default value set by Cassandra is 0.
278+ *
279+ * @param memtableFlushPeriodInMillis the memtable flush period in milliseconds.
280+ * @return this {@code TableOptions} object.
281+ */
282+ public T memtableFlushPeriodInMillis(Integer memtableFlushPeriodInMillis) {
283+ this.memtableFlushPeriodInMillis = Optional.fromNullable(memtableFlushPeriodInMillis);
284+ return self;
285+ }
286+
287+ /**
288+ * Define whether to populate IO cache on flush of sstables.
289+ *
290+ * If set, Cassandra adds newly flushed or compacted sstables to the operating system page cache, potentially evicting other cached data to make room.
291+ * Enable when all data in the table is expected to fit in memory.
292+ * <p>
293+ * If no call is made to this method, the default value set by Cassandra is {@code false}.
294+ *
295+ * @param populateIOOnCacheFlush whether to populate IO cache on flush of sstables.
296+ * @return this {@code TableOptions} object.
297+ *
298+ * @see <a href="http://www.datastax.com/documentation/cassandra/2.0/cassandra/configuration/configCassandra_yaml_r.html?scroll=reference_ds_qfg_n1r_1k__compaction_preheat_key_cache">the global option compaction_preheat_key_cache</a>
299+ */
300+ public T populateIOCacheOnFlush(Boolean populateIOOnCacheFlush) {
301+ this.populateIOOnCacheFlush = Optional.fromNullable(populateIOOnCacheFlush);
302+ return self;
303+ }
304+
305+ /**
306+ * Define the probability with which read repairs should be invoked on non-quorum reads. The value must be between 0 and 1.
307+ * <p>
308+ * If no call is made to this method, the default value set by Cassandra is 0.1.
309+ *
310+ * @param readRepairChance the read repair chance.
311+ * @return this {@code TableOptions} object.
312+ */
313+ public T readRepairChance(Double readRepairChance) {
314+ validateRateValue(readRepairChance, "Read repair chance");
315+ this.readRepairChance = Optional.fromNullable(readRepairChance);
316+ return self;
317+ }
318+
319+ /**
320+ * Define whether to replicate data on write (Cassandra 2.0.x only).
321+ *
322+ * When set to {@code true}, replicates writes to all affected replicas regardless of the consistency level specified by the client for a write request.
323+ * For counter tables, this should always be set to {@code true}.
324+ * <p>
325+ * If no call is made to this method, the default value set by Cassandra is {@code true}.
326+ *
327+ * @param replicateOnWrite whether to replicate data on write.
328+ * @return this {@code TableOptions} object.
329+ */
330+ public T replicateOnWrite(Boolean replicateOnWrite) {
331+ this.replicateOnWrite = Optional.fromNullable(replicateOnWrite);
332+ return self;
333+ }
334+
335+ /**
336+ * To override normal read timeout when read_repair_chance is not 1.0, sending another request to read, choose one of these values and use the property to create
337+ * or alter the table:
338+ * <ul>
339+ * <li>ALWAYS: Retry reads of all replicas.</li>
340+ * <li>Xpercentile: Retry reads based on the effect on throughput and latency.</li>
341+ * <li>Yms: Retry reads after specified milliseconds.</li>
342+ * <li>NONE: Do not retry reads.</li>
343+ * </ul>
344+ *
345+ * Using the speculative retry property, you can configure rapid read protection in Cassandra 2.0.2 and later.
346+ * Use this property to retry a request after some milliseconds have passed or after a percentile of the typical read latency has been reached,
347+ * which is tracked per table.
348+ *
349+ * <p>
350+ * If no call is made to this method, the default value set by Cassandra is {code 99percentile}.
351+ *
352+ * @param speculativeRetry the speculative retry. To create instances, use
353+ * {@link SchemaBuilder#noSpeculativeRetry()},
354+ * {@link SchemaBuilder#always()},
355+ * {@link SchemaBuilder#percentile(int)} or
356+ * {@link SchemaBuilder#millisecs(int)}.
357+ * @return this {@code TableOptions} object.
358+ */
359+ public T speculativeRetry(SpeculativeRetryValue speculativeRetry) {
360+ this.speculativeRetry = Optional.fromNullable(speculativeRetry);
361+ return self;
362+ }
363+
364+ /**
365+ * Define a free-form option as a key/value pair.
366+ * <p>
367+ * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
368+ *
369+ * @param key the name of the option.
370+ * @param value the value of the option. If it's a {@code String}, it will be included in single quotes, otherwise the result of invoking its
371+ * {@code toString} method will be used unquoted.
372+ * @return this {@code TableOptions} object.
373+ */
374+ public T freeformOption(String key, Object value) {
375+ if (Strings.isNullOrEmpty(key)) {
376+ throw new IllegalArgumentException("Key for custom option should not be null or blank");
377+ }
378+ customOptions.add(buildCustomOption(key, value));
379+ return self;
380+ }
381+
382+ private static String buildCustomOption(String key, Object value) {
383+ return String.format("%s = %s",
384+ key,
385+ (value instanceof String)
386+ ? "'" + value + "'"
387+ : value.toString());
388+ }
389+
390+ private List<String> buildCommonOptions() {
391+ List<String> options = new ArrayList<String>();
392+
393+ buildCachingOptions(options);
394+
395+ if (bloomFilterFPChance.isPresent()) {
396+ options.add("bloom_filter_fp_chance = " + bloomFilterFPChance.get());
397+ }
398+
399+ if (comment.isPresent()) {
400+ options.add("comment = '" + comment.get() + "'");
401+ }
402+
403+ if (compressionOptions.isPresent()) {
404+ options.add("compression = " + compressionOptions.get().build());
405+ }
406+
407+ if (compactionOptions.isPresent()) {
408+ options.add("compaction = " + compactionOptions.get().build());
409+ }
410+
411+ if (dcLocalReadRepairChance.isPresent()) {
412+ options.add("dclocal_read_repair_chance = " + dcLocalReadRepairChance.get());
413+ }
414+
415+ if (defaultTTL.isPresent()) {
416+ options.add("default_time_to_live = " + defaultTTL.get());
417+ }
418+
419+ if (gcGraceSeconds.isPresent()) {
420+ options.add("gc_grace_seconds = " + gcGraceSeconds.get());
421+ }
422+
423+ if (indexInterval.isPresent()) {
424+ options.add("index_interval = " + indexInterval.get());
425+ }
426+
427+ if (minIndexInterval.isPresent()) {
428+ options.add("min_index_interval = " + minIndexInterval.get());
429+ }
430+
431+ if (maxIndexInterval.isPresent()) {
432+ options.add("max_index_interval = " + maxIndexInterval.get());
433+ }
434+
435+ if (memtableFlushPeriodInMillis.isPresent()) {
436+ options.add("memtable_flush_period_in_ms = " + memtableFlushPeriodInMillis.get());
437+ }
438+
439+ if (populateIOOnCacheFlush.isPresent()) {
440+ options.add("populate_io_cache_on_flush = " + populateIOOnCacheFlush.get());
441+ }
442+
443+ if (readRepairChance.isPresent()) {
444+ options.add("read_repair_chance = " + readRepairChance.get());
445+ }
446+
447+ if (replicateOnWrite.isPresent()) {
448+ options.add("replicate_on_write = " + replicateOnWrite.get());
449+ }
450+
451+ if (speculativeRetry.isPresent()) {
452+ options.add("speculative_retry = " + speculativeRetry.get().value());
453+ }
454+
455+ options.addAll(customOptions);
456+
457+ return options;
458+ }
459+
460+ private void buildCachingOptions(List<String> options) {
461+ if (cassandra20Caching.isPresent() && cassandra21KeyCaching.isPresent()) {
462+ throw new IllegalStateException("Can't use Cassandra 2.0 and 2.1 caching at the same time, you must call only one version of caching()");
463+ }
464+ else if (cassandra20Caching.isPresent()) {
465+ options.add("caching = " + cassandra20Caching.get().value());
466+ } else if (cassandra21KeyCaching.isPresent() && cassandra21RowCaching.isPresent()) {
467+ options.add(String.format("caching = {'keys' : %s, 'rows_per_partition' : %s}",
468+ cassandra21KeyCaching.get().value(), cassandra21RowCaching.get().value()));
469+ }
470+ }
471+
472+ protected abstract void addSpecificOptions(List<String> options);
473+
474+ @Override
475+ public final String buildInternal() {
476+ List<String> options = buildCommonOptions();
477+ addSpecificOptions(options);
478+ return statementStart.buildInternal() + STATEMENT_START +
479+ "WITH " + Joiner.on(" AND ").join(options);
480+ }
481+
482+ static void validateRateValue(Double rateValue, String property) {
483+ if (rateValue != null && (rateValue < 0 || rateValue > 1.0)) {
484+ throw new IllegalArgumentException(property + " should be between 0 and 1");
485+ }
486+ }
487+
488+ /**
489+ * Compaction options for a CREATE or ALTER TABLE statement.
490+ * <p>
491+ * To create instances, use
492+ * {@link SchemaBuilder#sizedTieredStategy()},
493+ * {@link SchemaBuilder#leveledStrategy()} or
494+ * {@link SchemaBuilder#dateTieredStrategy()}
495+ */
496+ public static abstract class CompactionOptions<T extends CompactionOptions> {
497+
498+ private Strategy strategy;
499+
500+ private Optional<Boolean> enabled = Optional.absent();
501+
502+ private Optional<Integer> tombstoneCompactionIntervalInDay = Optional.absent();
503+
504+ private Optional<Double> tombstoneThreshold = Optional.absent();
505+
506+ private Optional<Boolean> uncheckedTombstoneCompaction = Optional.absent();
507+
508+ private List<String> customOptions = new ArrayList<String>();
509+
510+ @SuppressWarnings("unchecked")
511+ private final T self = (T)this;
512+
513+ CompactionOptions(Strategy compactionStrategy) {
514+ this.strategy = compactionStrategy;
515+ }
516+
517+ /**
518+ * Enable or disable background compaction.
519+ * <p>
520+ * If no call is made to this method, the default value set by Cassandra is {code true}.
521+ *
522+ * @param enabled whether to enable background compaction for the table.
523+ * @return this object (for call chaining).
524+ */
525+ public T enabled(Boolean enabled) {
526+ this.enabled = Optional.fromNullable(enabled);
527+ return self;
528+ }
529+
530+ /**
531+ * Define the minimum number of days to wait after an SSTable creation time before considering the SSTable for tombstone compaction.
532+ * Tombstone compaction is the compaction triggered if the SSTable has more garbage-collectable tombstones than tombstone_threshold.
533+ * <p>
534+ * If no call is made to this method, the default value set by Cassandra is 1.
535+ *
536+ * @param tombstoneCompactionInterval the tombstone compaction interval in day.
537+ * @return this object (for call chaining).
538+ */
539+ public T tombstoneCompactionIntervalInDay(Integer tombstoneCompactionInterval) {
540+ this.tombstoneCompactionIntervalInDay = Optional.fromNullable(tombstoneCompactionInterval);
541+ return self;
542+ }
543+
544+ /**
545+ * Define the ratio of garbage-collectable tombstones to all contained columns,
546+ * which if exceeded by the SSTable triggers compaction (with no other SSTables) for the purpose of purging the tombstones.
547+ * <p>
548+ * If no call is made to this method, the default value set by Cassandra is 0.2.
549+ *
550+ * @param tombstoneThreshold the threshold.
551+ * @return this object (for call chaining).
552+ */
553+ public T tombstoneThreshold(Double tombstoneThreshold) {
554+ validateRateValue(tombstoneThreshold, "Tombstone threshold");
555+ this.tombstoneThreshold = Optional.fromNullable(tombstoneThreshold);
556+ return self;
557+ }
558+
559+ /**
560+ * Enables more aggressive than normal tombstone compactions. A single SSTable tombstone compaction runs without
561+ * checking the likelihood of success (Cassandra 2.0.9 and later).
562+ * <p>
563+ * If no call is made to this method, the default value set by Cassandra is {code false}.
564+ *
565+ * @param uncheckedTombstoneCompaction whether to enable the feature.
566+ * @return this object (for call chaining).
567+ */
568+ public T uncheckedTombstoneCompaction(Boolean uncheckedTombstoneCompaction) {
569+ this.uncheckedTombstoneCompaction = Optional.fromNullable(uncheckedTombstoneCompaction);
570+ return self;
571+ }
572+
573+ /**
574+ * Define a free-form option as a key/value pair.
575+ * <p>
576+ * This method is provided as a fallback if the SchemaBuilder is used with a more recent version of Cassandra that has new, unsupported options.
577+ *
578+ * @param key the name of the option.
579+ * @param value the value of the option. If it's a {@code CharSequence}, it will be included in single quotes, otherwise the result of invoking its
580+ * {@code toString} method will be used unquoted.
581+ * @return this object (for call chaining).
582+ */
583+ public T freeformOption(String key, Object value) {
584+ if (Strings.isNullOrEmpty(key)) {
585+ throw new IllegalArgumentException("Key for custom option should not be null or blank");
586+ }
587+ customOptions.add(buildCustomOption(key, value));
588+ return self;
589+ }
590+
591+ private static String buildCustomOption(String key, Object value) {
592+ return String.format("'%s' : %s",
593+ key,
594+ (value instanceof CharSequence)
595+ ? "'" + value + "'"
596+ : value.toString());
597+ }
598+
599+ List<String> buildCommonOptions() {
600+
601+ List<String> options = new ArrayList<String>();
602+ options.add("'class' : " + strategy.strategyClass());
603+
604+ if (enabled.isPresent()) {
605+ options.add("'enabled' : " + enabled.get());
606+ }
607+
608+ if (tombstoneCompactionIntervalInDay.isPresent()) {
609+ options.add("'tombstone_compaction_interval' : " + tombstoneCompactionIntervalInDay.get());
610+ }
611+
612+ if (tombstoneThreshold.isPresent()) {
613+ options.add("'tombstone_threshold' : " + tombstoneThreshold.get());
614+ }
615+
616+ if (uncheckedTombstoneCompaction.isPresent()) {
617+ options.add("'unchecked_tombstone_compaction' : " + uncheckedTombstoneCompaction.get());
618+ }
619+
620+ options.addAll(customOptions);
621+
622+ return options;
623+ }
624+
625+ public abstract String build();
626+
627+ /**
628+ * Compaction options specific to SizeTiered strategy
629+ */
630+ public static class SizeTieredCompactionStrategyOptions extends CompactionOptions<SizeTieredCompactionStrategyOptions> {
631+
632+ private Optional<Double> bucketHigh = Optional.absent();
633+
634+ private Optional<Double> bucketLow = Optional.absent();
635+
636+ private Optional<Double> coldReadsRatioToOmit = Optional.absent();
637+
638+ private Optional<Integer> minThreshold = Optional.absent();
639+
640+ private Optional<Integer> maxThreshold = Optional.absent();
641+
642+ private Optional<Long> minSSTableSizeInBytes = Optional.absent();
643+
644+ SizeTieredCompactionStrategyOptions() {
645+ super(Strategy.SIZED_TIERED);
646+ }
647+
648+ /**
649+ * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
650+ * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
651+ * <p>
652+ * If no call is made to this method, the default value set by Cassandra is 1.5.
653+ *
654+ * @param bucketHigh the new value.
655+ * @return this object (for call chaining).
656+ */
657+ public SizeTieredCompactionStrategyOptions bucketHigh(Double bucketHigh) {
658+ this.bucketHigh = Optional.fromNullable(bucketHigh);
659+ return this;
660+ }
661+
662+ /**
663+ * Size-tiered compaction strategy (STCS) considers SSTables to be within the same bucket if the SSTable size diverges by 50%
664+ * or less from the default bucket_low and default bucket_high values: [average-size × bucket_low, average-size × bucket_high].
665+ * <p>
666+ * If no call is made to this method, the default value set by Cassandra is 0.5.
667+ *
668+ * @param bucketLow the new value.
669+ * @return this object (for call chaining).
670+ */
671+ public SizeTieredCompactionStrategyOptions bucketLow(Double bucketLow) {
672+ this.bucketLow = Optional.fromNullable(bucketLow);
673+ return this;
674+ }
675+
676+ /**
677+ * The maximum percentage of reads/sec that ignored SSTables may account for.
678+ * The recommended range of values is 0.0 and 1.0.
679+ * In Cassandra 2.0.3 and later, you can enable the cold_reads_to_omit property to tune performace per table.
680+ * The <a href="http://www.datastax.com/dev/blog/optimizations-around-cold-sstables">Optimizations around Cold SSTables</a> blog includes detailed information tuning performance using this property,
681+ * which avoids compacting cold SSTables. Use the ALTER TABLE command to configure cold_reads_to_omit.
682+ * <p>
683+ * If no call is made to this method, the default value set by Cassandra is 0.0 (disabled).
684+ *
685+ * @param coldReadsRatio the new value.
686+ * @return this object (for call chaining).
687+ */
688+ public SizeTieredCompactionStrategyOptions coldReadsRatioToOmit(Double coldReadsRatio) {
689+ validateRateValue(coldReadsRatio, "Cold read ratio to omit ");
690+ this.coldReadsRatioToOmit = Optional.fromNullable(coldReadsRatio);
691+ return this;
692+ }
693+
694+ /**
695+ * Sets the minimum number of SSTables to trigger a minor compaction
696+ * <p>
697+ * If no call is made to this method, the default value set by Cassandra is 4.
698+ *
699+ * @param minThreshold the new value.
700+ * @return this object (for call chaining).
701+ */
702+ public SizeTieredCompactionStrategyOptions minThreshold(Integer minThreshold) {
703+ this.minThreshold = Optional.fromNullable(minThreshold);
704+ return this;
705+ }
706+
707+ /**
708+ * Sets the maximum number of SSTables to allow in a minor compaction.
709+ * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
710+ * <p>
711+ * If no call is made to this method, the default value set by Cassandra is 32.
712+ *
713+ * @param maxThreshold the new value.
714+ * @return this object (for call chaining).
715+ */
716+ public SizeTieredCompactionStrategyOptions maxThreshold(Integer maxThreshold) {
717+ this.maxThreshold = Optional.fromNullable(maxThreshold);
718+ return this;
719+ }
720+
721+ /**
722+ * The SizeTieredCompactionStrategy groups SSTables for compaction into buckets.
723+ * The bucketing process groups SSTables that differ in size by less than 50%. This results in a bucketing process that is too fine grained for small SSTables.
724+ * If your SSTables are small, use min_sstable_size to define a size threshold (in bytes) below which all SSTables belong to one unique bucket
725+ * <p>
726+ * If no call is made to this method, the default value set by Cassandra is 52428800 (50 MB).
727+ *
728+ * @param minSSTableSize the new value.
729+ * @return this object (for call chaining).
730+ */
731+ public SizeTieredCompactionStrategyOptions minSSTableSizeInBytes(Long minSSTableSize) {
732+ this.minSSTableSizeInBytes = Optional.fromNullable(minSSTableSize);
733+ return this;
734+ }
735+
736+ @Override
737+ public String build() {
738+ final List<String> generalOptions = super.buildCommonOptions();
739+
740+ List<String> options = new ArrayList<String>(generalOptions);
741+
742+ if (bucketHigh.isPresent()) {
743+ options.add("'bucket_high' : " + bucketHigh.get());
744+ }
745+
746+ if (bucketLow.isPresent()) {
747+ options.add("'bucket_low' : " + bucketLow.get());
748+ }
749+
750+ if (coldReadsRatioToOmit.isPresent()) {
751+ options.add("'cold_reads_to_omit' : " + coldReadsRatioToOmit.get());
752+ }
753+
754+ if (minThreshold.isPresent()) {
755+ options.add("'min_threshold' : " + minThreshold.get());
756+ }
757+
758+ if (maxThreshold.isPresent()) {
759+ options.add("'max_threshold' : " + maxThreshold.get());
760+ }
761+
762+ if (minSSTableSizeInBytes.isPresent()) {
763+ options.add("'min_sstable_size' : " + minSSTableSizeInBytes.get());
764+ }
765+ return "{" + Joiner.on(", ").join(options) + "}";
766+ }
767+ }
768+
769+ /**
770+ * Compaction options specific to Leveled strategy
771+ */
772+ public static class LeveledCompactionStrategyOptions extends CompactionOptions<LeveledCompactionStrategyOptions> {
773+
774+ private Optional<Integer> ssTableSizeInMB = Optional.absent();
775+
776+ LeveledCompactionStrategyOptions() {
777+ super(Strategy.LEVELED);
778+ }
779+
780+ /**
781+ * The target size for SSTables that use the leveled compaction strategy.
782+ * Although SSTable sizes should be less or equal to sstable_size_in_mb, it is possible to have a larger SSTable during compaction.
783+ * This occurs when data for a given partition key is exceptionally large. The data is not split into two SSTables
784+ * <p>
785+ * If no call is made to this method, the default value set by Cassandra is 160.
786+ *
787+ * @param ssTableSizeInMB the new value.
788+ * @return this object (for call chaining).
789+ */
790+ public LeveledCompactionStrategyOptions ssTableSizeInMB(Integer ssTableSizeInMB) {
791+ this.ssTableSizeInMB = Optional.fromNullable(ssTableSizeInMB);
792+ return this;
793+ }
794+
795+ @Override
796+ public String build() {
797+ final List<String> generalOptions = super.buildCommonOptions();
798+
799+ List<String> options = new ArrayList<String>(generalOptions);
800+
801+ if (ssTableSizeInMB.isPresent()) {
802+ options.add("'sstable_size_in_mb' : " + ssTableSizeInMB.get());
803+ }
804+ return "{" + Joiner.on(", ").join(options) + "}";
805+ }
806+
807+ }
808+
809+ /**
810+ * Compaction options specific to the date-tiered strategy.
811+ */
812+ public static class DateTieredCompactionStrategyOptions extends CompactionOptions<DateTieredCompactionStrategyOptions> {
813+
814+ enum TimeStampResolution {MICROSECONDS, MILLISECONDS}
815+
816+ private Optional<Integer> baseTimeSeconds = Optional.absent();
817+
818+ private Optional<Integer> maxSSTableAgeDays = Optional.absent();
819+
820+ private Optional<Integer> minThreshold = Optional.absent();
821+
822+ private Optional<Integer> maxThreshold = Optional.absent();
823+
824+ private Optional<TimeStampResolution> timestampResolution = Optional.absent();
825+
826+ DateTieredCompactionStrategyOptions() {
827+ super(Strategy.DATE_TIERED);
828+ }
829+
830+ /**
831+ * Sets the size of the first window.
832+ * <p>
833+ * If no call is made to this method, the default value set by Cassandra is 3600 (1 hour).
834+ *
835+ * @param baseTimeSeconds the size of the first window.
836+ * @return this object (for call chaining).
837+ */
838+ public DateTieredCompactionStrategyOptions baseTimeSeconds(Integer baseTimeSeconds) {
839+ this.baseTimeSeconds = Optional.fromNullable(baseTimeSeconds);
840+ return this;
841+ }
842+
843+ /**
844+ * Stop compacting SSTables only having data older than these specified days.
845+ * <p>
846+ * If no call is made to this method, the default value set by Cassandra is 365.
847+ *
848+ * @param maxSSTableAgeDays the maximum age of the SSTables to compact.
849+ * @return this object (for call chaining).
850+ */
851+ public DateTieredCompactionStrategyOptions maxSSTableAgeDays(Integer maxSSTableAgeDays) {
852+ this.maxSSTableAgeDays = Optional.fromNullable(maxSSTableAgeDays);
853+ return this;
854+ }
855+
856+ /**
857+ * Sets the minimum number of SSTables to trigger a minor compaction
858+ * <p>
859+ * If no call is made to this method, the default value set by Cassandra is 4.
860+ *
861+ * @param minThreshold the new value.
862+ * @return this object (for call chaining).
863+ */
864+ public DateTieredCompactionStrategyOptions minThreshold(Integer minThreshold) {
865+ this.minThreshold = Optional.fromNullable(minThreshold);
866+ return this;
867+ }
868+
869+ /**
870+ * Sets the maximum number of SSTables to allow in a minor compaction.
871+ * In LeveledCompactionStrategy (LCS), it applies to L0 when L0 gets behind, that is, when L0 accumulates more than MAX_COMPACTING_L0 SSTables.
872+ * <p>
873+ * If no call is made to this method, the default value set by Cassandra is 32.
874+ *
875+ * @param maxThreshold the new value.
876+ * @return this object (for call chaining).
877+ */
878+ public DateTieredCompactionStrategyOptions maxThreshold(Integer maxThreshold) {
879+ this.maxThreshold = Optional.fromNullable(maxThreshold);
880+ return this;
881+ }
882+
883+ /**
884+ * Sets the timestamp resolution, depending on the timestamp unit of the data you insert.
885+ * <p>
886+ * If no call is made to this method, the default value set by Cassandra is {@code MICROSECONDS}.
887+ *
888+ * @param timestampResolution {@link TimeStampResolution#MICROSECONDS} or {@link TimeStampResolution#MILLISECONDS}.
889+ * @return this object (for call chaining).
890+ */
891+ public DateTieredCompactionStrategyOptions timestampResolution(TimeStampResolution timestampResolution) {
892+ this.timestampResolution = Optional.fromNullable(timestampResolution);
893+ return this;
894+ }
895+
896+ @Override public String build() {
897+ final List<String> generalOptions = super.buildCommonOptions();
898+
899+ List<String> options = new ArrayList<String>(generalOptions);
900+
901+ if (baseTimeSeconds.isPresent()) {
902+ options.add("'base_time_seconds' : " + baseTimeSeconds.get());
903+ }
904+
905+ if (maxSSTableAgeDays.isPresent()) {
906+ options.add("'max_sstable_age_days' : " + maxSSTableAgeDays.get());
907+ }
908+
909+ if (minThreshold.isPresent()) {
910+ options.add("'min_threshold' : " + minThreshold.get());
911+ }
912+
913+ if (maxThreshold.isPresent()) {
914+ options.add("'max_threshold' : " + maxThreshold.get());
915+ }
916+
917+ if (timestampResolution.isPresent()) {
918+ options.add("'timestamp_resolution' : '" + timestampResolution.get() + "'");
919+ }
920+
921+ return "{" + Joiner.on(", ").join(options) + "}";
922+ }
923+ }
924+
925+ /**
926+ * Compaction strategies. Possible values: SIZED_TIERED, LEVELED & DATE_TIERED
927+ */
928+ public static enum Strategy {
929+ SIZED_TIERED("'SizeTieredCompactionStrategy'"), LEVELED("'LeveledCompactionStrategy'"), DATE_TIERED("'DateTieredCompactionStrategy'");
930+
931+ private String strategyClass;
932+
933+ Strategy(String strategyClass) {
934+ this.strategyClass = strategyClass;
935+ }
936+
937+ public String strategyClass() {
938+ return strategyClass;
939+ }
940+
941+ @Override
942+ public String toString() {
943+ return strategyClass;
944+ }
945+ }
946+
947+ }
948+
949+ /**
950+ * The compression options for a CREATE or ALTER TABLE statement.
951+ * <p>
952+ * To create instances, use
953+ * {@link SchemaBuilder#noCompression()},
954+ * {@link SchemaBuilder#lz4()},
955+ * {@link SchemaBuilder#snappy()} or
956+ * {@link SchemaBuilder#deflate()}.
957+ */
958+ public static class CompressionOptions {
959+
960+ private Algorithm algorithm;
961+
962+ private Optional<Integer> chunkLengthInKb = Optional.absent();
963+
964+ private Optional<Double> crcCheckChance = Optional.absent();
965+
966+ CompressionOptions(Algorithm algorithm) {
967+ this.algorithm = algorithm;
968+ }
969+
970+ /**
971+ * On disk, SSTables are compressed by block to allow random reads.
972+ * This subproperty of compression defines the size (in KB) of the block.
973+ * Values larger than the default value might improve the compression rate, but increases the minimum size of data to be read from disk when a read occurs.
974+ * The default value is a good middle-ground for compressing tables.
975+ * Adjust compression size to account for read/write access patterns (how much data is typically requested at once) and the average size of rows in the table.
976+ * <p>
977+ * If no call is made to this method, the default value set by Cassandra is 54.
978+ *
979+ * @param chunkLengthInKb the new value.
980+ * @return this object (for call chaining).
981+ */
982+ public CompressionOptions withChunkLengthInKb(Integer chunkLengthInKb) {
983+ this.chunkLengthInKb = Optional.fromNullable(chunkLengthInKb);
984+ return this;
985+ }
986+
987+ /**
988+ * When compression is enabled, each compressed block includes a checksum of that block for the purpose of detecting disk bitrate and avoiding the propagation
989+ * of corruption to other replica. This option defines the probability with which those checksums are checked during read.
990+ * By default they are always checked. Set to 0 to disable checksum checking and to 0.5, for instance, to check them on every other read.
991+ * <p>
992+ * If no call is made to this method, the default value set by Cassandra is 1.0 (always check).
993+ *
994+ * @param crcCheckChance the new value.
995+ * @return this object (for call chaining).
996+ */
997+ public CompressionOptions withCRCCheckChance(Double crcCheckChance) {
998+ validateRateValue(crcCheckChance, "CRC check chance");
999+ this.crcCheckChance = Optional.fromNullable(crcCheckChance);
1000+ return this;
1001+ }
1002+
1003+ public String build() {
1004+ List<String> options = new ArrayList<String>();
1005+ options.add("'sstable_compression' : " + algorithm.value());
1006+
1007+ if (chunkLengthInKb.isPresent()) {
1008+ options.add("'chunk_length_kb' : " + chunkLengthInKb.get());
1009+ }
1010+
1011+ if (crcCheckChance.isPresent()) {
1012+ options.add("'crc_check_chance' : " + crcCheckChance.get());
1013+ }
1014+ return "{" + Joiner.on(", ").join(options) + "}";
1015+ }
1016+
1017+ /**
1018+ * Compression algorithms. Possible values: NONE, LZ4, SNAPPY, DEFLATE
1019+ */
1020+ public static enum Algorithm {
1021+ NONE("''"), LZ4("'LZ4Compressor'"), SNAPPY("'SnappyCompressor'"), DEFLATE("'DeflateCompressor'");
1022+
1023+ private String value;
1024+
1025+ Algorithm(String value) {
1026+ this.value = value;
1027+ }
1028+
1029+ public String value() {
1030+ return value;
1031+ }
1032+
1033+ @Override
1034+ public String toString() {
1035+ return value;
1036+ }
1037+ }
1038+
1039+ public static class NoCompression extends CompressionOptions {
1040+
1041+ public NoCompression() {
1042+ super(Algorithm.NONE);
1043+ }
1044+
1045+ public CompressionOptions withChunkLengthInKb(Integer chunkLengthInKb) {
1046+ return this;
1047+ }
1048+
1049+ public CompressionOptions withCRCCheckChance(Double crcCheckChance) {
1050+ return this;
1051+ }
1052+ }
1053+ }
1054+
1055+ /**
1056+ * The speculative retry options.
1057+ * <p>
1058+ * To create instances, use
1059+ * {@link SchemaBuilder#noSpeculativeRetry()},
1060+ * {@link SchemaBuilder#always()},
1061+ * {@link SchemaBuilder#percentile(int)} or
1062+ * {@link SchemaBuilder#millisecs(int)}.
1063+ */
1064+ public static class SpeculativeRetryValue {
1065+
1066+ private String value;
1067+
1068+ SpeculativeRetryValue(String value) {
1069+ this.value = value;
1070+ }
1071+
1072+ String value() {
1073+ return value;
1074+ }
1075+ }
1076+
1077+ /**
1078+ * Define the number of rows to be cached per partition when row caching is enabled
1079+ * (this feature is only applicable to Cassandra 2.1.x).
1080+ * <p>
1081+ * To create instances, use
1082+ * {@link SchemaBuilder#noRows()},
1083+ * {@link SchemaBuilder#allRows()} or
1084+ * {@link SchemaBuilder#rows(int)}.
1085+ */
1086+ public static class CachingRowsPerPartition {
1087+ private String value;
1088+
1089+ CachingRowsPerPartition(String value) {
1090+ this.value = value;
1091+ }
1092+
1093+ public String value() {
1094+ return value;
1095+ }
1096+ }
1097+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/UDTType.java +65 −0
@@ -0,0 +1,65 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import com.datastax.driver.core.DataType;
19+
20+/**
21+ * Represents a CQL type containing a user-defined type (UDT) in a SchemaBuilder statement.
22+ * <p>
23+ * Use {@link SchemaBuilder#frozen(String)} or {@link SchemaBuilder#udtLiteral(String)} to build instances of this type.
24+ */
25+public final class UDTType implements ColumnType {
26+ private final String asCQLString;
27+
28+ private UDTType(String asCQLString) {
29+ this.asCQLString = asCQLString;
30+ }
31+
32+ @Override public String asCQLString() {
33+ return asCQLString;
34+ }
35+
36+ static UDTType frozen(String udtName) {
37+ SchemaStatement.validateNotEmpty(udtName, "UDT name");
38+ return new UDTType("frozen<" + udtName + ">");
39+ }
40+
41+ static UDTType list(UDTType elementType) {
42+ return new UDTType("list<" + elementType.asCQLString() + ">");
43+ }
44+
45+ static UDTType set(UDTType elementType) {
46+ return new UDTType("set<" + elementType.asCQLString() + ">");
47+ }
48+
49+ static UDTType mapWithUDTKey(UDTType keyType, DataType valueType) {
50+ return new UDTType("map<" + keyType.asCQLString() + ", " + valueType + ">");
51+ }
52+
53+ static UDTType mapWithUDTValue(DataType keyType, UDTType valueType) {
54+ return new UDTType("map<" + keyType + ", " + valueType.asCQLString() + ">");
55+ }
56+
57+ static UDTType mapWithUDTKeyAndValue(UDTType keyType, UDTType valueType) {
58+ return new UDTType("map<" + keyType.asCQLString() + ", " + valueType.asCQLString() + ">");
59+ }
60+
61+ static UDTType literal(String literal) {
62+ SchemaStatement.validateNotEmpty(literal, "UDT type literal");
63+ return new UDTType(literal);
64+ }
65+}
added driver-core/src/main/java/com/datastax/driver/core/schemabuilder/package-info.java +21 −0
@@ -0,0 +1,21 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+/**
17+ * A CQL3 schema builder.
18+ * <p>
19+ * The main entry for this package is the {@code SchemaBuilder} class.
20+ */
21+package com.datastax.driver.core.schemabuilder;
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/AlterTest.java +197 −0
@@ -0,0 +1,197 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import com.datastax.driver.core.DataType;
23+
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
25+
26+public class AlterTest {
27+
28+ @Test(groups = "unit")
29+ public void should_alter_column_type() throws Exception {
30+ //When
31+ SchemaStatement statement = alterTable("test").alterColumn("name").type(DataType.ascii());
32+
33+ //Then
34+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test ALTER name TYPE ascii");
35+ }
36+
37+ @Test(groups = "unit")
38+ public void should_alter_column_type_with_keyspace() throws Exception {
39+ //When
40+ SchemaStatement statement = alterTable("ks", "test").alterColumn("name").type(DataType.ascii());
41+
42+ //Then
43+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE ks.test ALTER name TYPE ascii");
44+ }
45+
46+ @Test(groups = "unit")
47+ public void should_alter_column_type_to_UDT() throws Exception {
48+ //When
49+ SchemaStatement statement = alterTable("ks", "test").alterColumn("address").udtType(frozen("address"));
50+
51+ //Then
52+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE ks.test ALTER address TYPE frozen<address>");
53+ }
54+
55+ @Test(groups = "unit")
56+ public void should_add_column() throws Exception {
57+ //When
58+ SchemaStatement statement = alterTable("test").addColumn("location").type(DataType.ascii());
59+
60+ //Then
61+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test ADD location ascii");
62+ }
63+
64+ @Test(groups = "unit")
65+ public void should_add_column_with_UDT_type() throws Exception {
66+ //When
67+ SchemaStatement statement = alterTable("test").addColumn("location").udtType(frozen("address"));
68+
69+ //Then
70+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test ADD location frozen<address>");
71+ }
72+
73+ @Test(groups = "unit")
74+ public void should_rename_column() throws Exception {
75+ //When
76+ SchemaStatement statement = alterTable("test").renameColumn("name").to("description");
77+
78+ //Then
79+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test RENAME name TO description");
80+ }
81+
82+ @Test(groups = "unit")
83+ public void should_drop_column() throws Exception {
84+ //When
85+ SchemaStatement statement = alterTable("test").dropColumn("name");
86+
87+ //Then
88+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test DROP name");
89+ }
90+
91+ @Test(groups = "unit")
92+ public void should_alter_table_options() throws Exception {
93+ //When
94+ // Note that this does not necessarily represent a valid configuration, the goal is just to test all options
95+ // (some of which might be specific to C* 2.0 or 2.1)
96+ SchemaStatement statement = alterTable("test").withOptions()
97+ .bloomFilterFPChance(0.01)
98+ .caching(Caching.ROWS_ONLY)
99+ .comment("This is a comment")
100+ .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
101+ .compressionOptions(lz4())
102+ .dcLocalReadRepairChance(0.21)
103+ .defaultTimeToLive(100)
104+ .gcGraceSeconds(9999)
105+ .indexInterval(256)
106+ .minIndexInterval(64)
107+ .maxIndexInterval(512)
108+ .memtableFlushPeriodInMillis(12)
109+ .populateIOCacheOnFlush(true)
110+ .replicateOnWrite(true)
111+ .readRepairChance(0.42)
112+ .speculativeRetry(always());
113+
114+ SchemaStatement statementWith21Caching = alterTable("test").withOptions()
115+ .caching(KeyCaching.NONE, rows(100));
116+
117+ //Then
118+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test\n\t" +
119+ "WITH caching = 'rows_only' " +
120+ "AND bloom_filter_fp_chance = 0.01 " +
121+ "AND comment = 'This is a comment' " +
122+ "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
123+ "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
124+ "AND dclocal_read_repair_chance = 0.21 " +
125+ "AND default_time_to_live = 100 " +
126+ "AND gc_grace_seconds = 9999 " +
127+ "AND index_interval = 256 " +
128+ "AND min_index_interval = 64 " +
129+ "AND max_index_interval = 512 " +
130+ "AND memtable_flush_period_in_ms = 12 " +
131+ "AND populate_io_cache_on_flush = true " +
132+ "AND read_repair_chance = 0.42 " +
133+ "AND replicate_on_write = true " +
134+ "AND speculative_retry = 'ALWAYS'");
135+
136+ assertThat(statementWith21Caching.getQueryString()).isEqualTo("\n\tALTER TABLE test\n\t" +
137+ "WITH caching = {'keys' : 'none', 'rows_per_partition' : 100}");
138+ }
139+
140+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
141+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
142+ public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
143+ alterTable("add", "test")
144+ .addColumn("test").type(DataType.ascii());
145+ }
146+
147+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
148+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
149+ public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
150+ alterTable("add")
151+ .addColumn("test").type(DataType.ascii());
152+ }
153+
154+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
155+ expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
156+ public void should_fail_if_added_column_is_a_reserved_keyword() throws Exception {
157+ alterTable("test")
158+ .addColumn("add").type(DataType.ascii()).getQueryString();
159+ }
160+
161+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
162+ expectedExceptionsMessageRegExp = "The altered column name 'add' is not allowed because it is a reserved keyword")
163+ public void should_fail_if_altered_column_is_a_reserved_keyword() throws Exception {
164+ alterTable("test")
165+ .alterColumn("add").type(DataType.ascii()).getQueryString();
166+ }
167+
168+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
169+ expectedExceptionsMessageRegExp = "The renamed column name 'add' is not allowed because it is a reserved keyword")
170+ public void should_fail_if_renamed_column_is_a_reserved_keyword() throws Exception {
171+ alterTable("test")
172+ .renameColumn("add");
173+ }
174+
175+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
176+ expectedExceptionsMessageRegExp = "The new column name 'add' is not allowed because it is a reserved keyword")
177+ public void should_fail_if_new_renamed_column_is_a_reserved_keyword() throws Exception {
178+ alterTable("test")
179+ .renameColumn("col").to("add");
180+ }
181+
182+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
183+ expectedExceptionsMessageRegExp = "The dropped column name 'add' is not allowed because it is a reserved keyword")
184+ public void should_fail_if_drop_column_is_a_reserved_keyword() throws Exception {
185+ alterTable("test")
186+ .dropColumn("add").getQueryString();
187+ }
188+
189+ @Test(groups = "unit")
190+ public void should_add_static_column() throws Exception {
191+ //When
192+ SchemaStatement statement = alterTable("test").addStaticColumn("stat").type(DataType.text());
193+
194+ //Then
195+ assertThat(statement.getQueryString()).isEqualTo("\n\tALTER TABLE test ADD stat text static");
196+ }
197+}
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompactionOptionsTest.java +157 −0
@@ -0,0 +1,157 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dateTieredStrategy;
23+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.leveledStrategy;
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.sizedTieredStategy;
25+import static com.datastax.driver.core.schemabuilder.TableOptions.CompactionOptions.DateTieredCompactionStrategyOptions.TimeStampResolution;
26+
27+public class CompactionOptionsTest {
28+
29+ @Test(groups = "unit")
30+ public void should_create_sized_tiered_compaction_options() throws Exception {
31+ //When
32+ final String built = sizedTieredStategy()
33+ .bucketLow(0.5)
34+ .bucketHigh(1.2)
35+ .coldReadsRatioToOmit(0.89)
36+ .enabled(true)
37+ .minThreshold(2)
38+ .maxThreshold(4)
39+ .minSSTableSizeInBytes(5000000L)
40+ .tombstoneCompactionIntervalInDay(3)
41+ .tombstoneThreshold(0.7)
42+ .uncheckedTombstoneCompaction(true)
43+ .build();
44+
45+ //Then
46+ assertThat(built).isEqualTo("{'class' : 'SizeTieredCompactionStrategy', " +
47+ "'enabled' : true, " +
48+ "'tombstone_compaction_interval' : 3, " +
49+ "'tombstone_threshold' : 0.7, " +
50+ "'unchecked_tombstone_compaction' : true, " +
51+ "'bucket_high' : 1.2, " +
52+ "'bucket_low' : 0.5, " +
53+ "'cold_reads_to_omit' : 0.89, " +
54+ "'min_threshold' : 2, " +
55+ "'max_threshold' : 4, " +
56+ "'min_sstable_size' : 5000000}");
57+ }
58+
59+ @Test(groups = "unit")
60+ public void should_create_leveled_compaction_option() throws Exception {
61+ //When
62+ final String built = leveledStrategy()
63+ .enabled(true)
64+ .ssTableSizeInMB(160)
65+ .tombstoneCompactionIntervalInDay(3)
66+ .tombstoneThreshold(0.7)
67+ .uncheckedTombstoneCompaction(true)
68+ .build();
69+
70+ //Then
71+ assertThat(built).isEqualTo("{'class' : 'LeveledCompactionStrategy', " +
72+ "'enabled' : true, " +
73+ "'tombstone_compaction_interval' : 3, " +
74+ "'tombstone_threshold' : 0.7, " +
75+ "'unchecked_tombstone_compaction' : true, " +
76+ "'sstable_size_in_mb' : 160}");
77+ }
78+
79+ @Test(groups = "unit")
80+ public void should_create_date_tiered_compaction_option() throws Exception {
81+ //When
82+ String built = dateTieredStrategy()
83+ .baseTimeSeconds(7200)
84+ .enabled(true)
85+ .maxSSTableAgeDays(400)
86+ .minThreshold(2)
87+ .maxThreshold(4)
88+ .timestampResolution(TimeStampResolution.MICROSECONDS)
89+ .tombstoneCompactionIntervalInDay(3)
90+ .tombstoneThreshold(0.7)
91+ .uncheckedTombstoneCompaction(true)
92+ .build();
93+
94+ //Then
95+ assertThat(built).isEqualTo("{'class' : 'DateTieredCompactionStrategy', " +
96+ "'enabled' : true, " +
97+ "'tombstone_compaction_interval' : 3, " +
98+ "'tombstone_threshold' : 0.7, " +
99+ "'unchecked_tombstone_compaction' : true, " +
100+ "'base_time_seconds' : 7200, " +
101+ "'max_sstable_age_days' : 400, " +
102+ "'min_threshold' : 2, " +
103+ "'max_threshold' : 4, " +
104+ "'timestamp_resolution' : 'MICROSECONDS'}");
105+ }
106+
107+ @Test(groups = "unit")
108+ public void should_handle_freeform_options() {
109+ //When
110+ String built = dateTieredStrategy()
111+ .freeformOption("foo", "bar")
112+ .freeformOption("baz", 1)
113+ .build();
114+
115+ //Then
116+ assertThat(built).isEqualTo("{'class' : 'DateTieredCompactionStrategy', " +
117+ "'foo' : 'bar', " +
118+ "'baz' : 1}");
119+
120+ }
121+
122+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
123+ public void should_throw_exception_if_cold_read_ratio_out_of_range() throws Exception {
124+ sizedTieredStategy()
125+ .bucketLow(0.5)
126+ .bucketHigh(1.2)
127+ .coldReadsRatioToOmit(1.89)
128+ .build();
129+ }
130+
131+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
132+ public void should_throw_exception_if_cold_read_ratio_negative() throws Exception {
133+ sizedTieredStategy()
134+ .bucketLow(0.5)
135+ .bucketHigh(1.2)
136+ .coldReadsRatioToOmit(-1.0)
137+ .build();
138+ }
139+
140+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
141+ public void should_throw_exception_if_tombstone_threshold_out_of_range() throws Exception {
142+ sizedTieredStategy()
143+ .bucketLow(0.5)
144+ .bucketHigh(1.2)
145+ .tombstoneThreshold(1.89)
146+ .build();
147+ }
148+
149+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
150+ public void should_throw_exception_if_tombstone_threshold_negative() throws Exception {
151+ sizedTieredStategy()
152+ .bucketLow(0.5)
153+ .bucketHigh(1.2)
154+ .coldReadsRatioToOmit(-1.0)
155+ .build();
156+ }
157+}
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CompressionOptionsTest.java +64 −0
@@ -0,0 +1,64 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.deflate;
23+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.lz4;
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.noCompression;
25+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.snappy;
26+
27+public class CompressionOptionsTest {
28+
29+ @Test(groups = "unit")
30+ public void should_build_compressions_options_for_lz4() throws Exception {
31+ //When
32+ final String built = lz4().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build();
33+
34+ //Then
35+ assertThat(built).isEqualTo("{'sstable_compression' : 'LZ4Compressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}");
36+ }
37+
38+ @Test(groups = "unit")
39+ public void should_create_snappy_compressions_options() throws Exception {
40+ //When
41+ final String built = snappy().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build();
42+
43+ //Then
44+ assertThat(built).isEqualTo("{'sstable_compression' : 'SnappyCompressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}");
45+ }
46+
47+ @Test(groups = "unit")
48+ public void should_create_deflate_compressions_options() throws Exception {
49+ //When
50+ final String built = deflate().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build();
51+
52+ //Then
53+ assertThat(built).isEqualTo("{'sstable_compression' : 'DeflateCompressor', 'chunk_length_kb' : 128, 'crc_check_chance' : 0.6}");
54+ }
55+
56+ @Test(groups = "unit")
57+ public void should_create_no_compressions_options() throws Exception {
58+ //When
59+ final String built = noCompression().withChunkLengthInKb(128).withCRCCheckChance(0.6D).build();
60+
61+ //Then
62+ assertThat(built).isEqualTo("{'sstable_compression' : ''}");
63+ }
64+}
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateIndexTest.java +44 −0
@@ -0,0 +1,44 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createIndex;
23+
24+public class CreateIndexTest {
25+
26+ @Test(groups = "unit")
27+ public void should_create_index() throws Exception {
28+ //Given //When
29+ SchemaStatement statement = createIndex("myIndex").ifNotExists().onTable("ks", "test").andColumn("col");
30+
31+ //Then
32+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE INDEX IF NOT EXISTS myIndex ON ks.test(col)");
33+ }
34+
35+ @Test(groups = "unit")
36+ public void should_create_index_on_keys_of_map_column() throws Exception {
37+ //Given //When
38+ SchemaStatement statement = createIndex("myIndex").ifNotExists().onTable("ks", "test").andKeysOfColumn("col");
39+
40+ //Then
41+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE INDEX IF NOT EXISTS myIndex ON ks.test(KEYS(col))");
42+ }
43+
44+}
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTest.java +610 −0
@@ -0,0 +1,610 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import com.datastax.driver.core.DataType;
23+
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*;
25+
26+/**
27+ * Note: some addColumn variants are covered in {@link CreateTypeTest}.
28+ */
29+public class CreateTest {
30+
31+ @Test(groups = "unit")
32+ public void should_create_simple_table() throws Exception {
33+ //When
34+ SchemaStatement statement = createTable("test")
35+ .addPartitionKey("id", DataType.bigint())
36+ .addColumn("name", DataType.text());
37+
38+ //Then
39+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
40+ "id bigint,\n\t\t" +
41+ "name text,\n\t\t" +
42+ "PRIMARY KEY(id))");
43+ }
44+
45+ @Test(groups = "unit")
46+ public void should_create_table_with_udt_partition_key() throws Exception {
47+ //When
48+ SchemaStatement statement = createTable("test")
49+ .addUDTPartitionKey("u", frozen("user"));
50+
51+ //Then
52+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
53+ "u frozen<user>,\n\t\t" +
54+ "PRIMARY KEY(u))"
55+ );
56+ }
57+
58+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class)
59+ public void should_fail_when_creating_table_without_partition_key() throws Exception {
60+ createTable("test").addColumn("name", DataType.text()).getQueryString();
61+ }
62+
63+ @Test(groups = "unit")
64+ public void should_create_simple_table_if_not_exists() throws Exception {
65+ //When
66+ SchemaStatement statement = createTable("test")
67+ .ifNotExists()
68+ .addPartitionKey("id", DataType.bigint())
69+ .addColumn("name", DataType.text());
70+ //Then
71+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE IF NOT EXISTS test(\n\t\t" +
72+ "id bigint,\n\t\t" +
73+ "name text,\n\t\t" +
74+ "PRIMARY KEY(id))");
75+ }
76+
77+ @Test(groups = "unit")
78+ public void should_create_simple_table_with_keyspace() throws Exception {
79+ //When
80+ SchemaStatement statement = createTable("ks", "test")
81+ .addPartitionKey("id", DataType.bigint())
82+ .addColumn("name", DataType.text());
83+ //Then
84+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE ks.test(\n\t\t" +
85+ "id bigint,\n\t\t" +
86+ "name text,\n\t\t" +
87+ "PRIMARY KEY(id))");
88+ }
89+
90+ @Test(groups = "unit")
91+ public void should_create_simple_table_with_list() throws Exception {
92+ //When
93+ SchemaStatement statement = createTable("test")
94+ .addPartitionKey("id", DataType.bigint())
95+ .addColumn("friends", DataType.list(DataType.text()));
96+
97+ //Then
98+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
99+ "id bigint,\n\t\t" +
100+ "friends list<text>,\n\t\t" +
101+ "PRIMARY KEY(id))");
102+ }
103+
104+ @Test(groups = "unit")
105+ public void should_create_simple_table_with_set() throws Exception {
106+ //When
107+ SchemaStatement statement = createTable("test")
108+ .addPartitionKey("id", DataType.bigint())
109+ .addColumn("friends", DataType.set(DataType.text()));
110+
111+ //Then
112+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
113+ "id bigint,\n\t\t" +
114+ "friends set<text>,\n\t\t" +
115+ "PRIMARY KEY(id))");
116+ }
117+
118+ @Test(groups = "unit")
119+ public void should_create_simple_table_with_map() throws Exception {
120+ //When
121+ SchemaStatement statement = createTable("test")
122+ .addPartitionKey("id", DataType.bigint())
123+ .addColumn("friends", DataType.map(DataType.cint(), DataType.text()));
124+
125+ //Then
126+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
127+ "id bigint,\n\t\t" +
128+ "friends map<int, text>,\n\t\t" +
129+ "PRIMARY KEY(id))");
130+ }
131+
132+ @Test(groups = "unit")
133+ public void should_create_table_with_clustering_keys() throws Exception {
134+ //When
135+ SchemaStatement statement = createTable("test")
136+ .addPartitionKey("id", DataType.bigint())
137+ .addClusteringColumn("col1", DataType.uuid())
138+ .addClusteringColumn("col2", DataType.uuid())
139+ .addColumn("name", DataType.text());
140+
141+ //Then
142+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
143+ "id bigint,\n\t\t" +
144+ "col1 uuid,\n\t\t" +
145+ "col2 uuid,\n\t\t" +
146+ "name text,\n\t\t" +
147+ "PRIMARY KEY(id, col1, col2))");
148+ }
149+
150+ @Test(groups = "unit")
151+ public void should_create_table_with_udt_clustering_keys() throws Exception {
152+ //When
153+ SchemaStatement statement = createTable("test")
154+ .addPartitionKey("id", DataType.bigint())
155+ .addClusteringColumn("col1", DataType.uuid())
156+ .addUDTClusteringColumn("col2", frozen("address"))
157+ .addColumn("name", DataType.text());
158+
159+ //Then
160+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
161+ "id bigint,\n\t\t" +
162+ "col1 uuid,\n\t\t" +
163+ "col2 frozen<address>,\n\t\t" +
164+ "name text,\n\t\t" +
165+ "PRIMARY KEY(id, col1, col2))");
166+ }
167+
168+ @Test(groups = "unit")
169+ public void should_create_table_with_composite_partition_key() throws Exception {
170+ //When
171+ SchemaStatement statement = createTable("test")
172+ .addPartitionKey("id1", DataType.bigint())
173+ .addPartitionKey("id2", DataType.text())
174+ .addColumn("name", DataType.text());
175+
176+ //Then
177+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
178+ "id1 bigint,\n\t\t" +
179+ "id2 text,\n\t\t" +
180+ "name text,\n\t\t" +
181+ "PRIMARY KEY((id1, id2)))");
182+ }
183+
184+ @Test(groups = "unit")
185+ public void should_create_table_with_composite_partition_key_and_clustering_keys() throws Exception {
186+ //When
187+ SchemaStatement statement = createTable("test")
188+ .addPartitionKey("id1", DataType.bigint())
189+ .addPartitionKey("id2", DataType.text())
190+ .addClusteringColumn("col1", DataType.uuid())
191+ .addClusteringColumn("col2", DataType.uuid())
192+ .addColumn("name", DataType.text());
193+
194+ //Then
195+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
196+ "id1 bigint,\n\t\t" +
197+ "id2 text,\n\t\t" +
198+ "col1 uuid,\n\t\t" +
199+ "col2 uuid,\n\t\t" +
200+ "name text,\n\t\t" +
201+ "PRIMARY KEY((id1, id2), col1, col2))");
202+ }
203+
204+ @Test(groups = "unit")
205+ public void should_create_table_with_static_column() throws Exception {
206+ //When
207+ SchemaStatement statement = createTable("test")
208+ .addPartitionKey("id", DataType.bigint())
209+ .addClusteringColumn("col", DataType.uuid())
210+ .addStaticColumn("bucket", DataType.cint())
211+ .addColumn("name", DataType.text());
212+
213+ //Then
214+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
215+ "id bigint,\n\t\t" +
216+ "col uuid,\n\t\t" +
217+ "bucket int static,\n\t\t" +
218+ "name text,\n\t\t" +
219+ "PRIMARY KEY(id, col))");
220+ }
221+
222+ @Test(groups = "unit")
223+ public void should_create_table_with_udt_static_column() throws Exception {
224+ //When
225+ SchemaStatement statement = createTable("test")
226+ .addPartitionKey("id", DataType.bigint())
227+ .addClusteringColumn("col", DataType.uuid())
228+ .addUDTStaticColumn("bucket", frozen("address"))
229+ .addColumn("name", DataType.text());
230+
231+ //Then
232+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
233+ "id bigint,\n\t\t" +
234+ "col uuid,\n\t\t" +
235+ "bucket frozen<address> static,\n\t\t" +
236+ "name text,\n\t\t" +
237+ "PRIMARY KEY(id, col))");
238+ }
239+
240+ @Test(groups = "unit")
241+ public void should_create_table_with_clustering_order() throws Exception {
242+ //When
243+ SchemaStatement statement = createTable("test")
244+ .addPartitionKey("id", DataType.bigint())
245+ .addClusteringColumn("col1", DataType.uuid())
246+ .addClusteringColumn("col2", DataType.uuid())
247+ .addColumn("name", DataType.text())
248+ .withOptions()
249+ .clusteringOrder("col1", Direction.ASC)
250+ .clusteringOrder("col2", Direction.DESC);
251+
252+ //Then
253+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
254+ "id bigint,\n\t\t" +
255+ "col1 uuid,\n\t\t" +
256+ "col2 uuid,\n\t\t" +
257+ "name text,\n\t\t" +
258+ "PRIMARY KEY(id, col1, col2))\n\t" +
259+ "WITH CLUSTERING ORDER BY(col1 ASC, col2 DESC)");
260+ }
261+
262+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
263+ public void should_fail_when_blank_clustering_order_column_provided() throws Exception {
264+ createTable("test")
265+ .addPartitionKey("id", DataType.bigint())
266+ .addClusteringColumn("col1", DataType.uuid())
267+ .addClusteringColumn("col2", DataType.uuid())
268+ .addColumn("name", DataType.text())
269+ .withOptions().clusteringOrder("", Direction.DESC);
270+ }
271+
272+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
273+ public void should_fail_when_clustering_order_column_does_not_match_declared_clustering_keys() throws Exception {
274+ createTable("test")
275+ .addPartitionKey("id", DataType.bigint())
276+ .addClusteringColumn("col1", DataType.uuid())
277+ .addClusteringColumn("col2", DataType.uuid())
278+ .addColumn("name", DataType.text())
279+ .withOptions().clusteringOrder("col3", Direction.ASC);
280+ }
281+
282+ @Test(groups = "unit")
283+ public void should_create_table_with_compact_storage() throws Exception {
284+ //When
285+ SchemaStatement statement = createTable("test")
286+ .addPartitionKey("id", DataType.bigint())
287+ .addClusteringColumn("col1", DataType.uuid())
288+ .addClusteringColumn("col2", DataType.uuid())
289+ .addColumn("name", DataType.text())
290+ .withOptions()
291+ .compactStorage();
292+
293+ //Then
294+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
295+ "id bigint,\n\t\t" +
296+ "col1 uuid,\n\t\t" +
297+ "col2 uuid,\n\t\t" +
298+ "name text,\n\t\t" +
299+ "PRIMARY KEY(id, col1, col2))\n\t" +
300+ "WITH COMPACT STORAGE");
301+ }
302+
303+ @Test(groups = "unit")
304+ public void should_create_table_with_all_options() throws Exception {
305+ //When
306+ SchemaStatement statement = createTable("test")
307+ .addPartitionKey("id", DataType.bigint())
308+ .addClusteringColumn("col1", DataType.uuid())
309+ .addClusteringColumn("col2", DataType.uuid())
310+ .addColumn("name", DataType.text())
311+ .withOptions()
312+ .clusteringOrder("col1", Direction.ASC)
313+ .clusteringOrder("col2", Direction.DESC)
314+ .compactStorage()
315+ .bloomFilterFPChance(0.01)
316+ .caching(Caching.ROWS_ONLY)
317+ .comment("This is a comment")
318+ .compactionOptions(leveledStrategy().ssTableSizeInMB(160))
319+ .compressionOptions(lz4())
320+ .dcLocalReadRepairChance(0.21)
321+ .defaultTimeToLive(100)
322+ .gcGraceSeconds(9999)
323+ .minIndexInterval(64)
324+ .maxIndexInterval(512)
325+ .memtableFlushPeriodInMillis(12)
326+ .populateIOCacheOnFlush(true)
327+ .readRepairChance(0.05)
328+ .replicateOnWrite(true)
329+ .speculativeRetry(always());
330+
331+ //Then
332+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
333+ "id bigint,\n\t\t" +
334+ "col1 uuid,\n\t\t" +
335+ "col2 uuid,\n\t\t" +
336+ "name text,\n\t\tPRIMARY KEY(id, col1, col2))\n\t" +
337+ "WITH caching = 'rows_only' " +
338+ "AND bloom_filter_fp_chance = 0.01 " +
339+ "AND comment = 'This is a comment' " +
340+ "AND compression = {'sstable_compression' : 'LZ4Compressor'} " +
341+ "AND compaction = {'class' : 'LeveledCompactionStrategy', 'sstable_size_in_mb' : 160} " +
342+ "AND dclocal_read_repair_chance = 0.21 " +
343+ "AND default_time_to_live = 100 " +
344+ "AND gc_grace_seconds = 9999 " +
345+ "AND min_index_interval = 64 " +
346+ "AND max_index_interval = 512 " +
347+ "AND memtable_flush_period_in_ms = 12 " +
348+ "AND populate_io_cache_on_flush = true " +
349+ "AND read_repair_chance = 0.05 " +
350+ "AND replicate_on_write = true " +
351+ "AND speculative_retry = 'ALWAYS' AND CLUSTERING ORDER BY(col1 ASC, col2 DESC) AND COMPACT STORAGE");
352+ }
353+
354+ @Test(groups = "unit")
355+ public void should_build_table_with_new_caching_options() throws Exception {
356+ //When
357+ SchemaStatement statement = createTable("test")
358+ .addPartitionKey("id", DataType.bigint())
359+ .addColumn("name", DataType.text())
360+ .withOptions()
361+ .caching(KeyCaching.ALL, rows(100));
362+
363+ //Then
364+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
365+ "id bigint,\n\t\t" +
366+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
367+ "WITH caching = {'keys' : 'all', 'rows_per_partition' : 100}");
368+
369+ //When
370+ statement = createTable("test")
371+ .addPartitionKey("id", DataType.bigint())
372+ .addColumn("name", DataType.text())
373+ .withOptions()
374+ .caching(KeyCaching.ALL, allRows());
375+
376+ //Then
377+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
378+ "id bigint,\n\t\t" +
379+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
380+ "WITH caching = {'keys' : 'all', 'rows_per_partition' : 'all'}");
381+ }
382+
383+ @Test(groups = "unit")
384+ public void should_build_table_with_custom_option() throws Exception {
385+ //When
386+ SchemaStatement statement = createTable("test")
387+ .addPartitionKey("id", DataType.bigint())
388+ .addColumn("name", DataType.text())
389+ .withOptions()
390+ .freeformOption("key1", "value1")
391+ .freeformOption("key2", 1.0);
392+
393+ //Then
394+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
395+ "id bigint,\n\t\t" +
396+ "name text,\n\t\tPRIMARY KEY(id))\n\t" +
397+ "WITH key1 = 'value1' " +
398+ "AND key2 = 1.0");
399+ }
400+
401+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class)
402+ public void should_fail_when_both_caching_versions() throws Exception {
403+ createTable("test")
404+ .addPartitionKey("id", DataType.bigint())
405+ .addColumn("name", DataType.text())
406+ .withOptions()
407+ .caching(Caching.KEYS_ONLY)
408+ .caching(KeyCaching.ALL, allRows()).getQueryString();
409+ }
410+
411+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
412+ public void should_fail_when_negative_rows_per_partition() throws Exception {
413+ createTable("test")
414+ .addPartitionKey("id", DataType.bigint())
415+ .addColumn("name", DataType.text())
416+ .withOptions()
417+ .caching(KeyCaching.ALL, rows(-3));
418+ }
419+
420+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
421+ public void should_fail_when_read_repair_chance_out_of_bound() throws Exception {
422+ createTable("test")
423+ .addPartitionKey("id", DataType.bigint())
424+ .addColumn("name", DataType.text())
425+ .withOptions()
426+ .readRepairChance(1.3);
427+ }
428+
429+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
430+ public void should_fail_when_read_repair_chance_negative() throws Exception {
431+ createTable("test")
432+ .addPartitionKey("id", DataType.bigint())
433+ .addColumn("name", DataType.text())
434+ .withOptions()
435+ .readRepairChance(-1.3);
436+ }
437+
438+ @Test(groups = "unit")
439+ public void should_create_table_with_speculative_retry_none() throws Exception {
440+ //When
441+ SchemaStatement statement = createTable("test")
442+ .addPartitionKey("id", DataType.bigint())
443+ .addColumn("name", DataType.text())
444+ .withOptions()
445+ .speculativeRetry(noSpeculativeRetry());
446+
447+ //Then
448+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
449+ "id bigint,\n\t\t" +
450+ "name text,\n\t\t" +
451+ "PRIMARY KEY(id))\n\t" +
452+ "WITH speculative_retry = 'NONE'");
453+ }
454+
455+ @Test(groups = "unit")
456+ public void should_create_table_with_speculative_retry_in_percentile() throws Exception {
457+ //When
458+ SchemaStatement statement = createTable("test")
459+ .addPartitionKey("id", DataType.bigint())
460+ .addColumn("name", DataType.text())
461+ .withOptions()
462+ .speculativeRetry(percentile(95));
463+
464+ //Then
465+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
466+ "id bigint,\n\t\t" +
467+ "name text,\n\t\t" +
468+ "PRIMARY KEY(id))\n\t" +
469+ "WITH speculative_retry = '95percentile'");
470+ }
471+
472+ @Test(groups = "unit")
473+ public void should_create_table_with_speculative_retry_in_milli_secs() throws Exception {
474+ //When
475+ SchemaStatement statement = createTable("test")
476+ .addPartitionKey("id", DataType.bigint())
477+ .addColumn("name", DataType.text())
478+ .withOptions()
479+ .speculativeRetry(millisecs(12));
480+
481+ //Then
482+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TABLE test(\n\t\t" +
483+ "id bigint,\n\t\t" +
484+ "name text,\n\t\t" +
485+ "PRIMARY KEY(id))\n\t" +
486+ "WITH speculative_retry = '12ms'");
487+ }
488+
489+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
490+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and clustering keys at the same time")
491+ public void should_fail_if_same_partition_and_clustering_column() throws Exception {
492+ createTable("test")
493+ .addPartitionKey("pk", DataType.bigint())
494+ .addClusteringColumn("pk", DataType.bigint()).getQueryString();
495+ }
496+
497+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
498+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and simple columns at the same time")
499+ public void should_fail_if_same_partition_and_simple_column() throws Exception {
500+ createTable("test")
501+ .addPartitionKey("pk", DataType.bigint())
502+ .addColumn("pk", DataType.text()).getQueryString();
503+ }
504+
505+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
506+ expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and simple columns at the same time")
507+ public void should_fail_if_same_clustering_and_simple_column() throws Exception {
508+ createTable("test")
509+ .addPartitionKey("pk", DataType.bigint())
510+ .addClusteringColumn("cluster", DataType.bigint())
511+ .addColumn("cluster", DataType.text()).getQueryString();
512+ }
513+
514+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
515+ expectedExceptionsMessageRegExp = "The '\\[pk\\]' columns can not be declared as partition keys and static columns at the same time")
516+ public void should_fail_if_same_partition_and_static_column() throws Exception {
517+ createTable("test")
518+ .addPartitionKey("pk", DataType.bigint())
519+ .addStaticColumn("pk", DataType.text()).getQueryString();
520+ }
521+
522+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
523+ expectedExceptionsMessageRegExp = "The '\\[cluster\\]' columns can not be declared as clustering keys and static columns at the same time")
524+ public void should_fail_if_same_clustering_and_static_column() throws Exception {
525+ createTable("test")
526+ .addPartitionKey("pk", DataType.bigint())
527+ .addClusteringColumn("cluster", DataType.bigint())
528+ .addStaticColumn("cluster", DataType.text()).getQueryString();
529+ }
530+
531+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
532+ expectedExceptionsMessageRegExp = "The '\\[col\\]' columns can not be declared as simple columns and static columns at the same time")
533+ public void should_fail_if_same_simple_and_static_column() throws Exception {
534+ createTable("test")
535+ .addPartitionKey("pk", DataType.bigint())
536+ .addClusteringColumn("cluster", DataType.uuid())
537+ .addColumn("col", DataType.bigint())
538+ .addStaticColumn("col", DataType.text()).getQueryString();
539+ }
540+
541+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
542+ expectedExceptionsMessageRegExp = "The table 'test' cannot declare static columns '\\[stat\\]' without clustering columns")
543+ public void should_fail_if_static_column_in_non_clustered_table() throws Exception {
544+ createTable("test")
545+ .addPartitionKey("pk", DataType.bigint())
546+ .addStaticColumn("stat", DataType.text()).getQueryString();
547+ }
548+
549+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
550+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
551+ public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
552+ createTable("add", "test")
553+ .addPartitionKey("pk", DataType.bigint())
554+ .addColumn("col", DataType.text()).getQueryString();
555+ }
556+
557+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
558+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
559+ public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
560+ createTable("add")
561+ .addPartitionKey("pk", DataType.bigint())
562+ .addColumn("col", DataType.text()).getQueryString();
563+ }
564+
565+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
566+ expectedExceptionsMessageRegExp = "The partition key name 'add' is not allowed because it is a reserved keyword")
567+ public void should_fail_if_partition_key_is_a_reserved_keyword() throws Exception {
568+ createTable("test")
569+ .addPartitionKey("add", DataType.bigint())
570+ .addColumn("col", DataType.text()).getQueryString();
571+ }
572+
573+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
574+ expectedExceptionsMessageRegExp = "The clustering column name 'add' is not allowed because it is a reserved keyword")
575+ public void should_fail_if_clustering_key_is_a_reserved_keyword() throws Exception {
576+ createTable("test")
577+ .addPartitionKey("pk", DataType.bigint())
578+ .addClusteringColumn("add", DataType.uuid())
579+ .addColumn("col", DataType.text()).getQueryString();
580+ }
581+
582+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
583+ expectedExceptionsMessageRegExp = "The column name 'add' is not allowed because it is a reserved keyword")
584+ public void should_fail_if_simple_column_is_a_reserved_keyword() throws Exception {
585+ createTable("test")
586+ .addPartitionKey("pk", DataType.bigint())
587+ .addClusteringColumn("cluster", DataType.uuid())
588+ .addColumn("add", DataType.text()).getQueryString();
589+ }
590+
591+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
592+ expectedExceptionsMessageRegExp = "The static column name 'add' is not allowed because it is a reserved keyword")
593+ public void should_fail_if_static_column_is_a_reserved_keyword() throws Exception {
594+ createTable("test")
595+ .addPartitionKey("pk", DataType.bigint())
596+ .addClusteringColumn("cluster", DataType.uuid())
597+ .addStaticColumn("add", DataType.text())
598+ .addColumn("col", DataType.text()).getQueryString();
599+ }
600+
601+ @Test(groups = "unit", expectedExceptions = IllegalStateException.class,
602+ expectedExceptionsMessageRegExp = "Cannot create table 'test' with compact storage and static columns '\\[stat\\]'")
603+ public void should_fail_creating_table_with_static_columns_and_compact_storage() throws Exception {
604+ createTable("test")
605+ .addPartitionKey("pk", DataType.bigint())
606+ .addClusteringColumn("cluster", DataType.uuid())
607+ .addStaticColumn("stat", DataType.text())
608+ .withOptions().compactStorage().getQueryString();
609+ }
610+}
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/CreateTypeTest.java +147 −0
@@ -0,0 +1,147 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import com.datastax.driver.core.DataType;
23+
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createType;
25+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.frozen;
26+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.udtLiteral;
27+
28+public class CreateTypeTest {
29+
30+ @Test(groups = "unit")
31+ public void should_create_UDT() throws Exception {
32+ //When
33+ SchemaStatement statement = createType("ks", "myType")
34+ .addColumn("col1", DataType.text())
35+ .addColumn("col2", DataType.bigint());
36+
37+ //Then
38+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
39+ "col1 text,\n\t\t" +
40+ "col2 bigint)");
41+ }
42+
43+ @Test(groups = "unit")
44+ public void should_create_UDT_if_not_exists() throws Exception {
45+ //When
46+ SchemaStatement statement = createType("myType")
47+ .ifNotExists()
48+ .addColumn("col1", DataType.text())
49+ .addColumn("col2", DataType.bigint());
50+
51+ //Then
52+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE IF NOT EXISTS myType(\n\t\t" +
53+ "col1 text,\n\t\t" +
54+ "col2 bigint)");
55+ }
56+
57+ @Test(groups = "unit")
58+ public void should_create_simple_UDT_column() throws Exception {
59+ //When
60+ SchemaStatement statement = createType("ks", "myType")
61+ .addColumn("col1", DataType.text())
62+ .addUDTColumn("my_udt", frozen("address"));
63+
64+ //Then
65+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
66+ "col1 text,\n\t\t" +
67+ "my_udt frozen<address>)");
68+ }
69+
70+ @Test(groups = "unit")
71+ public void should_create_list_UDT_column() throws Exception {
72+ //When
73+ SchemaStatement statement = createType("ks", "myType")
74+ .addColumn("col1", DataType.text())
75+ .addUDTListColumn("my_udt", frozen("address"));
76+
77+ //Then
78+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
79+ "col1 text,\n\t\t" +
80+ "my_udt list<frozen<address>>)");
81+ }
82+
83+ @Test(groups = "unit")
84+ public void should_create_set_UDT_column() throws Exception {
85+ //When
86+ SchemaStatement statement = createType("ks", "myType")
87+ .addColumn("col1", DataType.text())
88+ .addUDTSetColumn("my_udt", frozen("address"));
89+
90+ //Then
91+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
92+ "col1 text,\n\t\t" +
93+ "my_udt set<frozen<address>>)");
94+ }
95+
96+ @Test(groups = "unit")
97+ public void should_create_key_UDT_map_column() throws Exception {
98+ //When
99+ SchemaStatement statement = createType("ks", "myType")
100+ .addColumn("col1", DataType.text())
101+ .addUDTMapColumn("my_udt", frozen("address"), DataType.text());
102+
103+ //Then
104+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
105+ "col1 text,\n\t\t" +
106+ "my_udt map<frozen<address>, text>)");
107+ }
108+
109+ @Test(groups = "unit")
110+ public void should_create_value_UDT_map_column() throws Exception {
111+ //When
112+ SchemaStatement statement = createType("ks", "myType")
113+ .addColumn("col1", DataType.text())
114+ .addUDTMapColumn("my_udt", DataType.cint(), frozen("address"));
115+
116+ //Then
117+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
118+ "col1 text,\n\t\t" +
119+ "my_udt map<int, frozen<address>>)");
120+ }
121+
122+ @Test(groups = "unit")
123+ public void should_create_key_value_UDT_map_column() throws Exception {
124+ //When
125+ SchemaStatement statement = createType("ks", "myType")
126+ .addColumn("col1", DataType.text())
127+ .addUDTMapColumn("my_udt", frozen("coords"), frozen("address"));
128+
129+ //Then
130+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
131+ "col1 text,\n\t\t" +
132+ "my_udt map<frozen<coords>, frozen<address>>)");
133+ }
134+
135+ @Test(groups = "unit")
136+ public void should_create_column_with_manual_type() throws Exception {
137+ //When
138+ SchemaStatement statement = createType("ks", "myType")
139+ .addColumn("col1", DataType.text())
140+ .addUDTColumn("my_udt", udtLiteral("frozen<address>"));
141+
142+ //Then
143+ assertThat(statement.getQueryString()).isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" +
144+ "col1 text,\n\t\t" +
145+ "my_udt frozen<address>)");
146+ }
147+}
No newline at the end of the file
added driver-core/src/test/java/com/datastax/driver/core/schemabuilder/DropTest.java +120 −0
@@ -0,0 +1,120 @@
1+/*
2+ * Copyright (C) 2012-2014 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.schemabuilder;
17+
18+import org.testng.annotations.Test;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropIndex;
23+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropTable;
24+import static com.datastax.driver.core.schemabuilder.SchemaBuilder.dropType;
25+
26+public class DropTest {
27+
28+ @Test(groups = "unit")
29+ public void should_drop_table() throws Exception {
30+ //When
31+ SchemaStatement statement = dropTable("test");
32+
33+ //Then
34+ assertThat(statement.getQueryString()).isEqualTo("DROP TABLE test");
35+ }
36+
37+ @Test(groups = "unit")
38+ public void should_drop_table_with_keyspace() throws Exception {
39+ //When
40+ SchemaStatement statement = dropTable("ks", "test");
41+
42+ //Then
43+ assertThat(statement.getQueryString()).isEqualTo("DROP TABLE ks.test");
44+ }
45+
46+ @Test(groups = "unit")
47+ public void should_drop_table_with_keyspace_if_exists() throws Exception {
48+ //When
49+ SchemaStatement statement = dropTable("ks", "test").ifExists();
50+
51+ //Then
52+ assertThat(statement.getQueryString()).isEqualTo("DROP TABLE IF EXISTS ks.test");
53+ }
54+
55+ @Test(groups = "unit")
56+ public void should_drop_type() throws Exception {
57+ //When
58+ SchemaStatement statement = dropType("test");
59+
60+ //Then
61+ assertThat(statement.getQueryString()).isEqualTo("DROP TYPE test");
62+ }
63+
64+ @Test(groups = "unit")
65+ public void should_drop_type_with_keyspace() throws Exception {
66+ //When
67+ SchemaStatement statement = dropType("ks", "test");
68+
69+ //Then
70+ assertThat(statement.getQueryString()).isEqualTo("DROP TYPE ks.test");
71+ }
72+
73+ @Test(groups = "unit")
74+ public void should_drop_type_with_keyspace_if_exists() throws Exception {
75+ //When
76+ SchemaStatement statement = dropType("ks", "test").ifExists();
77+
78+ //Then
79+ assertThat(statement.getQueryString()).isEqualTo("DROP TYPE IF EXISTS ks.test");
80+ }
81+
82+ @Test(groups = "unit")
83+ public void should_drop_index() throws Exception {
84+ //When
85+ SchemaStatement statement = dropIndex("test");
86+
87+ //Then
88+ assertThat(statement.getQueryString()).isEqualTo("DROP INDEX test");
89+ }
90+
91+ @Test(groups = "unit")
92+ public void should_drop_index_with_keyspace() throws Exception {
93+ //When
94+ SchemaStatement statement = dropIndex("ks", "test");
95+
96+ //Then
97+ assertThat(statement.getQueryString()).isEqualTo("DROP INDEX ks.test");
98+ }
99+
100+ @Test(groups = "unit")
101+ public void should_drop_index_with_keyspace_if_exists() throws Exception {
102+ //When
103+ SchemaStatement statement = dropIndex("ks", "test").ifExists();
104+
105+ //Then
106+ assertThat(statement.getQueryString()).isEqualTo("DROP INDEX IF EXISTS ks.test");
107+ }
108+
109+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
110+ expectedExceptionsMessageRegExp = "The keyspace name 'add' is not allowed because it is a reserved keyword")
111+ public void should_fail_if_keyspace_name_is_a_reserved_keyword() throws Exception {
112+ dropTable("add", "test").getQueryString();
113+ }
114+
115+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class,
116+ expectedExceptionsMessageRegExp = "The table name 'add' is not allowed because it is a reserved keyword")
117+ public void should_fail_if_table_name_is_a_reserved_keyword() throws Exception {
118+ dropTable("add").getQueryString();
119+ }
120+}