You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
1.8 KiB
Ruby
86 lines
1.8 KiB
Ruby
require 'sinatra'
|
|
require 'sinatra/custom_logger'
|
|
require 'logger'
|
|
|
|
require 'sidekiq'
|
|
require 'redis'
|
|
require 'sidekiq/api'
|
|
require 'haml'
|
|
require 'pg'
|
|
|
|
# postgres://postgres:testpassword@pg-${APP_NAME}-${INSTANCE_NAME}/example?sslmode=disable
|
|
module Db
|
|
class Client
|
|
def initialize
|
|
db_url = ENV['DATABASE_URL'].gsub('postgres://', '')
|
|
auth, host_db = db_url.split('@')
|
|
@user, @password = auth.split(':')
|
|
@host, db = host_db.split('/')
|
|
@db = db.split('?')[0]
|
|
end
|
|
|
|
def create_db
|
|
conn.exec("CREATE DATABASE #{@db};")
|
|
end
|
|
|
|
def create_table
|
|
conn(@db).exec("CREATE TABLE entries (
|
|
did SERIAL,
|
|
name varchar(40) NOT NULL check (name <> '')
|
|
);")
|
|
end
|
|
|
|
def select_all
|
|
conn(@db).exec("SELECT * from entries;")
|
|
end
|
|
|
|
def insert_value
|
|
conn(@db).exec("INSERT INTO entries (name) VALUES
|
|
('bob'), ('mary')
|
|
;")
|
|
end
|
|
|
|
private
|
|
|
|
def conn(db = nil)
|
|
if db
|
|
@conn ||= ::PG.connect(user: @user, password: @password, host: @host, dbname: db)
|
|
else
|
|
@conn ||= ::PG.connect(user: @user, password: @password, host: @host)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
class SimpleApp < Sinatra::Base
|
|
set :logger, Logger.new(STDOUT)
|
|
|
|
get '/' do
|
|
haml "%h3 Hello Cat!"
|
|
end
|
|
|
|
get '/db' do
|
|
db_url = ENV['DATABASE_URL']
|
|
auth, host_db = db_url.split('@')
|
|
@user, @password = auth.split(':')
|
|
@host, db = host_db.split('/')
|
|
@db = db.split('?')[0]
|
|
|
|
client = Db::Client.new
|
|
begin
|
|
client.create_db
|
|
rescue PG::DuplicateDatabase
|
|
end
|
|
client.create_table
|
|
haml "%h2 Db created"
|
|
end
|
|
|
|
get '/all' do
|
|
client = Db::Client.new
|
|
client.insert_value
|
|
values = client.select_all
|
|
|
|
haml :all, locals: { data: values }
|
|
end
|
|
end
|