Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql - can't create database - OperationalError: source database "template1" is being accessed by other users

I logged in to source database template1 and now I can't create database. When I try to create database, I get this error:

OperationalError: source database "template1" is being accessed by other users DETAIL:  There are 5 other session(s) using the database. 

Every time I login to template1, I use 'exit' command to logout, but as you can see it does not logout and number of sessions increases everytime I login. Is there a way to force disconnect every connection to template1 that logged in now?

like image 930
Andrius Avatar asked Jan 17 '13 08:01

Andrius


2 Answers

Database template1 exists only to provide barebone structure to create another empty database. You should never logon to template1, otherwise you will have problems.

Probably easiest solution for you is to restart PostgreSQL server process, and logon again. Database that should always exist and is safe to logon is postgres.

If restarting is not an option, you can use another emergency template database: template0.

By default, this statement:

CREATE DATABASE dbname; 

is equivalent to:

CREATE DATABASE dbname TEMPLATE template1; 

If template1 is not available or corrupted, you can use template0 as last resort:

CREATE DATABASE dbname TEMPLATE template0; 

You can read more about template databases here.

like image 190
mvp Avatar answered Sep 19 '22 15:09

mvp


This helped me solve my problem:

SELECT *, pg_terminate_backend(procpid)  FROM pg_stat_activity  WHERE usename='username';  --Use pid if PostgreSQL version 9.2 or above. 

I terminated all active connections to template1 and could create database normally

like image 35
Andrius Avatar answered Sep 21 '22 15:09

Andrius