Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rows as Arrays (not Hashes) in Sequel ORM?

Tags:

ruby

sequel

In the Sequel ORM for Ruby, the Dataset class has an all method which produces an Array of row hashes: each row is a Hash with column names as keys.

For example, given a table T:

a  b   c
--------------
0  22  "Abe"
1  35  "Betty"
2  58  "Chris"

then:

ds = DB['select a, b, c from T']
ah = ds.all # Array of row Hashes

should produce:

[{"a":0,"b":22,"c":"Abe"},{"a":1,"b":35,"c":"Betty"},{"a":2,"b":58,"c":"Chris"}]

Is there a way built in to Sequel to instead produce an Array of row Arrays, where each row is an array of only the values in each row in the order specified in the query? Sort of how select_rows works in ActiveRecord? Something like this:

aa = ds.rows # Array of row Arrays

which would produce:

[[0,22,"Abe"],[1,35,"Betty"],[2,58,"Chris"]]

Note: the expression:

aa = ds.map { |h| h.values }

produces an array of arrays, but the order of values in the rows is NOT guaranteed to match the order requested in the original query. In this example, aa might look like:

[["Abe",0,22],["Betty",1,35],["Chris",2,58]]
like image 242
jwfearn Avatar asked Apr 21 '11 23:04

jwfearn


3 Answers

Old versions of Sequel (pre 2.0) had the ability in some adapters to return arrays instead of hashes. But it caused numerous issues, nobody used it, and I didn't want to maintain it, so it was removed. If you really want arrays, you need to drop down to the connection level and use a connection specific method:

DB.synchronize do |conn|
  rows = conn.exec('SQL Here') # Hypothetical example code
end

The actual code you need will depend on the adapter you are using.

like image 140
Jeremy Evans Avatar answered Nov 19 '22 02:11

Jeremy Evans


DB[:table].where().select_map(:id)

like image 41
Cris R Avatar answered Nov 19 '22 02:11

Cris R


If you want just an array of array of values...

DB['select * from T'].map { |h| h.values }

seems to work

UPDATE given the updated requirement of the column order matching the query order...

cols= [:a, :c, :b]
DB[:T].select{cols}.collect{ |h| cols.collect {|c| h[c]}}

not very pretty but guaranteed order is the same as the select order. There does not appear to be a builtin to do this. You could make a request for the feature.

like image 3
Jim Morris Avatar answered Nov 19 '22 01:11

Jim Morris