kreynolds/cassandra-cql — pull request #68 by pauloricardomg (2014-02-16 18:51:21+00:00)
Title: added row.first and result.fetch_first methods allowing for the first value of a column to be retrieved in a nicer way

Many CQL queries return only a single column, and we're not interested in the column name, but only the column value. For instance, in order to fetch the type of a given CF in the system keyspace, we can do the following query:

type = system.execute("SELECT type FROM schema_columnfamilies WHERE keyspace_name = ? and columnfamily_name = ?, "system", "HintsColumnFamily").fetch_row[0]

Since the programmer knows beforehand the result will only result a single column, and is interested only in the column value, we added the syntactic sugar "fetch_first", which will encapsulate the array access, so the above code will look like:

type = system.execute("SELECT type FROM schema_columnfamilies WHERE keyspace_name = ? and columnfamily_name = ?, "system", "HintsColumnFamily").fetch_first

Furthermore, if for some reason, that query result is empty, the fetch_row[0] acess will throw a "NoMethodError: undefined method `[]' for nil:NilClass", while the fetch_first will return "nil", allowing the programmer to use something like:

type = "defaultType" or system.execute("SELECT type FROM schema_columnfamilies WHERE keyspace_name = ? and columnfamily_name = ?, "system", "HintsColumnFamily").fetch_first

Another use case for the fetch_first method is when the client is iterating over a result set but is only interested in the first column value returned. For instance, to retrieve all column family names from the system table, you can use the following code:

system.execute("SELECT columnfamily_name FROM schema_columnfamilies WHERE keyspace_name = ?", "system").fetch_array { |col|
puts col[0]
}

With the fetch_first, that array access is abstracted and the programmer will be able to use the column value directly during the iteration:

system.execute("SELECT columnfamily_name FROM schema_columnfamilies WHERE keyspace_name = ?", "system").fetch_first { |col|
puts col
}