Wednesday, December 19, 2012

Portable Postgre on Linux

I will show below a simple and easy way to create a postgre database on linux, I used portable database. In the bottom there are some instructions which differ for windows.

Download 

Download portable postgre for linux from link: Postgre Binaries
Untar the file using:
 $ tar -xvf postgresql-9.2.1-1-linux-binaries.tar.gz  
It will create the folder ./pgsql

Generating database files Then create the folder where you want your database to be created:
 $ mkdir -p pgsql/data  

Run initDB to create the database files into the recently created folder: $ pgsql/bin/initdb -D pgsql/data -U postgres -A trust

Startup and shutdown 

To startup or shut down the database use: "-l logfile" is to setup the log file for the startup command. "-m fast" will stop the database and will not wait for other threads to stop before shut down the database For other commands, check
 $ pgsql/bin/pg_ctl --help  

Configuring port 

The initdb command will create several files within data folder.
To setup the port where the database will listen to, do the following:

  1. Edit the generated file: pgsql/data/postgresql.conf 
  2. Search for the line #port = 5432
  3. Uncomment to your preferred port number: port = 5439
This way every time the database from that folder "pgsql/data" is started, it will run in the choosen port. No need for further configuration. Alternatively you can set a different port on every startup by setting up the environment param PGPORT, like below, just before the start command.

 $ export PGPORT=5439  

Create database and tables 

To create the database/tables etc, you can use pgsql/bin/psql and then simply run the sql commands, see example below:
 $ pgsql/bin/pg_ctl -D pgsql/data -l logfile start &  
 [1] 29063  
 $ server starting  
 $ pgsql/bin/psql -p 5439 -U postgres  
 postgres=# help  
 You are using psql, the command-line interface to PostgreSQL.  
 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=# create database myportal;  
 CREATE DATABASE  
 postgres=# \c myportal;  
 You are now connected to database "myportal" as user "postgres".  
 myportal=# create table myexample (key integer default 0);  
 CREATE TABLE  
 myportal=# \dt  
       List of relations  
  Schema |  Name  | Type | Owner  
 --------+-----------+-------+----------  
  public | myexample | table | postgres  
 (1 row)  
 myportal=# select * from myexample;  
  key  
 -----  
 (0 rows)  
 myportal=# \q  
 $  

To change password for the user postgre, run psql and then:
 postgres=# \password postgres;  

Windows Experience 

You can do basically the same thing, the difference is that instead of using pgsql/bin/psql, you can use pgsql/bin/pgAdmin3.exe to connect to the database and create the database and tables

No comments:

Post a Comment