Question

I am running an arbitrary sql using Ruby Sequel DB.run. I would like to find out the column names of the dataset.

Is it possible in Ruby Sequel ?

Was it helpful?

Solution

Could you provide a minimal working example (a code example to see what you want and if possible without )?

I'm guessing what you do:

require 'sequel'

db = Sequel.sqlite()
db.create_table(:test){
  field :x1
  field :x2
}
db[:test].insert(1,2)
p db.run('select * from test') #->nil

If you don't use run but [] you get another result:

p db['select * from test']  #-> #<Sequel::SQLite::Dataset: "select * from test">

Based on this solution you can use columns to get the fields:

p db['select * from test'].columns  #->[:x1, :x2]
p db['select x1 from test'].columns  #->[:x1]

OTHER TIPS

Using Sequel's basic statup-up example:

require "sequel"

# connect to an in-memory database
DB = Sequel.sqlite

# create an items table
DB.create_table :items do
  primary_key :id
  String :name
  Float :price
end

# create a dataset from the items table
items = DB[:items]

The columns method will return the fields defined for a particular table:

items.columns # => [:id, :name, :price]

You can also do it directly using:

DB[:items].columns # => [:id, :name, :price]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top