Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/vpd/postgresql_adapter.rb

Instance Method Summary collapse

Instance Method Details

#current_schemaObject

get the current schema



10
11
12
# File 'lib/vpd/postgresql_adapter.rb', line 10

def current_schema
  query('SELECT current_schema', 'SCHEMA')[0][0]
end

#extract_schema_and_table(name) ⇒ Object

Extracts the table and schema name from name

  • copied from HEAD but not in 3.0.7 yet



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/vpd/postgresql_adapter.rb', line 43

def extract_schema_and_table(name)
  schema, table = name.split('.', 2)

  unless table # A table was provided without a schema
    table  = schema
    schema = nil
  end

  if name =~ /^"/ # Handle quoted table names
    table  = name
    schema = nil
  end
  [schema, table]
end

#schema_exists?(name) ⇒ Boolean

tests it name schema exists

Returns:

  • (Boolean)


15
16
17
18
19
20
21
# File 'lib/vpd/postgresql_adapter.rb', line 15

def schema_exists?(name)
  query(<<-SQL).first[0].to_i > 0
      SELECT COUNT(*)
      FROM pg_namespace
      WHERE nspname = '#{name.gsub(/(^"|"$)/,'')}'
  SQL
end

#table_exists?(name) ⇒ Boolean

Overrides ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#table_exists? Change to only look in the current schema - unless schema is specified in the name This is required to enable rails migrations to run into the currently selected schema

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/vpd/postgresql_adapter.rb', line 26

def table_exists?(name)
  schema, table = extract_schema_and_table(name.to_s)
  schema ||= current_schema

  binds = [[nil, table.gsub(/(^"|"$)/,'')]]
  binds << [nil, schema] if schema

  query(<<-SQL, 'SCHEMA').first[0].to_i > 0
      SELECT COUNT(*)
      FROM pg_tables
      WHERE tablename = '#{table.gsub(/(^"|"$)/,'')}'
      #{schema ? "AND schemaname = '#{schema}'" : ''}
  SQL
end