Class: PostgresUpsert::WriteAdapters::TableAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/postgres_upsert/write_adapters/table_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(destination, options) ⇒ TableAdapter

Returns a new instance of TableAdapter.



4
5
6
7
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 4

def initialize(destination, options)
  @destination = destination
  @options = sanitize_options(options)
end

Instance Method Details

#column_namesObject



42
43
44
45
46
47
48
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 42

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

#database_connectionObject



18
19
20
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 18

def database_connection
  ActiveRecord::Base.connection
end

#primary_keyObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 22

def primary_key
  @primary_key ||= begin
    query = "      SELECT\n        pg_attribute.attname,\n        format_type(pg_attribute.atttypid, pg_attribute.atttypmod)\n      FROM pg_index, pg_class, pg_attribute\n      WHERE\n        pg_class.oid = '\#{@destination}'::regclass AND\n        indrelid = pg_class.oid AND\n        pg_attribute.attrelid = pg_class.oid AND\n        pg_attribute.attnum = any(pg_index.indkey)\n      AND indisprimary\n    SELECT_KEY\n  \n    pg_result = ActiveRecord::Base.connection.execute query\n    pg_result.each { |row| return row['attname'] }\n  end\nend\n"

#quoted_table_nameObject



50
51
52
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 50

def quoted_table_name
  @quoted_table_name ||= database_connection.quote_table_name(@destination)
end

#sanitize_options(options) ⇒ Object



9
10
11
12
13
14
15
16
# File 'lib/postgres_upsert/write_adapters/table_adapter.rb', line 9

def sanitize_options(options)
  options.slice(
    :delimiter, :unique_key
  ).reverse_merge(
    delimiter: ',',
    unique_key: [primary_key],
  )
end