|
require "sequel" |
|
require "logger" |
|
|
|
DB = Sequel.connect(ENV["DATABASE_URL"]) |
|
DB.extension :pg_json |
|
DB.loggers << Logger.new($stdout) |
|
DB.drop_table(:posts) |
|
|
|
Sequel.extension :pg_array, :pg_json, :pg_json_ops |
|
|
|
# This is the initial setup I run only once. |
|
DB.create_table(:posts) do |
|
primary_key :id |
|
jsonb :content |
|
end |
|
|
|
# This is the insert that comes in the first HTTP request. |
|
table = "posts" |
|
data = { id: 1, body: "something", title: "Title#1", tags: ["a", "b"], active: true, } # This is a json |
|
DB[Sequel.qualify(:public, table)] |
|
.insert(content: Sequel.pg_json(data)) |
|
|
|
# This is the query. It happens in other http request. |
|
table = "posts" # I receive this from the HTTP request |
|
columns = ["id", "body", "tags", "active"] # I receive this from the HTTP request |
|
select = columns.map { |field| Sequel.qualify(table, Sequel.lit("content->>?", field)).as(field) } |
|
# I also tried: |
|
# |
|
# select = columns.map { |field| Sequel.lit("content->>?", field).as(field) } |
|
# select = columns.map { |field| Sequel.lit("content->>? as ?", field, field.to_sym) } |
|
|
|
puts DB[Sequel.qualify(:public, table)].select(*select).all.inspect |
|
# This returns: |
|
# |
|
# [{:id=>"1", :body=>"something", :tags=>"[\"a\", \"b\"]", :active=>"true"}] |
|
# |
|
# It is supposed to return: |
|
# |
|
# [{:id=>1, :body=>"something", :tags=>["a", "b"], :active=> true}] |
|
|
|
# This returns all in the correct type |
|
puts DB[Sequel.qualify(:public, table)].all.inspect |
|
# [{:id=>1, :content=>{"id"=>1, "body"=>"something", "tags"=>["a", "b"], "title"=>"Title#1", "active"=>true}}] |
|
|
|
# This is my workaround: |
|
records = DB[Sequel.qualify(:public, table)].select(:content).all.map do |row| |
|
rrow = {} |
|
|
|
columns.each { |column| rrow[column.to_sym] = row[:content][column] } |
|
|
|
rrow |
|
end |
|
|
|
puts records.inspect |
|
# [{:id=>1, :body=>"something", :tags=>["a", "b"], :active=>true}] |