Createuser error could not connect to database postgres fatal role postgres does not exist

I'm a postgres novice. I installed the postgres.app for mac. I was playing around with the psql commands and I accidentally dropped the postgres database. I don't know what was in it. I'm curre...

I’m a postgres novice.

I installed the postgres.app for mac. I was playing around with the psql commands and I accidentally dropped the postgres database. I don’t know what was in it.

I’m currently working on a tutorial: http://www.rosslaird.com/blog/building-a-project-with-mezzanine/

And I’m stuck at sudo -u postgres psql postgres

ERROR MESSAGE: psql: FATAL: role "postgres" does not exist

$ which psql

/Applications/Postgres.app/Contents/MacOS/bin/psql

This is what prints out of psql -l

                                List of databases
    Name    |   Owner    | Encoding | Collate | Ctype |     Access privileges     
------------+------------+----------+---------+-------+---------------------------
 user       | user       | UTF8     | en_US   | en_US | 
 template0  | user       | UTF8     | en_US   | en_US | =c/user                  +
            |            |          |         |       | user      =CTc/user      
 template1  | user       | UTF8     | en_US   | en_US | =c/user                  +
            |            |          |         |       | user      =CTc/user      
(3 rows)

So what are the steps I should take? Delete an everything related to psql and reinstall everything?

Thanks for the help guys!

Daniil Ryzhkov's user avatar

asked Mar 8, 2013 at 19:31

user805981's user avatar

2

NOTE: If you installed postgres using homebrew, see the comment from @user3402754 below.

Note that the error message does NOT talk about a missing database, it talks about a missing role. Later in the login process it might also stumble over the missing database.

But the first step is to check the missing role: What is the output within psql of the command du ? On my Ubuntu system the relevant line looks like this:

                              List of roles
 Role name |            Attributes             | Member of 
-----------+-----------------------------------+-----------
 postgres  | Superuser, Create role, Create DB | {}        

If there is not at least one role with superuser, then you have a problem :-)

If there is one, you can use that to login. And looking at the output of your l command: The permissions for user on the template0 and template1 databases are the same as on my Ubuntu system for the superuser postgres. So I think your setup simple uses user as the superuser. So you could try this command to login:

sudo -u user psql user

If user is really the DB superuser you can create another DB superuser and a private, empty database for him:

CREATE USER postgres SUPERUSER;
CREATE DATABASE postgres WITH OWNER postgres;

But since your postgres.app setup does not seem to do this, you also should not. Simple adapt the tutorial.

moveson's user avatar

moveson

5,0431 gold badge14 silver badges32 bronze badges

answered Mar 9, 2013 at 10:13

A.H.'s user avatar

A.H.A.H.

62.9k14 gold badges91 silver badges123 bronze badges

8

For MAC:

  1. Install Homebrew
  2. brew install postgres
  3. initdb /usr/local/var/postgres
  4. /usr/local/Cellar/postgresql/<version>/bin/createuser -s postgres or /usr/local/opt/postgres/bin/createuser -s postgres which will just use the latest version.
  5. start postgres server manually: pg_ctl -D /usr/local/var/postgres start

To start server at startup

  • mkdir -p ~/Library/LaunchAgents
  • ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
  • launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Now, it is set up, login using psql -U postgres -h localhost or use PgAdmin for GUI.

By default user postgres will not have any login password.

Check this site for more articles like this: https://medium.com/@Nithanaroy/installing-postgres-on-mac-18f017c5d3f7

answered Feb 10, 2016 at 6:19

Nitin's user avatar

NitinNitin

6,8996 gold badges30 silver badges36 bronze badges

3

The key is «I installed the postgres.app for mac.» This application sets up the local PostgreSQL installation with a database superuser whose role name is the same as your login (short) name.

When Postgres.app first starts up, it creates the $USER database,
which is the default database for psql when none is specified. The
default user is $USER, with no password.

Some scripts (e.g., a database backup created with pgdump on a Linux systsem) and tutorials will assume the superuser has the traditional role name of postgres.

You can make your local install look a bit more traditional and avoid these problems by doing a one time:

/Applications/Postgres.app/Contents/Versions/9.*/bin/createuser -s postgres

which will make those FATAL: role «postgres» does not exist go away.

Laurel's user avatar

Laurel

5,90314 gold badges30 silver badges56 bronze badges

answered Jul 23, 2013 at 14:25

jwd630's user avatar

jwd630jwd630

4,5281 gold badge20 silver badges22 bronze badges

12

createuser postgres --interactive

or make a superuser postgresl just with

createuser postgres -s

answered Aug 10, 2017 at 20:10

CesareoAguirre's user avatar

3

And if you are here in 2023 and wondering what works with the latest Postgres on the latest macOS (macOS Monterey )

follow this:

brew install postgresql
createuser -s postgres
brew services restart postgresql

answered Feb 1, 2022 at 13:46

Amit Meena's user avatar

Amit MeenaAmit Meena

2,30419 silver badges30 bronze badges

3

This happens when you run initdb with a user whose ID is not postgres, without specifying the postgres username with --username=postgres or -U postgres.

The database cluster is then created with the system’s user account that you used to run initdb, and it is given superuser permissions.

To fix it, simply create a new user named postgres with the option --superuser using the createuser utility that comes with Postgres. The utility can be found in the Postgres’ bin directory. e.g.

createuser --superuser postgres

If you have a custom hostname or port then be sure to set the appropriate options.

Don’t forget to delete the other user account that was created for you by initdb.

answered Mar 20, 2019 at 21:11

isapir's user avatar

isapirisapir

19.7k12 gold badges110 silver badges112 bronze badges

0

If you installed postgres from brew, run this in your terminal :

/usr/local/opt/postgres/bin/createuser -s postgres

Steffen Moritz's user avatar

answered Aug 10, 2020 at 12:50

Saket Sinha's user avatar

Saket SinhaSaket Sinha

5114 silver badges3 bronze badges

2

First you need create a user:

sudo -u postgres createuser --superuser $USER

After you create a database:

sudo -u postgres createdb $USER

Change $USER to your system username.

You can see the the complete solution here.

answered Jul 29, 2015 at 22:54

ruzenhack's user avatar

ruzenhackruzenhack

9632 gold badges8 silver badges18 bronze badges

1

I needed to unset $PGUSER:

$ unset PGUSER
$ createuser -s postgres

answered Jan 2, 2018 at 6:54

Beau Barker's user avatar

Beau BarkerBeau Barker

1,9262 gold badges22 silver badges21 bronze badges

0

If you installed postgres from Brew and are using an Apple Silicon (M1) mac, run this in your terminal:

/opt/homebrew/opt/postgresql/bin/createuser -s postgres

If you’re using an Intel (x86) mac, run this in your terminal:

/usr/local/opt/postgres/bin/createuser -s postgres

answered May 3, 2021 at 12:27

SwiftPush's user avatar

SwiftPushSwiftPush

1711 silver badge6 bronze badges

1

Running this on the command line should fix it

/Applications/Postgres.app/Contents/Versions/9.4/bin/createdb <Mac OSX Username Here>

answered Feb 13, 2015 at 21:41

Alex Levine's user avatar

Alex LevineAlex Levine

1,41115 silver badges16 bronze badges

1

This article helped me to solve same issue psql: FATAL: role “postgres” does not exist.

I am using mac, so I entered this command in terminal:

createuser -s postgres

And it worked for me.

answered May 12, 2021 at 16:03

user9347049's user avatar

user9347049user9347049

1,7952 gold badges23 silver badges52 bronze badges

This worked for me

createuser -s postgres

note: I’m using mac catalina

answered Oct 14, 2021 at 4:38

Mba Gozpel's user avatar

Mba GozpelMba Gozpel

2032 silver badges6 bronze badges

If you’re using docker, make sure you’re NOT using POSTGRES_USER=something_else, as this variable is used by the standard image to know the name of the PostgreSQL admin user (default as postgres).

In my case, I was using this variable with the intent to set another user to my specific database, but it ended up of course changing the main PostgreSQL user.

answered Jul 23, 2020 at 9:30

B Medeiros's user avatar

B MedeirosB Medeiros

2,22421 silver badges34 bronze badges

We have a db named postgres after brew install postgresql and brew services start postgresql. So we can open psql like this by default.

psql postgres

And then we can add users with any name like this in that psql console.

CREATE USER postgres

And if we want a super user, then we can add SUPERUSER at the end.

answered Jul 28, 2021 at 1:02

kangkyu's user avatar

kangkyukangkyu

4,8142 gold badges33 silver badges35 bronze badges

1

For m1 chips, if you have not installed postgresql package by homebrew, install it in terminal with:

brew install postgre

then create a username manually by:

/opt/homebrew/bin/createuser -s <username> 

your error is probably fixed; but if you occur the error

FATAL: database «databasename» does not exist

then you have to create your database manually by:

/opt/homebrew/bin/createdb -U <username>  <databasename>    

answered Jun 27, 2022 at 10:43

Seyede Zahra Borghei's user avatar

Dropping the postgres database doesn’t really matter. This database is initially empty and its purpose is simply for the postgres user to have a kind of «home» to connect to, should it need one.

Still you may recreate it with the SQL command CREATE DATABASE postgres;

Note that the tutorial mentioned in the question is not written with postgres.app in mind.
Contrary to PostgreSQL for Unix in general, postgres.app tries to look like a normal application as opposed to a service that would be run by a dedicated postgres user having different privileges than your normal user. postgres.app is run and managed by your own account.

So instead of this command: sudo -u postgres psql -U postgres, it would be more in the spirit of postgres.app to just issue: psql, which automatically connects to a database matching your users’s name, and with a db account of the same name that happens to be superuser, so it can do anything permissions-wise.

answered Mar 8, 2013 at 20:53

Daniel Vérité's user avatar

Daniel VéritéDaniel Vérité

56.1k15 gold badges125 silver badges150 bronze badges

4

This is the only one that fixed it for me :

createuser -s -U $USER

answered Mar 2, 2016 at 0:10

Bax's user avatar

BaxBax

4,1505 gold badges42 silver badges65 bronze badges

1

For what it is worth, i have ubuntu and many packages installed and it went in conflict with it.

For me the right answer was:

sudo -i -u postgres-xc
psql

answered Jan 11, 2017 at 15:37

softwareplay's user avatar

softwareplaysoftwareplay

1,3793 gold badges27 silver badges64 bronze badges

I’ve faced similar problem today, actually i was not sure what was the username. Here is the 2 thing, if you are under enterprise and don’t have system admin access the postgres will create your enterprise username as the postgres admin username. If you install through Homebrew it will definitely happening. In that case simply run your psql service with brew and do an echo of the username

brew services start postgresql

then

echo $USER

You will see your username of the postgres user.

answered Nov 25, 2021 at 16:42

Ananda G's user avatar

Ananda GAnanda G

2,30921 silver badges39 bronze badges

2

If you are experiencing this problem right after running a docker container try destroying the container and recreating it. That solved it for me:

docker-compose down
docker-compose up --force-recreate

This should recreate the db with postgresuser as default user

answered Oct 27, 2021 at 7:16

palamunder's user avatar

palamunderpalamunder

2,4651 gold badge19 silver badges20 bronze badges

With a new mac (M1) and latest postgres (14.0) installed via homebrew, nothing helped me from this topic, but i just reinstalled postgres and it helped:

brew services stop postgresql
rm -rf /opt/homebrew/var/postgres/*
brew reinstall postgresql
initdb --locale=C -E UTF-8 /opt/homebrew/var/postgres
brew services restart postgresql

So, it’s a miracle or something like that…

Then just:

psql -d postgres

Zlatan Omerović's user avatar

answered Nov 5, 2021 at 8:37

stefanitsky's user avatar

stefanitskystefanitsky

4136 silver badges9 bronze badges

2

If you are a MAC (M1) user and installed the Postgres using HomeBrew then follow these steps:

  1. Check your Postgres location using which psql
  2. then run the command /opt/homebrew/bin/createuser -s postgres if the output for the first command is /opt/homebrew/bin/psql

The idea is to create a user named ‘postgres’ using the Postgres installation location. So you may need to change the command based on the location of your Postgres.

answered Dec 14, 2022 at 6:02

Amar Bisht's user avatar

On Ubuntu system, I purged the PostgreSQL and re-installed it. All the databases are restored.
This solved the problem for me.

Advice — Take the backup of the databases to be on the safer side.

answered Nov 20, 2018 at 5:52

Gaurav Neema's user avatar

Gaurav NeemaGaurav Neema

1361 gold badge1 silver badge12 bronze badges

Context

I am adding an answer for a case I have not seen here, which is an edge case if you have multiple users on the same machine and the user who is trying to use postgres services is not the user who installed postgres on the machine.

What I have tried

Among other similar commands, for me all these commands failed:

createuser -s [your username]
# createuser: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  role "[your username]" does not exist
createuser -s postgres
# createuser: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  role "[your username]" does not exist
sudo -u postgres createuser --superuser [your username]
# sudo: unknown user: postgres
# sudo: error initializing audit plugin sudoers_audit
psql -U postgres
# psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  role "postgres" does not exist

Reason

The reason is because neither postgres role nor [your username] (aka whoami on your command line) are in postgres.

Solution

In such edge case I had to first login with the user who installed postgres:

sudo su - [username that installed postgres]

And then create a role for my new user:

createuser -s [your username]

answered Jan 8 at 18:42

Fed's user avatar

FedFed

1,58621 silver badges29 bronze badges

I don’t think that sudo is needed here because psql -l returns a list of databases. This tells me that initdb was run under the user’s current user, not under the postgres user.

You can just:

psql

And continue the tutorial.

I would suggest A.H’s general points of creating the postgres user and db because many applications may expect this to exist.

A brief explanation:

PostgreSQL will not run with administrative access to the operating system. Instead it runs with an ordinary user, and in order to support peer authentication (asking the OS who is trying to connect) it creates a user and db with the user that runs the initialization process. In this case it was your normal user.

answered Mar 9, 2013 at 14:36

Chris Travers's user avatar

Chris TraversChris Travers

25k6 gold badges63 silver badges181 bronze badges

1

I became stuck on this issue having executed brew services stop postgresql the day prior.
The day following: brew services start postgresql would not work. This is because as is shown when you install using homebrew. postgresql uses a launchd … which loads when your computer is powered on.

resolution:
brew services start postgresql
Restart your computer.

answered Jun 26, 2017 at 12:33

Michael Dimmitt's user avatar

The du command return:

Role name = postgres@implicit_files

And that command postgres=# password postgres return error:

ERROR: role «postgres» does not exist.

But that postgres=# password postgres@implicit_files run fine.

Also after sudo -u postgres createuser -s postgres the first variant also work.

answered Jun 28, 2018 at 8:32

Michael's user avatar

MichaelMichael

1,0631 gold badge11 silver badges28 bronze badges

For m1 chips and homebrew version 3.4.9, the createuser is moved inside Cellar of the particular package.
This worked for me
/opt/homebrew/Cellar/postgresql@12/12.10_1/bin/createuser -s postgres

answered May 2, 2022 at 6:56

Nitesh Rawat's user avatar

Here’s a question from one of our regular reader Sam. He says that PostgreSQL does not allow to create user or database and fails with an error message “Createuser could not connect to database postgres” while issuing createuser command and “createdb: could not connect to database template1” while executing createdb command.  The command fails when executed as privileged user as well. Here’s the solution for this error.

Before we see the solution, have a look at the error message:

[sam@openca ]$ createdb openca
createdb: could not connect to database template1: FATAL: role "sam" does not exist

[sam@openca ]$ su -
[root@ra openca ]# createuser openca
createuser: could not connect to database postgres: FATAL: role "root" does not exist

How to fix the error – createuser could not connect to database postgres

According to the snapshot, createuser and createdb commands were executed as ‘sam’ and ‘root’ user. It means, the PostgreSQL administrator has not created a PostgreSQL user account for ‘sam’ & ‘root’. Note, the PostgreSQL user accounts are different from the regular UNIX user accounts. So, even if you have valid UNIX accounts, it’s not a valid PostgreSQL user account until administrator creates one. That’s the reason, PostgreSQL denied users ‘sam’ & ‘root’ from creating user or database. In order to fix this error, you need to switch to a user that’s running PostgreSQL server. By default, UNIX user 'postgres' is the one that will be running PostgreSQL server. So the createdb & createuser commands should be executed as 'postgres' user account as shown below.

$ sudo su - postgres

(or)

$ sudo -u postgres -i

You can now create database as ‘postgres’ user as shown below:

$ createdb openca

Create PostgreSQL user account as below:

$ createuser sam

Verify, if PostgreSQL user is created properly by logging-in to ‘sam’ user and type psql as shown below.

# sudo su - sam

[sam@openca ]$ psql
psql (9.2.23)
Type "help" for help.

postgres=# q

That’s it!

Note:

You don’t require to enter password if the PostgreSQL allows ident based authentication.

How to allow users to create PostgreSQL database?

By default, PostgreSQL does not allow users to create or drop database. If you ever want to allow users to create PostgreSQL database, then the administrator has to provide necessary privileges.

To do that, switch to the user that is running PostgreSQL server.

$ sudo su - postgres

Type psql to enter PostgreSQL prompt.

$ psql
psql (9.2.23)
Type "help" for help.

postgres=#

Grant CREATEDB privilege using ALTER statement as shown below:

postgres=# ALTER USER sam CREATEDB;
ALTER ROLE

Note:

Replace ‘sam’ with the user account you wish to grant privilege.

Test if user ‘sam’ has enough privileges to create a database.

[sam@openca ]$ createdb test

[sam@openca ]$ psql -d test
psql (9.2.23)
Type "help" for help.

test=>

In case, if you don’t have privilege to create database in PostgreSQL, then you will see an error as shown below:

# createdb
createdb: could not connect to database template1: FATAL: role "sam" does not exist

Running PostgreSQL server on Void Linux. After installing ran initdb as OS user ‘postgres’:

[user@host]$ sudo -u postgres -i

$ initdb -D '/var/lib/postgresql/data'

Received output:

creating directory /var/lib/postgresql/data … ok creating
subdirectories … ok selecting default max_connections … 100
selecting default shared_buffers … 128MB selecting dynamic shared
memory implementation … posix creating configuration files … ok
running bootstrap script … ok performing post-bootstrap
initialization … locale: Cannot set LC_MESSAGES to default locale:
No such file or directory ok syncing data to disk … ok

WARNING: enabling «trust» authentication for local connections You can
change this by editing pg_hba.conf or using the option -A, or
—auth-local and —auth-host, the next time you run initdb.

Success. You can now start the database server using:
pg_ctl -D /var/lib/postgresql/data -l logfile start

I’ve then proceeded to create the service, grant the ownership to ‘postgres’ and start it:

[user@host]$ ln -s /etc/sv/postgresql /var/service
[user@host]$ sudo chown postgres: /var/service/postgresql
[user@host]$ sudo sv start postgresql
[user@host]$ ls -l /var/service/postgresql
lrwxrwxrwx 1 postgres postgres 18 nov   2 17:05 /var/service/postgresql -> /etc/sv/postgresql

Running:

[user@host]$ sudo -u postgres psql ...

will give me the following error:

psql: FATAL:  role "postgres" does not exist

I’ve tried granting ownership of /etc/sv/postgresql to ‘postgres’, but no luck.

These were my sources:

https://wiki.voidlinux.eu/PostgreSQL

PostgreSQL error: Fatal: role “username” does not exist

I do not know what to do next.

EDIT: Stumbled upon psql: FATAL: role “postgres” does not exist. Cannot run psql -l because I get the same error, no matter which user I run psql as.

17 ответов

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

Но первым шагом является проверка отсутствующей роли: каков вывод в psql команды du? В моей системе Ubuntu соответствующая строка выглядит так:

                              List of roles
 Role name |            Attributes             | Member of 
-----------+-----------------------------------+-----------
 postgres  | Superuser, Create role, Create DB | {}        

Если в superuser нет хотя бы одной роли, у вас есть проблема:-)

Если он есть, вы можете использовать его для входа в систему. И посмотрев вывод вашей команды l: Разрешения для user в базах template0 и template1 такие же, как в моей системе Ubuntu для суперпользователя postgres. Поэтому я думаю, что ваша настройка просто использует user как суперпользователя. Поэтому вы можете попробовать эту команду для входа в систему:

sudo -u user psql user

Если user на самом деле является суперпользователем DB, вы можете создать для него еще один суперпользователь DB и частную, пустую базу данных:

CREATE USER postgres SUPERUSER;
CREATE DATABASE postgres WITH OWNER postgres;

Но так как ваша установка postgres.app, похоже, не делает этого, вам также не следует. Простая адаптация учебника.

A.H.
09 март 2013, в 12:07

Поделиться

Ключ «Я установил postgres.app для Mac». Это приложение устанавливает локальную установку PostgreSQL с суперпользователем базы данных, чье имя роли совпадает с вашим логином (коротким).

Когда Postgres.app запускается впервые, он создает базу данных $ USER, которая является базой данных по умолчанию для psql, если ни одна из них не указана. Пользователь по умолчанию — $ USER, без пароля.

Некоторые сценарии (например, резервная копия базы данных, созданная с помощью pgdump в системе Linux) и учебные пособия предполагают, что суперпользователь имеет традиционное имя роли postgres.

Вы можете сделать вашу локальную установку более традиционной и избежать этих проблем, выполнив один раз:

/Applications/Postgres.app/Contents/Versions/9.*/bin/createuser -s postgres

что сделает тех ФАТАЛЬНЫМИ: роль «postgres» не существует.

jwd630
23 июль 2013, в 15:48

Поделиться

Для MAC:

  1. Установить Homebrew
  2. brew install postgres
  3. initdb/usr/local/var/postgres
  4. /usr/local/Cellar/postgresql/<version>/bin/createuser -s postgres или /usr/local/opt/postgres/bin/createuser -s postgres которые будут использовать только последнюю версию.
  5. запустить сервер postgres вручную: pg_ctl -D/usr/local/var/postgres start

Чтобы запустить сервер при запуске

  • mkdir -p ~/Library/LaunchAgents
  • ln -sfv/usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
  • launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Теперь он настроен, войдите в систему с помощью psql -U postgres -h localhost или используйте PgAdmin для GUI.

По умолчанию у пользователя postgres не будет пароля для входа.

Зайдите на этот сайт, чтобы найти больше статей, подобных этой: https://medium.com/@Nithanaroy/install-postgres-on-mac-18f017c5d3f7

Nitin
10 фев. 2016, в 07:00

Поделиться

createuser postgres --interactive

или сделать postgresl суперпользователя только с

createuser postgres -s

SyntheticMeshwork
10 авг. 2017, в 20:15

Поделиться

Сначала вам нужно создать пользователя:

sudo -u postgres createuser --superuser $USER

После вы создаете базу данных:

sudo -u postgres createdb $USER

Измените $USER на имя пользователя вашей системы.

Вы можете увидеть полное решение здесь.

ruzenhack
29 июль 2015, в 23:43

Поделиться

Мне нужно было $PGUSER:

$ unset PGUSER
$ createuser -s postgres

Beau Barker
02 янв. 2018, в 08:33

Поделиться

Запуск этого в командной строке должен исправить его

/Applications/Postgres.app/Contents/Versions/9.4/bin/createdb <Mac OSX Username Here>

Alex Levine
13 фев. 2015, в 23:17

Поделиться

Отбрасывание базы данных postgres не имеет значения. Эта база данных изначально пуста, и ее целью является просто для пользователя postgres иметь своего рода «домашний» для подключения к нему, если он понадобится.

Тем не менее вы можете воссоздать его с помощью команды SQL CREATE DATABASE postgres;

Обратите внимание, что учебник, упомянутый в вопросе, не написан с учетом postgres.app.
В отличие от PostgreSQL для Unix в целом, postgres.app пытается выглядеть как обычное приложение, в отличие от службы, которая будет выполняться выделенным пользователем postgres, имеющим разные привилегии, чем ваш обычный пользователь. postgres.app запускается и управляется вашей собственной учетной записью.

Итак, вместо этой команды: sudo -u postgres psql -U postgres было бы больше в духе postgres.app просто выпустить: psql, который автоматически соединяется с базой данных, соответствующей вашему имени пользователя, и с учетной записью db одно и то же имя, которое является суперпользователем, поэтому он может делать все необходимые разрешения.

Daniel Vérité
08 март 2013, в 21:13

Поделиться

Для чего это стоит, у меня установлено ubuntu и многие пакеты, и он вступил в конфликт с ним.

Для меня правильный ответ был:

sudo -i -u postgres-xc
psql

softwareplay
11 янв. 2017, в 16:41

Поделиться

Я столкнулся с этой проблемой после сборки PostgreSQL с использованием Homebrew из-за конфликта OpenSSL.

Я предлагаю следующее:

Переустановить OpenSSL

brew remove openssl
brew install openssl

Формирование символической ссылки для OpenSSL

brew link --force openssl

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

sudo -u <administrator account> createuser <standard account> -d -P

Этот метод создаст базу данных, используя <standard account> в качестве имени, а также установит для нее пароль. Флаги в конце можно удалить, если это нежелательно.

Наконец, операции postgresql, такие как createdb <dbname>, могут использоваться без предшествующих ошибок FATAL.

badfilms
29 апр. 2016, в 01:57

Поделиться

Это происходит, когда вы запускаете initdb с пользователем, чей ID не является postgres, и вы не указали имя пользователя, используя --username=postgres (или -U postgres).

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

Чтобы исправить это, просто создайте нового пользователя с именем postgres с createuser утилиты createuser которая поставляется с Postgres и может быть найдена в каталоге bin. Например

createuser --superuser postgres

Если у вас есть пользовательское имя хоста или порт, то обязательно установите соответствующие параметры.

Не забудьте удалить другую учетную запись пользователя, созданную для вас initdb.

isapir
20 март 2019, в 22:52

Поделиться

В системе Ubuntu я удалил PostgreSQL и переустановил его. Все базы данных восстановлены. Это решило проблему для меня.

Совет: сделайте резервную копию баз данных, чтобы быть на более безопасной стороне.

Gaurav Neema
20 нояб. 2018, в 05:57

Поделиться

Это единственное, что зафиксировало это для меня:

createuser -s -U $USER

Bax
02 март 2016, в 00:44

Поделиться

Команда du return:

Имя роли = [email protected]_files

И эта команда postgres=# password postgres возвращает ошибку:

ОШИБКА: роли «postgres» не существует.

Но это postgres=# password [email protected]_files работает нормально.

Также после sudo -u postgres createuser -s postgres также работает первый вариант.

Michael
28 июнь 2018, в 08:59

Поделиться

Я застрял в этой проблеме, выполнив brew services stop postgresql за день до этого.
На следующий день: brew services start postgresql не работает. Это происходит потому, что показано, когда вы устанавливаете с помощью homebrew. postgresql использует startd… который загружается, когда ваш компьютер включен. Разрешение

brew services start postgresql
Перезагрузите компьютер.

Michael Dimmitt
26 июнь 2017, в 14:15

Поделиться

Я не думаю, что здесь требуется sudo, потому что psql -l возвращает список баз данных. Это говорит мне, что initdb запускался под пользователем текущего пользователя, а не под пользователем postgres.

Вы можете просто:

psql

И продолжайте учебник.

Я бы предложил A.H общие моменты создания пользователя postgres и db, потому что многие приложения могут ожидать, что это будет существовать.

Краткое объяснение:

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

Chris Travers
09 март 2013, в 16:01

Поделиться

Ещё вопросы

  • 0Как читать текстовый файл в 2D массив — C ++
  • 0CakePhp настроить функцию перевода
  • 1Как увидеть полную ошибку сборки муравья, которая обрезана
  • 1Как сделать dll с UIElement для Windows Phone
  • 1Создать новые столбцы из агрегированных категорий
  • 0Я не могу получить доступ к Facebook страницам (учетной записи) php sdk 4.0
  • 0Получить значение строки запроса из URL внутри большей строки с помощью PHP
  • 0Хотите получить результаты двух запросов в одном запросе путем объединения этих запросов
  • 1Удалить номер из списка номеров, разделенных запятыми
  • 1(Java) Перестановка N списков с сбросом на диск
  • 0Правильный способ в PHP для форматирования / экранирования строки для использования в XML
  • 0параметр постоянной функции в качестве размера статического массива?
  • 1Извлечение дня и месяца из объекта datetime
  • 1Python: удалить список связанных узлов
  • 0Тестовый выход () с буст-тестами
  • 0Отображать набор изображений с заголовком, сохраняя масштаб по высоте
  • 1Sublime Text и проект Java на Mac
  • 1Отображение здоровья врага над врагом [работает, но не реально]?
  • 1почему модуль re python2 не может идентифицировать символ u’® ‘
  • 1Скрытие серии из встроенных графиков
  • 0Доступ к элементам, помещенным в массив
  • 1Logback усекается вместо добавления в файл журнала
  • 0Mysql сравнить два номера списка
  • 1Как вернуть объект из службы отдыха в Java?
  • 0Межпоточная связь
  • 1Функция JavaScript Prime Checker с синтаксисом троичного оператора
  • 1Как прочитать контактный номер с помощью Android
  • 0как реорганизовать / переименовать макросы в Eclipse C ++
  • 0Передача входных данных между текстовыми полями HTML
  • 0Получить значения первой записи и последней записи по дате в подзапросе MySQL
  • 0Показывать окно оповещения, когда пользователь выбирает неприемлемый файл в плагине danialfarid / ng-file-upload
  • 1Удаление строки из базы данных с помощью столбца _id в контекстном меню из ListView
  • 1Имя схемы Sql-сервер из java-соединения jdbc
  • 1Расчет BigDecimal
  • 0Получение кнопки отправки для работы в PHP-файле
  • 1Ошибка пользовательского действия Wix в .NET3.5
  • 0Foreach возвращает один элемент многим
  • 1Обновлять словарь за итерацию, а не за весь
  • 1Можно ли закрепить индикатор выбора вкладки TabLayout в верхней части экрана при прокрутке?
  • 0JQPlot, JSON и ошибка «Данные не указаны»
  • 1Добавление Jpanel, содержащего JButton, нарушает структуру кадра
  • 1Java: использование интерфейса
  • 1Highcharter — переместить метку данных в верхнюю часть столбца
  • 0MySQL Как динамически выбирать, из какой таблицы получать данные при создании представления
  • 0Doxygen — неправильный порядок модулей в pdf
  • 0Вложенные функции $ http.get
  • 1Android VideoView LinearLayout LayoutParams
  • 1Обновить запись в базе данных
  • 1Есть ли альтернатива TextView?
  • 1Изображение становится черным после изменения размера Java Swing

I’ve been trying to setup postgresql locally on my mac but I’m having a hard time. I tried to look up solutions and resolve it myself but can’t seem to figure it out.

I was following this tutorial to set it up http://iamdavidxie.com/2016/10/31/install-postgresql-94-with-homebrew/

On step 3 — when I try to create a superuser with this command

createuser -d -a -s -P postgres

I’m get this error exist

createuser: could not connect to database postgres: FATAL:  role "username" does not exist

level 1

For whatever reason the createuser command is trying to connect to postgres with the username ‘username’. Do you have an envvar set somewhere like PGUSER=username or something weird? Maybe try -U root with it?

level 2

now I’m getting

createuser: could not connect to database postgres: FATAL:  role "root" does not exist    

Edit:

My first psql installation went wrong so I uninstalled everything manually and deleted postgres user from «Users & Groups» in System preferences on my mac. Maybe that has to do something with it?

level 1

Just a shot in the dark, but check the manual for iniydb, I suspect something got left out of the linked guide and the cluster is not even initislized yet

0 / 0 / 0

Регистрация: 16.09.2012

Сообщений: 4

1

16.09.2012, 17:41. Показов 29899. Ответов 7


Здравствуйте, имею Ubuntu 12.04, установил туда PSQL 9.1. В системе есть только одна учётная запись alexander. Не могу создать базу данных: получаю сообщение:
createdb: could not connect to database postgres: FATAL: role «alexander» does not exist
Пробовал создать роль alexander командой
createuser alexander
— получаю следующее:
Shall the new role be a superuser? (y/n) y
createuser: could not connect to database postgres: FATAL: role «alexander» does not exist
Что делать?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

16.09.2012, 17:41

Ответы с готовыми решениями:

Начало работы в С++
Какую среду для С++ использовать, чтоб был хороший компилятор? как установить и начать работать?…

Начало работы с Qt
Приветствую вас уважаемые юзеры. Хочу попробовать себя в работе с программой Qt, где можно скачать…

Начало Работы
Посоветуйте:

1)Хорошую инструкцию по установке, И вообще что мне устанавливать для создния…

Начало работы в qt
Здравствуйте,начал изучать qt(в с++ новичок), установив и создав свой первый проект вылезает эта…

7

Эксперт Java

4087 / 3821 / 745

Регистрация: 18.05.2010

Сообщений: 9,331

Записей в блоге: 11

17.09.2012, 14:18

2

Выдержка из документации

Another response could be this:

createdb: could not connect to database postgres: FATAL: role «joe» does not exist

where your own login name is mentioned. This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 19 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name.



0



0 / 0 / 0

Регистрация: 16.09.2012

Сообщений: 4

17.09.2012, 15:51

 [ТС]

3

Я так понял, что нужно подключиться к начальной роли postgres. Как это сделать? Когда я пытаюсь создать новую роль от имени postgres, получаю сообщение, что peer authentication has failed.



0



17 / 17 / 0

Регистрация: 19.02.2012

Сообщений: 68

21.09.2012, 12:41

4

Пробуем запустить консоль PostgreSQL:

$ psql
psql: FATAL: role «vladimir» does not exist
$ sudo psql
psql: FATAL: role «root» does not exist

После неудачных попыток делаем следующее:

vladimir@rubydev:~$ sudo su postgres
postgres@rubydev:/home/vladimir$ psql

Источник: http://rubydev.ru/2012/03/inst… ntu_linux/

Авось поможет…



1



0 / 0 / 0

Регистрация: 16.09.2012

Сообщений: 4

21.09.2012, 16:55

 [ТС]

5

Сделал, как Вы сказали, — получился вход в консоль PSQL. Какую команду ни ввожу, реакции нету, даже help вводил — нет реакции, просто вновь выводится приглашение postgres=# с новой строки. Пробовал в Windows XP установить PSQL — там тоже в консоли нет реакции на команды.



0



17 / 17 / 0

Регистрация: 19.02.2012

Сообщений: 68

21.09.2012, 17:03

6

Цитата
Сообщение от Александр.91
Посмотреть сообщение

Сделал, как Вы сказали, — получился вход в консоль PSQL. Какую команду ни ввожу, реакции нету, даже help вводил — нет реакции, просто вновь выводится приглашение postgres=# с новой строки. Пробовал в Windows XP установить PSQL — там тоже в консоли нет реакции на команды.

Если мне не изменяет память (долбанный склероз), то psql воспринимает команду только в случае если в конце строки стоит разделитель «;». Иначе он считает что команда еще не завершена и не выполняет ее.

Добавлено через 3 минуты
И вообще… в чем смыл использовать именно psql? Установите pgAdmin 3… С GUI-ем проще жить… чем без него.



2



0 / 0 / 0

Регистрация: 16.09.2012

Сообщений: 4

22.09.2012, 00:06

 [ТС]

7

У меня долг по одному предмету, мне нужна БД на PSQL.
Спасибо: Вы мне помогли! Создав от имени postgres роль alexander, я смог от своего имени создать базу данных и подключиться к ней. Проблема была в том, что я не мог делать действия от имени начального пользователя postgres, а команда sudo su postgres расставила всё на свои места.
Я правильно понимаю: su имя — подключение к указанной учётной записи?
P. S. Какую клавишу нажать после вывода справки в командной строке PSQL? А то выводится (END), а дальше нет реакции, приходится заново открывать терминал.



0



17 / 17 / 0

Регистрация: 19.02.2012

Сообщений: 68

23.09.2012, 17:41

8

Цитата
Сообщение от Александр.91
Посмотреть сообщение

Я правильно понимаю: su имя — подключение к указанной учётной записи?
P. S. Какую клавишу нажать после вывода справки в командной строке PSQL? А то выводится (END), а дальше нет реакции, приходится заново открывать терминал.

Да, подключение к учетной записи…
Насчет справки не могу сказать, с psql знаком весьма косвенно.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

23.09.2012, 17:41

Помогаю со студенческими работами здесь

Начало работы
Здравствуйте, уважаемые форумчане. Дали курсовую по 1С, с которым мы никогда не работали. Сейчас…

Начало работы с ПО С++
Доброго времени суток. Подскажите пожалуйста в небольшом вопросе.
Начал смотреть видео уроки по…

Начало работы
Работал с mysql, сейчас нужно научиться работать с оракл. Подскажите, каков принцип? В mysql после…

1с начало работы
Здравствуйте! Помогите новичку, никак не могу разобраться. Объясните пожалуйста, вот я установил 1с…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

I’m a postgres novice.

I installed the postgres.app for mac. I was playing around with the psql commands and I accidentally dropped the postgres database. I don’t know what was in it.

I’m currently working on a tutorial: http://www.rosslaird.com/blog/building-a-project-with-mezzanine/

And I’m stuck at sudo -u postgres psql postgres

ERROR MESSAGE: psql: FATAL: role "postgres" does not exist

$ which psql

/Applications/Postgres.app/Contents/MacOS/bin/psql

This is what prints out of psql -l

                                List of databases
    Name    |   Owner    | Encoding | Collate | Ctype |     Access privileges     
------------+------------+----------+---------+-------+---------------------------
 user       | user       | UTF8     | en_US   | en_US | 
 template0  | user       | UTF8     | en_US   | en_US | =c/user                  +
            |            |          |         |       | user      =CTc/user      
 template1  | user       | UTF8     | en_US   | en_US | =c/user                  +
            |            |          |         |       | user      =CTc/user      
(3 rows)

So what are the steps I should take? Delete an everything related to psql and reinstall everything?

Thanks for the help guys!

asked Mar 8 ’13 at 19:31

Note that the error message does NOT talk about a missing database, it talks about a missing role. Later in the login process it might also stumble over the missing database.

But the first step is to check the missing role: What is the output within psql of the command du ? On my Ubuntu system the relevant line looks like this:

                              List of roles
 Role name |            Attributes             | Member of 
-----------+-----------------------------------+-----------
 postgres  | Superuser, Create role, Create DB | {}        

If there is not at least one role with superuser, then you have a problem :-)

If there is one, you can use that to login. And looking at the output of your l command: The permissions for user on the template0 and template1 databases are the same as on my Ubuntu system for the superuser postgres. So I think your setup simple uses user as the superuser. So you could try this command to login:

sudo -u user psql user

If user is really the DB superuser you can create another DB superuser and a private, empty database for him:

CREATE USER postgres SUPERUSER;
CREATE DATABASE postgres WITH OWNER postgres;

But since your postgres.app setup does not seem to do this, you also should not. Simple adapt the tutorial.

answered Mar 9 ’13 at 10:13

The key is «I installed the postgres.app for mac.» This application sets up the local PostgresSQL installation with a database superuser whose role name is the same as your login (short) name.

When Postgres.app first starts up, it creates the $USER database,
which is the default database for psql when none is specified. The
default user is $USER, with no password.

Some scripts (e.g., a database backup created with pgdump on a Linux systsem) and tutorials will assume the superuser has the traditional role name of postgres.

You can make your local install look a bit more traditional and avoid these problems by doing a one time:

/Applications/Postgres.app/Contents/Versions/9.*/bin/createuser -s postgres

which will make those FATAL: role «postgres» does not exist go away.

answered Jul 23 ’13 at 14:25

For MAC:

  1. Install Homebrew
  2. brew install postgres
  3. initdb /usr/local/var/postgres
  4. /usr/local/Cellar/postgresql/<version>/bin/createuser -s postgres or /usr/local/opt/postgres/bin/createuser -s postgres which will just use the latest version.
  5. start postgres server manually: pg_ctl -D /usr/local/var/postgres start

To start server at startup

  • mkdir -p ~/Library/LaunchAgents
  • ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
  • launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Now, it is set up, login using psql -U postgres -h localhost or use PgAdmin for GUI.

By default user postgres will not have any login password.

Check this site for more articles like this: https://sites.google.com/site/nitinpasumarthy/blog/installingpostgresonmac

answered Feb 10 ’16 at 6:19

createuser postgres --interactive

or make a superuser postgresl just with

createuser postgres -s

answered Aug 10 ’17 at 20:10

First you need create a user:

sudo -u postgres createuser --superuser $USER

After you create a database:

sudo -u postgres createdb $USER

Change $USER to your system username.

You can see the the complete solution here.

answered Jul 29 ’15 at 22:54

Running this on the command line should fix it

/Applications/Postgres.app/Contents/Versions/9.4/bin/createdb <Mac OSX Username Here>

answered Feb 13 ’15 at 21:41

I needed to unset $PGUSER:

$ unset PGUSER
$ createuser -s postgres

answered Jan 2 at 6:54

Dropping the postgres database doesn’t really matter. This database is initially empty and its purpose is simply for the postgres user to have a kind of «home» to connect to, should it need one.

Still you may recreate it with the SQL command CREATE DATABASE postgres;

Note that the tutorial mentioned in the question is not written with postgres.app in mind.
Contrary to PostgreSQL for Unix in general, postgres.app tries to look like a normal application as opposed to a service that would be run by a dedicated postgres user having different privileges than your normal user. postgres.app is run and managed by your own account.

So instead of this command: sudo -u postgres psql -U postgres, it would be more in the spirit of postgres.app to just issue: psql, which automatically connects to a database matching your users’s name, and with a db account of the same name that happens to be superuser, so it can do anything permissions-wise.

answered Mar 8 ’13 at 20:53

For what it is worth, i have ubuntu and many packages installed and it went in conflict with it.

For me the right answer was:

sudo -i -u postgres-xc
psql

answered Jan 11 ’17 at 15:37

I don’t think that sudo is needed here because psql -l returns a list of databases. This tells me that initdb was run under the user’s current user, not under the postgres user.

You can just:

psql

And continue the tutorial.

I would suggest A.H’s general points of creating the postgres user and db because many applications may expect this to exist.

A brief explanation:

PostgreSQL will not run with administrative access to the operating system. Instead it runs with an ordinary user, and in order to support peer authentication (asking the OS who is trying to connect) it creates a user and db with the user that runs the initialization process. In this case it was your normal user.

answered Mar 9 ’13 at 14:36

This is the only one that fixed it for me :

createuser -s -U $USER

answered Mar 2 ’16 at 0:10

I became stuck on this issue having executed brew services stop postgresql the day prior.
The day following: brew services start postgresql would not work. This is because as is shown when you install using homebrew. postgresql uses a launchd … which loads when your computer is powered on.

resolution:
brew services start postgresql
Restart your computer.

answered Jun 26 ’17 at 12:33

The du command return:

Role name = postgres@implicit_files

And that command postgres=# password postgres return error:

ERROR: role «postgres» does not exist.

But that postgres=# password postgres@implicit_files run fine.

Also after sudo -u postgres createuser -s postgres the first variant also work.

answered Jun 28 at 8:32

Not the answer you’re looking for? Browse other questions tagged macos postgresql terminal or ask your own question.

I use Windows 7 on my own home computer. I have installed PostgreSQL and now I would like to create an database.

I tried with createdb mydatabase but I got this error message:

createdb: could not connect to database postgres: FATAL: role "Jonas" does
not exist

I have also tried to create a role «Jonas» with createuser Jonas but I got the same error, even if I was logged in as Administrator in PowerShell.

How can I create a PostgreSQL database on my Windows 7 machine?

asked Dec 10, 2010 at 21:46

Jonas's user avatar

JonasJonas

26.1k47 gold badges104 silver badges125 bronze badges

http://www.postgresql.org/docs/8.1/static/tutorial-createdb.html

Another response could be this:

createdb: could not connect to database postgres: FATAL:  user "joe" does not
exist

where your own login name is mentioned. This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 18 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account.

Community's user avatar

answered Dec 10, 2010 at 22:32

ta.speot.is's user avatar

ta.speot.ista.speot.is

14.2k3 gold badges33 silver badges48 bronze badges

4

From http://www.postgresql.org/docs/8.1/static/tutorial-createdb.html

It could also be that you were assigned a PostgreSQL user name that is
different from your operating system user name; in that case you need
to use the -U switch or set the PGUSER environment variable to specify
your PostgreSQL user name.

I met the same problem, now I do it with

createdb -U postgres dbname

answered Jan 30, 2014 at 20:07

Tony's user avatar

TonyTony

1911 silver badge5 bronze badges

Понравилась статья? Поделить с друзьями:
  • Createservice failed with 1072 как исправить war thunder
  • Createremotethread error access denied
  • Createprofile failed org freedesktop dbus error
  • Createprocessw failed error 193
  • Createprocessasuser error 1314