Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Basi Dati F1 Bis
1. Motives for Using Stored Procedures
Stored Procedures, UDFs and PL / pgSQL
` `
What are Stored procedures and what are they used for So far we implicitly assumed that we use a database from a
client machine and issue SQL statements to a database
` What is a User Defined Function (UDF) and what is it used for
` PostgreSQL syntax for UDFs
` DBMS and the database itself reside on a different machine –
` SQL UDFs
database Server machine
` Procedural Language / PosgreSQL (PL/pgSQL)
` Language Structure
` `
Declarations There are a number of situations that make running small
database procedures or functions on the server itself
` Parameters and Types
preferable
` Special Statements
Basi di Dati ` Control Structures
` Triggers ` These small programs are historically known as database
stored procedures
PL / pgSQL
Reading:
` SQL:1999 standard calls them persistent stored modules (PSM)
` PostgreSQL 8.3 Documentation Chapter V.38
PL / pgSQL PL / pgSQL
3 4
Use Stored Procedures Declaring a Stored Procedure SQL/Persistent Stored Modules (PSM)
` When: `
` SQL:1999 Standard introduces PSM
Commercial DBMS allow writing stored procedures
` Several applications need the same procedure, combining SQL and general purpose languages ` It is a programming language that contains:
` Data transfer should be reduced,
` Statements to create procedures and functions, and
` Tighter security control is needed,
` Procedural programming constructs for writing the body of a
` A stored procedure can be either a procedure or a
` More complex types of derived data should be made available
procedure or a function
to users, function
` The body can also be a pure SQL statement
` Complex constraints, that cannot be specified by SQL
declarative mechanisms, are needed ` Procedural constructs include:
` It is stored as a database object and can be:
` Efficient execution of precompiled procedures is needed ` Conditional IF/THEN/ELSE constructs, and
` Used in SELECT statements, or ` Several looping constructs:
` Stored procedures allow for greater flexibility, if they are ` Called from within JDBC transaction programs, where a ` WHILE/DO/END WHILE
changed all programs that call them remain intact CollableStatement object has to be used ` REPEAT/UNTIL/END REPEAT
PL / pgSQL PL / pgSQL PL / pgSQL
5 6 7
2. User Defined Functions The basic PostgreSQL UDF Syntax A Simple SQL Function
` `
A DBMS comes with many predefined functions A user defined function may be written using SQL
` Integer addition,
CREATE FUNCTION poundtokg(float)
` String concatenation RETURNS float
CREATE [ OR REPLACE ] FUNCTION AS ‘SELECT $1*0.545;’
` An ORDBMS allows users to define new functions LANGUAGE ‘SQL’;
name ( [ [ argmode ] [ argname ] argtype [, ...] ] )
` These functions are called server side functions since they SELECT poundtokg(3.0);
[ RETURNS rettype ]
reside at the database server AS 'definition'
poundtokg
` Unlike client side functions, server side functions may be LANGUAGE langname --------------------
used from within SQL statements 1.635
(1 row)
` Each server side function may be called from any client
side program
` $1 is a positional parameter
PL / pgSQL PL / pgSQL PL / pgSQL
8 9 10
What is PL/pgSQL Advantages of using PL/pg SQL Supported Data Types
` Conventional queries:
` `
PL/pgSQL is a language that combines: PL/pgSQL functions accept as arguments and can return
` Each SQL statement is submitted from a client to the database as results any of the following data types:
` The expressive power of SQL with
server for execution
` Scalar (base and user defined),
` The more typical features of a procedural programming
` The server returns each result to the client
language: ` Array,
` This incurs inter process communication and may incur
` Control structures ` Composite (row type),
network overhead
` Complex computation
` Record (a placeholder whose structure is defined by the calling
` User defined functions written in PL/pgSQL:
` Exception handling query)
` Reside on database server
` It is aimed for: ` Polymorphic types (anyelement or anyarray),
` Compile once per duration of a database connection
` Creating user defined functions ` Set,
` Can comprise several SQL queries connected by procedural
` Creating trigger procedures constructs ` Void (no useful return value), and
`
` All SQL queries of a function are executed with no
Efficient execution (vaguely speaking it is precompiled) ` Null
intermediate client/server communication
` Easy of use
PL / pgSQL PL / pgSQL PL / pgSQL
11 12 13
3. Record Type Body of a PL/pgSQL Function Language Structure
` PL/pgSQL is a block structured language
` Variables of the record type have no predefined
` Each block starts with either a DECLARE, or BEGIN statement
CREATE OR REPLACE FUNCTION some_func()
structure ` Ends with an END; statement
RETURNS <data_type> AS
` They take on the actual row structure of the row they are ` Each block can contain another block (also called subblock)
assigned to during a SELECT command
BEGIN
$$ --start of the body
` The structure of a record variable can change each time statements
-- here comes the function body
it is assigned to BEGIN
[DECLARE declarations] statemnets
` The record type is not a true type, only a record END;
BEGIN --denotes start of block statements
placeholder END;
END;--denotes the end of a block
$$ --end of the body
` BEGIN/END statements do not denote the start and the end
of a transaction, but only the boundaries of a block
LANGUAGE ‘plpgsql’;
PL / pgSQL PL / pgSQL PL / pgSQL
14 15 16
Declarations Function Parameters (1) Function Parameters (2)
` There are two ways to define function parameters `
` The other way to define function parameters is
All variables in a block must be declared in the
` One is to define their types only
declaration section of the block (the only exception is the
CREATE FUNCTION area(a int, b int)
variable of the for loop, which is an integer by
CREATE FUNCTION area(int, int) RETURNS int
default)
RETURNS int AS $$
` Examples: AS $$ BEGIN
` BEGIN
StudenName varchar;--initialized to null
RETURN a*b;
RETURN $1*$2;
` NumOfMarks real := 100.00; --assignment END;
END;
` Grade char(2) DEFAULT 'A+'; $$ LANGUAGE 'plpgsql';
$$ LANGUAGE 'plpgsql';
`
` Here, a contains the value of the first parameter, and b
Here, $1 contains the value of the first parameter, and
$2 contains the value of the second parameter contains the value of the second parameter
PL / pgSQL PL / pgSQL PL / pgSQL
17 18 19
4. Functions in SQL Queries With Tables Functions in SQL Queries With Tables
RETURN Statement
` To return single valued data from a function we use: ` A powerful use of functions is in queries that retrieve data CREATE OR REPLACE FUNCTION
from tables
RETURN expression area(real, real) RETURNS real
statement AS 'SELECT $1*$2;' LANGUAGE 'SQL';
CREATE TABLE Rectangle (RectId int, a real, b real);
` The RETURN statement with expression terminates
INSERT INTO Rectangle VALUES(1, 5.5, 6.6);
the function and returns the value of the expression
SELECT RectId, area(a, b) as Rec_Area
to the caller INSERT INTO Rectangle VALUES(2, 3.3, 4.4);
FROM Rectangle;
` The return value of a function must be defined:
` If control reaches the end of the top level block without hitting
RectId a b
a RETURN statement, a run time error will occur
RectId Rec_Area
` 1 5.5 6.6
Even if the function’s return value is declared to be void, a
1 36.3
RETURN statement must still be provided (but will return 2 3.3 4.4
nothing) 2 14.52
PL / pgSQL PL / pgSQL PL / pgSQL
20 21 22
Example 1
SELECT . . . INTO (1) SELECT . . .INTO (2)
` If a SELECT command returns no rows, null values are
` The result of a SELECT command yielding multiple assigned to the target DECLARE
columns (but only one row) can be assigned to a record s record;
variable ` If a SELECT command returns multiple rows only one of the BEGIN
them, the first one retrieved is assigned to the target, SELECT * INTO s FROM student
WHERE studentid=4;
SELECT <attrbute_list> INTO <target> IF s.StudentId IS NULL THEN
DECLARE
s record; --s is the target RAISE NOTICE 'There is no student with id = 4';
FROM… BEGIN RETURN NULL;
SELECT * INTO s FROM Student; ELSE
RETURN s; RETURN s;
` If the target type is record, it automatically END; END IF;
configures to the query result END;
` If the table is empty, s will be (, , , ) – a structure with null
components
PL / pgSQL PL / pgSQL PL / pgSQL
23 24 25
5. Example 2 Obtaining the Result Status (FOUND) An Example for the FOUND Variable
` To determine the result of a command, you can check a
DECLARE DECLARE
special variable named FOUND of the type boolean
t record; t record;
BEGIN BEGIN
IF p < 0 THEN --p is a variable SELECT * INTO t FROM Grades
` The following commands set FOUND:
SELECT * INTO t FROM Student WHERE StudentId = 007 AND CourseId= 'COMP302';
` SELECT...INTO... sets it true if it returns any row, false
WHERE StudentId = 007; IF NOT FOUND THEN
otherwise
ELSE SELECT * INTO t FROM Student
` PERFORM sets it true if it returns (and discards) any row, false
SELECT * INTO t FROM Grades WHERE StudentId = 007;
otherwise
WHERE StudentId = 007 AND CourseId ='COMP302'; END IF;
END IF; RETURN t;
` UPDATE, INSERT, and DELETE set it true if at least one
return t; END;
row is affected, false otherwise
END;
` FOUND is a local variable within each PL/pgSQL function
PL / pgSQL PL / pgSQL PL / pgSQL
26 27 28
Control Statements
RAISE Statement A RAISE NOTICE Example
` PL/pgSQL supports different forms of IF conditional:
DECLARE
` Even though PL/pgSQL doesn’t offer a way to intercept
` From:
errors, the RAISE statement is provided to raise an error s record;
` IF. . .THEN. . .END IF;
BEGIN
` To:
SELECT * INTO s FROM Student;
` Syntax: ` IF. . .THEN. . .ELSEIF. . .THEN. . .ELSE. . .
IF NOT FOUND THEN END IF;
RAISE severity 'message' [, variable []];
` Also, PL/pgSQL supports the following looping statements:
RAISE NOTICE 'Table is empty';
where severity can be:
` LOOP,
RETURN null;
` DEBUG
` EXIT,
ELSE
` NOTICE – just to send a message to the client application
` WHILE, and
RETURN s;
` EXCEPTION – to raise an exception, which is handled as ` FOR
END IF;
described in the manual
` Have a look in the manual for particulars
END;
PL / pgSQL PL / pgSQL PL / pgSQL
29 30 31
6. Next topic The Trigger Syntax Trigger Procedures in PL/pg SQL
` `
Triggers A trigger procedure is created with
<trigger>::= CREATE TRIGGER <trigger_name>
CREATE FUNCTION
{AFTER | BEFORE} <triggering_event> [OR...]
command, which:
ON <table_name>
` Does not have any parameters, and
[FOR [EACH] { ROW | STATEMENT }]
` Has a trigger return type
EXECUTE PROCEDURE <function_name>(arguments);
<triggering_events>::=
` When a PL/pgSQL function is called as a trigger, several
<triggerng_event> [OR <triggering_event>…..]
special variables are created automatically in the top level
block
<triggering_event>::= {INSERT | DELETE | UPDATE}
PL / pgSQL PL / pgSQL PL / pgSQL
32 33 34
Automatically Created Variables RETURN Type Returning a Value Being Not NULL
` A row level trigger fired BEFORE may return NULL to
` `
The most important automatically created variables: A trigger has to return:
signal the trigger manager to skip the rest of operations
` Either NULL, or
` NEW of data type RECORD holding the new database row for
for this row (the INSERT/DELETE/UPDATE will not be
` A record/row value having exactly the structure of the table
INSERT/UPDATE operations in row level triggers
executed for this row)
the trigger was fired for
` OLD of data type RECORD holding the old database row for
UPDATE/DELETE operations in row level triggers
` If a BEFORE row level trigger returns a non null value,
` The return value of a: the operation proceeds with that row value:
` BEFORE or AFTER per statement trigger, or
` There are also other variables generated (have a look in ` Returning a row value different from the original value of NEW
` alters the row that will be inserted or updated (but has no
An AFTER row level trigger is always ignored
the PostgreSQL Manual)
influence on delete operation)
` Both should be NULL
` Altering a row to be stored is accomplished either by replacing
` But they can still abort an entire operation by raising en error
single values directly in NEW, or building a completely new
record/row
PL / pgSQL PL / pgSQL PL / pgSQL
35 36 37
7. Triggers Examples Summary (1)
Referential Integrity Trigger INSERT
` `
Consider the following part of a relational database Stored Procedures have a widespread use in industry
CREATE TRIGGER ins_ref_int
schema: since they allow for:
BEFORE INSERT ON Exam FOR EACH ROW
EXECUTE PROCEDURE ins_ref_int();
` Code sharing,
`
CREATE OR REPLACE FUNCTION ins_ref_int() Tighter security control,
Student (StudId, Name, NoOfPts, Degree) RETURNS trigger AS $$
` Efficient execution
DECLARE s RECORD;
Exam (StudId, CourseId, Term, Grade) BEGIN
` User Defined Functions (UDFs):
SELECT * INTO s FROM Student WHERE NEW.StudId = StudId;
`
IF NOT FOUND THEN Can be defined using SQL only, or a combination of SQL and a
` Suppose DBMS does not support referential integrity RAISE NOTICE 'There is no student %', NEW.StudId;
procedural language
RETURN NULL;
constraints `
ELSE Can be used as stored procedures,
RETURN NEW;
` Can be used as trigger procedures
END IF;
END;
$$ LANGUAGE 'PLpgSQL';
PL / pgSQL PL / pgSQL PL / pgSQL
38 39 40
Summary (2) Summary (3)
` PL/pgSQL is a simple language that combines procedural constructs with
` Triggers are active rules that are automatically fired when
SQL statements
an event occurs
` It is designed to provide for:
` In the PostgreSQL environment triggers use PL/pgSQL ` Creating user defined functions
procedures ` Creating trigger procedures
` Triggers are extensively used to implement constraints ` Efficient execution (vaguely speaking it is precompiled)
` Easy to use
` It is block structured
` Supports
` A waste range of data types
` Conditionals
` Looping
` Special statements (SELECT INTO)
PL / pgSQL PL / pgSQL
41 42