Skip to content

Commit

Permalink
create schemas in schema_search_path if it does not yet exist when cr…
Browse files Browse the repository at this point in the history
…eating database with rake task
  • Loading branch information
saturnflyer committed Dec 21, 2008
1 parent 3b317b7 commit fe629a3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
Expand Up @@ -621,6 +621,18 @@ def drop_database(name) #:nodoc:
end
end

# Creates a schema for the given user
#
# Example:
# create_schema('products', 'jim')
def create_schema(name, username)
query("CREATE SCHEMA #{name} AUTHORIZATION #{username}")
end

# Returns an array of all schemas in the database
def all_schemas
query('SELECT schema_name FROM information_schema.schemata').flatten
end

# Returns the list of all tables in the schema search path or a specified schema.
def tables(name = nil)
Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/cases/active_schema_test_postgresql.rb
Expand Up @@ -16,6 +16,10 @@ def test_create_database_with_encoding
assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt)
assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1)
end

def test_create_schema
assert_equal %(CREATE SCHEMA "products" AUTHORIZATION "jim"), create_schema(:products, :jim)
end

private
def method_missing(method_symbol, *arguments)
Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/cases/adapter_test.rb
Expand Up @@ -69,6 +69,10 @@ def test_show_nonexistent_variable_returns_nil
def test_encoding
assert_not_nil @connection.encoding
end

def test_all_schemas
assert_equal @connection.all_schemas, %w{test_schema test_schema2}
end
end

def test_table_alias
Expand Down
6 changes: 6 additions & 0 deletions railties/lib/tasks/databases.rake
Expand Up @@ -65,8 +65,14 @@ namespace :db do
end
when 'postgresql'
@encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
schema_search_path = config['schema_search_path'] || 'public'
first_in_schema_search_path = schema_search_path.split(',').first.strip
begin
ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
unless ActiveRecord::Base.connection.all_schemas.include?(first_in_schema_search_path)
ActiveRecord::Base.connection.create_schema(first_in_schema_search_path, config['username'])
$stderr.puts "Schema #{first_in_schema_search_path} has been created."
end
ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
ActiveRecord::Base.establish_connection(config)
rescue
Expand Down

0 comments on commit fe629a3

Please sign in to comment.