Permalink
Browse files

Merge pull request #1410 from lucasts/pg_schema

a little step to better postgresql schema support in rails
  • Loading branch information...
2 parents 65858a4 + c44418e commit 7278547a5d1ac8a7c20d0edf62bc76c5434da6f5 @tenderlove tenderlove committed May 30, 2011
Showing with 11 additions and 5 deletions.
  1. +11 −5 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -659,7 +659,10 @@ def drop_database(name) #:nodoc:
# Returns the list of all tables in the schema search path or a specified schema.
def tables(name = nil)
query(<<-SQL, 'SCHEMA').map { |row| row[0] }
- SELECT tablename
+ SELECT case schemaname
+ when 'public' then tablename
+ else schemaname||'.'||tablename
+ end as tablename
FROM pg_tables
WHERE schemaname = ANY (current_schemas(false))
SQL
@@ -805,8 +808,8 @@ def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc:
end
if pk && sequence
- quoted_sequence = quote_column_name(sequence)
-
+ quoted_sequence = quote_table_name(sequence)
+
select_value <<-end_sql, 'Reset sequence'
SELECT setval('#{quoted_sequence}', (SELECT COALESCE(MAX(#{quote_column_name pk})+(SELECT increment_by FROM #{quoted_sequence}), (SELECT min_value FROM #{quoted_sequence})) FROM #{quote_table_name(table)}), false)
end_sql
@@ -818,18 +821,21 @@ def pk_and_sequence_for(table) #:nodoc:
# First try looking for a sequence with a dependency on the
# given table's primary key.
result = exec_query(<<-end_sql, 'SCHEMA').rows.first
- SELECT attr.attname, seq.relname
+ SELECT attr.attname, ns.nspname, seq.relname
FROM pg_class seq
INNER JOIN pg_depend dep ON seq.oid = dep.objid
INNER JOIN pg_attribute attr ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
+ INNER JOIN pg_namespace ns ON seq.relnamespace = ns.oid
WHERE seq.relkind = 'S'
AND cons.contype = 'p'
AND dep.refobjid = '#{quote_table_name(table)}'::regclass
end_sql
# [primary_key, sequence]
- [result.first, result.last]
+ sequence = result.second == 'public' ? result.last : "#{result.second}.#{result.last}"
+
+ [result.first, sequence]
rescue
nil
end

0 comments on commit 7278547

Please sign in to comment.