Sha256: 5fbe987871017b15b7c9d967d0b0fc42d7d7c58832ea392fe8952e11f9387367

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

module PostgresUpsert
  # alternate version of PostgresUpsert::Writer which does not rely on AR table information.  We 
  # 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 = <<-sql
          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
        sql

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

    def column_names
      @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.0.0 lib/postgres_upsert/table_writer.rb