Skip to content

Commit 47f25b2

Browse files
committed
Add support for :if_not_exists and :force options to create_schema
1 parent be0cb4e commit 47f25b2

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add support for `:if_not_exists` and `:force` options to `create_schema`
2+
3+
*fatkodima*
4+
15
* Fix `index_errors` having incorrect index in association validation errors.
26

37
*lulalala*

activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,16 @@ def schema_names
209209
end
210210

211211
# Creates a schema for the given schema name.
212-
def create_schema(schema_name)
213-
execute "CREATE SCHEMA #{quote_schema_name(schema_name)}"
212+
def create_schema(schema_name, force: nil, if_not_exists: nil)
213+
if force && if_not_exists
214+
raise ArgumentError, "Options `:force` and `:if_not_exists` cannot be used simultaneously."
215+
end
216+
217+
if force
218+
drop_schema(schema_name, if_exists: true)
219+
end
220+
221+
execute("CREATE SCHEMA#{' IF NOT EXISTS' if if_not_exists} #{quote_schema_name(schema_name)}")
214222
end
215223

216224
# Drops the schema for the given schema name.

activerecord/test/cases/adapters/postgresql/schema_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,32 @@ def test_raise_create_schema_with_existing_schema
131131
@connection.drop_schema "test_schema3"
132132
end
133133

134+
def test_force_create_schema
135+
@connection.create_schema "test_schema3"
136+
assert_queries_match(/DROP SCHEMA IF EXISTS "test_schema3"/) do
137+
@connection.create_schema "test_schema3", force: true
138+
end
139+
assert @connection.schema_names.include?("test_schema3")
140+
ensure
141+
@connection.drop_schema "test_schema3"
142+
end
143+
144+
def test_create_schema_if_not_exists
145+
@connection.create_schema "test_schema3"
146+
assert_queries_match('CREATE SCHEMA IF NOT EXISTS "test_schema3"') do
147+
@connection.create_schema "test_schema3", if_not_exists: true
148+
end
149+
assert @connection.schema_names.include?("test_schema3")
150+
ensure
151+
@connection.drop_schema "test_schema3"
152+
end
153+
154+
def test_create_schema_raises_if_both_force_and_if_not_exists_provided
155+
assert_raises(ArgumentError, match: "Options `:force` and `:if_not_exists` cannot be used simultaneously.") do
156+
@connection.create_schema "test_schema3", force: true, if_not_exists: true
157+
end
158+
end
159+
134160
def test_drop_schema
135161
begin
136162
@connection.create_schema "test_schema3"

0 commit comments

Comments
 (0)