1 if defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter)
3 module ConnectionAdapters
4 class PostgreSQLAdapter
5 def supports_disable_referential_integrity?() #:nodoc:
6 version = query("SHOW server_version")[0][0].split('.')
7 (version[0].to_i >= 9 || (version[0].to_i == 8 && version[1].to_i >= 1)) ? true : false
12 def pk_and_sequence_for(table)
13 # First try looking for a sequence with a dependency on the
14 # given table's primary key.
15 result = query(<<-end_sql, 'PK and serial sequence')[0]
16 SELECT attr.attname, seq.relname
22 WHERE seq.oid = dep.objid
24 AND attr.attrelid = dep.refobjid
25 AND attr.attnum = dep.refobjsubid
26 AND attr.attrelid = cons.conrelid
27 AND attr.attnum = cons.conkey[1]
28 AND cons.contype = 'p'
29 AND dep.classid = '"pg_class"'::regclass
30 AND dep.refclassid = '"pg_class"'::regclass
31 AND dep.refobjid = '#{quote_table_name(table)}'::regclass
34 if result.nil? or result.empty?
35 # If that fails, try parsing the primary key's default value.
36 # Support the 7.x and 8.0 nextval('foo'::text) as well as
37 # the 8.1+ nextval('foo'::regclass).
38 result = query(<<-end_sql, 'PK and custom sequence')[0]
41 WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN
42 substr(split_part(def.adsrc, '''', 2),
43 strpos(split_part(def.adsrc, '''', 2), '.')+1)
44 ELSE split_part(def.adsrc, '''', 2)
47 JOIN pg_attribute attr ON (t.oid = attrelid)
48 JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)
49 JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])
50 WHERE t.oid = '#{quote_table_name(table)}'::regclass
51 AND cons.contype = 'p'
52 AND def.adsrc ~* 'nextval'
56 # [primary_key, sequence]
57 [result.first, result.last]