Class: PgSlice::GenericTable

Inherits:
Object
  • Object
show all
Defined in:
lib/pgslice/generic_table.rb

Direct Known Subclasses

Table

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table) ⇒ GenericTable

Returns a new instance of GenericTable.



5
6
7
# File 'lib/pgslice/generic_table.rb', line 5

def initialize(table)
  @table = table.to_s
end

Instance Attribute Details

#tableObject (readonly)

Returns the value of attribute table.



3
4
5
# File 'lib/pgslice/generic_table.rb', line 3

def table
  @table
end

Instance Method Details

#columnsObject



17
18
19
# File 'lib/pgslice/generic_table.rb', line 17

def columns
  execute("SELECT column_name FROM information_schema.columns WHERE table_schema || '.' || table_name = $1", [table]).map{ |r| r["column_name"] }
end

#exists?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/pgslice/generic_table.rb', line 13

def exists?
  existing_tables(like: table).any?
end

#foreign_keysObject



39
40
41
# File 'lib/pgslice/generic_table.rb', line 39

def foreign_keys
  execute("SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = #{regclass(table)} AND contype ='f'").map { |r| r["pg_get_constraintdef"] }
end

#index_defsObject



62
63
64
# File 'lib/pgslice/generic_table.rb', line 62

def index_defs
  execute("SELECT pg_get_indexdef(indexrelid) FROM pg_index WHERE indrelid = #{regclass(table)} AND indisprimary = 'f'").map { |r| r["pg_get_indexdef"] }
end

#primary_keyObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pgslice/generic_table.rb', line 44

def primary_key
  query = "    SELECT\n      pg_attribute.attname,\n      format_type(pg_attribute.atttypid, pg_attribute.atttypmod)\n    FROM\n      pg_index, pg_class, pg_attribute, pg_namespace\n    WHERE\n      nspname || '.' || relname = $1 AND\n      indrelid = pg_class.oid AND\n      pg_class.relnamespace = pg_namespace.oid AND\n      pg_attribute.attrelid = pg_class.oid AND\n      pg_attribute.attnum = any(pg_index.indkey) AND\n      indisprimary\n  SQL\n  execute(query, [table]).map { |r| r[\"attname\"] }\nend\n"

#sequencesObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pgslice/generic_table.rb', line 22

def sequences
  query = "    SELECT\n      a.attname as related_column,\n      s.relname as sequence_name\n    FROM pg_class s\n      JOIN pg_depend d ON d.objid = s.oid\n      JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid\n      JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)\n      JOIN pg_namespace n ON n.oid = s.relnamespace\n    WHERE s.relkind = 'S'\n      AND n.nspname = $1\n      AND t.relname = $2\n  SQL\n  execute(query, table.split(\".\", 2))\nend\n"

#to_sObject



9
10
11
# File 'lib/pgslice/generic_table.rb', line 9

def to_s
  table
end