Sha256: 64c0444c54809415bf1c3ee8d91f414fc2763f839ce69fdb3ec0f19418668798

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

require File.join(File.dirname(__FILE__), "service")

module Charrington
  class CreateTable
    # This service will create a table dynamically based on the JSON structure.
    # This is potentially called from Insert when an insert fails.

    include Service
    attr_reader :connection, :event, :table_name, :columns
    attr_accessor :column_types

    Error = Class.new(StandardError)
    CreateFailed = Class.new(Error)

    def initialize(connection, event, table_name, columns)
      @connection = connection
      @event = event.to_hash
      @table_name = table_name
      @columns = columns
      @column_types = []
    end

    def call
      set_column_types
      create_table
      true
    rescue => e
      raise CreateFailed, e.message
    ensure
      @column_types.clear if @column_types.is_a? Array
    end

    private

    def set_column_types
      columns.each do |column|
        case event[column]
        when Time, LogStash::Timestamp
          column_types << "#{column} TIMESTAMP"
        when Date
          column_types << "#{column} DATE"
        when Integer
          column_types << "#{column} BIGINT"
        when BigDecimal
          column_types << "#{column} DECIMAL"
        when Float
          column_types << "#{column} DOUBLE PRECISION"
        when true, false
          column_types << "#{column} BOOLEAN"
        else
          column_types << "#{column} VARCHAR"
        end
      end
    end

    def create_table
      execute("CREATE TABLE IF NOT EXISTS #{table_name} (#{column_types.join(', ')})")
    end

    def execute(sql)
      statement = connection.prepareStatement( sql.gsub(/\s+/, " ").strip )
      statement.execute()
    rescue Java::OrgPostgresqlUtil::PSQLException => e
      # @logger.error("#{e.message}")
    ensure
      statement.close unless statement.nil?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
logstash-output-charrington-0.2.0 lib/logstash/outputs/charrington/create_table.rb