Sha256: 021bcfcffa1a7060dfaacd810622c4a3d3af901ea17a25012709056ada789ee3

Contents?: true

Size: 1.51 KB

Versions: 6

Compression:

Stored size: 1.51 KB

Contents

require 'pg'

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'
      result = if values
        EnrichmentDb::db_connection.exec(query, values)
      else
        EnrichmentDb::db_connection.exec(query)
      end
    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

6 entries across 6 versions & 1 rubygems

Version Path
enrichment_db-0.1.10 lib/enrichment_db/db.rb
enrichment_db-0.1.9 lib/enrichment_db/db.rb
enrichment_db-0.1.8 lib/enrichment_db/db.rb
enrichment_db-0.1.7 lib/enrichment_db/db.rb
enrichment_db-0.1.6 lib/enrichment_db/db.rb
enrichment_db-0.1.5 lib/enrichment_db/db.rb