Sha256: cfb22ec972a84df5a424d9ac299c66bc1388f39743236adce36c7ca7adc78e79

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 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'
      return EnrichmentDb::db_connection.exec(query, values) if values
      
      EnrichmentDb::db_connection.exec(query)
    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.request_type(query)
    result = query.downcase.match(/(^(?:drop|select|insert|delete|\\d))/)
    return unless result

    result[0]
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
enrichment_db-0.1.14 lib/enrichment_db/db.rb