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 - ...
PostgreSQL Setup : InstallInstall PostgreSQL  yum install postgresql  yum install postgresql-server  yum install postgresq...
PostgreSQL Setup : VersionThe postgres server version can be found by using --version on the postmaster$ postmaster --vers...
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 d...
pg_ctl : PGDATA variableThe pg_ctl commands are dependent on the PGDATA variable that contains directory location of datab...
pg_lsclusters : Location of    Database Clusters : Ubuntupg_lsclusters :$ pg_lsclusters # to clusters and data directory  ...
pg_ctl : Control PostgreSQL                  ServerStart Server :                              Stop Server :$ pg_ctl start...
PostgreSQLModule : PostgreSQL Admin Tools           www.opengurukul.com    11
PhpPgAdmin : Download & InstallDownload phpPgAdmin from  http://sourceforge.net/projects/phppgadmin/Install phpPgAdmin usi...
PhpPgAdmin : phppgadmin/etc/apache2/conf.d/phppgadmin  Uncomment # allow from all                    www.opengurukul.com  ...
PhpPgAdmin : Configure/usr/share/phpPgAdmin/conf/config.inc.php :Modify extra_login_security to false in /usr/share/phpPgA...
PhpPgAdmin : Configurepg_hba.conf :Modify /var/lib/pgsql/data/pg_hba.conf file to change the method to "trust" from  "iden...
PgAdmin: Download & InstallDownload & Install pgadmin3 from www.pgadmin.org  pgadmin3-1.12.2-2.fc14.i686  rpm -i pgadmin3-...
PgAdmin: Configure1> pg_hba.conf : edit pg_hba.conf file (use trust) otherwise you  wiill not be able to connect# TYPE DAT...
PostgreSQL       psql  www.opengurukul.com   18
psql : PGDATA$ su - postgres$ pwd/var/lib/pgsql$$ echo $PGDATA/var/lib/pgsql/data$                      www.opengurukul.co...
psql : command line$ psql -U<user_name> -d<db_name><DB_NAME>=# helpYou are using psql, the command-line interface to Postg...
psql : default databaseNOTE :The default database is postgres.Example : Default connect to postgres$ psqlpsql (8.4.5)Type ...
psql : -d : connect to databaseExample : Connect to template1$ psql -dtemplate1psql (8.4.5)Type "help" for help.template1=...
psql : s : display history or save                historySyntax :s [FILE]       display history or save it to fileExample ...
psql : i : execute commands from                  fileSyntax :i FILE             execute commands from fileExample :$ cat ...
psql : o : send all query results to                 fileSyntax :o [FILE]            send all query results to file or |pi...
psql : ! : execute command in                  shellSyntax :! [COMMAND]       execute command in shell or                 ...
psql : internal variablesSyntax :prompt [TEXT] NAME   prompt user to set internal                      variableset [NAME [...
psql : Display Internal Variablespostgres-# setAUTOCOMMIT = onPROMPT1 = %/%R%# PROMPT2 = %/%R%# PROMPT3 = >> VERBOSITY = d...
psql : set variables : Examplepostgres-# prompt name:  SITEname: www.opengurukul.compostgres-# set...SITE = www.openguruku...
psql : promptThe psql prompt will bedatabasename=# for database super userdatabasename=> for users without super user priv...
PostgreSQLPostgreSQL Introduction       www.opengurukul.com   31
Introduction : postgresTo start PostgreSQL server, you can directly use  /usr/bin/postgres$ /usr/bin/postgres -D /var/lib/...
Introduction : postmasterThe postmaster is an alias for PostgreSQL Database Server.$ which postmaster/usr/bin/postmaster$$...
Introduction : Initialize database          cluster : initdbThe initdb command is used to initalize a database  cluster.A ...
Introduction: initdb : template1Whenever you create a new database in the cluster, everything in the template1 database is...
Introduction: initdb : exampleSyntax :$ initdb --pgdata | -D pgdata_directoryGenerally, The default pgdata directory is /v...
Introduction: start d/b clusterExport PGDATA   $ export PGDATA=~/data1Modify the port in ~/data1/postgresql.conf to 5433. ...
Introduction : Create Database :             createdbThe createdb (executable) or  "CREATE DATABASE" (psql                ...
Introduction : Create Database :          createdb : Example$ su - postgres$ createdb xExample :postgres=# CREATE DATABASE...
Introduction : Delete Database :              dropdbThe dropdb command can be used to delete the  PostgreSQL database.Synt...
Introduction : Connect to                databasec[onnect] [DBNAME|- USER|- HOST|- PORT|-]connect to new database (current...
Introduction : psql : S, +Informational(options: S = show system objects, + = additional detail)d[S+]           list table...
Introduction : psql : d : Describe                  Tablepostgres=# dS pg_roles             View "pg_catalog.pg_roles"+---...
Introduction : vacuumdb : garbage-            collect databaseThe vacuumdb is a utility for cleaning a PostgreSQL database...
Introduction : vacuumdb : options--full : Perform full vaccuming--dbname <dbname> : name of the pariculat database  to be ...
Introduction : vacuumdb : ExampleExample :-bash-4.1$ vacuumdb --full --all --analyzevacuumdb: vacuuming database "postgres...
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.Sy...
pg_dump : plain dump : usageTo dump a database called "mydb" into a SQL- script file:  $ pg_dump mydb > db.sqlTo reload su...
pg_dump : tableTo dump specific tables, specify them after -tTo skip specific tables, specify them after -TBoth -t and -T ...
pg_dump : archive fileTo dump a database into a custom-format archive file:$ pg_dump -Fc mydb > db.dumpTo reload an archiv...
PostgreSQLUsers & Privileges    www.opengurukul.com   52
createuser : create user accountTo create a user account (also called role), createuser command is used.Only superusers an...
createuser : create user account :              exampleExample :To create a user matsya1 on the default database  server:$...
dropuser - remove user accountThe dropuser is used to remove an existing PostgreSQL user.Only superusers and users with th...
dropuser - remove user account :             exampleExample :To remove user matsya1 from the default database  server:$ dr...
list users : duYou can use psql command du to see the users (also called roles).Example :List Users / Rolespostgres=> du  ...
list users : pg_rolesThe users (also called roles) are present in pg_roles. We can also  check rolename in pg_roles.Exampl...
Role Membership : Grant & RevokeA group role is created using "CREATE ROLE" command.This role will also represent a group....
Role Membership : Grant & Revoke :            ExampleExample :create a group role and assign priviliges to a userCREATE RO...
PostgreSQL  PL/pgSQL  www.opengurukul.com   61
createlang : add procedural              languageThe createlang is used to add a support of a procedural  language in the ...
createlang : list procedural               languages$ createlang --listProcedural Languages    Name | Trusted?---------+--...
pg_language : list procedural               languages :postgres=# select * from pg_language;+------------+--------------+-...
PL/pgSQL : StructurePL/pgSQL is a block-structured language.PL/pgSQL Block Structure[ <<label>> ][ DECLARE  declarations ]...
PL/pgSQL : Data TypesFrequently used data type areinteger - for numbersvarchar - for variable length character arraychar -...
PL/pgSQL : Variable DeclarationsPL/pgSQL variables can              Examples :  have any SQL data type,                   ...
PL/pgSQL : Variable AssignmentIn PL/pgSQL the              Example :  assignment operator        x := 20;  is :=          ...
PL/pgSQL : RAISE : Report             MessagesThe RAISE can be used to report messages on PL/pgSQL.Syntax:RAISE LEVEL form...
PL/pgSQL : Create or Replace FunctionThe CREATE OR REPLACE FUNCTION call is used to create (replace) a function.          ...
PL/pgSQL : Create or Replace Function             : Example$ cat add.sql                              $ psqlcreate or repl...
PL/pgSQL : List of Functions: dfTo get List of Functions use dfSyntax :    df [PATTERN]Example : Get list of functions usi...
PL/pgSQL : Call FunctionUse select to call the              Example :  function.                                    postgr...
PL/pgSQL : Drop FunctionUse DROP FUNCTION to drop a function.Example :postgres=# drop function sum(integer, integer);DROP ...
PL/pgSQL : Develop Function :                 Example 2$ cat msg.sqlcreate or replace function msg()RETURNS INTEGERAS$$beg...
PL/pgSQL : Create Function : Example                 2postgres=# i msg.sqlCREATE FUNCTIONpostgres=#                  www.o...
PL/pgSQL : List Function : Example 2List Function :postgres=# df msg                    List of functions+-----------+----...
PL/pgSQL : Call Function : Example 2Call Function :postgres=# select msg();NOTICE: hello worldmsg-----  0(1 row)postgres=#...
PL/pgSQL : Drop Function : Example 2Drop Function :postgres=# drop function msg();DROP FUNCTIONpostgres=                  ...
PostgreSQL Transactions  www.opengurukul.com   80
TransactionsTransactions are a fundamental concept of all database  systems.A transaction bundles multiple steps into a si...
Transactions : Savepoint &              RollbackCreate a savepoint  SAVEPOINT [<savepoint_name>];Rollback to a savepoint  ...
Transactions : Savepoint &           Rollback : ExampleTake a case of Bank Database, suppose we debit $100.00 fro Rams acc...
PostgreSQL   Thanks  www.opengurukul.com   84
Thanks       Thanks for attending the session.For additional support, please post your query on          PostgreSQL discus...
Upcoming SlideShare
Loading in …5
×

OpenGurukul : Database : PostgreSQL

2,383 views
2,251 views

Published on

PostgreSQL By OpenGurukul

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,383
On SlideShare
0
From Embeds
0
Number of Embeds
369
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

OpenGurukul : Database : PostgreSQL

  1. 1. PostgreSQL By OpenGurukul.comFree/Open Source Software Laboratory
  2. 2. PostgreSQLModule : PostgreSQL Setup www.opengurukul.com 2
  3. 3. 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
  4. 4. PostgreSQL Setup : InstallInstall PostgreSQL yum install postgresql yum install postgresql-server yum install postgresql-libsInstall pgadmin tool yum install pgadmin3 www.opengurukul.com 4
  5. 5. 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
  6. 6. PostgreSQLModule : pg_ctl : Control PostgreSQL Server www.opengurukul.com 6
  7. 7. 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
  8. 8. 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
  9. 9. pg_lsclusters : Location of Database Clusters : Ubuntupg_lsclusters :$ pg_lsclusters # to clusters and data directory www.opengurukul.com 9
  10. 10. 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$
  11. 11. PostgreSQLModule : PostgreSQL Admin Tools www.opengurukul.com 11
  12. 12. PhpPgAdmin : Download & InstallDownload phpPgAdmin from http://sourceforge.net/projects/phppgadmin/Install phpPgAdmin using yum install phpPgAdmin www.opengurukul.com 12
  13. 13. PhpPgAdmin : phppgadmin/etc/apache2/conf.d/phppgadmin Uncomment # allow from all www.opengurukul.com 13
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. 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 127.0.0.1/32 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
  18. 18. PostgreSQL psql www.opengurukul.com 18
  19. 19. psql : PGDATA$ su - postgres$ pwd/var/lib/pgsql$$ echo $PGDATA/var/lib/pgsql/data$ www.opengurukul.com 19
  20. 20. 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
  21. 21. 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
  22. 22. psql : -d : connect to databaseExample : Connect to template1$ psql -dtemplate1psql (8.4.5)Type "help" for help.template1=# q$ www.opengurukul.com 22
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. 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-#
  29. 29. psql : set variables : Examplepostgres-# prompt name: SITEname: www.opengurukul.compostgres-# set...SITE = www.opengurukul.compostgres-# www.opengurukul.com 29
  30. 30. 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
  31. 31. PostgreSQLPostgreSQL Introduction www.opengurukul.com 31
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. 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
  38. 38. 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
  39. 39. 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$
  40. 40. Introduction : Delete Database : dropdbThe dropdb command can be used to delete the PostgreSQL database.Syntax :$ dropdb <dbname> www.opengurukul.com 40
  41. 41. 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
  42. 42. 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
  43. 43. 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 | |
  44. 44. 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
  45. 45. 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
  46. 46. Introduction : vacuumdb : ExampleExample :-bash-4.1$ vacuumdb --full --all --analyzevacuumdb: vacuuming database "postgres"vacuumdb: vacuuming database "template1"-bash-4.1$ www.opengurukul.com 46
  47. 47. PostgreSQLpg_dump : Backup & Resotre www.opengurukul.com 47
  48. 48. 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
  49. 49. 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
  50. 50. 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
  51. 51. 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
  52. 52. PostgreSQLUsers & Privileges www.opengurukul.com 52
  53. 53. 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
  54. 54. 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
  55. 55. 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
  56. 56. dropuser - remove user account : exampleExample :To remove user matsya1 from the default database server:$ dropuser matsya1 www.opengurukul.com 56
  57. 57. 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=>
  58. 58. 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
  59. 59. 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
  60. 60. 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
  61. 61. PostgreSQL PL/pgSQL www.opengurukul.com 61
  62. 62. 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
  63. 63. createlang : list procedural languages$ createlang --listProcedural Languages Name | Trusted?---------+----------plpgsql | yesplperl | yes$ www.opengurukul.com 63
  64. 64. 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
  65. 65. PL/pgSQL : StructurePL/pgSQL is a block-structured language.PL/pgSQL Block Structure[ <<label>> ][ DECLARE declarations ]BEGIN statementsEND [ label ]; www.opengurukul.com 65
  66. 66. 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
  67. 67. 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
  68. 68. PL/pgSQL : Variable AssignmentIn PL/pgSQL the Example : assignment operator x := 20; is := www.opengurukul.com 68
  69. 69. 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
  70. 70. PL/pgSQL : Create or Replace FunctionThe CREATE OR REPLACE FUNCTION call is used to create (replace) a function. www.opengurukul.com 70
  71. 71. 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
  72. 72. 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
  73. 73. 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
  74. 74. 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
  75. 75. 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$
  76. 76. PL/pgSQL : Create Function : Example 2postgres=# i msg.sqlCREATE FUNCTIONpostgres=# www.opengurukul.com 76
  77. 77. 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
  78. 78. PL/pgSQL : Call Function : Example 2Call Function :postgres=# select msg();NOTICE: hello worldmsg----- 0(1 row)postgres=# www.opengurukul.com 78
  79. 79. PL/pgSQL : Drop Function : Example 2Drop Function :postgres=# drop function msg();DROP FUNCTIONpostgres= www.opengurukul.com 79
  80. 80. PostgreSQL Transactions www.opengurukul.com 80
  81. 81. 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
  82. 82. Transactions : Savepoint & RollbackCreate a savepoint SAVEPOINT [<savepoint_name>];Rollback to a savepoint ROLLBACK [to <savepoint_name>];Commit the changes COMMIT; www.opengurukul.com 82
  83. 83. 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
  84. 84. PostgreSQL Thanks www.opengurukul.com 84
  85. 85. 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

×