Sha256: e32799066874617f9198ca0b34e169025cce3f0482476e2fa3627f8c8b4103c4

Contents?: true

Size: 1.75 KB

Versions: 3

Compression:

Stored size: 1.75 KB

Contents

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
enrichment_db-0.1.13 lib/enrichment_db/db.rb
enrichment_db-0.1.12 lib/enrichment_db/db.rb
enrichment_db-0.1.11 lib/enrichment_db/db.rb