• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
OpenGurukul : Database : PostgreSQL

OpenGurukul : Database : PostgreSQL



PostgreSQL By OpenGurukul

PostgreSQL By OpenGurukul



Total Views
Views on SlideShare
Embed Views



2 Embeds 300

http://www.opengurukul.com 298
http://translate.googleusercontent.com 2



Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    OpenGurukul : Database : PostgreSQL OpenGurukul : Database : PostgreSQL Presentation Transcript

    • PostgreSQL By OpenGurukul.comFree/Open Source Software Laboratory
    • PostgreSQLModule : PostgreSQL Setup www.opengurukul.com 2
    • PostgreSQL Setup : ManualsPostgreSQL Manuals : all versions http://www.postgresql.org/docs/manuals/For PostgreSQL 9.1 - with user comments http://www.postgresql.org/docs/9.1/interactive/index.htmlFor PostgreSQL 9.1 - without user comments http://www.postgresql.org/docs/9.1/static/index.html www.opengurukul.com 3
    • PostgreSQL Setup : InstallInstall PostgreSQL yum install postgresql yum install postgresql-server yum install postgresql-libsInstall pgadmin tool yum install pgadmin3 www.opengurukul.com 4
    • PostgreSQL Setup : VersionThe postgres server version can be found by using --version on the postmaster$ postmaster --versionpostgres (PostgreSQL) 8.4.5$ www.opengurukul.com 5
    • PostgreSQLModule : pg_ctl : Control PostgreSQL Server www.opengurukul.com 6
    • pg_ctlThe pg_ctl utility is used toInitialize PostgreSQL database clusterStart PostgreSQL database serverStop PostgreSQL database serverRestart PostgreSQL database serverDisplay status of a running PostgreSQL database server www.opengurukul.com 7
    • pg_ctl : PGDATA variableThe pg_ctl commands are dependent on the PGDATA variable that contains directory location of database cluster.The PGDATA directory location can be specified using -D in case PGDATA environment variable is not set.Generally, we switch to “postgres” user in case the database cluster was created by “postgres” user. www.opengurukul.com 8
    • pg_lsclusters : Location of Database Clusters : Ubuntupg_lsclusters :$ pg_lsclusters # to clusters and data directory www.opengurukul.com 9
    • pg_ctl : Control PostgreSQL ServerStart Server : Stop Server :$ pg_ctl start $ pg_ctl stopserver starting waiting for server to shut down.... done$ server stopped $Restart Server : Server Status :$ pg_ctl restart $ pg_ctl statuswaiting for server to shut down.... pg_ctl: server is running (PID: 8384) done /usr/bin/postgresserver stopped $server starting www.opengurukul.com 10$
    • PostgreSQLModule : PostgreSQL Admin Tools www.opengurukul.com 11
    • PhpPgAdmin : Download & InstallDownload phpPgAdmin from http://sourceforge.net/projects/phppgadmin/Install phpPgAdmin using yum install phpPgAdmin www.opengurukul.com 12
    • PhpPgAdmin : phppgadmin/etc/apache2/conf.d/phppgadmin Uncomment # allow from all www.opengurukul.com 13
    • PhpPgAdmin : Configure/usr/share/phpPgAdmin/conf/config.inc.php :Modify extra_login_security to false in /usr/share/phpPgAdmin/conf/config.inc.phpIf extra login security is true, then logins via phpPgAdmin with no password or certain usernames (pgsql, postgres, root, administrator) will be denied.Set this to FALSE to access it using postgres etc.Its default value is true. // $conf[extra_login_security] = true;Set it to false $conf[extra_login_security] = false; www.opengurukul.com 14
    • PhpPgAdmin : Configurepg_hba.conf :Modify /var/lib/pgsql/data/pg_hba.conf file to change the method to "trust" from "ident".New Settings: local all all trustOld Settings: #local all all identRestart :Apache Web ServerRestart PostgreSQL Server www.opengurukul.com 15
    • PgAdmin: Download & InstallDownload & Install pgadmin3 from www.pgadmin.org pgadmin3-1.12.2-2.fc14.i686 rpm -i pgadmin3-1.12.2-2.fc14.i686Directly Install pgadmin3 yum install pgadmin3Invoke pgadmin3 $ pgadmin3 www.opengurukul.com 16
    • PgAdmin: Configure1> pg_hba.conf : edit pg_hba.conf file (use trust) otherwise you wiill not be able to connect# TYPE DATABASE USER CIDR-ADDRESS METHODhost all all trusthost all all ::1/128 trust2> restart PostgresSQL Server3> Configure a Server using PgAdmin3Host localhost, Port 5432user – postgres, password - postgresservice – postgresql, database - postgres, edb etc. www.opengurukul.com 174> The configuration can be checked in postgresql.conf
    • PostgreSQL psql www.opengurukul.com 18
    • psql : PGDATA$ su - postgres$ pwd/var/lib/pgsql$$ echo $PGDATA/var/lib/pgsql/data$ www.opengurukul.com 19
    • psql : command line$ psql -U<user_name> -d<db_name><DB_NAME>=# helpYou are using psql, the command-line interface to PostgreSQL.Type: copyright for distribution termsh for help with SQL commands? for help with psql commandsg or terminate with semicolon to execute queryq to quit<DB_NAME>=# q$ www.opengurukul.com 20
    • psql : default databaseNOTE :The default database is postgres.Example : Default connect to postgres$ psqlpsql (8.4.5)Type "help" for help.postgres=# q$ www.opengurukul.com 21
    • psql : -d : connect to databaseExample : Connect to template1$ psql -dtemplate1psql (8.4.5)Type "help" for help.template1=# q$ www.opengurukul.com 22
    • psql : s : display history or save historySyntax :s [FILE] display history or save it to fileExample : will list history of commands executed.postgres-# s www.opengurukul.com 23
    • psql : i : execute commands from fileSyntax :i FILE execute commands from fileExample :$ cat /tmp/in.sqll$postgres=# i /tmp/in.sql...will give a list of databases ...postgres=# www.opengurukul.com 24
    • psql : o : send all query results to fileSyntax :o [FILE] send all query results to file or |pipeExample :postgres=# o /tmp/out.txt lOutput :$ cat /tmp/out.txtwill have list of databases$ www.opengurukul.com 25
    • psql : ! : execute command in shellSyntax :! [COMMAND] execute command in shell or start interactive shellExample :postgres-# ! shsh-4.1$ pwd/var/lib/pgsqlsh-4.1$ exitexitpostgres-# www.opengurukul.com 26
    • psql : internal variablesSyntax :prompt [TEXT] NAME prompt user to set internal variableset [NAME [VALUE]] set internal variable, or list all if no parametersunset NAME unset (delete) internal variable www.opengurukul.com 27
    • psql : Display Internal Variablespostgres-# setAUTOCOMMIT = onPROMPT1 = %/%R%# PROMPT2 = %/%R%# PROMPT3 = >> VERBOSITY = defaultVERSION = PostgreSQL 8.4.5 on i386-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.5.1 20100924 (Red Hat 4.5.1-4), 32-bitDBNAME = postgresUSER = postgresPORT = 5432ENCODING = UTF8 www.opengurukul.com 28postgres-#
    • psql : set variables : Examplepostgres-# prompt name: SITEname: www.opengurukul.compostgres-# set...SITE = www.opengurukul.compostgres-# www.opengurukul.com 29
    • psql : promptThe psql prompt will bedatabasename=# for database super userdatabasename=> for users without super user privileges.NOTE :Whichever user has done initdb will have DB super user privileges or if added otherwise. www.opengurukul.com 30
    • PostgreSQLPostgreSQL Introduction www.opengurukul.com 31
    • Introduction : postgresTo start PostgreSQL server, you can directly use /usr/bin/postgres$ /usr/bin/postgres -D /var/lib/pgsql/data -p 5432-D : pgdata directory-p : port www.opengurukul.com 32
    • Introduction : postmasterThe postmaster is an alias for PostgreSQL Database Server.$ which postmaster/usr/bin/postmaster$$ ls -l /usr/bin/postmasterlrwxrwxrwx. 1 root root 8 Jan 27 2011 /usr/bin/postmaster -> postgres$ www.opengurukul.com 33
    • Introduction : Initialize database cluster : initdbThe initdb command is used to initalize a database cluster.A database cluster consists of a data directory that can have multiple databases served be a postgres instance.The initdb creates the directories in which the database data will live.The initdb generates the shared catalog tables (tables that belong to the whole cluster rather than to any particular database).The initdb creates two databases : www.opengurukul.com 34 template1 and postgres
    • Introduction: initdb : template1Whenever you create a new database in the cluster, everything in the template1 database is copied.We should install only those things in template1 that we would like to copy to other databases. www.opengurukul.com 35
    • Introduction: initdb : exampleSyntax :$ initdb --pgdata | -D pgdata_directoryGenerally, The default pgdata directory is /var/lib/pgsql/data.If you dont specify any pgdata directory, it will be picked up from PGDATA environment variableExample : Create a D/B cluster data1 in home directory$ initdb -D ~/data1$ www.opengurukul.com 36
    • Introduction: start d/b clusterExport PGDATA $ export PGDATA=~/data1Modify the port in ~/data1/postgresql.conf to 5433. $ export PGPORT=5433 # export portAdd user (the one who did initdb) to group “postgres” in /etc/group file to allow writing to /var/run/postgres/Start D/B pg_ctl startInvoke psql with new port psql -p <new port> -d postgres www.opengurukul.com 37
    • Introduction : Create Database : createdbThe createdb (executable) or "CREATE DATABASE" (psql # from psql prompt command) is used to create database on PostgreSQL. CREATE DATABASE name; # from shell command line createdb name; www.opengurukul.com 38
    • Introduction : Create Database : createdb : Example$ su - postgres$ createdb xExample :postgres=# CREATE DATABASE sample;CREATE DATABASEpostgres=# l [List of databases]Postgres=# q www.opengurukul.com 39$
    • Introduction : Delete Database : dropdbThe dropdb command can be used to delete the PostgreSQL database.Syntax :$ dropdb <dbname> www.opengurukul.com 40
    • Introduction : Connect to databasec[onnect] [DBNAME|- USER|- HOST|- PORT|-]connect to new database (currently "postgres")Example :postgres-# c samplepsql (8.4.5)You are now connected to database "sample".sample-# www.opengurukul.com 41
    • Introduction : psql : S, +Informational(options: S = show system objects, + = additional detail)d[S+] list tables, views, and sequencesNOTE: dS+ shows size alsoFor postgrres, we must specify "S" otherwise objects will not be shown.Example :postgres-# dS [List of relations] ...... www.opengurukul.com 42
    • Introduction : psql : d : Describe Tablepostgres=# dS pg_roles View "pg_catalog.pg_roles"+---------------+--------------------------+-----------+| Column | Type | Modifiers |+---------------+--------------------------+-----------+| rolname | name | || rolsuper | boolean | || rolinherit | boolean | || rolcreaterole | boolean | || rolcreatedb | boolean | || rolcatupdate | boolean | || rolcanlogin | boolean | || rolconnlimit | integer | || rolpassword | text | | www.opengurukul.com 43| rolvaliduntil | timestamp with time zone | |
    • Introduction : vacuumdb : garbage- collect databaseThe vacuumdb is a utility for cleaning a PostgreSQL database.VACUUM reclaims storage occupied by dead tuples.In normal PostgreSQL operation, tuples that are deleted or obsoleted by an update are not physically removed from their table; they remain present until a VACUUM is done.It is necessary to do VACUUM periodically, especially on frequently-updated tables. www.opengurukul.com 44
    • Introduction : vacuumdb : options--full : Perform full vaccuming--dbname <dbname> : name of the pariculat database to be cleaned or analyzed--table table [ (column [,...]) ] : table to be cleaned. columns can also be specified.--all : Vacuum all databases--analyze : Calculate statistics for use by the optimizer--verbose : verbose display www.opengurukul.com 45
    • Introduction : vacuumdb : ExampleExample :-bash-4.1$ vacuumdb --full --all --analyzevacuumdb: vacuuming database "postgres"vacuumdb: vacuuming database "template1"-bash-4.1$ www.opengurukul.com 46
    • PostgreSQLpg_dump : Backup & Resotre www.opengurukul.com 47
    • pg_dump : plain dump : script fileThe pg_dump command is used to extract a PostgreSQL database into a .sql script file.Syntax :pg_dump database_name > database.sql www.opengurukul.com 48
    • pg_dump : plain dump : usageTo dump a database called "mydb" into a SQL- script file: $ pg_dump mydb > db.sqlTo reload such a script into a (freshly created) database named "newdb". $ psql -d newdb -f db.sql www.opengurukul.com 49
    • pg_dump : tableTo dump specific tables, specify them after -tTo skip specific tables, specify them after -TBoth -t and -T supports regular expression.Example :$ pg_dump -t mytab1_* -T mytab2_* mydb > db.sql www.opengurukul.com 50
    • pg_dump : archive fileTo dump a database into a custom-format archive file:$ pg_dump -Fc mydb > db.dumpTo reload an archive file into a (freshly created) database named newdb :$ pg_restore -d newdb db.dumpThe default dump format is plain (p) script file that is specified using -Fp. www.opengurukul.com 51
    • PostgreSQLUsers & Privileges www.opengurukul.com 52
    • createuser : create user accountTo create a user account (also called role), createuser command is used.Only superusers and users with CREATEROLE privilege can create new users.You can also use "CREATE ROLE" to achieve it. www.opengurukul.com 53
    • createuser : create user account : exampleExample :To create a user matsya1 on the default database server:$ createuser matsya1Shall the new role be a superuser? (y/n) nShall the new role be allowed to create databases? (y/n) nShall the new role be allowed to create more new roles? (y/n) n www.opengurukul.com 54
    • dropuser - remove user accountThe dropuser is used to remove an existing PostgreSQL user.Only superusers and users with the CREATEROLE privilege can remove PostgreSQL users.You can also use "DROP ROLE <rolename>" to achieve it. www.opengurukul.com 55
    • dropuser - remove user account : exampleExample :To remove user matsya1 from the default database server:$ dropuser matsya1 www.opengurukul.com 56
    • list users : duYou can use psql command du to see the users (also called roles).Example :List Users / Rolespostgres=> du List of rolesRole name | Attributes | Member of-----------+-------------+-----------postgres | Superuser | {} : Create role : Create DBsurikuma | Create role | {} : Create DB www.opengurukul.com 57postgres=>
    • list users : pg_rolesThe users (also called roles) are present in pg_roles. We can also check rolename in pg_roles.Example :Users/Roles from pg_rolespostgres=# select rolname from pg_roles;rolname----------postgressurikuma(2 rows)postgres=# www.opengurukul.com 58
    • Role Membership : Grant & RevokeA group role is created using "CREATE ROLE" command.This role will also represent a group.A group role (priviliges) will not have LOGIN attribute generally but it is not mandatory.Syntax:GRANT <group role> to <user role>;GRANT <group role> from <user role>; www.opengurukul.com 59
    • Role Membership : Grant & Revoke : ExampleExample :create a group role and assign priviliges to a userCREATE ROLE admin NOINHERIT;CREATE ROLE guru LOGIN INHERIT;GRANT admin TO guru; www.opengurukul.com 60
    • PostgreSQL PL/pgSQL www.opengurukul.com 61
    • createlang : add procedural languageThe createlang is used to add a support of a procedural language in the database.Syntax :$ createlang plpgsql$ createlang plperl www.opengurukul.com 62
    • createlang : list procedural languages$ createlang --listProcedural Languages Name | Trusted?---------+----------plpgsql | yesplperl | yes$ www.opengurukul.com 63
    • pg_language : list procedural languages :postgres=# select * from pg_language;+------------+--------------+---------+---------------+-----------------+----------------+--------+| lanname | lanowner | lanispl | lanpltrusted | lanplcallfoid | lanvalidator | lanacl |+------------+-------------+---------+----------------+-----------------+---------------+---------+| internal | 10 |f |f | 0 | 2246 | ||c | 10 |f |f | 0 | 2247 | || sql | 10 |f |t | 0 | 2248 | || plpgsql | 10 |t |t | 16810 | 16811 | |+-----------+-------------+---------+----------------+----------------+----------------+---------+(4 rows)postgres=# www.opengurukul.com 64
    • PL/pgSQL : StructurePL/pgSQL is a block-structured language.PL/pgSQL Block Structure[ <<label>> ][ DECLARE declarations ]BEGIN statementsEND [ label ]; www.opengurukul.com 65
    • PL/pgSQL : Data TypesFrequently used data type areinteger - for numbersvarchar - for variable length character arraychar - for fixed length character arraydate - for calendar date (year, month, day)time - for time of daytimestamp - for date & timeThe data types table is present onhttp://www.postgresql.org/docs/9.1/interactive/datatype.html www.opengurukul.com 66
    • PL/pgSQL : Variable DeclarationsPL/pgSQL variables can Examples : have any SQL data type, user_id integer; such as integer, varchar, a and char. quantity numeric(5);The variable name is url varchar; specified first and data myrow tablename type is specified next. %ROWTYPE; myfield tablename.columnname %TYPE; www.opengurukul.com 67
    • PL/pgSQL : Variable AssignmentIn PL/pgSQL the Example : assignment operator x := 20; is := www.opengurukul.com 68
    • PL/pgSQL : RAISE : Report MessagesThe RAISE can be used to report messages on PL/pgSQL.Syntax:RAISE LEVEL format [,expression [, ...]] ;Possible levels are DEBUG, LOG, INFO, NOTICE, WARNING, and EXCEPTION.EXCEPTION raises an error.Inside the format string, % is replaced by the next optional arguments string representationExample :RAISE NOTICE Calling cs_create_job(%), v_job_id; www.opengurukul.com 69
    • PL/pgSQL : Create or Replace FunctionThe CREATE OR REPLACE FUNCTION call is used to create (replace) a function. www.opengurukul.com 70
    • PL/pgSQL : Create or Replace Function : Example$ cat add.sql $ psqlcreate or replace function postgres=#i add.sqladd(x integer, y integer) CREATE FUNCTIONreturns integer AS $$ postgres=#qdeclare $ total integer;begin total := x + y +z ; RETURN total;end;$$language plpgsql; www.opengurukul.com 71
    • PL/pgSQL : List of Functions: dfTo get List of Functions use dfSyntax : df [PATTERN]Example : Get list of functions using dfpostgres=# df List of functions+--------+--------+------------------+---------------------------------+--------+| Schema | Name | Result data type | Argument data types | Type |+--------+--------+------------------+---------------------------------+--------+| public | add | integer | x integer, y integer | normal |+--------+--------+------------------+---------------------------------+--------+(1 rows) www.opengurukul.com 72
    • PL/pgSQL : Call FunctionUse select to call the Example : function. postgres=# selectselect funcname(funcargs); add(1,2); sum ----- 3 (1 row) postgres=# www.opengurukul.com 73
    • PL/pgSQL : Drop FunctionUse DROP FUNCTION to drop a function.Example :postgres=# drop function sum(integer, integer);DROP FUNCTIONpostgres=#NOTE :The drop function must be called with argument types otherwise it will not work. www.opengurukul.com 74
    • PL/pgSQL : Develop Function : Example 2$ cat msg.sqlcreate or replace function msg()RETURNS INTEGERAS$$begin RAISE NOTICE hello world; RETURN 0;end;$$language plpgsql; www.opengurukul.com 75$
    • PL/pgSQL : Create Function : Example 2postgres=# i msg.sqlCREATE FUNCTIONpostgres=# www.opengurukul.com 76
    • PL/pgSQL : List Function : Example 2List Function :postgres=# df msg List of functions+-----------+---------+---------------------+-----------------------------+-----------+| Schema | Name | Result data type | Argument data types | Type |+-----------+---------+----------------------+-----------------------------+----------+| public | msg | integer | | normal |+-----------+---------+----------------------+-----------------------------+-----------+(1 row)postgres=# www.opengurukul.com 77
    • PL/pgSQL : Call Function : Example 2Call Function :postgres=# select msg();NOTICE: hello worldmsg----- 0(1 row)postgres=# www.opengurukul.com 78
    • PL/pgSQL : Drop Function : Example 2Drop Function :postgres=# drop function msg();DROP FUNCTIONpostgres= www.opengurukul.com 79
    • PostgreSQL Transactions www.opengurukul.com 80
    • TransactionsTransactions are a fundamental concept of all database systems.A transaction bundles multiple steps into a single, all-or- nothing operation.The intermediate states between the steps are not visible to other concurrent transactions.If some failure occurs that prevents the transaction from completing, then none of the steps affect the database at all.A transaction is said to be atomic: from the point of view of other transactions, it either happens completely or not at all. www.opengurukul.com 81
    • Transactions : Savepoint & RollbackCreate a savepoint SAVEPOINT [<savepoint_name>];Rollback to a savepoint ROLLBACK [to <savepoint_name>];Commit the changes COMMIT; www.opengurukul.com 82
    • Transactions : Savepoint & Rollback : ExampleTake a case of Bank Database, suppose we debit $100.00 fro Rams account, and credit Laxmans account, only to find later that we should have credited Sitas accountBEGIN UPDATE accounts SET balance = balance - 100.00 WHERE name = Ram; SAVEPOINT my_savepoint; UPDATE accounts SET balance = balance + 100.00 WHERE name = Laxman; -- oops ... forget that and use Sitas account ROLLBACK TO my_savepoint; UPDATE accounts SET balance = balance + 100.00 WHERE name = Sita; COMMIT;END; www.opengurukul.com 83
    • PostgreSQL Thanks www.opengurukul.com 84
    • Thanks Thanks for attending the session.For additional support, please post your query on PostgreSQL discussion forum at www.opengurukul.com www.opengurukul.com 85