class PostgresUpsert::TableWriter

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

Public Class Methods

new(table_name, source, options = {}) click to toggle source
Calls superclass method
# File lib/postgres_upsert/table_writer.rb, line 5
def initialize(table_name, source, options = {})
  @table_name = table_name
  super(nil, source, options)
end

Private Instance Methods

database_connection() click to toggle source
# File lib/postgres_upsert/table_writer.rb, line 12
def database_connection
  ActiveRecord::Base.connection
end
destination_columns() click to toggle source
# File lib/postgres_upsert/table_writer.rb, line 36
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
primary_key() click to toggle source
# File lib/postgres_upsert/table_writer.rb, line 16
    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
quoted_table_name() click to toggle source
# File lib/postgres_upsert/table_writer.rb, line 44
def quoted_table_name
  @quoted_table_name ||= ActiveRecord::Base.connection.quote_table_name(@table_name)
end