Skip to content

Commit a6a4790

Browse files
committed
add rename_schema method for postgres
1 parent 0bd254e commit a6a4790

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
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 `rename_schema` method for PostgreSQL.
2+
3+
*T S Vallender*
4+
15
* Implement support for deprecating associations:
26

37
```ruby

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,11 @@ def drop_schema(schema_name, **options)
279279
execute "DROP SCHEMA#{' IF EXISTS' if options[:if_exists]} #{quote_schema_name(schema_name)} CASCADE"
280280
end
281281

282+
# Renames the schema for the given schema name.
283+
def rename_schema(schema_name, new_name)
284+
execute "ALTER SCHEMA #{quote_schema_name(schema_name)} RENAME TO #{quote_schema_name(new_name)}"
285+
end
286+
282287
# Sets the schema search path to a string of comma-separated schema names.
283288
# Names beginning with $ have to be quoted (e.g. $user => '$user').
284289
# See: https://www.postgresql.org/docs/current/static/ddl-schemas.html

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,33 @@ def test_drop_schema_with_nonexisting_schema
201201
end
202202
end
203203

204+
def test_rename_schema
205+
@connection.create_schema("test_schema3")
206+
@connection.rename_schema("test_schema3", "test_schema4")
207+
assert_not_includes @connection.schema_names, "test_schema3"
208+
assert_includes @connection.schema_names, "test_schema4"
209+
ensure
210+
@connection.drop_schema("test_schema3", if_exists: true)
211+
@connection.drop_schema("test_schema4", if_exists: true)
212+
end
213+
214+
def test_rename_schema_with_nonexisting_schema
215+
assert_raises(ActiveRecord::StatementInvalid) do
216+
@connection.rename_schema("idontexist", "neitherdoi")
217+
end
218+
end
219+
220+
def test_rename_schema_with_existing_target_name
221+
@connection.create_schema("test_schema3")
222+
@connection.create_schema("test_schema4")
223+
assert_raises(ActiveRecord::StatementInvalid) do
224+
@connection.rename_schema("test_schema3", "test_schema4")
225+
end
226+
ensure
227+
@connection.drop_schema("test_schema3", if_exists: true)
228+
@connection.drop_schema("test_schema4", if_exists: true)
229+
end
230+
204231
def test_raise_wrapped_exception_on_bad_prepare
205232
assert_raises(ActiveRecord::StatementInvalid) do
206233
@connection.exec_query "select * from developers where id = ?", "sql", [bind_param(1)]

0 commit comments

Comments
 (0)