creating user for postgresql on rails - ruby-on-rails

I chose postgresql for my database for rails but i ran into an apparently common error where 'FATAL: role "app" does not exist' when i try to run rake db:create:all. I found two solutions but im not sure which one is the right one to use. One website says to
su -
su - postgres
createuser -s Application
exit
exit
while the other says to
su - postgres
create role myapp with createdb login password 'password1'
what's the difference between the two? and which one should i use?

You should use this for the development environment only
Login in postgres console:
$> sudo -u postgres psql
create user with name rails and password:
=# create user rails with password 'password';
make user rails superuser:
=# alter role rails superuser createrole createdb replication;
create database projectname with owner rails:
=# create database projectname owner rails;
in database.yml:
development:
adapter: postgresql
encoding: unicode
database: projectname
pool:
username: rails
password: password

To create a user type this in your console
createuser
Enter the username and make it a superuser
Also you could add a password also by adding pwprompt to createuser like this
createuser --pwprompt
Next you enter pgsql as postgres and create your database
sudo -u postgres psql postgres
create database db_name owner user_name;
Hope it helps
Refer this site for more details
https://www.digitalocean.com/community/articles/how-to-install-and-use-postgresql-on-ubuntu-12-04

The second option is invalid. That does not work.
The first one:
I don't recommend the first one and depending on your operating system some of the steps are unnecessary.
You become a superuser and make the shell a login shell (as if you would log in directly). I think it is risky and not necessary. Why not suing directly to postgre user (that's just a matter of setup)?
You become postgre and make the shell a login shell
You create a superuser Application in PostgreSQL. So you have the privileges of a superuser for your application. I think that is risky too. Superuser for an application is very bad. Often you need createdb, login and password to get started and other privileges, if ever needed, can be added/revoked later.
You quit the postgres shell session.
You quit the superuser shell session
The second one:
That's not correct. You forget to execute psql command as second step. The second command would become the third. It would be like that.
You become postgres and make the shell a login shell
You log into postgres command shell by default with user postgres
You create a role myapp with options createdb, login and (usually by default encrypted) password with value password1.
The difference is that the first one grants superuser privileges to the Application role while the second grants only the listed permissions to the myapp role.
The second option is more secure. Among the two option opt for the seoconde one.
Note: In PostgreSQL a user is simply a role with login permission. It's more of a conceptual distinction. Technically a user and role are pretty much the same as far as I know.

Related

change config/database.yml's username to be the same as your OSX user account

I'm using on online tutorial for homebrew to get Ruby on Rails working
https://gorails.com/setup/osx/10.11-el-capitan
Toward the end I am told to change config/database.yml's username to be the same as your OSX user account. I am unclear on how exactly to be accessing this infroamtion, and then even executing it.
I need to update the config/database.yml file to match the database username and password and I'm not sure how to be doing it from the terminal. Thank you!!
postgresql requires a role and a password in database.yml.
This tells you how to open postgresql console from terminal and create a role.
Step 1: Enter postgresql console from terminal
psql -d postgres -U username
Step 2: Create Role
create role rolename with createdb login password 'password1';
Use rolename as username and password1 as password in database.yml.

Set password in PostgreSQL

I am trying to set new password in postgreSQL.But I am getting error like below.
[root#localhost ~]# sudo -u postgres psql
could not change directory to "/root"
Welcome to psql 8.1.23, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit`postgres=# \password postgres
Query buffer is empty.
\p: extra argument "assword" ignored
\p: extra argument "postgres" ignored`
This works for me.
ALTER USER postgres WITH ENCRYPTED PASSWORD 'password';
Try this? Link
Login to your database and use the ALTER USER Postgres WITH PASSWORD '<newpassword>'; command.
Highly recommended to avoid ever using the ALTER USER Postgres WITH PASSWORD... syntax as there is a possibility whatever password you submit will be saved forever in your on disk logs.
Whenever possible, the best way to do it is through an interactive psql CL like so:
psql=# \password user_name
If you cannot do that, consider using SCRAM-SHA-256 authentication and the method described here.

What steps should I follow to get postgresql into development in my Rails app?

I'm learning Rails and my final app will be hosted on Heroku, which uses postgres, so I figured it'd be smart to work with postgres in development too as I'm building what is supposed to be a rather simple search function and want to avoid as many problems as possible actually deploying it.
Sadly, I'm using Ubuntu 14.04 so naturally the steps will be harder than on for example Windows.
Here's what I've done so far, which is a rather comical enterprise into a world that gives me nothing but problems at every step:
Actually installed postgresql. sudo apt-get install postgresql-9.4 as per the official website of course didn't work so I had to find a workaround (as always) but it should be installed now. I ran sudo apt-get install -y postgresql postgresql-contrib to get it working.
Tried logging in per some instructions with su postgres, but even after setting a password for su or using sudo su postgres that didn't work. Ended up creating a user with sudo -u postgres createuser -P my_user matching the name of my app. Created a database too.
Tried creating a new rails project with rails new my_app --database=postgresql. Didn't work as it complained lacking a pg gem (sorry for not pre-emptively making a Gemfile for you?) so I gave that up and just created it without specifying a database.
Removed the sqlite gem and added gem 'pg' in the Gemfile. Ran bundle install, but it didn't work. Had to run sudo apt-get install libpq-dev to install something I'm not sure what it is and then it worked.
Modified the database.yml as per some instructions and ran rake db:setup. Rails gave this error: FATAL: Peer authentication failed for user "my_user". Well, that's cool.
Not quite sure why, but I added a database here called my_app_development for it with the owner my_user but then db:setup instead complained that it lacked permissions to create a database (but I just created it FOR you?).
I ran chmod -R 0666 my_app as someone highly upvoted on SO suggested but holy shit that was bad as it didn't even give me permissions to enter the folder myself! Reverted that quickly and tried something else.
Someone suggested running psql -U my_user postgres but that only gives me the error psql: FATAL: Peer authentication failed for user "my_user"
Experimented logging in via psql postgres (I don't know what psql is, I'm just following suggestions) and tried ALTER ROLE my_user CREATEDB; but it only returns a permission denied error.
Officially gave up and came here.
Can anyone help me with the actual steps to follow from the beginning? It shouldn't be THIS hard, right?
By the way, this is what my database.yml looks like:
default: &default
adapter: sqlite3
pool: 5
timeout: 5000
development:
adapter: postgresql
encoding: unicode
database: my_app_development
host: localhost
pool: 5
username: my_user
password: my_password
test:
<<: *default
database: db/test.sqlite3
production:
<<: *default
database: db/production.sqlite3
Edit: Thanks alot to Ajay for walking me through how to setup postgres. If anyone comes across this thread, as frustrated as I am with postgres, here are a few pointers:
PG::InsufficientPrivilege: ERROR: permission denied to create database means the user doesn't have the right privileges. Log in via sudo -u postgres psql and you should see postgres=# before everything you type in the terminal. While there, type ALTER ROLE my_user CREATEDB; and it should work. I don't know why it didn't the first time I used that, perhaps I forgot sudo?
FATAL: Peer authentication failed for user "my_user" means you need to change some things in a file as per the instructions in one of the answers. Make sure to change it for both local and postgres. I have it set to md5 for everything but local and it works.
Login via sudo -u postgres psql and type `select * from pg_catalog.pg_user;' to check your current users. Good way to see if you created the user correctly and what privileges it has.
default: &default
adapter: sqlite3
pool: 5
timeout: 5000
Above adapter: sqlite3 is causing the error
Please try this:
default: &default
adapter: postgresql
pool: 5
timeout: 5000
development:
<<: *default
database: my_app_development
username: psql #postgres username
password: your_password #password
After you entered the valid postgres credentials(username/password) here. Try following in your terminal :
$ rake db:create #this will create your my_app_development database.
$ rake db:migrate #migrate your database.
5. Modified the database.yml as per some instructions and ran rake
db:setup. Rails gave this error: FATAL: Peer authentication failed
for user "my_user". Well, that's cool.
you need to open your pg_hba.conf (probally located at /etc/postgresql/9.4/main/pg_hba.conf) and change the authentication method from "peer" to "md5" (which will asks for password) or to "trust" (which will unsecuritly allow access without password).
To know where your pg_hba is located, execute this on your terminal (terminal of the machine where the postgresql are running):
ps ax | grep postgresql.conf
it should return something like:
8803 ? S 0:00 /usr/lib/postgresql/9.4/bin/postgres -D /var/lib/postgresql/9.4/main -c config_file=/etc/postgresql/9.4/main/postgresql.conf
look the folder where config_file is located. In this case is /etc/postgresql/9.4/main/. Inside this folder there's another configuration file called pg_hba.conf (the permissions file). Edit it (with super user):
sudo nano /etc/postgresql/9.4/main/pg_hba.conf
on the lasts lines you will see something like that:
# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
local all postgres trust
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 md5
#host replication postgres ::1/128 md5
You see the "trust" references? In your default pg_hba.conf they should be "peer". In my example, I had changed to "trust" (i.e, doesn't ask for passwords) all local connections, because my postgresql server not accept outside connections. But you can change to "md5", which will permit access when the user provide the correct password.
After change this, save and exit (in nano is Ctrl+O, Enter to confirm, Ctrl+X to exit). Then, restart postgresql (sudo /etc/init.d/postgresql restart - maybe works with just a reload)
UPDATE:
DISCLAIMER:
although trusting your local connections will not create a hole security (unless, of course you are sharing the machine with anothers users), do it only for testing purposes - to discover where the problem is (if is a permission/pg_hba problem or not). After discover where the problem are, its more concise to have one specific user to your project and use an authentication for it ("md5", "peer").
Using one single user for all your projects on the machine (e.g. the "postgres" user), and/or not use an authentication ("trust"), is like create a Rails project and use just one generic controller, instead having a controller for each table/group of logic.

Automatically set username in database.yml for Postgres

When you generate a new rails app with postgres as db it automatically set username to appname in database.yml.
You then have to manually change it to your username or the app will not run.
Is there any way to automatically set it to logged in user (at time of running rails new) or other preset username?
In development and test environments it will always be the same username and production does not matter as it always deployed on heroku.
I am on ubuntu, but would be great to hear solutions for mac users also.
Ok I ended up doing this:
In my template I added this line to replace the username:
gsub_file "config/database.yml", /username: .*/, "username: myusername"
I have a simple workflow of sole developer on dev machine so usernames for developement and test will always be the same and production does not matter as it deploys to heroku.
It is a good habit to make a new user for each application. to do this, first create adminpack extension as follows:
$ psql postgres -c 'CREATE EXTENSION "adminpack”;'
Open database prompt to create a new user. lets say your app called blog:
$ psql -d postgres
postgres=# create role blog login createdb ;
postgres=# \q
Now create your database and associate that to the user you just made:
$ createdb -E UTF8 -w -O blog blog_development
To check of its created:
$ psql -l

Rails and PostgreSQL: Role postgres does not exist

I have installed PostgreSQL on my Mac OS Lion, and am working on a rails app. I use RVM to keep everything separate from my other Rails apps.
For some reason when I try to migrate the db for the first time rake cannot find the postgres user. I get the error
FATAL: role "postgres" does not exist
I have pgAdmin so I can clearly see there is a postgres user in the DB - the admin account in fact - so I'm not sure what else to do.
I read somewhere about people having issues with PostgreSQL because of which path it was installed in, but then I don't think I would have gotten that far if it couldn't find the db.
Actually, for some unknown reason, I found the issue was actually because the postgresql role hadn't been created.
Try running:
createuser -s -r postgres
Note that roles are the way that PostgreSQL maintains database permissions. If there is no role for the postgres user, then it can't access anything. The createuser command is a thin wrapper around the commands CREATE USER, CREATE ROLE, etc.
Recently i got this problem immediately after installing postgres.
If it comes immediately after installation, you might be missing the default user, postgres.
In that case, you can create default user postgres using below command.
createuser -s -U $USER
Ex: createuser -s -U $USER
enter your required role name: postgres
enter password for your the user:
It will prompt you to enter required database role name and password
Once you complete the process, you can login to the postgres console using below command
psql -U 'your_database_name'
Ex: psql -U postgres
Here, You need to enter the password if you have given any, while creating the user.
Hope it helps :)
I was on OSX 10.8, and everything I tried would give me the FATAL: role "USER" does not exist. Like many people said here, run createuser -s USER, but that gave me the same error. This finally worked for me:
$ sudo su
# su postgres
# createuser -s --username=postgres MYUSERNAME
The createuser -s --username=postgres creates a superuser (-s flag) by connecting as postgres (--username=postgres flag).
I see that your question has been answered, but I want to add this answer in for people using OSX trying to install PostgreSQL 9.2.4.
This message pops up, when the database user does not exist. Compare the manual here.
Multiple local databases cannot be the explanation. Roles are valid cluster-wide. The manual again:
Note that roles are defined at the database cluster level, and so are
valid in all databases in the cluster.
You must be ending up in another database-cluster. That would be another server running on the same machine, listening to a different port. Or, more likely, on a different machine.
Could it be that the message comes, in fact, from the remote server?
I met this issue right on when I first install the Heroku's POSTGRES.app thing. After one morning trial and error i think this one line of code solved problem. As describe earlier, this is because postgresql does not have default role the first time it is set up. And we need to set that.
sovanlandy=# CREATE ROLE postgres LOGIN;
You must log in to your respective psql console to use this psql command.
Also noted that, if you already created the role 'postgre' but still get permission errors, you need to alter with command:
sovanlandy=# ALTER ROLE postgres LOGIN;
Hope it helps!
In the Heroku documentation; Getting started whit rails 4, they say:
You will also need to remove the username field in your database.yml
if there is one so: In file config/database.yml remove: username:
myapp
Then you just delete that line in "development:", if you don't pg tells to the database that works under role "myapp"
This line tells rails that the database myapp_development should be
run under a role of myapp. Since you likely don’t have this role in
your database we will remove it. With the line remove Rails will try
to access the database as user who is currently logged into the
computer.
Also remember to create the database for development:
$createdb myapp_development
Repleace "myapp" for your app name
The installation procedure creates a user account called postgres that is associated with the default Postgres role. In order to use Postgres, you can log into that account. But if not explicitly specified the rails app looks for a different role, more particularly the role having your unix username which might not be created in the postgres roles.
To overcome that, you can create a new role, first by switching over to the default role postgres which was created during installation
sudo -i -u postgres
After you are logged in to the postgres account, you can create a new user by the command:
createuser --interactive
This will prompt you with some choices and, based on your responses, execute the correct Postgres commands to create a user.
Pass over a role name and some permissions and the role is created, you can then migrate your db
Could you have multiple local databases? Check your database.yml and make sure you are hitting the pg db that you want. Use rails console to confirm.
My answer was much more simple. Just went to the db folder and deleted the id column, which I had tried to forcefully create, but which is actually created automagically. I also deleted the USERNAME in the database.yml file (under the config folder).
In Ubuntu local user command prompt, but not root user, type
sudo -u postgres createuser username
username above should match the name indicated in the message "FATAL: role 'username' does not exist."
Enter password for username.
Then re-enter the command that generated role does not exist message.
I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me:
We created a new app using "
rails new blog -d postgresql
Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all, then we can run rake db:migrate
The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.
Hope this helps.
After a bunch of installing and uninstalling of Postgres, here's what now seems to work consistently for me with Os X Mavericks, Rails 4 and Ruby 2.
In the database.yml file, I change the default usernames to my computer's username which for me is just "admin".
In the command line I run rake db:create:all
Then I run rake db:migrate
When I run the rails server and check the local host it says "Welcome aboard".
You might be able to workaround this by running initdb -U postgres -D /path/to/data or running it as user postgres, since it defaults to the current user. GL!

Resources