From 80a24c6f6c2323de0f0d0b1adbb99605fbfb9f1e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sun, 11 Apr 2010 14:48:49 -0700 Subject: [PATCH] mode postgresql adapters table_exists? method take the schema in to account. [#4341 state:resolved] --- .../connection_adapters/postgresql_adapter.rb | 24 +++++++++++++++++++- activerecord/test/cases/schema_test_postgresql.rb | 15 ++++++++++++ 2 files changed, 38 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 7169c8f..ceb1adc 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -670,8 +670,30 @@ module ActiveRecord def tables(name = nil) query(<<-SQL, name).map { |row| row[0] } SELECT tablename + FROM pg_tables + WHERE schemaname = ANY (current_schemas(false)) + SQL + end + + def table_exists?(name) + name = name.to_s + 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 + + query(<<-SQL).first[0].to_i > 0 + SELECT COUNT(*) FROM pg_tables - WHERE schemaname = ANY (current_schemas(false)) + WHERE tablename = '#{table.gsub(/(^"|"$)/,'')}' + #{schema ? "AND schemaname = '#{schema}'" : ''} SQL end diff --git a/activerecord/test/cases/schema_test_postgresql.rb b/activerecord/test/cases/schema_test_postgresql.rb index a294848..3ed7378 100644 --- a/activerecord/test/cases/schema_test_postgresql.rb +++ b/activerecord/test/cases/schema_test_postgresql.rb @@ -52,6 +52,21 @@ class SchemaTest < ActiveRecord::TestCase @connection.execute "DROP SCHEMA #{SCHEMA_NAME} CASCADE" end + def test_table_exists? + [Thing1, Thing2, Thing3, Thing4].each do |klass| + name = klass.table_name + assert @connection.table_exists?(name), "'#{name}' table should exist" + end + end + + def test_table_exists_wrong_schema + assert(!@connection.table_exists?("foo.things"), "table should not exist") + end + + def test_table_exists_quoted_table + assert(@connection.table_exists?('"things.table"'), "table should exist") + end + def test_with_schema_prefixed_table_name assert_nothing_raised do assert_equal COLUMNS, columns("#{SCHEMA_NAME}.#{TABLE_NAME}") -- 1.6.6