PostgreSQL: create_ and drop_database support. Closes #9042.

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9182 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Jeremy Kemper
2008-04-01 05:01:10 +00:00
parent dc1166d12b
commit e4e3df8ef8
3 changed files with 70 additions and 0 deletions

View File

@@ -1,5 +1,7 @@
*SVN*
* PostgreSQL: create_ and drop_database support. #9042 [ez, pedz, nicksieger]
* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [nik.wakelin, cavalle]
* Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. [Jeremy Kemper]

View File

@@ -474,6 +474,50 @@ module ActiveRecord
# SCHEMA STATEMENTS ========================================
def recreate_database(name) #:nodoc:
drop_database(name)
create_database(name)
end
# Create a new PostgreSQL database. Options include :owner, :template,
# :encoding, :tablespace, and :connection_limit (note that MySQL uses
# :charset while PostgreSQL uses :encoding).
#
# Example:
# create_database config[:database], config
# create_database 'foo_development', :encoding => 'unicode'
def create_database(name, options = {})
options = options.reverse_merge(:encoding => "utf8")
option_string = options.symbolize_keys.sum do |key, value|
case key
when :owner
" OWNER = '#{value}'"
when :template
" TEMPLATE = #{value}"
when :encoding
" ENCODING = '#{value}'"
when :tablespace
" TABLESPACE = #{value}"
when :connection_limit
" CONNECTION LIMIT = #{value}"
else
""
end
end
execute "CREATE DATABASE #{name}#{option_string}"
end
# Drops a PostgreSQL database
#
# Example:
# drop_database 'matt_development'
def drop_database(name) #:nodoc:
execute "DROP DATABASE IF EXISTS #{name}"
end
# Returns the list of all tables in the schema search path or a specified schema.
def tables(name = nil)
schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')

View File

@@ -0,0 +1,24 @@
require 'cases/helper'
class PostgresqlActiveSchemaTest < Test::Unit::TestCase
def setup
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
alias_method :real_execute, :execute
def execute(sql, name = nil) sql end
end
end
def teardown
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:alias_method, :execute, :real_execute)
end
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
private
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
end
end