Programming in postgresql with PL/pgSQL. Procedural Language extension to postgresql



Similar documents
14 Triggers / Embedded SQL

Programming Database lectures for mathema

Chapter 39. PL/pgSQL - SQL Procedural Language

PostgreSQL Functions By Example

SQL NULL s, Constraints, Triggers

Oracle 11g PL/SQL training

Introduction to Triggers using SQL

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

PL / SQL Basics. Chapter 3

A basic create statement for a simple student table would look like the following.

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

Procedural Extension to SQL using Triggers. SS Chung

Writing Control Structures

Lecture 6. SQL, Logical DB Design

Using Temporary Tables to Improve Performance for SQL Data Services

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

How To Create A Table In Sql (Ahem)

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Lab 2: PostgreSQL Tutorial II: Command Line

Persistent Stored Modules (Stored Procedures) : PSM

Database Programming with PL/SQL: Learning Objectives

Oracle Database 10g Express

Maintaining Stored Procedures in Database Application

Oracle Database: SQL and PL/SQL Fundamentals

Database Security. Chapter 21

An Introduction to PL/SQL. Mehdi Azarmi

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

SQL. Short introduction

Chapter 5. SQL: Queries, Constraints, Triggers

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

There are five fields or columns, with names and types as shown above.

CSC 443 Database Management Systems. The SQL Programming Language

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle For Beginners Page : 1

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 6 Program Control

CS143 Notes: Views & Authorization

5.1 Database Schema Schema Generation in SQL

Firebird. Embedded SQL Guide for RM/Cobol

Bull s Database Migration Business Unit Oracle PL/SQL to PostgreSQL PL/pgSQL Translation Technical Notes

ISYS PL/SQL Basics. Week 03

SQL: Queries, Programming, Triggers

Oracle Database: SQL and PL/SQL Fundamentals

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Review: Participation Constraints

Temporal Features in SQL standard

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Advanced PostgreSQL SQL Injection and Filter Bypass Techniques

Oracle For Beginners Page : 1

A table is a collection of related data entries and it consists of columns and rows.

12 Embedding SQL in Programming languages

SQL Server Database Coding Standards and Guidelines

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

Create a Database Driven Application

Package sjdbc. R topics documented: February 20, 2015

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Handling PL/SQL Errors

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

Introduction to Microsoft Jet SQL

Oracle 10g PL/SQL Training

DECLARATION SECTION. BODY STATEMENTS... Required

J a v a Quiz (Unit 3, Test 0 Practice)

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

Mini User's Guide for SQL*Plus T. J. Teorey

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Monitoring Agent for PostgreSQL Fix Pack 10. Reference IBM

FileMaker 13. SQL Reference

Data Tool Platform SQL Development Tools

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

12 Embedding SQL in Programming languages

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

PL/SQL (Cont d) Let s start with the mail_order database, shown here:

A Brief Introduction to MySQL

SQL Server An Overview

Oracle SQL, introduced in the previous chapter, is not a language that can be

4 Simple Database Features

1 SQL Data Types and Schemas

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

Proposed solutions Project Assignment #1 (SQL)

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

While Loop. 6. Iteration

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

The Relational Model. Why Study the Relational Model?

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Transcription:

Programming in postgresql with PL/pgSQL Procedural Language extension to postgresql 1

Why a Programming Language? Some calculations cannot be made within a query (examples?) Two options: Write a program within the database to calculate the solution Write a program that communicates with the database and calculates the solution Both options are useful, depending on the circumstances. Option 1 reduces the communication need, and can be faster! 2

PL/pgSQL Specific for Postgres (similar languages available for other db systems) Allows using general programming tools with SQL, for example: loops, conditions, functions, etc. This allows a lot more freedom than general SQL We write PL/pgSQL code in a regular file, for example firstpl.sql, and load it with \i in the psql console. Documentation available at: http://www.postgresql.org/docs/8.1/static/plpgsql.h tml#plpgsql-overview 3

BASIC STRUCTURE OF A PL/PGSQL PROGRAM 4

PL/pgSQL Blocks PL/pgSQL code is built of Blocks, with a unique structure: DECLARE (optional) /* All Variables Declared Here*/ BEGIN (mandatory) /* Executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Exception handling*/ END; (mandatory) 5

Creating a Function CREATE OR REPLACE FUNCTION funcname(varname1 vartype1, ) RETURNS returnvartype AS DECLARE (optional) /* All Variables Declared Here*/ BEGIN (mandatory) /* Executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Exception handling*/ END; (mandatory) language plpgsql 6

Example Create or replace function mymultiplication(var1 integer, var2 integer) returns integer as BEGIN return var1*var2; END; language plpgsql 7

The Function Body String The body of the function is a string, from the standpoint of the db We can use quotes to create this string, or use dollar string encoding (will be used from now on in example) Create or replace function mymultiplication(var1 integer, var2 integer) returns integer as $$ BEGIN return var1*var2; END; $$ language plpgsql 8

The Return Value If the function returns a single parameter, you can use the return syntax below Must use a return statement to return the value Create or replace function mymultiplication(var1 integer, var2 integer) returns integer as $$ BEGIN return var1*var2; END; $$ language plpgsql Functions can also return multiple values (details omitted) 9

first.sql: Calling Functions Create or replace function addtax(price real) returns real as $$ begin Return price*1.155; end; $$language plpgsql; In the psql console write: \i first.sql Then you can call the function using, e.g., : Insert into pricestable values(addtax(20)); Select (addtax(price)) from catalog; Perform addtax(20); 10

11 DECLARING VARIABLES

Defining Variables (1) All variables must be defined in the declare section. The general syntax of a variable declaration is: name [CONSTANT] type [ NOT NULL] [{DEFAULT := } expression] Examples: user_id integer; name CONSTANT integer := 10; name CONSTANT integer DEFAULT 10; url varchar NOT NULL := http://www.abc.com ; 12

Declaring Variables (2): The %TYPE Attribute Examples DECLARE sname fav_boat my_fav_boat Sailors.sname%TYPE; VARCHAR(30); fav_boat%type := 'Pinta'; 13

Declaring Variables (3): The %ROWTYPE Attribute Declare a variable with the type of a ROW of a table. reserves_record Reserves%ROWTYPE; And how do we access the fields in reserves_record? reserves_record.sid := 9; Reserver_record.bid := 877; 14

Declaring Variables (4): Records A record is similar to row-type, but we don t have to predefine its structure unknownrec record; 15

COMMON OPERATIONS WITHIN FUNCTION BODY 16

Some Common Operations In this part we discuss: Using the result of a query within a function Conditionals (if/then/else) Loops Exceptions 17

Select Into We will often wish to run a query, and take a query result, store it in a variable, and perform further calculations Storing the result in a variable is done using the Select Into command Note in the following slides what happens when applied to queries that return multiple rows 18

Select Into Create or replace function sillyfunc(var1 integer) returns integer as $$ DECLARE s_var sailors%rowtype; BEGIN select * into s_var from sailors; return s_var.age*var1; END; $$language plpgsql 1. If select returns more than one result, the first row will be put into sp_var 2. If no rows were returned, nulls will be put in sp_var Notice that unless Order by was specified, the first row is not well defined 19

Select Into Strict Create or replace function sillyfunc(var1 integer) returns integer as $$ DECLARE s_var sailors%rowtype; BEGIN select * into strict s_var from sailors; return sp_var.age*var1; END; $$language plpgsql In this case, if more or less than one row is returned, a run-time error will occur 20

Using Records in Select Into DECLARE v record; BEGIN select * into v from Sailors S, Reserves R where S.sname= Sam and S.sid = R.sid END; 21

Checking if a Row was Returned By Select Into Declare v record; Begin Select * into v from Sailors where age=4; If not found then 22

IF boolean-expression THEN statements END IF; IF v_age > 22 THEN UPDATE employees SET salary = salary+1000 WHERE eid = v_sid; END IF; Conditioning Assume variables in blue were defined above the code fragment 23

IF boolean-expression THEN statements ELSIF boolean-expression THEN statements ELSIF boolean-expression THEN statements ELSE statements END IF ; More Conditioning 24

Example CREATE or replace FUNCTION assessrate(rating real) RETURNS text AS $$ BEGIN if rating>9 then return 'great'; elsif rating>7 then return 'good'; elsif rating>5 then return 'keep on working'; elsif rating>3 then return 'work harder!'; else return 'you are hopeless'; end if; END; $$ LANGUAGE plpgsql; Select assessrate(6.7); 25

Another Example Write a function that when called by a user: if user is already in table mylog, increment num_run. Otherwise, insert user into table who Peter John Moshe mylog num_run 3 4 2 26

CREATE FUNCTION updatelogged() RETURNS void AS $$ DECLARE cnt integer; BEGIN Select count(*) into cnt from mylog where who=user; If cnt>0 then update mylog set num_run = num_run + 1 where who = user; else insert into mylog values(user, 1); end if; end; $$ LANGUAGE plpgsql; 27

Simple loop LOOP statements END LOOP; Terminated by Exit or return Exit: only causes termination of the loop Can be specified with a condition: Exit when 28

Examples LOOP -- some computations IF count > 0 THEN EXIT; END IF; END LOOP; LOOP -- some computations EXIT WHEN count > 0; END LOOP; 29

Continue The next iteration of the loop is begun Create or replace function mytest(var1 integer) returns integer as $$ DECLARE i integer; BEGIN i:=1; loop exit when i>var1; i=i+1; continue when i<20; raise notice 'num is %',i; end loop; return i*var1; END $$language plpgsql What does this print for mytest(30)? 30

While loop WHILE expression LOOP --statements END LOOP ; WHILE money_amount > 0 AND happiness < 9 LOOP -- buy more END LOOP; 31

For loop FOR var IN [ REVERSE ] strange..endrange LOOP statements END LOOP; The variable var is not declared in the declare section for this type of loop. FOR i IN 1..10 LOOP RAISE NOTICE 'i is %', i; END LOOP; FOR i IN REVERSE 10..1 LOOP -- some computations here END LOOP; 32

Looping Through Query Results FOR target IN query LOOP statements END LOOP; CREATE or replace FUNCTION assessrates() RETURNS void AS $$ DECLARE i record; BEGIN For i in select rating from ratings order by rating loop if i.rating>9 then raise notice 'great'; elsif i.rating>7 then raise notice 'good'; elsif i.rating>5 then raise notice 'keep on working'; elsif i.rating>3 then raise notice 'work harder!'; else raise notice 'you are hopeless'; end if; end loop; END; $$ LANGUAGE plpgsql; 33

Trapping exceptions DECLARE declarations BEGIN statements EXCEPTION WHEN condition [ OR condition... ] THEN handler_statements WHEN condition [ OR condition... ] THEN handler_statements... END; See http://www.postgresql.org/docs/8.1/static/ errcodes-appendix.html for a list of all exceptions 34

Exception Example Create or replace function errors(val integer) returns real as $$ Declare val2 real; BEGIN val2:=val/(val-1); return val2; Exception when division_by_zero then raise notice 'caught a zero division'; return 0; End; $$ LANGUAGE plpgsql; 35

36 Triggers

Triggers A trigger defines an action we want to take place whenever some event has occurred. When defining a trigger, you have to define: 1. Triggering Event 2. Trigger Timing 3. Trigger Level 37

Triggering Event When defining a trigger, you must choose an event (or events) upon which you want the trigger to be automatically called Possible events: Update of a specific table Insert into a specific table Delete from a specific table For example, if you define a trigger on inserting into table R, then whenever an insert is performed your trigger will be called by the database! 38

Trigger Timing Triggers run when a predefined event has occurred. The trigger can run before or after the event For example, if you define a trigger before insert on R, then after the user calls an insert command on R, but before it has been executed, your trigger will be called 39

Trigger Level Triggers run when a predefined event has occurred. The trigger level determines the number of times that the trigger will run. If the trigger level is statement, then the trigger will run once for the triggering event If the trigger level is row, then the trigger will run once for each row changed by the triggering event For example, a statement level trigger, defined upon delete will run once, for each delete statement. A row level trigger will run once for each row deleted by the delete statement 40

Defining Triggers There are two parts to defining a trigger: 1. Writing a trigger function, i.e., a function with return type trigger 2. Calling create trigger, defining triggering events, trigger timing and level, and using the trigger function We first explain #2, and then #1 41

Create Trigger: Timing CREATE TRIGGER name { BEFORE AFTER } { event [ OR... ] } ON table [ FOR EACH ROW STATEMENT ] EXECUTE PROCEDURE funcname ( arguments ) CREATE TRIGGER emp_trig BEFORE INSERT OR UPDATE ON employee FOR EACH ROW EXECUTE PROCEDURE emp_trig_func )(; 42

Create Trigger: Triggering Event CREATE TRIGGER name { BEFORE AFTER } { event [ OR... ] } ON table [ FOR EACH ROW STATEMENT ] EXECUTE PROCEDURE funcname ( arguments ) CREATE TRIGGER emp_trig BEFORE INSERT OR UPDATE ON employee FOR EACH ROW EXECUTE PROCEDURE emp_trig_func )(; 43

Create Trigger: Trigger Level CREATE TRIGGER name { BEFORE AFTER } { event [ OR... ] } ON table [ FOR EACH ROW STATEMENT ] EXECUTE PROCEDURE funcname ( arguments ) CREATE TRIGGER emp_trig BEFORE INSERT OR UPDATE ON employee FOR EACH ROW EXECUTE PROCEDURE emp_trig_func )(; 44

Writing a Trigger Function CREATE FUNCTION funcname() RETURNS trigger AS $$ There are several variables automatically available for the trigger function: New: Available for row level triggers, defined upon insert or update. Is a record containing the new values for the row Old: Available for row level triggers, defined upon delete or update. Is a record containing the old values for the row TG_OP: Name of the operation which caused the trigger 45

Example CREATE FUNCTION toupper() RETURNS trigger AS $$ BEGIN new.sname := UPPER(new.sname); return new; END; $$ LANGUAGE plpgsql; CREATE TRIGGER touppertrig BEFORE INSERT or UPDATE on Sailors FOR EACH ROW execute procedure toupper(); 46

Important! Row Level Triggers, BEFORE A return value of null signals to the trigger manager to skip the rest of the operation for this row subsequent triggers are not fired for this row the INSERT/UPDATE does not occur for this row. A return value that is non-null causes the operation to proceed with that row value. Returning a row value different from the original value of NEW alters the row that will be inserted or updated (but has no direct effect in the DELETE case). 47

Important! All Other Types of Triggers The return value of a BEFORE or AFTER statement-level trigger or an AFTER row-level trigger is always ignored; it may as well be null. However, any of these types of triggers can still abort the entire operation by raising an error. 48

Another Example CREATE TABLE emp ( empname text, salary integer, last_date timestamp, last_user text ); 49

CREATE FUNCTION emp_stamp() RETURNS trigger AS $$ BEGIN -- Check that empname and salary are given IF NEW.empname IS NULL THEN RAISE EXCEPTION 'empname cannot be null'; END IF; IF NEW.salary IS NULL THEN RAISE EXCEPTION '% cannot have null salary', NEW.empname; END IF; IF NEW.salary < 0 THEN RAISE EXCEPTION '% cannot have a negative salary', NEW.empname; END IF; NEW.last_date := current_timestamp; NEW.last_user := current_user; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp FOR EACH ROW EXECUTE PROCEDURE emp_stamp )(; 50

Another Example: Backing Up Information CREATE TABLE emp ( empname text NOT NULL, salary integer ); CREATE TABLE emp_backup( operation char(1) NOT NULL, stamp timestamp NOT NULL, userid text NOT NULL, empname text NOT NULL, salary integer ); 51

CREATE OR REPLACE FUNCTION process_emp_backup() RETURNS TRIGGER AS $$ BEGIN IF (TG_OP = 'DELETE') THEN INSERT INTO emp_backup SELECT 'D', current_timestamp, current_user, OLD.*; RETURN null; ELSIF (TG_OP = 'UPDATE') THEN INSERT INTO emp_backup SELECT 'U', current_timestamp, current_user, NEW.*; RETURN null; ELSIF (TG_OP = 'INSERT') THEN INSERT INTO emp_backup SELECT 'I', current_timestamp, current_user, NEW.*; RETURN null; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; 52

Example (cont) CREATE TRIGGER emp_backup AFTER INSERT OR UPDATE OR DELETE ON emp FOR EACH ROW EXECUTE PROCEDURE process_emp_backup )(; 53

Statement Trigger Example CREATE FUNCTION shabbat_trig_func() RETURNS trigger AS $$ BEGIN if (TO_CHAR(current_date,'DY')='SAT') then raise exception no work on shabbat! ; end if; Return null; END; $$ LANGUAGE plpgsql; CREATE TRIGGER no_work_on_shabbat_trig BEFORE INSERT or DELETE or UPDATE on sailors for each statement execute procedure shabbat_trig_func(); 54