Sha256: 6fc02f40cf07e1810d13590d6a34c0ed5c7d5d9fc17f9e280d61222bdb1b6c8e

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module PostgresUpsert
  # alternate version of PostgresUpsert::Writer which does not rely on AR table information.  
  # We can use this model to upsert data into views, or tables not associated to rails models
  class TableWriter < Writer
    def initialize(table_name, source, options = {})
      @table_name = table_name
      super(nil, source, options)
    end

  private

    def database_connection
      ActiveRecord::Base.connection
    end

    def primary_key
      @primary_key ||= begin
        query = <<-SELECT_KEY
          SELECT
            pg_attribute.attname,
            format_type(pg_attribute.atttypid, pg_attribute.atttypmod)
          FROM pg_index, pg_class, pg_attribute
          WHERE
            pg_class.oid = '#{@table_name}'::regclass AND
            indrelid = pg_class.oid AND
            pg_attribute.attrelid = pg_class.oid AND
            pg_attribute.attnum = any(pg_index.indkey)
          AND indisprimary
        SELECT_KEY

        pg_result = ActiveRecord::Base.connection.execute query
        pg_result.each { |row| return row['attname'] }
      end
    end

    def destination_columns
      @column_names ||= begin
        query = "SELECT * FROM information_schema.columns WHERE TABLE_NAME = '#{@table_name}'"
        pg_result = ActiveRecord::Base.connection.execute query
        pg_result.map { |row| row['column_name'] }
      end
    end

    def quoted_table_name
      @quoted_table_name ||= ActiveRecord::Base.connection.quote_table_name(@table_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
postgres_upsert-5.1.0 lib/postgres_upsert/table_writer.rb