Skip to content

Instantly share code, notes, and snippets.

@dmitryrck
Last active October 25, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitryrck/32ef27d32bbb75b800d207523aaafa29 to your computer and use it in GitHub Desktop.
Save dmitryrck/32ef27d32bbb75b800d207523aaafa29 to your computer and use it in GitHub Desktop.
$ bundle install
$ bundle exec ruby ./pg.rb

PG version:

postgres=# SELECT version();
                                                     version                                                      
------------------------------------------------------------------------------------------------------------------
 PostgreSQL 12.0 (Debian 12.0-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
(1 row)
source "https://rubygems.org"
gem "pg"
gem "sequel_pg", require: "sequel"
GEM
remote: https://rubygems.org/
specs:
pg (1.1.4)
sequel (5.25.0)
sequel_pg (1.12.2)
pg (>= 0.18.0)
sequel (>= 4.38.0)
PLATFORMS
ruby
DEPENDENCIES
pg
sequel_pg
BUNDLED WITH
1.17.3
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}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment