Меню

Ошибка нельзя переименовать текущую базу данных postgresql

I’m trying to rename a DB in pgAdmin 4. But I this get error: ERROR: current database cannot be renamed.

What’s the process for renaming a database in pgAdmin (the docs are USELESS)? And google can’t provide a solution.

asked May 9, 2018 at 7:05

1

Using pgAdmin 4,

1) switch to the dashboard view

2) select the database to be renamed, right-click it and select Disconnect Database

3) Again select the database to be renamed, right-click it and select properties

4) change the name of the database in the Database field -click save

enter image description here

answered Sep 26, 2019 at 8:37

KenBuckley's user avatar

KenBuckleyKenBuckley

5536 silver badges13 bronze badges

right click on db name and Properties, then change the name and click Saveenter image description here:

Or just click on other db (eg postgres), open query tool and run

alter database "old" rename to "new";

answered May 9, 2018 at 7:14

Vao Tsun's user avatar

Vao TsunVao Tsun

45.5k10 gold badges93 silver badges124 bronze badges

You are probably trying to rename the database you are connected to.
Switch to a different db and then execute the ALTER command.

answered Jun 22, 2020 at 13:17

Pavan's user avatar

PavanPavan

412 bronze badges

I’m trying to rename a DB in pgAdmin 4. But I this get error: ERROR: current database cannot be renamed.

What’s the process for renaming a database in pgAdmin (the docs are USELESS)? And google can’t provide a solution.

asked May 9, 2018 at 7:05

1

Using pgAdmin 4,

1) switch to the dashboard view

2) select the database to be renamed, right-click it and select Disconnect Database

3) Again select the database to be renamed, right-click it and select properties

4) change the name of the database in the Database field -click save

enter image description here

answered Sep 26, 2019 at 8:37

KenBuckley's user avatar

KenBuckleyKenBuckley

5536 silver badges13 bronze badges

right click on db name and Properties, then change the name and click Saveenter image description here:

Or just click on other db (eg postgres), open query tool and run

alter database "old" rename to "new";

answered May 9, 2018 at 7:14

Vao Tsun's user avatar

Vao TsunVao Tsun

45.5k10 gold badges93 silver badges124 bronze badges

You are probably trying to rename the database you are connected to.
Switch to a different db and then execute the ALTER command.

answered Jun 22, 2020 at 13:17

Pavan's user avatar

PavanPavan

412 bronze badges

Может ли кто-нибудь помочь мне переименовать базу данных в postgresql из оболочки Linux

ALTER DATABASE name RENAME TO newname

Приведенный выше оператор не выполняется

6 ответы

Какая версия postgresql? От Документация 8.1:

ИЗМЕНИТЬ имя БАЗЫ ПЕРЕИМЕНОВАТЬ НА новое имя;

Только владелец базы данных или суперпользователь может переименовать базу данных; Владельцы, не являющиеся суперпользователями, также должны иметь привилегию CREATEDB. Текущая база данных не может быть переименована. (Подключитесь к другой базе данных, если вам нужно это сделать.)

Создан 06 июн.

Это может быть глупо очевидный вопрос. Вы используете psql как пользователь postgres?

например

$ sudo -u postgres psql
# alter database FOO rename to BAR;
# q

ответ дан 17 авг.

Вам могут потребоваться привилегии для renmae db. Это может сделать только владелец db или суперпользователь, владельцу также нужен пользователь createdb.

Также нельзя переименовать базу данных, к которой вы подключены, вам нужно подключиться к другой.

Создан 27 фев.

Вы не можете переименовать базу данных, к которой вы подключены. Перед изменением имени базы данных убедитесь, что вы отключены. В PGAdmin вы можете просто щелкнуть правой кнопкой мыши по самой базе данных, перейти в свойства и переименовать ее оттуда. Как указывали другие, вы также можете попробовать команду: ALTER DATABASE (DB NAME) RENAME TO (NEW NAME);

ответ дан 23 дек ’16, 15:12

Отключить базу данных (Ctrl + F2 в DataGrip)

А потом:

$ psql -U postgres
postgres=# ALTER DATABASE db_a RENAME TO db_b;

GL

Создан 19 июля ’20, 09:07

Ниже приведены шаги по переименованию базы данных в postgresql.

1) Щелкните правой кнопкой мыши базу данных и выберите «Обновить».
2) Щелкните правой кнопкой мыши еще раз и выберите параметр свойств.
3) На вкладке свойств вы можете изменить имя на желаемое.

Создан 02 ноя.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

postgresql

or задайте свой вопрос.

ALTER DATABASE — change a database

Synopsis

ALTER DATABASE name [ [ WITH ] option [ ... ] ]

where option can be:

    ALLOW_CONNECTIONS allowconn
    CONNECTION LIMIT connlimit
    IS_TEMPLATE istemplate

ALTER DATABASE name RENAME TO new_name

ALTER DATABASE name OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }

ALTER DATABASE name SET TABLESPACE new_tablespace

ALTER DATABASE name REFRESH COLLATION VERSION

ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }
ALTER DATABASE name SET configuration_parameter FROM CURRENT
ALTER DATABASE name RESET configuration_parameter
ALTER DATABASE name RESET ALL

Description

ALTER DATABASE changes the attributes of a database.

The first form changes certain per-database settings. (See below for details.) Only the database owner or a superuser can change these settings.

The second form changes the name of the database. Only the database owner or a superuser can rename a database; non-superuser owners must also have the CREATEDB privilege. The current database cannot be renamed. (Connect to a different database if you need to do that.)

The third form changes the owner of the database. To alter the owner, you must own the database and also be a direct or indirect member of the new owning role, and you must have the CREATEDB privilege. (Note that superusers have all these privileges automatically.)

The fourth form changes the default tablespace of the database. Only the database owner or a superuser can do this; you must also have create privilege for the new tablespace. This command physically moves any tables or indexes in the database’s old default tablespace to the new tablespace. The new default tablespace must be empty for this database, and no one can be connected to the database. Tables and indexes in non-default tablespaces are unaffected.

The remaining forms change the session default for a run-time configuration variable for a PostgreSQL database. Whenever a new session is subsequently started in that database, the specified value becomes the session default value. The database-specific default overrides whatever setting is present in postgresql.conf or has been received from the postgres command line. Only the database owner or a superuser can change the session defaults for a database. Certain variables cannot be set this way, or can only be set by a superuser.

Parameters

name

The name of the database whose attributes are to be altered.

allowconn

If false then no one can connect to this database.

connlimit

How many concurrent connections can be made to this database. -1 means no limit.

istemplate

If true, then this database can be cloned by any user with CREATEDB privileges; if false, then only superusers or the owner of the database can clone it.

new_name

The new name of the database.

new_owner

The new owner of the database.

new_tablespace

The new default tablespace of the database.

This form of the command cannot be executed inside a transaction block.

REFRESH COLLATION VERSION

Update the database collation version. See Notes for background.

configuration_parameter
value

Set this database’s session default for the specified configuration parameter to the given value. If value is DEFAULT or, equivalently, RESET is used, the database-specific setting is removed, so the system-wide default setting will be inherited in new sessions. Use RESET ALL to clear all database-specific settings. SET FROM CURRENT saves the session’s current value of the parameter as the database-specific value.

See SET and Chapter 20 for more information about allowed parameter names and values.

Notes

It is also possible to tie a session default to a specific role rather than to a database; see ALTER ROLE. Role-specific settings override database-specific ones if there is a conflict.

Examples

To disable index scans by default in the database test:

ALTER DATABASE test SET enable_indexscan TO off;

Compatibility

The ALTER DATABASE statement is a PostgreSQL extension.

I need to rename the database but when I do in
PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld" it told me that it cannot.

How can I do it?

(Version 8.3 on WindowsXP)

Update

  • The first error message : Cannot because I was connect to it. So I selected an other database and did the queries.

  • I get a second error message telling me that it has come user connect. I see in the PGAdmin screen that it has many PID but they are inactive… I do not see how to kill them.

Jai Chauhan's user avatar

Jai Chauhan

3,8053 gold badges36 silver badges58 bronze badges

asked Sep 27, 2008 at 15:00

Patrick Desjardins's user avatar

6

Try not quoting the database name:

ALTER DATABASE people RENAME TO customers;

Also ensure that there are no other clients connected to the database at the time. Lastly, try posting the error message it returns so we can get a bit more information.

answered Sep 27, 2008 at 15:03

bmdhacks's user avatar

5

For future reference, you should be able to:

-- disconnect from the database to be renamed
c postgres

-- force disconnect all other clients from the database to be renamed
SELECT pg_terminate_backend( pid )
FROM pg_stat_activity
WHERE pid <> pg_backend_pid( )
    AND datname = 'name of database';

-- rename the database (it should now have zero clients)
ALTER DATABASE "name of database" RENAME TO "new name of database";

Note that table pg_stat_activity column pid was named as procpid in versions prior to 9.2. So if your PostgreSQL version is lower than 9.2, use procpid instead of pid.

Mohayemin's user avatar

Mohayemin

3,8114 gold badges27 silver badges54 bronze badges

answered Oct 6, 2011 at 18:43

gsiems's user avatar

gsiemsgsiems

3,3801 gold badge23 silver badges24 bronze badges

2

I just ran into this and below is what worked:

1) pgAdmin is one of the sessions. Use psql instead.
2) Stop the pgBouncer and/or scheduler services on Windows as these also create sessions

answered Aug 25, 2013 at 15:29

smoore4's user avatar

smoore4smoore4

4,2323 gold badges32 silver badges54 bronze badges

Unexist told me in comment to restart the database and it works! Restarting the database kill all existing connection and then I connect to an other database and was able to rename it with my initial query.

Thx all.

answered Sep 27, 2008 at 15:16

Patrick Desjardins's user avatar

Instead of deploying a nuke (restarting the server) you should try to close those connections that bother you either by finding where are they from and shutting down the client processes or by using the pg_cancel_backend() function.

answered Sep 27, 2008 at 15:43

Milen A. Radev's user avatar

Milen A. RadevMilen A. Radev

58.8k22 gold badges105 silver badges110 bronze badges

0

When connected via pgadmin, the default database will be postgres.

ALTER DATABASE postgres RENAME TO pgnew;

This will not work.

You need to right click on server in pgadmin and set Maintenance DB to some other DB and save. Then retry and it should work if no other connections exists.

answered Apr 5, 2021 at 10:49

Valsaraj Viswanathan's user avatar

For anyone running into this issue using DBeaver and getting an error message like this:

ERROR: database "my_stubborn_db" is being accessed by other users
  Detail: There is 1 other session using the database.

Disconnect your current connection, and reconnect to the same server with a connection that doesn’t target the database you are renaming.

Changing the active database is not enough.

answered Mar 6, 2020 at 5:03

rovyko's user avatar

rovykorovyko

3,8795 gold badges30 silver badges42 bronze badges

Может кто-нибудь помочь мне переименовать базу данных в postgresql из оболочки Linux

ALTER DATABASE name RENAME TO newname

Вышеприведенный оператор не выполняет

4b9b3361

Ответ 1

Какая версия postgresql? Из 8.1 Документация:

ALTER DATABASE name RENAME TO новое имя;

Только владелец базы данных или суперпользователь может переименовать базу данных; непривилигированной владельцы также должны иметь CREATEDB привилегия. Текущая база данных не может переименовываться. (Подключитесь к другому если вам нужно это сделать.)

Ответ 2

Это может быть глупо очевидный вопрос. Вы используете psql в качестве пользователя postgres?

например.

$ sudo -u postgres psql
# alter database FOO rename to BAR;
# q

Ответ 3

Вам может потребоваться priviliges для renmae db. Только владелец db или суперпользователь может это сделать, владельцу также нужна собственная личность.

Также нельзя переименовать базу данных, к которой вы подключены, вам нужно подключиться к другой.

Ответ 4

Вы не можете переименовать базу данных, к которой вы подключены. Перед изменением имени db убедитесь, что вы отключены.
В PGAdmin вы можете просто щелкнуть правой кнопкой мыши по самой базе данных, перейти к свойствам и переименовать ее оттуда.
Как указывали другие, вы также можете попробовать команду:
ALTER DATABASE (DB NAME) ИЗМЕНИТЬ (НОВОЕ ИМЯ БД);

Ответ 5

Ниже приведены шаги для переименования базы данных в postgresql.

1) Щелкните правой кнопкой мыши по базе данных и выберите обновление.
2) Щелкните правой кнопкой мыши еще раз и выберите вариант свойств.
3) На вкладке свойств вы можете изменить имя с тем, которое вы хотите.


Мне нужно переименовать базу данных, но когда я это сделал,
PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld"мне сказали, что это невозможно.

Как мне это сделать?

( Версия 8.3 для WindowsXP )

Обновить

  • Первое сообщение об ошибке: Невозможно, потому что я подключился к нему. Поэтому я выбрал другую базу данных и выполнил запросы.

  • Я получаю второе сообщение об ошибке, в котором говорится, что пользователь подключился. Я вижу на PGAdminэкране, что их много, PIDно они неактивны … Не вижу, как их убить.






Ответы:


Старайтесь не цитировать имя базы данных:

ALTER DATABASE people RENAME TO customers;

Также убедитесь, что к базе данных не подключены другие клиенты. Наконец, попробуйте опубликовать сообщение об ошибке, которое он возвращает, чтобы мы могли получить немного больше информации.







Для справки в будущем вы должны уметь:

-- disconnect from the database to be renamed
c postgres

-- force disconnect all other clients from the database to be renamed
SELECT pg_terminate_backend( pid )
FROM pg_stat_activity
WHERE pid <> pg_backend_pid( )
    AND datname = 'name of database';

-- rename the database (it should now have zero clients)
ALTER DATABASE "name of database" RENAME TO "new name of database";

Обратите внимание, что pg_stat_activityстолбец таблицы pidбыл назван так, как procpidв версиях до 9.2. Поэтому, если ваша версия PostgreSQL ниже 9.2, используйте procpidвместо pid.



Я только что столкнулся с этим, и вот что сработало:

1) pgAdmin— одна из сессий. psqlВместо этого используйте .
2) Остановите pgBouncerслужбы и / или службы планировщика в Windows, поскольку они также создают сеансы


Unexist сказал мне в комментарии перезапустить базу данных, и она работает! Перезапуск базы данных уничтожает все существующие соединения, а затем я подключаюсь к другой базе данных и смог переименовать ее с помощью моего первоначального запроса.

Спасибо всем.


Вместо развертывания ядерной бомбы (перезапуска сервера) вы должны попытаться закрыть те соединения, которые вас беспокоят, либо обнаружив, откуда они и завершив клиентские процессы, либо с помощью этой pg_cancel_backend()функции.


Для тех, кто сталкивается с этой проблемой при использовании DBeaver и получает такое сообщение об ошибке:

ERROR: database "my_stubborn_db" is being accessed by other users
  Detail: There is 1 other session using the database.

Отключите текущее соединение и повторно подключитесь к тому же серверу с подключением, которое не нацелено на базу данных, которую вы переименовываете.

Менять активную базу данных недостаточно.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка нельзя выполнить установку ps4