pgslice 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,89 +0,0 @@
1
- module PgSlice
2
- class GenericTable
3
- attr_reader :table
4
-
5
- def initialize(table)
6
- @table = table.to_s
7
- end
8
-
9
- def to_s
10
- table
11
- end
12
-
13
- def exists?
14
- existing_tables(like: table).any?
15
- end
16
-
17
- def columns
18
- execute("SELECT column_name FROM information_schema.columns WHERE table_schema || '.' || table_name = $1", [table]).map{ |r| r["column_name"] }
19
- end
20
-
21
- # http://www.dbforums.com/showthread.php?1667561-How-to-list-sequences-and-the-columns-by-SQL
22
- def sequences
23
- query = <<-SQL
24
- SELECT
25
- a.attname as related_column,
26
- s.relname as sequence_name
27
- FROM pg_class s
28
- JOIN pg_depend d ON d.objid = s.oid
29
- JOIN pg_class t ON d.objid = s.oid AND d.refobjid = t.oid
30
- JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum)
31
- JOIN pg_namespace n ON n.oid = s.relnamespace
32
- WHERE s.relkind = 'S'
33
- AND n.nspname = $1
34
- AND t.relname = $2
35
- SQL
36
- execute(query, table.split(".", 2))
37
- end
38
-
39
- def foreign_keys
40
- execute("SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = #{regclass(table)} AND contype ='f'").map { |r| r["pg_get_constraintdef"] }
41
- end
42
-
43
- # http://stackoverflow.com/a/20537829
44
- def primary_key
45
- query = <<-SQL
46
- SELECT
47
- pg_attribute.attname,
48
- format_type(pg_attribute.atttypid, pg_attribute.atttypmod)
49
- FROM
50
- pg_index, pg_class, pg_attribute, pg_namespace
51
- WHERE
52
- nspname || '.' || relname = $1 AND
53
- indrelid = pg_class.oid AND
54
- pg_class.relnamespace = pg_namespace.oid AND
55
- pg_attribute.attrelid = pg_class.oid AND
56
- pg_attribute.attnum = any(pg_index.indkey) AND
57
- indisprimary
58
- SQL
59
- execute(query, [table]).map { |r| r["attname"] }
60
- end
61
-
62
- def index_defs
63
- execute("SELECT pg_get_indexdef(indexrelid) FROM pg_index WHERE indrelid = #{regclass(table)} AND indisprimary = 'f'").map { |r| r["pg_get_indexdef"] }
64
- end
65
-
66
- protected
67
-
68
- def existing_tables(like:)
69
- query = "SELECT schemaname, tablename FROM pg_catalog.pg_tables WHERE schemaname = $1 AND tablename LIKE $2"
70
- execute(query, like.split(".", 2)).map { |r| "#{r["schemaname"]}.#{r["tablename"]}" }.sort
71
- end
72
-
73
- def execute(*args)
74
- $client.send(:execute, *args)
75
- end
76
-
77
- def quote_ident(value)
78
- PG::Connection.quote_ident(value)
79
- end
80
-
81
- def quote_table(table)
82
- table.to_s.split(".", 2).map { |v| quote_ident(v) }.join(".")
83
- end
84
-
85
- def regclass(table)
86
- "'#{quote_table(table)}'::regclass"
87
- end
88
- end
89
- end