Skip to content

Instantly share code, notes, and snippets.

@ochrons
Last active March 26, 2018 15:21
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ochrons/10681050 to your computer and use it in GitHub Desktop.
Save ochrons/10681050 to your computer and use it in GitHub Desktop.
Super thin Scala wrapper for common DataStax Cassandra Java driver functionality.
object CassandraWrapper {
import scala.language.implicitConversions
import scala.language.postfixOps
/**
* Converts a `ResultSetFuture` into a Scala `Future[ResultSet]`
* @param f ResultSetFuture to convert
* @return Converted Future
*/
implicit def resultSetFutureToScala(f: ResultSetFuture): Future[ResultSet] = {
val p = Promise[ResultSet]()
Futures.addCallback(f,
new FutureCallback[ResultSet] {
def onSuccess(r: ResultSet) = p success r
def onFailure(t: Throwable) = p failure t
})
p.future
}
/**
* Adds a new easy way to add values to an insert statement.
*
* <pre>
* val query = insertInto(table) values("id" -> id, "col1" -> x, "col2" -> y)
* </pre>
* @param insert
*/
implicit class insertValues(insert:Insert) {
def values(vals:(String,Any)*) = {
vals.foldLeft(insert)((i, v) => i.value(v._1, v._2))
}
}
// define convenient operators for query building
implicit class columnNameWrapper(col: String) {
def ===(value: Any) = QueryBuilder.eq(col, value)
def in(values: Seq[AnyRef]) = QueryBuilder.in(col, values: _*)
def >(value: Any) = QueryBuilder.gt(col, value)
def >=(value: Any) = QueryBuilder.gte(col, value)
def <(value: Any) = QueryBuilder.lt(col, value)
def <=(value: Any) = QueryBuilder.lte(col, value)
def :=(value: Any) = QueryBuilder.set(col, value)
def +=(value: Set[Any]) = QueryBuilder.addAll(col, value)
def +=(value: Any) = QueryBuilder.add(col, value)
def -=(value: Any) = QueryBuilder.remove(col, value)
def -=(value: Set[Any]) = QueryBuilder.removeAll(col, value)
def ++ = QueryBuilder.incr(col)
def -- = QueryBuilder.decr(col)
def ++=(value: Long) = QueryBuilder.incr(col, value)
def --=(value: Long) = QueryBuilder.decr(col, value)
def desc = QueryBuilder.desc(col)
def asc = QueryBuilder.asc(col)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment