/arch-linux-postgresql-joy

Basic PostgreSQL configuration and usage documentation with Emacs Org mode

# Inspect the PostgreSQL environment
  1. Become the postgres user

    $ sudo su - postgres
    
  2. Open the PostgreSQL interactive terminal

    $ psql
    
  3. Get help with psql commands

    \?
    
  4. List the users

    \dg
    
  5. List all the databases

    \l
    

How to create users

Create a superuser with your login name (app-createuser.html)

sudo -u postgres createuser --pwprompt --superuser joe

Creating new users with the create user client program

Create the user joe as a superuser, and assign a password immediately

  1. Run the create user program

    createuser --pwprompt --superuser --echo joe
    Enter password for new role: xyzzy
    Enter it again: xyzzy
    CREATE ROLE joe PASSWORD 'md5b5f5ba1a423792b526f799ae4eb3d59e' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;
    

Creating new users with CREATE USER from PostgreSQL interactive terminal

  1. Become the "postgres" user

    sudo su - postgres
    
  2. Open the PostgreSQL interactive terminal

    psql
    
  3. Run the CREATE USER SQL command

    CREATE ROLE jonathan LOGIN;
    

How to remove users

Removing users with SQL from PostgreSQL interactive terminal

  1. Become the "postgres" user

    $ sudo su - postgres
    
  2. Open the PostgreSQL interactive terminal

    $ psql
    
  3. DROP USER

    DROP USER IF EXISTS joe
    
ALTER USER david WITH PASSWORD 'hu8jmn3';
ALTER USER weight WITH PASSWORD 'weight';

Creating new databases

Create a new database with createdb

  1. Run creatdb

    createdb demo --owner railsapp
    

Create a new database with createdb

  1. Become the postgres user

    sudo su - postgres
    
  2. Run the "CREATE DATABASE" SQL command

    CREATE DATABASE sales OWNER salesapp TABLESPACE salesspace;
    CREATE DATABASE bootstrap_development OWNER bootstrap;
    CREATE DATABASE bootstrap_test OWNER bootstrap;
    CREATE DATABASE bootstrap_production OWNER bootstrap;
    

How to restart PostgreSQL

Ubuntu

service --status-all
sudo service postgresql-8.4  --full-restart

Documentation Links

Heroku PostgreSQL

Ubuntu Unicode encoding = 'UTF8';

In order to connect to template0, we need to change that flag:

template1=# UPDATE pg_database SET datallowconn = TRUE
template1-# WHERE datname = 'template0';
UPDATE 1

Now we can connect, and drop the Template1 database in order to replace it with a copy of Template0.

template0=# UPDATE pg_database SET datistemplate = FALSE
template0-# WHERE datname = 'template1';
UPDATE 1

# Risky!!! Backup First!!!
template0=# drop database template1;
DROP
template0=# create database template1 with template = template0;
create database template1 with template = template0 encoding = 'UTF8';
CREATE