Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *      Copyright (C) 2012 DataStax Inc.
   *
   *   Licensed under the Apache License, Version 2.0 (the "License");
   *   you may not use this file except in compliance with the License.
   *   You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *   Unless required by applicable law or agreed to in writing, software
  *   distributed under the License is distributed on an "AS IS" BASIS,
  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *   See the License for the specific language governing permissions and
  *   limitations under the License.
  */
 package com.datastax.driver.core.querybuilder;
 
 import java.util.*;
 
Static methods to build a CQL3 query.

The queries built by this builder will provide a value for the com.datastax.driver.core.Query.getRoutingKey() method only when a com.datastax.driver.core.TableMetadata is provided to the builder. It is thus advised to do so if a com.datastax.driver.core.policies.TokenAwarePolicy is in use.

The provider builders perform very little validation of the built query. There is thus no guarantee that a built query is valid, and it is definitively possible to create invalid queries.

Note that it could be convenient to use an 'import static' to use the methods of this class.

 
 public final class QueryBuilder {
 
     private QueryBuilder() {}

    
Start building a new SELECT query that selects the provided names. Note that select(c1, c2) is just a shortcut for select().column(c1).column(c2) .

Parameters:
columns the columns names that should be selected by the query.
Returns:
an in-construction SELECT query (you will need to provide at least a FROM clause to complete the query).
 
     public static Select.Builder select(String... columns) {
         return new Select.Builder(Arrays.asList((Object[])columns));
     }

    
Start building a new SELECT query.

Returns:
an in-construction SELECT query (you will need to provide a column selection and at least a FROM clause to complete the query).
 
     public static Select.Selection select() {
         return new Select.Selection();
     }

    
Start building a new INSERT query.

Parameters:
table the name of the table in which to insert.
Returns:
an in-construction INSERT query.
 
     public static Insert insertInto(String table) {
         return new Insert(nulltable);
     }

    
Start building a new INSERT query.

Parameters:
keyspace the name of the keyspace to use.
table the name of the table to insert into.
Returns:
an in-construction INSERT query.
 
     public static Insert insertInto(String keyspaceString table) {
         return new Insert(keyspacetable);
     }

    
Start building a new INSERT query.

Parameters:
table the name of the table to insert into.
Returns:
an in-construction INSERT query.
 
     public static Insert insertInto(TableMetadata table) {
         return new Insert(table);
     }

    
Start building a new UPDATE query.

Parameters:
table the name of the table to update.
Returns:
an in-construction UPDATE query (at least a SET and a WHERE clause needs to be provided to complete the query).
    public static Update update(String table) {
        return new Update(nulltable);
    }

    
Start building a new UPDATE query.

Parameters:
keyspace the name of the keyspace to use.
table the name of the table to update.
Returns:
an in-construction UPDATE query (at least a SET and a WHERE clause needs to be provided to complete the query).
    public static Update update(String keyspaceString table) {
        return new Update(keyspacetable);
    }

    
Start building a new UPDATE query.

Parameters:
table the name of the table to update.
Returns:
an in-construction UPDATE query (at least a SET and a WHERE clause needs to be provided to complete the query).
    public static Update update(TableMetadata table) {
        return new Update(table);
    }

    
Start building a new DELETE query that deletes the provided names.

Parameters:
columns the columns names that should be deleted by the query.
Returns:
an in-construction DELETE query (At least a FROM and a WHERE clause needs to be provided to complete the query).
    public static Delete.Builder delete(String... columns) {
        return new Delete.Builder(Arrays.asList((Object[])columns));
    }

    
Start building a new DELETE query.

Returns:
an in-construction SELECT query (you will need to provide a column selection and at least a FROM and a WHERE clause to complete the query).
    public static Delete.Selection delete() {
        return new Delete.Selection();
    }

    
Built a new BATCH query on the provided statements.

This method will build a logged batch (this is the default in CQL3). To create unlogged batches, use unloggedBatch(com.datastax.driver.core.Statement[]). Also note that for convenience, if the provided statements are counter statements, this method will create a COUNTER batch even though COUNTER batches are never logged (so for counters, using this method is effectively equivalent to using unloggedBatch(com.datastax.driver.core.Statement[])).

Parameters:
statements the statements to batch.
Returns:
a new Statement that batch statements.
    public static Batch batch(Statement... statements) {
        return new Batch(statementstrue);
    }

    
Built a new UNLOGGED BATCH query on the provided statements.

Compared to logged batches (the default), unlogged batch don't use the distributed batch log server side and as such are not guaranteed to be atomic. In other words, if an unlogged batch timeout, some of the batched statements may have been persisted while some have not. Unlogged batch will however be slightly faster than logged batch.

If the statements added to the batch are counter statements, the resulting batch will be a COUNTER one.

Parameters:
statements the statements to batch.
Returns:
a new Statement that batch statements without using the batch log.
    public static Batch unloggedBatch(Statement... statements) {
        return new Batch(statementsfalse);
    }

    
Creates a new TRUNCATE query.

Parameters:
table the name of the table to truncate.
Returns:
the truncation query.
    public static Truncate truncate(String table) {
        return new Truncate(nulltable);
    }

    
Creates a new TRUNCATE query.

Parameters:
keyspace the name of the keyspace to use.
table the name of the table to truncate.
Returns:
the truncation query.
    public static Truncate truncate(String keyspaceString table) {
        return new Truncate(keyspacetable);
    }

    
Creates a new TRUNCATE query.

Parameters:
table the table to truncate.
Returns:
the truncation query.
    public static Truncate truncate(TableMetadata table) {
        return new Truncate(table);
    }

    
Quotes a columnName to make it case sensitive.

Parameters:
columnName the column name to quote.
Returns:
the quoted column name.
    public static String quote(String columnName) {
        StringBuilder sb = new StringBuilder();
        sb.append("\"");
        Utils.appendName(columnNamesb);
        sb.append("\"");
        return sb.toString();
    }

    
The token of a column name.

Parameters:
columnName the column name to take the token of.
Returns:
"token(" + columnName + ")".
    public static String token(String columnName) {
        StringBuilder sb = new StringBuilder();
        sb.append("token(");
        Utils.appendName(columnNamesb);
        sb.append(")");
        return sb.toString();
    }

    
The token of column names.

This variant is most useful when the partition key is composite.

Parameters:
columnNames the column names to take the token of.
Returns:
a string representing the token of the provided column names.
    public static String token(String... columnNames) {
        StringBuilder sb = new StringBuilder();
        sb.append("token(");
        Utils.joinAndAppendNames(sb",", Arrays.asList((Object[])columnNames));
        sb.append(")");
        return sb.toString();
    }

    
Creates an "equal" where clause stating the provided column must be equal to the provided value.

Parameters:
name the column name
value the value
Returns:
the corresponding where clause.
    public static Clause eq(String nameObject value) {
        return new Clause.SimpleClause(name"="value);
    }

    
Create an "in" where clause stating the provided column must be equal to one of the provided values.

Parameters:
name the column name
values the values
Returns:
the corresponding where clause.
    public static Clause in(String nameObject... values) {
        return new Clause.InClause(name, Arrays.asList(values));
    }

    
Creates a "lesser than" where clause stating the provided column must be less than the provided value.

Parameters:
name the column name
value the value
Returns:
the corresponding where clause.
    public static Clause lt(String nameObject value) {
        return new Clause.SimpleClause(name"<"value);
    }

    
Creates a "lesser than or equal" where clause stating the provided column must be lesser than or equal to the provided value.

Parameters:
name the column name
value the value
Returns:
the corresponding where clause.
    public static Clause lte(String nameObject value) {
        return new Clause.SimpleClause(name"<="value);
    }

    
Creates a "greater than" where clause stating the provided column must be greater to the provided value.

Parameters:
name the column name
value the value
Returns:
the corresponding where clause.
    public static Clause gt(String nameObject value) {
        return new Clause.SimpleClause(name">"value);
    }

    
Creates a "greater than or equal" where clause stating the provided column must be greater than or equal to the provided value.

Parameters:
name the column name
value the value
Returns:
the corresponding where clause.
    public static Clause gte(String nameObject value) {
        return new Clause.SimpleClause(name">="value);
    }

    
Ascending ordering for the provided column.

Parameters:
columnName the column name
Returns:
the corresponding ordering
    public static Ordering asc(String columnName) {
        return new Ordering(columnNamefalse);
    }

    
Descending ordering for the provided column.

Parameters:
columnName the column name
Returns:
the corresponding ordering
    public static Ordering desc(String columnName) {
        return new Ordering(columnNametrue);
    }

    
Option to set the timestamp for a modification query (insert, update or delete).

Parameters:
timestamp the timestamp (in microseconds) to use.
Returns:
the corresponding option
Throws:
java.lang.IllegalArgumentException if timestamp &gt; 0.
    public static Using timestamp(long timestamp) {
        if (timestamp < 0)
            throw new IllegalArgumentException("Invalid timestamp, must be positive");
        return new Using("TIMESTAMP"timestamp);
    }

    
Option to set the ttl for a modification query (insert, update or delete).

Parameters:
ttl the ttl (in seconds) to use.
Returns:
the corresponding option
Throws:
java.lang.IllegalArgumentException if ttl &gt; 0.
    public static Using ttl(int ttl) {
        if (ttl < 0)
            throw new IllegalArgumentException("Invalid ttl, must be positive");
        return new Using("TTL"ttl);
    }

    
Simple "set" assignment of a value to a column.

This will generate: name = value.

Parameters:
name the column name
value the value to assign
Returns:
the correspond assignment (to use in an update query)
    public static Assignment set(String nameObject value) {
        return new Assignment.SetAssignment(namevalue);
    }

    
Incrementation of a counter column.

This will generate: name = name + 1.

Parameters:
name the column name to increment
Returns:
the correspond assignment (to use in an update query)
    public static Assignment incr(String name) {
        return incr(name, 1L);
    }

    
Incrementation of a counter column by a provided value.

This will generate: name = name + value.

Parameters:
name the column name to increment
value the value by which to increment
Returns:
the correspond assignment (to use in an update query)
    public static Assignment incr(String namelong value) {
        return new Assignment.CounterAssignment(namevaluetrue);
    }

    
Incrementation of a counter column by a provided value.

This will generate: name = name + value.

Parameters:
name the column name to increment
value a bind marker representing the value by which to increment
Returns:
the correspond assignment (to use in an update query)
    public static Assignment incr(String nameBindMarker value) {
        return new Assignment.CounterAssignment(namevaluetrue);
    }

    
Decrementation of a counter column.

This will generate: name = name - 1.

Parameters:
name the column name to decrement
Returns:
the correspond assignment (to use in an update query)
    public static Assignment decr(String name) {
        return decr(name, 1L);
    }

    
Decrementation of a counter column by a provided value.

This will generate: name = name - value.

Parameters:
name the column name to decrement
value the value by which to decrement
Returns:
the correspond assignment (to use in an update query)
    public static Assignment decr(String namelong value) {
        return new Assignment.CounterAssignment(namevaluefalse);
    }

    
Decrementation of a counter column by a provided value.

This will generate: name = name - value.

Parameters:
name the column name to decrement
value a bind marker representing the value by which to decrement
Returns:
the correspond assignment (to use in an update query)
    public static Assignment decr(String nameBindMarker value) {
        return new Assignment.CounterAssignment(namevaluefalse);
    }

    
Prepend a value to a list column.

This will generate: name = [ value ] + name.

Parameters:
name the column name (must be of type list).
value the value to prepend
Returns:
the correspond assignment (to use in an update query)
    public static Assignment prepend(String nameObject value) {
        Object v = value == . ? value : Collections.singletonList(value);
        return new Assignment.ListPrependAssignment(namev);
    }

    
Prepend a list of values to a list column.

This will generate: name = list + name.

Parameters:
name the column name (must be of type list).
list the list of values to prepend.
Returns:
the correspond assignment (to use in an update query)
    public static Assignment prependAll(String nameList<?> list) {
        return new Assignment.ListPrependAssignment(namelist);
    }

    
Prepend a list of values to a list column.

This will generate: name = list + name.

Parameters:
name the column name (must be of type list).
list a bind marker representing the list of values to prepend.
Returns:
the correspond assignment (to use in an update query)
    public static Assignment prependAll(String nameBindMarker list) {
        return new Assignment.ListPrependAssignment(namelist);
    }

    
Append a value to a list column.

This will generate: name = name + [value].

Parameters:
name the column name (must be of type list).
value the value to append
Returns:
the correspond assignment (to use in an update query)
    public static Assignment append(String nameObject value) {
        Object v = value == . ? value : Collections.singletonList(value);
        return new Assignment.CollectionAssignment(namevtrue);
    }

    
Append a list of values to a list column.

This will generate: name = name + list.

Parameters:
name the column name (must be of type list).
list the list of values to append
Returns:
the correspond assignment (to use in an update query)
    public static Assignment appendAll(String nameList<?> list) {
        return new Assignment.CollectionAssignment(namelisttrue);
    }

    
Append a list of values to a list column.

This will generate: name = name + list.

Parameters:
name the column name (must be of type list).
list a bind marker representing the list of values to append
Returns:
the correspond assignment (to use in an update query)
    public static Assignment appendAll(String nameBindMarker list) {
        return new Assignment.CollectionAssignment(namelisttrue);
    }

    
Discard a value from a list column.

This will generate: name = name - [value].

Parameters:
name the column name (must be of type list).
value the value to discard
Returns:
the correspond assignment (to use in an update query)
    public static Assignment discard(String nameObject value) {
        Object v = value == . ? value : Collections.singletonList(value);
        return new Assignment.CollectionAssignment(namevfalse);
    }

    
Discard a list of values to a list column.

This will generate: name = name - list.

Parameters:
name the column name (must be of type list).
list the list of values to discard
Returns:
the correspond assignment (to use in an update query)
    public static Assignment discardAll(String nameList<?> list) {
        return new Assignment.CollectionAssignment(namelistfalse);
    }

    
Discard a list of values to a list column.

This will generate: name = name - list.

Parameters:
name the column name (must be of type list).
list a bind marker representing the list of values to discard
Returns:
the correspond assignment (to use in an update query)
    public static Assignment discardAll(String nameBindMarker list) {
        return new Assignment.CollectionAssignment(namelistfalse);
    }

    
Sets a list column value by index.

This will generate: name[idx] = value.

Parameters:
name the column name (must be of type list).
idx the index to set
value the value to set
Returns:
the correspond assignment (to use in an update query)
    public static Assignment setIdx(String nameint idxObject value) {
        return new Assignment.ListSetIdxAssignment(nameidxvalue);
    }

    
Adds a value to a set column.

This will generate: name = name + {value}.

Parameters:
name the column name (must be of type set).
value the value to add
Returns:
the correspond assignment (to use in an update query)
    public static Assignment add(String nameObject value) {
        Object v = value == . ? value : Collections.singleton(value);
        return new Assignment.CollectionAssignment(namevtrue);
    }

    
Adds a set of values to a set column.

This will generate: name = name + set.

Parameters:
name the column name (must be of type set).
set the set of values to append
Returns:
the correspond assignment (to use in an update query)
    public static Assignment addAll(String nameSet<?> set) {
        return new Assignment.CollectionAssignment(namesettrue);
    }

    
Adds a set of values to a set column.

This will generate: name = name + set.

Parameters:
name the column name (must be of type set).
set a bind marker representing the set of values to append
Returns:
the correspond assignment (to use in an update query)
    public static Assignment addAll(String nameBindMarker set) {
        return new Assignment.CollectionAssignment(namesettrue);
    }

    
Remove a value from a set column.

This will generate: name = name - {value}.

Parameters:
name the column name (must be of type set).
value the value to remove
Returns:
the correspond assignment (to use in an update query)
    public static Assignment remove(String nameObject value) {
        Object v = value == . ? value : Collections.singleton(value);
        return new Assignment.CollectionAssignment(namevfalse);
    }

    
Remove a set of values from a set column.

This will generate: name = name - set.

Parameters:
name the column name (must be of type set).
set the set of values to remove
Returns:
the correspond assignment (to use in an update query)
    public static Assignment removeAll(String nameSet<?> set) {
        return new Assignment.CollectionAssignment(namesetfalse);
    }

    
Remove a set of values from a set column.

This will generate: name = name - set.

Parameters:
name the column name (must be of type set).
set a bind marker representing the set of values to remove
Returns:
the correspond assignment (to use in an update query)
    public static Assignment removeAll(String nameBindMarker set) {
        return new Assignment.CollectionAssignment(namesetfalse);
    }

    
Puts a new key/value pair to a map column.

This will generate: name[key] = value.

Parameters:
name the column name (must be of type map).
key the key to put
value the value to put
Returns:
the correspond assignment (to use in an update query)
    public static Assignment put(String nameObject keyObject value) {
        return new Assignment.MapPutAssignment(namekeyvalue);
    }

    
Puts a map of new key/value pairs to a map column.

This will generate: name = name + map.

Parameters:
name the column name (must be of type map).
map the map of key/value pairs to put
Returns:
the correspond assignment (to use in an update query)
    public static Assignment putAll(String nameMap<?, ?> map) {
        return new Assignment.CollectionAssignment(namemaptrue);
    }

    
Puts a map of new key/value pairs to a map column.

This will generate: name = name + map.

Parameters:
name the column name (must be of type map).
map a bind marker representing the map of key/value pairs to put
Returns:
the correspond assignment (to use in an update query)
    public static Assignment putAll(String nameBindMarker map) {
        return new Assignment.CollectionAssignment(namemaptrue);
    }

    
A bind marker (a question mark).

This can be used wherever a value is expected. For instance, one can do:

 Insert i = QueryBuilder.insertInto("test").value("k", 0)
                                               .value("c", QueryBuilder.bindMarker());
     PreparedState p = session.prepare(i.toString());
 
 

Returns:
a new bind marker.
    public static BindMarker bindMarker() {
        return .;
    }

    
Creates a raw string value. This allows inputing a string value that is not interpreted/escapted by the query builder in any way. By default, the query builder escape single quotes and recognize function calls in string values. This function avoid both of those behavior.

The following table exemplify the behavior of this function:

CodeResulting query string
select().from("t").where(eq("c", "C'est la vie!")); "SELECT * FROM t WHERE c='C''est la vie!';"
select().from("t").where(eq("c", raw("C'est la vie!"))); "SELECT * FROM t WHERE c='C'est la vie!';"
select().from("t").where(eq("c", "now()")); "SELECT * FROM t WHERE c=now();"
select().from("t").where(eq("c", raw("now()"))); "SELECT * FROM t WHERE c='now()';"
Note: the 2nd example in this table is not a valid CQL3 query as the quote is not correctly escaped.

Parameters:
str the string value to use
Returns:
the value but protected from being interpreted/escaped by the query builder.
    public static Object raw(String str) {
        return new Utils.RawString("'" + str + "'");
    }

    
Creates a function call.

Parameters:
name the name of the function to call.
parameters the paramters for the function.
Returns:
the function call.
    public static Object fcall(String nameObject... parameters) {
        return new Utils.FCall(nameparameters);
    }

    
Declares that the name in argument should be treated as a column name.

This mainly meant for use with Select.Selection.fcall(java.lang.String,java.lang.Object[]) when a function should apply to a column name, not a string value.

Parameters:
name the name of the column.
Returns:
the name as a column name.
    public static Object column(String name) {
        return new Utils.CName(name);
    }
New to GrepCode? Check out our FAQ X