Postgresql error role does not exist

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 acc...

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.

Erwin Brandstetter's user avatar

asked Aug 12, 2012 at 3:00

h9uest's user avatar

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 drees 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 running initdb) it
will have the same name as the operating system user that initialized
the database cluster. Customarily, this role will be named postgres.
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 Brandstetter's user avatar

Erwin BrandstetterErwin Brandstetter

579k139 gold badges1035 silver badges1189 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's user avatar

Vaibhav Mule

4,9403 gold badges35 silver badges52 bronze badges

answered Sep 9, 2013 at 23:27

dsrees's user avatar

dsreesdsrees

6,0262 gold badges25 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's user avatar

the

20.5k11 gold badges67 silver badges101 bronze badges

answered May 29, 2014 at 13:35

Mohammed Saleem's user avatar

Mohammed SaleemMohammed Saleem

1,8631 gold badge11 silver badges6 bronze badges

5

This works for me:

psql -h localhost -U postgres

ssbl's user avatar

ssbl

432 silver badges6 bronze badges

answered Aug 12, 2014 at 11:39

mateusz.szymborski's user avatar

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 Erickson's user avatar

Miles EricksonMiles Erickson

2,5542 gold badges17 silver badges17 bronze badges

2

psql postgres

postgres=# CREATE ROLE username superuser;
postgres=# ALTER ROLE username WITH LOGIN;

answered Apr 7, 2019 at 15:08

Abel's user avatar

AbelAbel

3,91132 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

Kalyan Halder's user avatar

0

Working method,

  1. vi /etc/postgresql/9.3/main/pg_hba.conf
  2. local all postgres peer
    here change peer to trust
  3. restart, sudo service postgresql restart

  4. now try, psql -U postgres

answered Sep 10, 2017 at 16:23

Mohideen bin Mohammed's user avatar

2

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 Tolstoy's user avatar

Andriy TolstoyAndriy Tolstoy

5,5522 gold badges30 silver badges30 bronze badges

1

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

Jan's user avatar

JanJan

10.4k6 gold badges48 silver badges84 bronze badges

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.

Erwin Brandstetter's user avatar

answered Jun 21, 2015 at 20:28

Robert Cambil's user avatar

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

Community's user avatar

answered Aug 28, 2018 at 19:53

Natacha's user avatar

NatachaNatacha

1,05516 silver badges22 bronze badges

0

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

srghma's user avatar

srghmasrghma

4,5902 gold badges34 silver badges54 bronze badges

sudo -u postgres createuser --superuser $USER

sudo -u postgres createdb $USER

This should definitely work for you.

answered Jul 25, 2022 at 13:05

Boy Nandi's user avatar

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

Siwei's user avatar

SiweiSiwei

18.6k5 gold badges71 silver badges93 bronze badges

Follow These Steps and it Will Work For You :

  1. run msfconsole
  2. type db_console
  3. 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 the database.yml in the emplacement: /usr/share/metasploit-framework/config
  4. you will see. rebuilding the model cache in the background.
  5. 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.

ankit suthar's user avatar

ankit suthar

2,7267 gold badges35 silver badges56 bronze badges

answered Aug 17, 2017 at 10:20

Loli Pronoms's user avatar

Follow these steps to get postgres working.

  1. In your terminal, locate the Application Support folder with the following command.
    /Users/[name of the user]/library/application support
  2. Delete the application, Postgres.
  3. Reinstall the app and it should work just fine.

answered Jul 11, 2021 at 5:48

Oteri Eyenike's user avatar

Something as simple as changing port from 5432 to 5433 worked for me.

answered Aug 12, 2020 at 0:23

Guka Nozadze's user avatar

1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

es6Test opened this issue

Mar 1, 2016

· 15 comments

Comments

@es6Test

I just done a clean install of postgressApp and the app says connected and started on port 5432. However the terminal gives me something like this:

Last login: Mon Feb 29 22:45:28 on ttys006
'/Applications/Postgres.app/Contents/Versions/9.5/bin'/psql -p5432
➜  ~  '/Applications/Postgres.app/Contents/Versions/9.5/bin'/psql -p5432
psql: FATAL:  role "me" does not exist
➜  ~   

Before installing I removed postgress brew and enterprise psql

@jakob

By default, psql tries to connect to the PostgreSQL server using the same user name as your system user. So in order to make connecting easier, Postgres.app creates a user with the same name as your system user when it starts the first time.

If you change your system user name, those user names won’t match anymore. Then you have to connect using psql --username=OLDUSERNAME, or with psql --username=postgres to connect as the postgres user.

psql also uses your environment variables for configuration. So for troubleshooting, type export in Terminal to make sure there are no settings for PGUSER etc. that override the defaults.

rob-johansen, intelligent-rohit, uncl3-b3nny, texpert, mariogaljr, salmicrosoft, dstj, nicknish, dennohpeter, aqifilyaskhan, and 17 more reacted with thumbs up emoji
GisTypical, Victor-Villacis, and garzo94 reacted with heart emoji
AzyCrw4282 reacted with eyes emoji

@es6Test

Hi, and thx, when I do export I get

USER=me

@es6Test

I’m not sure what to do about the role error.

@jakob

So I assume your local username is «me». Did you ever change that?

Try the following:

  1. quit Postgres.app
  2. delete the data directory (~/Library/Application Support/Postgres — check the docs for details)
  3. then start Postgres.app again

Then it should create a new data dir and create a postgres user (role) with the name «me», and it after tht you should be able to connect

@cdonadeo

Just had the same issue after installing Postgres 9.5.1.0. What I did:

  • Stopped my 9.4 installation
  • Ensured no Postgres processes were running (ps aux | grep postgres)
  • Moved the old 9.4 app to /Applications/Postgres-9.4 (mv /Applications/Postgres /Applications/Postgres-9.4)
  • Moved the new 9.5 app to /Applications/Postgres (mv ~/Downloads/Postgres /Applications/Postgres)
  • Started the app by double clicking the icon, started with no obvious issues

Result:

➜  ~ /Applications/Postgres.app/Contents/Versions/9.5/bin/psql
psql: FATAL:  role "chrisdonadeo" does not exist
➜  ~ /Applications/Postgres.app/Contents/Versions/9.5/bin/psql -U postgres
psql (9.5.1)
Type "help" for help.

postgres=# SELECT rolname FROM pg_roles;
 rolname
----------
 postgres
(1 row)

It appears that no role with my username was created when the database was initialized. I think I recall that this did happen with 9.4 versions, and the documentation states that you should use your username and a blank password.

@jakob

Well, first of all you can of course create a new user and corresponding database using the folowing two commands:

createuser -U postgres -s YOURUSERNAME
createdb YOURUSERNAME

This is what Postgres.app should have done right after initialising the data directory.

So it would be interesting why creating the user failed in the first place — Postgres.app should show an error if it fails to create the user.

For troubleshooting purposes, could you try the procedure I suggested above (quit Postgres, delete or move data dir, start Postgres again) to see if initialisation works properly? Also, check the log file inside the data dir to see if there’s anything that could explain this…

developer239, vejalingo, gregory, amgad-naiem, MrCoffey, akhilpatil7, shukrikhalid, bhuvnesht26, datonedoe, vamsi, and 23 more reacted with thumbs up emoji
AlexeyShalikWork reacted with thumbs down emoji
Brayonski, virtualroot, and analyn-cajocson reacted with laugh emoji
amgad-naiem, bhuvnesht26, rchrdchn, andthomas, Brayonski, and analyn-cajocson reacted with hooray emoji
rchrdchn, andthomas, Brayonski, and analyn-cajocson reacted with heart emoji

@es6Test

@jakob, thx but after deleting ~/Library/Application Support/Postgres and restarting I get the same error. And now I did not change «me».

@jakob

@es6Test
did you get any errors? are you able to connect using psql -U postgres?

Can you try the following command and see what happens?

psql -U postgres -c 'SHOW data_directory;'

Also, is there anything in the log? You can view it using

cat ~/Library/Application Support/Postgres/var-9.5/postgres-server.log

(Assuming you are running 9.5 and using the default data dir)

@es6Test

I had to add this to the path:

export PATH="/Applications/Postgres.app/Contents/Versions/9.5/bin:$PATH"
`➜ ~ psql -U postgres -c ‘SHOW data_directory;’

data_directory

/Users/me/Library/Application Support/Postgres/var-9.5
(1 row)`

LOG:  using stale statistics instead of current ones because stats collector is not responding
LOG:  received fast shutdown request
LOG:  aborting any active transactions
LOG:  autovacuum launcher shutting down
LOG:  shutting down
LOG:  database system is shut down
LOG:  database system was shut down at 2016-03-05 09:13:16 GMT
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started
FATAL:  role "me" does not exist

thx 4 helping!!

@es6Test

I noticed I have a user call postgres, how can I tell psql to use that instead of ‘me’?

@es6Test

the postgres user is part of group daemon

@es6Test

I ran psql manually in the terminal by supplying -U postgres

@leehinde

I was having the same issue and quitting the new install (9.5), deleting the ~/Library/Application Support/Postgres/var-9.5 directory and relaunching fixed it.

@mrsalmanahmad

This comment has been minimized.

@opadotun-taiwo

My psql command was working before and I have tried almost everything I could. I am trying to design a game in python

Let’s first try to create this error here. I’m going to generate a new rails project, so I’m going to say rails new MyPgProject -T --database=postgressql. I’m going to have it skip the test, so it loads a little bit faster. Then I’m also going to make sure that I am using the database of PostgreSQL.

Now, this assumes that you already have Postgres installed on your system, so I’m going to run this. It’s going to go install all the dependencies, and bundle install and everything like that. Now, if I type ls, you can see that we have MyPgProject right there.

large

Let’s switch into that, cd MyPgProject/ and you may think that we’d be able to type rails db:create just like this, and usually that will work. If you run into the rule does not exist bug, like we’re going to right here, then this is going to break.

If I run this then you’re going to see that we get this giant very scary looking error message. Scroll all the way up to the top. Then you’re going to see where it says PG::ConnectionBad Fatal role "jordan" does not exist.

large

Now, do not let this intimidate you. All it means is that that Postgres was looking for the username JORDAN. It says role, but it’s actually looking for a username Jordan, and it was not able to find it. That is what the entire issue is related to.

I’m going to show you that we can fix it just like this. The very first thing that we have to do is we have to switch in and use our Postgres user. To do that type sudo su. That stands for super user. Then sudo su - postgres. What this means is right now we’re logged in as Jordan, well, I am.

Yours is going to say whatever your name is, but you can see right here I’m logged in as Jordan into this version of Linux. I want to be logged in as a Postgres user. If I hit enter. It’s going to ask me for my system password. Now you can see that it says postgres@jordan. Now I am logged in as the Postgres user.

large

Now what I can do is create that user, so I can say create user -s -r jordan. Most likely, unless your name is Jordan, and you gave Jordan as your system role or your system name, then this is going to be your name is.

Whenever you have that error and it says «role does not exist» for mine it says Jordan. Yours is going to say whatever your name is. That is what you want to type in. So createuser - s -r jordan. Hit enter, and that’s it.

Now hit control + d. That’s going to switch you back into your default user. Assuming that you’re still in the project. Now let’s try rails db:create once again, and you’re going to see that this is actually working. We no longer get that error message.

large

You can do a really quick scaffold, so you can say rails g scaffold Blog title:string, just like this. Then it’s going to generate all this for us. Then we’re going to be able to update the database. Now I can say rails db:migrate.

This is going to update the database tables that we already created. Type rails s to start the rails server. Now we should be able to go to localhost 3000 in our browser, and update everything.

We can actually type different titles in for blogs and different things like that just to make sure that we actually have persistence. That what we’re typing into the screen is going to be able to be saved in the database.

If I type localhost3000/blogs, you can see that now we have our blogs showing up. I can type new title My test, hit create blog, and that is stored.

large

That means that this is stored in the database, which means that our database configuration is working perfectly. That is how you can fix the role not found, and fix that fatal Postgres error when you’re working on Linux.

There are a lot of PostgreSQL errors out there.
Way too much, right?

You as a sysadmin know that for sure – Syntax Errors, Relation Errors, Server Connection Errors, and other Error Codes.

Here you’ll find a list of the most common PostgreSQL errors and proven quick fix solutions:

    1. PostgreSQL error “Syntax error at or near ‘grant’”
    2. PostgreSQL error code “42501” or “Permission denied”
    3. PostgreSQL error code “1053” or “The service did not respond to the start or control request in a timely fashion”
    4. PostgreSQL error “Role does not exist”
    5. PostgreSQL error “Relation does not exist”
    6. PostgreSQL error ”Could not connect to server: no such file or directory” or “Could not connect to server: connection refused”
    7. PostgreSQL error “Invalid input syntax”
    8. PostgreSQL error “Permission denied for database”
    9. PostgreSQL error Code “42703” or “Column does not exist”
    10. PostgreSQL error “Could not extend file” or “No space left on device”

And you’ll find the solution to get rid of ALL PostgreSQL errors – forever: Test PRTG as your new monitoring tool and get started within minutes!

 1. PostgreSQL error

“Error: syntax error at or near ‘grant’”

time blueQuick fix

The error message “syntax error at or near ‘grant’” is one of the most common PostgreSQL database errors. However, it can easily be identified and resolved.

To understand this issue, you need to know that SQL distinguishes between reserved and non-reserved key word tokens. Reserved key words, such as “grant”, are never allowed as identifiers. Most reserved tokens are not allowed as column or table names, but may be allowed as an “AS” column label name.

If you come across this error message, check your code and make sure that the reserved keyword, for example “grant”, is quoted. Without using quotes, the error message will pop up in the PostgreSQL database.

Best Solution: https://severalnines.com/blog/decoding-postgresql-error-logs

 2. PostgreSQL error

“Error 42501” or “Permission Denied”

time blueQuick fix

PostgreSQL error 42501 is a common error that sometimes occurs in response to a PostgreSQL database query. In most cases, error code 42501 implies that the user has insufficient privilege for the database. As soon as a user with insufficient privileges make a query, PostgreSQL responds with the error message.

To fix the problem, check the database user privileges. If the user who attempted the query lacks permission, simply change the privileges accordingly. You can give privileges for a table either to the public using “GRANT SELECT ON table_name TO PUBLIC;” or to only a few users using the command “GRANT SELECT ON table_name to user_name;”.

Best Solution: https://bobcares.com/blog/postgresql-error-42501/364570

 3. PostgreSQL error

“Error 1053” or “The service did not respond to the start or control request in a timely fashion”

time blueQuick fix

Are you facing error code 1053 while working with the PostgreSQL database? Then you have come across a common PostgreSQL error. The error code is usually accompanied by the message “the service did not respond to the start or control request in a timely fashion”.

There are several possible causes for error 1053, such as low timeout values, firewall restrictions, corrupted files and permission of files. The solution for PostgreSQL error 1052 depends on the individual cause:

  1. If caused by a low timeout value, get rid of error code 1053 by setting a ServicesPipeTimeout DWORD value in the registry editor to override the default timeout time of your database.
  2. If your firewall prevents your PostgreSQL database from working correctly, disable your firewall or change the settings to allow all database requests to run smoothly.
  3. If corrupted files or permission of files are the cause of this error to occur, use the file checking tools to check the system file structure and replace corrupted files to eliminate of error 1053.

Best Solution: https://bobcares.com/blog/postgresql-error-1053/

4. PostgreSQL error

“Role does not exist”

time blueQuick fix

PostgreSQL error message “role does not exist” occurs when connecting to PostgreSQL using a user name that does not exist. The full error message usually states something similar to “FATAL: role “username” does not exist”.

For easy troubleshooting, make sure you have logged in to the correct user. If the user does not exist yet, create the user account on the PostgreSQL database. You should now be able to connect to PostgreSQL.

Best Solution: https://knowledgebase.progress.com/articles/Article/postgresql-error-role-does-not-exist

 5. PostgreSQL error

“Relation does not exist”

time blueQuick fix

Are you looking for a solution to PostgreSQL error message “relation does not exist”? As there are several possible causes for this common error, it is often necessary to do some digging in order to find out what causes the PostgreSQL database to respond with the error message.

One of many possible causes is that your postgres user is configured not to use a password, while your connection string includes “password=”. This configuration can result in the error “relation does not exist” to occur. To solve the problem, remove “password=” from the connection string. It should now look like this:

“host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”

Another workaround is to alter the postgres user to require a password, then change the connecting string accordingly.

Best Solution: https://medium.com/@raajyaverdhanmishra/when-you-get-relation-does-not-exist-in-postgres-7ffb0c3c674b

 6. PostgreSQL error

”Could not connect to server: no such file or directory” or “Could not connect to server: connection refused”

 7. PostgreSQL error

“Invalid input syntax”

time blueQuick fix

If you have encountered the error message “invalid input syntax” while working with the PostgreSQL database, you are dealing with a common error. The full error message usually looks like this, or similar:

ERROR: invalid input syntax for type numeric: «b» at character 26

The error occurs when the user attempts to insert a value that does not match the column type. If the problem is not caused by an attempt to enter a faulty, it may be an application side error that needs to be solved by the developer.

Best Solution: https://severalnines.com/blog/decoding-postgresql-error-logs

 8. PostgreSQL error

«Permission denied for database»

time blueQuick fix

“Permission denied for database” is a group of PostgreSQL errors that is in most cases caused by a lack of user privileges. Depending on the reason for the error to occur, common error messages include “Permission denied for relation”, “Permission denied for sequence”, or “Permission denied for schema”. All of these PostgreSQL errors are related privilege issues.

To solve the problem, there are several possible troubleshooting methods:

  1. Make sure that the user is granted the Connect privilege. To grant the privilege, use the command “GRANT CONNECT ON DATABASE userdb TO user ;”.
  2. To read data from the table, users require the privilege Connect, Create, Temporary and Select. Whenever you are granting access to a new user, make sure that all necessary privilege is granted.
  3. The permission denied error can also be caused by a missing user. If this is the case, update all PostgreSQL users with the proper password and sync it with the Plesk panel.

Best Solution: https://bobcares.com/blog/permission-denied-for-database-postgres/

 9. PostgreSQL error

“42703” or “Column does not exist”

time blueQuick fix

Another common error code with PostgreSQL database is 42703 as well as the error message “column does not exist”. This error indicates either that the requested column does not it exist, or that the query is not correct.

There are many possible reasons for this issue. To get started, check your query for any mistakes. Often, the error is caused by a lack of quotes. If this is the case, add double quotes to the column name, then try again. 

Best Solution: https://stackoverflow.com/questions/52007364/postgresql-column-doesnt-exist

 10. PostgreSQL error

“Could not extend file” or “No space left on device”

time blueQuick fix

Lack of disk space is a common problem that can easily be prevented. If you are facing the error message “no space left on device”, there is not enough space on your disk to run the database.

To solve the problem, free some space on the disk and make sure to avoid running out of disk space in the future.

Best Solution: https://www.percona.com/blog/2020/06/05/10-common-postgresql-errors/

Choose your solution: Bugfix or replacement

prtg logo white

With PRTG you’ll never have to deal
with PostgreSQL errors again. Forever.

Trusted by 500,000 users and recognized
by industry analysts as a leader

trustpilot preview

“Fantastic network and infrastructure monitoring solution that is easy to deploy and easier still to use. Simply the best available.”

Read more reviews

gartner preview

“Software is absolutely perfect, Support is superior. Meets all needs and requirements, this is a must have solution if you are needing any form of monitoring.”

Read more reviews

pcmag preview

“The tool excels at its primary focus of being a unified infrastructure management and network monitoring service.”

Read more reviews

Contents

  1. Introduction
  2. Client Installation
  3. Installation

    1. Installing PostGIS, procedural languages, client interfaces, etc
    2. Administration
  4. Basic Server Setup

    1. Create database
    2. Install Server Instrumentation (for PgAdmin) for Postgresql 8.4 or 9.3
  5. Alternative Server Setup
  6. Using pgAdmin III GUI
  7. Managing the Server

    1. Managing users and rights
    2. restarting the server
  8. Further reading
  9. Troubleshooting

    1. fe_sendauth: no password supplied
    2. FATAL: role «myusername» does not exist
    3. FATAL: database «myusername» does not exist
    4. FATAL: Peer authentication failed for user «myusername»
    5. could not connect to server: No such file or directory
  10. External Links

    1. Official PostgreSQL downloads
    2. EnterpriseDB
    3. Turnkey Linux

Introduction

PostgreSQL is a powerful object-relational database management system, provided under a flexible BSD-style license.[1] PostgreSQL contains many advanced features, is very fast and standards compliant.

PostgreSQL has bindings for many programming languages such as C, C++, Python, Java, PHP, Ruby… It can be used to power anything from simple web applications to massive databases with millions of records.

Client Installation

If you only wish to connect to an external PostgreSQL server, do not install the main PostgreSQL package, but install the PostgreSQL client package instead. To do this, use the following command

 sudo apt-get install postgresql-client

you then connect to the server with the following command

 psql -h server.domain.org database user

After you inserted the password you access PostgreSQL with line commands. You may for instance insert the following

 SELECT * FROM table WHERE 1;

You exit the connection with

 q

Installation

To install the server locally use the command line and type:

 sudo apt-get install postgresql postgresql-contrib

This will install the latest version available in your Ubuntu release and the commonly used add-ons for it.

See «External Links» below for options for getting newer releases.

Installing PostGIS, procedural languages, client interfaces, etc

Additional packages contain procedural language runtimes, add-ons like PostGIS, language client interfaces like psycopg2 for Python, etc. You can get a listing with:

 apt-cache search postgres

Administration

pgAdmin III is a handy GUI for PostgreSQL, it is essential to beginners. To install it, type at the command line:

 sudo apt-get install pgadmin3

You may also use the Synaptic package manager from the System>Administration menu to install these packages.

Basic Server Setup

To start off, we need to set the password of the PostgreSQL user (role) called «postgres»; we will not be able to access the server externally otherwise. As the local “postgres” Linux user, we are allowed to connect and manipulate the server using the psql command.

In a terminal, type:

sudo -u postgres psql postgres

this connects as a role with same name as the local user, i.e. «postgres», to the database called «postgres» (1st argument to psql).

Set a password for the «postgres» database role using the command:

password postgres

and give your password when prompted. The password text will be hidden from the console for security purposes.

Type Control+D or q to exit the posgreSQL prompt.

Create database

To create the first database, which we will call «mydb», simply type:

 sudo -u postgres createdb mydb

Install Server Instrumentation (for PgAdmin) for Postgresql 8.4 or 9.3

PgAdmin requires the installation of an add-on for full functionality. The «adminpack» addon, which it calls Server Instrumentation, is part of postgresql-contrib, so you must install that package if you haven’t already:

 sudo apt-get install postgresql-contrib

Then to activate the extension, for «»Postgresql 8.4″», run the adminpack.sql script, simply type:

 sudo -u postgres psql < /usr/share/postgresql/8.4/contrib/adminpack.sql

For «Postgresql 9.3″+ install the adminpack «extension» in the «postgres» database:

 sudo -u postgres psql
 CREATE EXTENSION adminpack;

Alternative Server Setup

If you don’t intend to connect to the database from other machines, this alternative setup may be simpler.

By default in Ubuntu, Postgresql is configured to use ‘ident sameuser’ authentication for any connections from the same machine. Check out the excellent Postgresql documentation for more information, but essentially this means that if your Ubuntu username is ‘foo’ and you add ‘foo’ as a Postgresql user then you can connect to the database without requiring a password.

Since the only user who can connect to a fresh install is the postgres user, here is how to create yourself a database account (which is in this case also a database superuser) with the same name as your login name and then create a password for the user:

 sudo -u postgres createuser --superuser $USER
 sudo -u postgres psql
 postgres=# password $USER

Client programs, by default, connect to the local host using your Ubuntu login name and expect to find a database with that name too. So to make things REALLY easy, use your new superuser privileges granted above to create a database with the same name as your login name:

 sudo -u postgres createdb $USER

Connecting to your own database to try out some SQL should now be as easy as:

 psql

Creating additional database is just as easy, so for example, after running this:

 create database amarokdb;

You can go right ahead and tell Amarok to use postgresql to store its music catalog. The database name would be amarokdb, the username would be your own login name, and you don’t even need a password thanks to ‘ident sameuser’ so you can leave that blank.

Using pgAdmin III GUI

To get an idea of what PostgreSQL can do, you may start by firing up a graphical client. In a terminal type :

 pgadmin3

You will be presented with the pgAdmin III interface. Click on the «Add a connection to a server» button (top left). In the new dialog, enter the address 127.0.0.1 (Local host is default, so it can be left out.), a description of the server, the default database («mydb» in the example above), your username («postgres») and your password. One more step is required in order to allow pgAdmin III to connect to the server, and that is to edit pg_hba.conf file and change the authentication method from peer to md5 (will not work if you have not set the password):

sudo nano /etc/postgresql/9.3/main/pg_hba.conf

and change the line

# Database administrative login by Unix domain socket
local   all             postgres                                peer

to

# Database administrative login by Unix domain socket
local   all             postgres                                md5

Now you should reload the server configuration changes and connect pgAdmin III to your PostgreSQL database server.

sudo /etc/init.d/postgresql reload

With this GUI you may start creating and managing databases, query the database, execute SQl etc.

Managing the Server

To learn more about managing PostgreSQL (but without the Ubuntu specifics) see the official PostgreSQL documentation

Managing users and rights

User management is discussed in detail in the client authentication chapter of the PostgreSQL documentation; the following is an introduction to get you started.

To manage users, you first have to edit /etc/postgresql/current/main/pg_hba.conf and modify the default configuration which is very locked down and secure. For example, if you want postgres to manage its own users (not linked with system users), you will add the following line:

8<-------------------------------------------
# TYPE  DATABASE    USER        IP-ADDRESS        IP-MASK           METHOD
host    all         all         10.0.0.0       255.255.255.0    md5
8<-------------------------------------------

Which means that on your local network (10.0.0.0/24 — replace with your own local network !), postgres users can connect through the network to the database providing a classical couple user / password.

Besides allowing a user to connect over the network to the to a database on the server, you must enable PostgreSQL to listen across different networks. To do that, open up /etc/postgresql/current/main/postgresql.conf in your favourite editor and alter the listen_addresses as below:

listen_addresses = '*'

to listen on all network interfaces. See the docs for listen_addresses for other options.

To create a database with a user that have full rights on the database, use the following command:

sudo -u postgres createuser -D -A -P myuser
sudo -u postgres createdb -O myuser mydb

The first command line creates the user with no database creation rights (-D) with no add user rights -A) and will prompt you for entering a password (-P). The second command line create the database ‘mydb with ‘myuser‘ as owner.

This little example will probably suit most of your needs. For more details, please refer to the corresponding man pages or the online documentation.

restarting the server

After configuring the networking / users you may need to reload the server, here is a suggested command to do so.

sudo /etc/init.d/postgresql reload

Some settings changes in postgresql.conf require a full restart, which will terminate active connections and abort uncommitted transactions:

sudo /etc/init.d/postgresql restart

Further reading

If you are not familiar with SQL you may want to look into this powerful language, although some simple uses of PostgreSQL may not require this knowledge (such as a simple Django project).

The PostgreSQL website contains a wealth of information on using this database. In particular, the tutorial is a useful starting point, but you can skip the installation step as you’ve already installed it using Ubuntu packages.

Troubleshooting

fe_sendauth: no password supplied

Your pg_hba.conf specifies that md5 authentication is to be used for this connection based on the origin host, connection method and the requested username/database, but your application didn’t supply a password.

Change the authentication mode or set a password for the user you’re connecting to and then specify that password in your application’s connection settings.

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.

FATAL: database «myusername» does not exist

A user named «myusername» exists, but there’s no database of the same name.

By default PostgreSQL connects to the database with the same name as the user you’re connecting as, but it doesn’t auto-create the database if it doesn’t exist.

Create the database, or specify a different database to connect to.

FATAL: Peer authentication failed for user «myusername»

You are connecting to localhost via a unix socket. A user named «myusername» exists, but your current unix user is not the same as that username. PostgreSQL is set to use «peer» authentication on unix sockets for this user/db combo so it requires your unix and postgresql usernames to match.

Connect from the unix user that matches the desired PostgreSQL user — perhaps with sudo -u theusername psql — or change pg_hba.conf to use a different authentication mode like «md5» for this username.

could not connect to server: No such file or directory

An error like this (possibly with a different unix socket path, depending on your install):

 psql: could not connect to server: No such file or directory
 Is the server running locally and accepting
 connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

can mean a number of things:

* The server isn’t running;

* The server has a different unix_socket_directories to the default in your client’s libpq, either due to different compiled-in defaults or a mismatched setting;

* The server is listening on a different «port». PostgreSQL emulates TCP/IP ports on unix sockets by using the port number as the suffix for the socket file, e.g. 5432.

Eliminate these in turn.

First make sure the server is running. On Ubuntu, ps -u postgres -f will show you any processes running as user postgres — you want to see multiple ones named postgres.

Now make sure the server is listening where your client thinks it is. To find out your PostgreSQL server’s socket directory:

 sudo -u postgres psql -c "SHOW unix_socket_directories;"

or on older PostgreSQL versions, unix_socket_directory as the parameter changed name. To show the server’s port (which applies for both TCP/IP and unix sockets):

 sudo -u postgres psql -c "SHOW port;"

If you can’t even connect with psql under unix user postgres you can check the socket dir with lsof:

 $ sudo lsof -U -a -c postgres
 COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF   NODE NAME
 postgres 6565 postgres    5u  unix 0xffff88005a049f80      0t0 183009 /tmp/.s.PGSQL.5432
 postgres 6566 postgres    1u  unix 0xffff88013bc22d80      0t0 183695 socket
 postgres 6566 postgres    2u  unix 0xffff88013bc22d80      0t0 183695 socket

In this case the first line is the socket location. This server has socket directory /tmp with port 5432.

If your client is looking in a different socket directory, you’re probably trying to connect over unix sockets to the default socket path and/or to the default port, and the libpq your client application is linked to has a different compiled-in unix socket path and/or port than your running PostgreSQL. Most likely your LD_LIBRARY_PATH or /etc/ld.so.conf has a different libpq before the one that came with your version of PostgreSQL. This doesn’t generally matter much, you can just override the socket directory.

To specify an alternative socket directory and/port port to connect to, specify the socket dir as the host parameter in your connection options, e.g. to connect as user bob to the server listening in /tmp on port 5433:

 psql -h /tmp -p 5433 -U bob ...

or in connection-string form:

 psql "host=/tmp port=5433 user=bob ..."

The same works with any client that uses libpq (all the PostgreSQL client tools, plus e.g. psycopg2, the Pg gem in Ruby/Rails, PHP’s postgres and PDO, Perl’s DBB::Pg, etc). It does NOT work with non-libpq clients like PgJDBC, py-postgresql, etc, but most of these don’t support unix sockets at all. See the client documentation for non-libpq based clients.


[1] You do not have to pay in order to use PostgreSQL for any application, such as commercial closed source software. See http://www.postgresql.org/about/licence/.

External Links

Official PostgreSQL downloads

The PostgreSQL project provides an official list of download locations, including an Ubuntu software repository, at its download page. In particular, Ubuntu users can get newer PostgreSQL versions than those packaged in their Ubuntu release using apt-get via apt.postgresql.org.

For support and services around PostgreSQL see the services and support page.

EnterpriseDB

The PostgreSQL Linux downloads page contains a section on «Graphical installer» built by EnterpriseDB. You download the installer, change its properties to allow to run it as command (it has .run extension), and run it from command prompt as in «sudo whateveritwas.run».

You end up with

  • configured DB server instance, which starts with your server
  • pgAdmin III UI client application

Note that the installed software will not be integrated with Ubuntu software center. As a result, you will not receive any security updates from Ubuntu. However, the installed version will closely match the latest Ubuntu version.

Turnkey Linux

An Ubuntu-based PostgreSQL appliance is one of the easiest ways to get up and running with PostgreSQL on Ubuntu. It’s part of a family of pre-integrated TurnKey Linux Software Appliances based on Ubuntu 10.04.1 (Lucid LTS).

Понравилась статья? Поделить с друзьями:
  • Postgresql error permission denied to create database
  • Power query error handling
  • Postgresql error permission denied for table
  • Power probing error no power found перевод
  • Postgresql error permission denied for schema