Skip to content

Commit

Permalink
Merge pull request #51790 from fatkodima/create_schema-if_not_exists
Browse files Browse the repository at this point in the history
Add support for `:if_not_exists` and `:force` options to `create_schema`
  • Loading branch information
carlosantoniodasilva committed May 11, 2024
2 parents be0cb4e + 47f25b2 commit 77f0822
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
* Add support for `:if_not_exists` and `:force` options to `create_schema`

*fatkodima*

* Fix `index_errors` having incorrect index in association validation errors.

*lulalala*
Expand Down
Expand Up @@ -209,8 +209,16 @@ def schema_names
end

# Creates a schema for the given schema name.
def create_schema(schema_name)
execute "CREATE SCHEMA #{quote_schema_name(schema_name)}"
def create_schema(schema_name, force: nil, if_not_exists: nil)
if force && if_not_exists
raise ArgumentError, "Options `:force` and `:if_not_exists` cannot be used simultaneously."
end

if force
drop_schema(schema_name, if_exists: true)
end

execute("CREATE SCHEMA#{' IF NOT EXISTS' if if_not_exists} #{quote_schema_name(schema_name)}")
end

# Drops the schema for the given schema name.
Expand Down
26 changes: 26 additions & 0 deletions activerecord/test/cases/adapters/postgresql/schema_test.rb
Expand Up @@ -131,6 +131,32 @@ def test_raise_create_schema_with_existing_schema
@connection.drop_schema "test_schema3"
end

def test_force_create_schema
@connection.create_schema "test_schema3"
assert_queries_match(/DROP SCHEMA IF EXISTS "test_schema3"/) do
@connection.create_schema "test_schema3", force: true
end
assert @connection.schema_names.include?("test_schema3")
ensure
@connection.drop_schema "test_schema3"
end

def test_create_schema_if_not_exists
@connection.create_schema "test_schema3"
assert_queries_match('CREATE SCHEMA IF NOT EXISTS "test_schema3"') do
@connection.create_schema "test_schema3", if_not_exists: true
end
assert @connection.schema_names.include?("test_schema3")
ensure
@connection.drop_schema "test_schema3"
end

def test_create_schema_raises_if_both_force_and_if_not_exists_provided
assert_raises(ArgumentError, match: "Options `:force` and `:if_not_exists` cannot be used simultaneously.") do
@connection.create_schema "test_schema3", force: true, if_not_exists: true
end
end

def test_drop_schema
begin
@connection.create_schema "test_schema3"
Expand Down

0 comments on commit 77f0822

Please sign in to comment.