Ошибка удалить шаблон базы данных нельзя

4 Answers

postgres=# UPDATE pg_database SET datistemplate='false' WHERE datname='template_postgis';
UPDATE 1
postgres=# DROP DATABASE template_postgis;
DROP DATABASE
postgres=# 

answered Jul 9, 2012 at 3:33

dbkaplun's user avatar

dbkaplundbkaplun

3,4172 gold badges26 silver badges34 bronze badges

3

  • I looked in the script I used that created the template. There was the line psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';".

    Jul 9, 2012 at 3:35

  • This causes further problems. I made an upgrade from 9.1 -> 9.2 on ubuntu. This created template1 implicitly. I then executed your command and it seems to work. However, now I installed phpPgAdmin and I cannot login, it says : ‘FATAL: database «template1» does not exist’

    Jan 13, 2014 at 11:47

You can use the alter database command. Much simpler and safer than upsetting metadata.

postgres=# create database tempDB is_template true;
CREATE DATABASE
postgres=# drop database tempDB;
ERROR:  cannot drop a template database
postgres=# alter database tempDB is_template false;
ALTER DATABASE
postgres=# drop database tempDB;
DROP DATABASE
postgres=# 

Documentation

answered Aug 9, 2016 at 20:05

VynlJunkie's user avatar

VynlJunkieVynlJunkie

1,95322 silver badges26 bronze badges

4

  • This solution works and is far less complicated than the selected solution.

    Oct 4, 2016 at 16:26

  • @amoe Great spot. Edited to add documentation link

    Apr 4, 2017 at 8:45

  • Thank god you exist man. All the other solutions didn’t work. Thanks!

    Apr 26, 2018 at 16:09

  • This works, but make sure to add single quotes around 'false' POSTGRES v10

    May 20, 2018 at 0:17

In addition to other answers, you can drop template0 and template1 databases which PostgreSQL has by default with the SQLs below:

ALTER DATABASE template0 IS_TEMPLATE FALSE;
DROP DATABASE template0;
ALTER DATABASE template1 IS_TEMPLATE FALSE;
DROP DATABASE template1;

answered Aug 11 at 14:27

Super Kai - Kazuya Ito's user avatar

update pg_database set datistemplate=false where datname='template0';
update pg_database set datistemplate=false where datname='template1';

....

Creating script to analyze new cluster                      ok
Creating script to delete old cluster                       ok
Checking for hash indexes                                   ok

Upgrade Complete
----------------

DieterDP's user avatar

DieterDP

4,0492 gold badges30 silver badges38 bronze badges

answered Aug 29, 2019 at 11:20

dba's user avatar

4 Answers

postgres=# UPDATE pg_database SET datistemplate='false' WHERE datname='template_postgis';
UPDATE 1
postgres=# DROP DATABASE template_postgis;
DROP DATABASE
postgres=# 

answered Jul 9, 2012 at 3:33

dbkaplun's user avatar

dbkaplundbkaplun

3,4172 gold badges26 silver badges34 bronze badges

3

  • I looked in the script I used that created the template. There was the line psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis';".

    Jul 9, 2012 at 3:35

  • This causes further problems. I made an upgrade from 9.1 -> 9.2 on ubuntu. This created template1 implicitly. I then executed your command and it seems to work. However, now I installed phpPgAdmin and I cannot login, it says : ‘FATAL: database «template1» does not exist’

    Jan 13, 2014 at 11:47

You can use the alter database command. Much simpler and safer than upsetting metadata.

postgres=# create database tempDB is_template true;
CREATE DATABASE
postgres=# drop database tempDB;
ERROR:  cannot drop a template database
postgres=# alter database tempDB is_template false;
ALTER DATABASE
postgres=# drop database tempDB;
DROP DATABASE
postgres=# 

Documentation

answered Aug 9, 2016 at 20:05

VynlJunkie's user avatar

VynlJunkieVynlJunkie

1,95322 silver badges26 bronze badges

4

  • This solution works and is far less complicated than the selected solution.

    Oct 4, 2016 at 16:26

  • @amoe Great spot. Edited to add documentation link

    Apr 4, 2017 at 8:45

  • Thank god you exist man. All the other solutions didn’t work. Thanks!

    Apr 26, 2018 at 16:09

  • This works, but make sure to add single quotes around 'false' POSTGRES v10

    May 20, 2018 at 0:17

In addition to other answers, you can drop template0 and template1 databases which PostgreSQL has by default with the SQLs below:

ALTER DATABASE template0 IS_TEMPLATE FALSE;
DROP DATABASE template0;
ALTER DATABASE template1 IS_TEMPLATE FALSE;
DROP DATABASE template1;

answered Aug 11 at 14:27

Super Kai - Kazuya Ito's user avatar

update pg_database set datistemplate=false where datname='template0';
update pg_database set datistemplate=false where datname='template1';

....

Creating script to analyze new cluster                      ok
Creating script to delete old cluster                       ok
Checking for hash indexes                                   ok

Upgrade Complete
----------------

DieterDP's user avatar

DieterDP

4,0492 gold badges30 silver badges38 bronze badges

answered Aug 29, 2019 at 11:20

dba's user avatar

Drop A Template Database From PostgreSQL

postgres=# DROP DATABASE tempdb;
ERROR: cannot drop a template database

METHOD 1:

  • if we want to drop any database means you need to set datistemplate=false
  • if you want to connect to template0 you need to set dataallowcomm=true

temp0=# UPDATE pg_database SET datistemplate='false' WHERE datname='temp0';
UPDATE 1

—Becouse you cannot drop from connected database temp0 if you want to drop the database you need to connect as another database and drop the temp0 database 

temp0=# DROP DATABASE temp0;                                               
ERROR: cannot drop the currently open database

postgres=# DROP DATABASE tempdb;
DROP DATABASE

METHOD 2:

postgres=# create database temp11 is_template true;
CREATE DATABASE
postgres=# drop database tempdb;
ERROR: cannot drop a template database
postgres=# alter database tempdb is_template false;
ALTER DATABASE
postgres=# drop database tempdb;
DROP DATABASE

Popular posts from this blog

How to find the server is whether standby (slave) or primary(master) in Postgresql replication ?

Method 1 You can check the mode of the server using «pg_controldata». [pgsql@test~]$ pg_controldata /usr/local/pgsql/data84/ Database cluster state: in archive recovery —> This is Standby Database Database cluster state: in production —> This is Production Database [Master] Method 2 You can use pg_is_in_recovery() which returns True if recovery is still in progress(so the server is running in standby mode or slave) postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- t (1 row) If Return    false   so the server is running in primary mode or master postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- f (1 row)

7 Steps to configure BDR replication in postgresql

Image

 The  BDR  (Bi-Directional Replication) project adds multi-master replication to PostgreSQL 9.4.  Postgres-BDR has a lower impact on the masters(s) than trigger-based replication solutions. There is no write-amplification, as it does not require triggers to write to queue tables in order to replicate writes.   Here We are using  postgres version 9.4.12 and bdr version 1.0.2. for configuring  multi master replication . Simply Following 7 steps you can configure the multi master replication in postgresql. To download the bdr in below link. .   https://github.com/2ndQuadrant/bdr/archive/bdr-pg/REL9_4_12-1.tar.gz $ tar -xzvf REL9_4_12-1.tar.gz $ wget https://github.com/2ndQuadrant/bdr/archive/bdr-plugin/1.0.2.tar.gz $ tar -xzvf 1.0.2.tar.gz 1. To install BDR. $ cd ~/bdr-bdr-pg-REL9_4_12-1 $ ./configure —prefix=/usr/lib/postgresql/9.4 —enable-debug —with-openssl $ make -j4 -s install-world $ cd ~/bdr-bdr-plugin-1.0.2 $ PATH=/usr/lib/postgresql/9.4/bin:»$PATH» ./c

How to Get Table Size, Database Size, Indexes Size, schema Size, Tablespace Size, column Size in PostgreSQL Database

In this post, I am sharing few important function for finding the size of database, table and index in PostgreSQL. Finding object size in postgresql database is very important and common. Is it very useful to know the exact size occupied by the object at the tablespace. The object size in the following scripts is in GB. The scripts have been formatted to work very easily with PUTTY SQL Editor. 1. Checking table size excluding table dependency: SELECT pg_size_pretty(pg_relation_size(‘mhrordhu_shk.mut_kharedi_audit’)); pg_size_pretty —————- 238 MB (1 row) 2. Checking table size including table dependency: SELECT pg_size_pretty(pg_total_relation_size(‘mhrordhu_shk.mut_kharedi_audit’)); pg_size_pretty —————- 268 MB (1 row) 3. Finding individual postgresql database size SELECT pg_size_pretty(pg_database_size(‘db_name’)); 4. Finding individual table size for postgresql database -including dependency index: SELECT pg_size_pretty(pg_total_rel

apt-add-repository

apt-add-repository -V (return code: 2) Usage: apt-add-repository <sourceline> apt-add-repository is a script for adding apt sources.list entries. It can be used to add any repository and also provides a shorthand syntax for adding a Launchpad PPA (Personal Package Archive) repository. <sourceline> — The apt repository source line to add. This is one of: a complete apt line in quotes, a repo url and areas in quotes (areas defaults to ‘main’) a PPA shortcut. a distro component Examples: apt-add-repository ‘deb http://myserver/path/to/repo stable myrepo’ apt-add-repository ‘http://myserver/path/to/repo myrepo’ apt-add-repository ‘https://packages.medibuntu.org free non-free’ apt-add-repository http://extras.ubuntu.com/ubuntu apt-add-repository ppa:user/repository apt-add-repository ppa:user/distro/repository apt-add-repository multiverse If —remove is given the tool will remove the given sourceline fr

vacuumlo — removing large objects orphans from a database PostgreSQL

vacuumlo   is a simple utility program that will remove any   “ orphaned ”   large objects from a   PostgreSQL   database. An orphaned large object (LO) is considered to be any LO whose OID does not appear in any   oid   or   lo   data column of the database. OIDs basically give you a built-in, globally unique id for every row,default is on( default_with_oids ( boolean )). If you use this, you may also be interested in the   lo_manage   trigger in the   lo   module.   lo_manage   is useful to try to avoid creating orphaned LOs in the first place. More about lo module  there are two ways to store large objects in the PostgreSQL:   bytea oid and lo  Working process of vacuumlo: First, vacuumlo builds a temporary table which contains all of the OIDs of the large objects in the selected database. It then scans through all columns in the database that are of type oid or lo, and removes matching entries from the temporary table. (Note: only types with these names are con

When i try to create other database with the name «eCommerce» in pgadmin 4 this message appears

ERROR: source database «template1» is being accessed by other users
DETAIL: There are 2 other sessions using the database.

I try to delete the others databases but is not working and appears

ERROR: cannot drop a template database

What should i do?

asked Nov 16, 2019 at 20:26

Sabrina MK's user avatar

3

It’s impossible to drop a database in pgAdmin4 by right-clicking on it and selecting Delete/Drop from the context menu. Because as soon as you right-click on it pgAdmin opens a connection to that database.

But there is another way in pgAdmin4:

  1. Close connections to the databases you would like to delete by right-clicking on it and selecting «Disconnect database…»

  2. Left-click on «Databases» (One up in the hierarchy: The folder that contains all your databases)

  3. Select tab «Properties» on the right hand side

  4. There you can select all your databases you would like to delete and click on the trashcan icon:

enter image description here

answered Nov 18, 2020 at 8:10

softi's user avatar

softisofti

4911 gold badge4 silver badges3 bronze badges

2

You simply need to terminate the connections before deleting the database :)

    //Terminate all Connections on HostDB
     SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'Database_you_want_to_delete';

After that deleting shall work without an further problems.

Edit: For further information please take a look at this thread: Kill a postgresql session/connection

answered Nov 16, 2019 at 22:26

mZed's user avatar

mZedmZed

3392 silver badges7 bronze badges

0

The Simplest Solution, I think, is closing opened tabs

simply closing any opened tabs related to that database in pgAdmin solves it.

In your case, 2 processes «might» be translated as at most two tabs in pgAdmin related to that database!

answered Feb 10, 2021 at 14:53

Muluken Getachew's user avatar

You can not drop the currently open database. Run query DROP DATABASE db_name; in Query Tool from another database.

answered Mar 4, 2022 at 10:10

dodiws's user avatar

Using pgAdmin, I followed @softi’s solution but tweaked it a little bit and it worked

First, Close connections to the database(s) you would like to delete by right-clicking on it and selecting «Disconnect database…»

Left-click on «Databases» (One up in the hierarchy: The folder that contains all your databases)

Select «Dashboard» tab on the right hand side and terminate the session(s) of the database(s) you want to delete/drop

Then go to the «Properties» tab (next to the Dashboard tab), then select the database(s) you would like to delete and click on the trashcan icon above the list

answered May 25, 2022 at 21:57

Hope Chijuka's user avatar

  1. Close PgAdmin
  2. Open a terminal
  3. psql
  4. drop database [db_name];

Bonus points:
to create a database:
create database [db_name];

answered Sep 3 at 20:09

RoyalBigMack's user avatar

Я этого не знал template0 а также template1 Шаблоны базы данных необходимы для создания пустых баз данных. Я удалил их, чтобы очистить postgres. Теперь я не могу создать новую базу данных. Дает мне эту ошибку:

ERROR:  template database "template1" does not exist

Что я могу сделать, чтобы дела пошли еще раз. Я буду очень благодарен за любую помощь.

2015-01-16 20:51

1
ответ

Решение

К счастью, я имел postgres база данных сохранилась, потому что это было необходимо для postgres пользователь, чтобы войти psql, Таким образом, создали template0 а также template1 база данных:

create database template0 TEMPLATE postgres;

и то же самое для template1. Затем выполнено:

update pg_database set datistemplate=true  where datname='template0';

чтобы обе базы данных не смогли случайно удалить эти шаблоны снова.

Теперь все отлично работает:)

2015-01-16 21:14

На моем компьютере с CentOS 7 мне не так повезло, что у меня все еще была база данных для подключения. Тем не мение:

su postgres -c "initdb /var/lib/pgsql/data"

(как root) создал template0 и template 1 для работы.

2019-04-23 20:39

Для postgres 12.3 у меня сработало следующее.

я удалил template1не зная, что это было. Я смог создать это изtemplate0. Вы также можете создать его изpostgres.

createdb -T template0 template1
createdb -T postgres template1

Это предлагается в документах —

template1 и template0 не имеют никакого специального статуса, кроме того факта, что имя template1 является именем исходной базы данных по умолчанию для CREATE DATABASE. Например, можно отбросить template1 и воссоздать его из template0 без каких-либо побочных эффектов.

https://www.postgresql.org/docs/current/manage-ag-templatedbs.html

2020-05-28 02:36

На моей машине debian я обновил некоторые кластеры до версии 11. базы данных шаблона [01] в целевом кластере были отброшены, и я использовал базы данных из более старых версий.

как root я создал новый кластер с помощью pg_createcluster.

как пользователь postgres:

дамп базы данных нового кластера с помощью pg_dumpall (с флагом —clean).

отбросьте новый кластер.

импортируйте полученный источник в свой кластер с помощью psql.

я бы удалил postgres роли drop и создание того же самого.

С уважением, Алекс

2020-02-19 21:41

Понравилась статья? Поделить с друзьями:
  • Ошибка ф05 на стиральной машине хотпоинт аристон
  • Ошибка ф05 на стиральной машине индезит
  • Ошибка ф05 на стиральной машине вирпул
  • Ошибка установки лаунчера фогейм
  • Ошибка ф05 на котле висман