How to get strings as arrays (not hashes) in an ORM extension?

In Sequel ORM for Ruby, the Dataset class has an all method that creates an array of row hashes: each row is a hash with column names as keys.

For example, given table T:

 abc -------------- 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 

must produce:

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

Is there a way that you can create an array of string arrays in Sequel, where each row is an array of only the values โ€‹โ€‹in each row in the order specified in the request? How does select_rows work in ActiveRecord? Something like that:

 aa = ds.rows # Array of row Arrays 

which will produce:

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

Note: expression:

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

creates an array of arrays, but the order of the values โ€‹โ€‹in the strings is NOT guaranteed to match the order specified in the original query. In this example, aa might look like this:

 [["Abe",0,22],["Betty",1,35],["Chris",2,58]] 
+6
source share
5 answers

If you only need an array of arrays of values โ€‹โ€‹...

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

seems to work

UPDATE, given the updated column order requirement corresponding to query order ...

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

not very beautiful, but the guaranteed order coincides with the order of choice. There seems to be no built-in tool for this. You can request this feature.

+3
source

In older versions of Sequel (pre 2.0), some adapters have the ability to return arrays instead of hashes. But this caused numerous problems, nobody used it, and I did not want to support it, so it was deleted. If you really need arrays, you need to go down to the connection level and use a special connection 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 use.

+10
source

DB [: table]. Where () select_map. (: ID)

+2
source

I have not yet found a built-in method for returning an array of row arrays, where the values โ€‹โ€‹in the row arrays are ordered by column order in the original query. The following function does *, although I suspect that the internal method may be more efficient:

 def rows( ds ) ret = [] column_keys = ds.columns # guaranteed to match query order? ds.all { |row_hash| row_array = [] column_keys.map { |column_key| row_array << row_hash[column_key] } ret << row_array } ret end 

* This function depends on the order of the array returned by Dataset.columns . If this order is undefined, then this rows function is not very useful.

0
source

Have you tried this?

 ds = DB['select a, b, c from T'].to_a 

Not sure if it works, but give it a chance.

0
source

Source: https://habr.com/ru/post/886436/


All Articles