require 'pg' require 'cache' module EnrichmentDb def self.db_connection @__db_connection ||= PGconn.connect( host: 'geo-mappings.cfmmyp7uix0j.ap-southeast-2.rds.amazonaws.com', dbname: 'geo', user: 'lexer', password: 'campl3x3r' ) end def self.reset_connection @__api_connection = nil end def self.table_names(schema = 'public') query = "SELECT table_name FROM information_schema.tables WHERE table_schema='#{schema}' AND table_type='BASE TABLE'" request(schema, query).collect do |h| h['table_name'] end end def self.table_columns(table, schema = 'public') query = "SELECT * FROM information_schema.columns WHERE table_schema = '#{schema}' AND table_name = '#{table}'" request(schema, query).collect do |h| h['column_name'] end end def self.request(db, query, values = nil) type = request_type(query) case type when :select, 'select', '\d' get_or_request(query, values) when :insert, :drop, :delete, 'insert', 'drop', 'delete' fail EnrichmentDb::RequestError, "Postgres method '#{type}' is unsupported" else fail EnrichmentDb::RequestError, "Postgres query '#{query}' is unsupported" end end def self.get_or_request(query, values = nil) result = EnrichmentDb::Cache.get(query, values) return result unless result.nil? result = if values EnrichmentDb::db_connection.exec(query, values) else EnrichmentDb::db_connection.exec(query) end EnrichmentDb::Cache.set(query, values, result) end def self.request_type(query) result = query.downcase.match(/(^(?:drop|select|insert|delete|\\d))/) return unless result result[0] end end