PhoenixPostgres - wendysmoak/wiki GitHub Wiki

= Phoenix Postgres Setup =

Having gotten Elixir and the Phoenix Framework's Hello Phoenix app running locally and deployed to Heroku (see PhoenixHeroku) I then tried to run the tests:

$ mix test
** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: psql: could not connect to server: Connection refused
	Is the server running on host "localhost" (::1) and accepting
	TCP/IP connections on port 5432?
could not connect to server: Connection refused
	Is the server running on host "localhost" (127.0.0.1) and accepting
	TCP/IP connections on port 5432?

Well, that's because Postgres isn't running locally. I'm not even sure it's installed. The easiest way to do that on a Mac is to grab Postgres.app from http://postgresapp.com and copy it to the Applications folder. Trying again:

$ mix test
** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: psql: FATAL:  role "postgres" does not exist

Okay, now it needs a role. Why does it think the role should be called "postgres"? That's in config/test.exs. And there we can see the password and the database name it's going to use as well. How do we create a role?

Open psql (click the elephant in the toolbar and choose 'open psql') and:

# CREATE ROLE postgres PASSWORD 'postgres';

Note: use single quotes around the password but NOT the role name, and end with a semicolon.

$ mix test
** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: psql: FATAL:  role "postgres" is not permitted to log in

Better, but it needs to be able to log in. You can probably ALTER it, but I want to figure out a single command that works.

# DROP ROLE postgres;
# CREATE ROLE postgres LOGIN PASSWORD 'postgres';
$ mix test
** (Mix) The database for PhoenixHerokuWsmoak.Repo couldn't be created, reason given: ERROR:  permission denied to create database

So close!

# DROP ROLE postgres;
# CREATE ROLE postgres LOGIN CREATEDB PASSWORD 'postgres';

Remember these options are listed on http://www.postgresql.org/docs/8.1/static/sql-createrole.html

$ mix test
....

Finished in 0.9 seconds (0.8s on load, 0.1s on tests)
4 tests, 0 failures

Randomized with seed 791319

Success! So to run the tests, you need to have Postgres running, and have a role matching the username in config/test.exs with the password shown there, with the ability to log in and create a database.

Hopefully this will prevent someone from just creating the postgres role as SUPERUSER (which is what I did the first time, just to get it working.)

Now let's go see what's in those tests: PhoenixTest

====

Note, if you brew install postgres then you need to psql postgres to get to the prompt where you can create the role. (postgres here is the database name to connect to.)

\du to list existing roles

\dt to list existing tables (relations)

\quit to get out of psql

⚠️ **GitHub.com Fallback** ⚠️