added row.first and result.fetch_first methods allowing for the first value of a column to be retrieved in a nicer way #68

Merged
merged 1 commit into from Mar 2, 2017

Conversation

Projects
None yet
2 participants
Contributor

pauloricardomg commented Feb 16, 2014

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 =  system.execute("SELECT type FROM schema_columnfamilies WHERE keyspace_name = ? and columnfamily_name = ?, "system", "HintsColumnFamily").fetch_first or "defaultType"

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
}

@kreynolds kreynolds merged commit acfd093 into kreynolds:master Mar 2, 2017

1 check passed

default The Travis CI build passed
Details
Owner

kreynolds commented Mar 2, 2017

I honestly have no idea why I'm just seeing this now, but it seems like a fine addition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment