I have been reading this tutorial. There is the below command to login as a user:
# login as user "user"
psql -U user
when I execute the above command, I get an error saying the following:
psql: FATAL: role "user" does not exist
The only help I saw online was here, the have said the following:
FATAL: role «myusername» does not exist
By default PostgreSQL connects to the PostgreSQL user with the same
name as the current unix user. You have not created a PostgreSQL user
by that name in your database.Create a suitable user, or specify a different username to connect
with. In the command line tools the -U flag does this.
But I still don’t quite understand why I am getting this error.
halfer
19.8k17 gold badges98 silver badges185 bronze badges
asked Sep 3, 2015 at 10:59
Alexander SolonikAlexander Solonik
9,74818 gold badges73 silver badges173 bronze badges
1
You have first to login in a linux shell as the user postgres
and than create new postgres user with the command createuser
. The system user postgres
is created automatically by the Postgres installer.
Execute this code in the console (change your_username
with a username of your choice):
sudo -u postgres -i
createuser -l -d -P your_username
Better you create a database with the same name too (this makes the login later easier):
createdb your_username -O your_username
Then you should be able to connect in psql with
psql -h localhost -U your_username
answered Sep 3, 2015 at 13:07
Please check to see if the user exists.
dg
If not, you need what is missing in the tutorial and you edit it if necessary.
CREATE USER user WITH PASSWORD '<here you password>';
answered Sep 3, 2015 at 12:45
RenéRené
813 bronze badges
I’m setting up my PostgreSQL 9.1. I can’t do anything with PostgreSQL: can’t createdb
, can’t createuser
; all operations return the error message
Fatal: role h9uest does not exist
h9uest
is my account name, and I sudo apt-get install
PostgreSQL 9.1 under this account.
Similar error persists for the root
account.
asked Aug 12, 2012 at 3:00
7
Use the operating system user postgres
to create your database — as long as you haven’t set up a database role with the necessary privileges that corresponds to your operating system user of the same name (h9uest
in your case):
sudo -u postgres -i
As recommended here or here.
Then try again. Type exit
when done with operating as system user postgres
.
Or execute the single command createuser
as postgres
with sudo
, like demonstrated by
dsrees in another answer.
The point is to use the operating system user matching the database role of the same name to be granted access via ident
authentication. postgres
is the default operating system user to have initialized the database cluster. The manual:
In order to bootstrap the database system, a freshly initialized
system always contains one predefined role. This role is always a
“superuser”, and by default (unless altered when runninginitdb
) it
will have the same name as the operating system user that initialized
the database cluster. Customarily, this role will be namedpostgres
.
In order to create more roles you first have to connect as this
initial role.
I have heard of odd setups with non-standard user names or where the operating system user does not exist. You’d need to adapt your strategy there.
Read about database roles and client authentication in the manual.
answered Aug 12, 2012 at 4:13
Erwin BrandstetterErwin Brandstetter
596k144 gold badges1058 silver badges1215 bronze badges
6
After trying many other people’s solutions, and without success, this answer finally helped me.
https://stackoverflow.com/a/16974197/2433309
In short, running
sudo -u postgres createuser owning_user
creates a role with name owning_user (in this case, h9uest). After that you can run rake db:create
from the terminal under whatever account name you set up without having to enter into the Postgres environment.
Vaibhav Mule
4,9864 gold badges35 silver badges52 bronze badges
answered Sep 9, 2013 at 23:27
dsreesdsrees
6,0662 gold badges26 silver badges26 bronze badges
9
sudo su - postgres
psql template1
creating role on pgsql with privilege as «superuser»
CREATE ROLE username superuser;
eg. CREATE ROLE demo superuser;
Then create user
CREATE USER username;
eg. CREATE USER demo;
Assign privilege to user
GRANT ROOT TO username;
And then enable login that user, so you can run e.g.: psql template1
, from normal $
terminal:
ALTER ROLE username WITH LOGIN;
the
20.8k11 gold badges68 silver badges101 bronze badges
answered May 29, 2014 at 13:35
Mohammed SaleemMohammed Saleem
1,8731 gold badge11 silver badges6 bronze badges
5
This works for me:
psql -h localhost -U postgres
ssbl
432 silver badges6 bronze badges
answered Aug 12, 2014 at 11:39
4
Installing postgres using apt-get
does not create a user role or a database.
To create a superuser role and a database for your personal user account:
sudo -u postgres createuser -s $(whoami); createdb $(whoami)
answered Jul 18, 2016 at 19:01
Miles EricksonMiles Erickson
2,5742 gold badges17 silver badges18 bronze badges
2
psql postgres
postgres=# CREATE ROLE username superuser;
postgres=# ALTER ROLE username WITH LOGIN;
answered Apr 7, 2019 at 15:08
AbelAbel
3,93932 silver badges31 bronze badges
4
For version Postgres 9.5 use following comand:
psql -h localhost -U postgres
Hope this will help.
answered Jan 13, 2019 at 5:07
0
Working method,
vi /etc/postgresql/9.3/main/pg_hba.conf
local all postgres peer
here change peer to trust-
restart,
sudo service postgresql restart
-
now try,
psql -U postgres
answered Sep 10, 2017 at 16:23
2
I did a healthcheck with docker-compose.
healthcheck:
test: ['CMD-SHELL', 'pg_isready']
interval: 5s
timeout: 5s
retries: 5
If you also have that change the user:
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres'] # <<<---
interval: 5s
timeout: 5s
retries: 5
answered Aug 7, 2021 at 8:07
JanJan
11.9k9 gold badges52 silver badges87 bronze badges
For Windows users : psql -U postgres
You should see then the command-line interface to PostgreSQL: postgres=#
answered Feb 8, 2019 at 12:13
Andriy TolstoyAndriy Tolstoy
5,6422 gold badges31 silver badges30 bronze badges
1
In local user prompt, not root user prompt, type
sudo -u postgres createuser <local username>
Then enter password for local user.
Then enter the previous command that generated «role ‘username’ does not exist.»
Above steps solved the problem for me.
If not, please send terminal messages for above steps.
answered Jun 21, 2015 at 20:28
0
Manually creating a DB cluster solved it in my case.
For some reason, when I installed postgres, the «initial DB» wasn’t created. Executing initdb
did the trick for me.
This solution is provided in the PostgreSQL Wiki — First steps:
initdb
Typically installing postgres to your OS creates an «initial DB» and starts the postgres server daemon running. If not then you’ll need to run initdb
answered Aug 28, 2018 at 19:53
NatachaNatacha
1,12415 silver badges23 bronze badges
0
sudo -u postgres createuser --superuser $USER
sudo -u postgres createdb $USER
This should definitely work for you.
answered Jul 25, 2022 at 13:05
dump and restore with --no-owner --no-privileges
flags
e.g.
dump — pg_dump --no-owner --no-privileges --format=c --dbname=postgres://userpass:username@postgres:5432/schemaname > /tmp/full.dump
restore — pg_restore --no-owner --no-privileges --format=c --dbname=postgres://userpass:username@postgres:5432/schemaname /tmp/full.dump
answered Jul 25, 2019 at 12:29
srghmasrghma
4,7002 gold badges38 silver badges54 bronze badges
for those who using docker and correctly followed the instructions from official doc, if you still met this problem, RESTART windows and try again.
answered Apr 27, 2022 at 4:57
SiweiSiwei
19.4k6 gold badges74 silver badges94 bronze badges
Follow These Steps and it Will Work For You :
- run
msfconsole
- type db_console
- some information will be shown to you chose the information who tell you to make:
db_connect user:pass@host:port.../database
sorry I don’t remember it but it’s like this one then replace the user and the password and the host and the database with the information included in thedatabase.yml
in the emplacement:/usr/share/metasploit-framework/config
- you will see. rebuilding the model cache in the background.
- Type apt-get update && apt-get upgrade after the update restart the terminal and lunch msfconsole and it works you can check that by typing in
msfconsole: msf>db_status
you will see that it’s connected.
answered Aug 17, 2017 at 10:20
Follow these steps to get postgres working.
- In your terminal, locate the Application Support folder with the following command.
/Users/[name of the user]/library/application support - Delete the application, Postgres.
- Reinstall the app and it should work just fine.
answered Jul 11, 2021 at 5:48
Something as simple as changing port from 5432 to 5433 worked for me.
answered Aug 12, 2020 at 0:23
1
Используйте пользователя postgres
операционной системы для создания вашей базы данных — если вы не настроили роль базы данных с необходимыми привилегиями, соответствующими пользователю вашей операционной системы с таким же именем (h9uest
в вашем случае):
sudo -u postgres -i
Как рекомендуется здесь или здесь.
Тогда попробуйте еще раз. Напечатайте exit
когда закончите с работой как системный пользователь postgres
.
Или выполните одну команду createuser
как postgres
с sudo
, как продемонстрировано drees в другом ответе.
Смысл заключается в том, чтобы использовать пользователя операционной системы, совпадающего с ролью базы данных с тем же именем, для предоставления доступа через ident
аутентификацию. postgres
— это пользователь операционной системы по умолчанию, который инициализировал кластер базы данных. Руководство:
Для начальной загрузки системы базы данных, недавно инициализированная система всегда содержит одну предопределенную роль. Эта роль всегда является «суперпользователем», и по умолчанию (если она не изменена при запуске
initdb
) она будет иметь то же имя, что и пользователь операционной системы, который инициализировал кластер базы данных. Обычно эта роль будет называтьсяpostgres
. Чтобы создать больше ролей, сначала необходимо подключиться к этой начальной роли.
Я слышал о странных установках с нестандартными именами пользователей или о том, где пользователь операционной системы не существует. Вам нужно будет адаптировать свою стратегию там.
Читайте о ролях базы данных и аутентификации клиента в руководстве.
2021-01-13 3 min
After installing PostgreSQL in mac os x using brew, you may have encountered the next error when executing the psql
command.
FATAL: role "postgres" does not exist
According to the message, there’s no user named postgres in the DB. So, let’s try to create it with the createuser
command installed together with postgres. Make sure the postgres user have admin permissions by providing the --superuser
operator.
$ createuser --superuser postgres
But after pressing enter, to my surprise, the same error shows again.
Wait! What is happening here? How can I create a new user when the tools do not allow? Why the postgres user has not been created by default?
Let’s take a step (or two) back.
Clearly, when postgres was installed something was missing: no postgres user has been created. So I feel curios about how the brew postgres tap worked.
The version that interested me is postgres 13. It is not a large file, it took me less than a minute to figure it out what it does. Right at the end is what I was looking for.
test do
system "#{bin}/initdb", "pgdata"
end
initdb
is the postgres command to initilize the DB. Besides the pgdata argument, there’s no other hint about the user creation. So, I assumed the default user creation it is taken care of by initdb
.
Because I did not feel satisfied, I went into the guts of initdb source. Right between lines 3193 and 3195, I found that if no username (--username
operator) is provided, the one used by default is the current os username. That’s what get_id
function does.
effective_user = get_id();
if (!username)
username = effective_user;
Obviously, as you might expect, my username is not postgres.
With this information at hand, it just took providing my username into createuser command to create the postgres DB user.
$ createuser -s postgres -U <os-username>
There you go. Error fixed.
But, there’s still a pending question. If initdb
assumes the os user as the default root user, why psql
and createuser
commands assume there is a postgres user? It seems there’s a gap here.
I checked the docs and look what I found in the initdb
docs, under the --username
operator:
Selects the user name of the database superuser. This defaults to the name of the effective user running initdb. It is really not important what the superuser’s name is, but one might choose to keep the customary name postgres, even if the operating system user’s name is different.
And, there’s also more info at the “First steps” article in the postgres wiki:
typically initdb creates a table named “postgres” owned by user “current logged in user name”
however, when you use pg_ctl it defaults to connecting as user “current user” to database “current user” so specify user postgres here
so that it avoids confusion of having them named differently.
$ /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data -U postgres
Conclusion: postgres username it is just a convention in the postgres community. And for obvious security reasons, it is up to us to create it.
Now, yes! Mystery solved.
#postgresql #authentication #psql #fatal-error
Вопрос:
Пользователь Windows 10 пытается либо навсегда удалить роль, чтобы ошибка не отображалась, либо создать суперпользователя без пароля.
Я искал несколько часов безрезультатно. Пытался:
Создание нового пользователя и базы данных с помощью СУПЕРПОЛЬЗОВАТЕЛЯ CREATE USER Nistic; Регистрация БАЗЫ ДАННЫХ С ПОМОЩЬЮ ВЛАДЕЛЬЦА Nistic;
Роль была успешно создана, но при выходе из системы и повторном входе в систему ввод «psql» в терминале все равно вызовет ту же ошибку. [РЕДАКТИРОВАТЬ] Я могу войти под именем пользователя postgres, введя psql-U postgres, но по какой-либо причине имя пользователя по умолчанию по-прежнему имеет значение Nistic.
Я уже проверил файл conf и настроил все методы на доверие. Я попытался удалить пользователя и воссоздать его заново.
Я просто хотел, чтобы заголовок включал пользователя более общего характера, несмотря на то, что он показан выше.
Я в значительной степени перепробовал все остальное, что смог найти, ПОЭТОМУ.
Пожалуйста, помогите, спасибо.
Экран ниже, чтобы показать некоторые из странностей (пожалуйста, прочитайте каждую строку перед комментарием — проблема в том, что после избавления от Nistic он все еще ожидает Nistic)
Комментарии:
1. Если вы не можете войти в систему с
psql
помощью как это делаетсяCREATE USER
иCREATE DATABASE
? Кроме того, как бы вы это ни делали, что отображается в качестве имени пользователя? Есть ли у вас более одного запущенного экземпляра Postgres, и если да, то уверены ли вы, что подключаетесь к правильному экземпляру. Кроме того, вы уверены, что редактируете правильныйpg_hba.conf
файл?2. Я могу войти в систему с помощью psql-U postgres, и все. Команды «Создать» определенно работают. Извините, что я не решался предоставить эту информацию, потому что я не хотел, чтобы это звучало так, как будто я кого-то принижаю на самом деле, но да, я все это перепробовал, и я уверен, что редактировал правильный файл (pg_hba.conf).
3. Мне кажется, что зависть
PGUSER
была установлена. См. Раздел Переменные Env . Я больше недостаточно использую Windows, чтобы рассказать вам, как это проверить. Это автоматически приведет к эквивалентному pf-U Nistic
при использованииpsql
без a-U <some_user>
. В противном случае по умолчанию для-U
in без указания егоpsql
значения будет использоваться имя пользователя операционнойfoste
системы . Тем временем вам нужно будет принудительно указать имя пользователя, указав-U <some_name>
его .
4. Имя пользователя, которое вы создали, было в нижнем регистре, так как вы не заключили имя в двойные кавычки в SQL. Но у того, под чьим именем вы пытались войти, была заглавная буква.
5. Я не могу в это поверить, но это был правильный ответ, @jjanes. Я упустил это из виду, потому что думал, что все роли автоматически делаются строчными, и не понимал, что это можно изменить с помощью кавычек.