PowerPoint Presentation
Professor: Dr. Shu-Ching Chen
TA:Sheng Guan
Views, Sequence, and Stored Procedure used in PosgreSQL
What are stored procedures
A subroutine available to applications that access a relational database system.
PL/pgSQL : A loadable procedural language.
Creates functions and trigger procedures
Adds control structures
Performs complex computation
Inherits all user-defined types, functions
Can be defined to be trusted by the server
Easy to use
PL/pgSQL is a loadable procedural language for the PostgreSQL database system.
The design goals of PL/pgSQL were to create a loadable procedural language that can be used to create functions and trigger procedures, adds control structures to the SQL language, can perform complex computations,
inherits all user-defined types, functions, and operators, can be defined to be trusted by the server,
is easy to use.
A stored procedure is a subroutine available to applications that access a relational database system.
Typical uses for stored procedures include data validation (integrated into the database) or access control mechanisms. Furthermore, stored procedures can consolidate and centralize logic that was originally implemented in applications. Extensive or complex processing that requires execution of several SQL statements is moved into stored procedures, and all applications call the procedures. One can use nested stored procedures, by executing one stored procedure from within another.
Stored procedures are similar to user-defined functions (UDFs).
2
Why do we need stored procedure
One Query
Wait, receive, process/compute
Database Server
Internet
Reduce roundtrips across the network
Can make security easier to manage
Are precompiled
Reduce roundtrips across the network – Stored procedures take zero or more input parameters, do something, and return a result, much like a function in any language. By “black boxing” that functionality on the database server, we avoid the need to move large datasets across the wire to the application server for processing. This can decrease network utilization and application latency.
Can make security easier to manage – While views can help simplify the permissions needed for complex queries, stored procedures make it even easier. Instead of giving a user/application the correct rights to specific tables (or columns), a person only needs execution rights to the stored procedure.
Are precompiled – Stored procedures are stored in a precomplied state on the server, meaning that the query optimizer doesn’t have to recalculate the most efficient execution path each time the query is run. This reduces server overhead and can speed things up a bit.
3
Structure of PL/pgSQL
PL/pgSQL code is organized in blocks of code. This method of organization is known as block structured code. Code blocks are entered within a SQL CREATE FUNCTION call that creates the PL/pgSQL function in the PostgreSQL database. This CREATE FUNCTION command names the new function, states its argument types, and states the return type. The function’s main code block then starts with a declaration section.
All variables are declared and optionally initialized to a default value in the declaration section of a code block. A variable declaration specifies the variable’s name and type. The declaration section is denoted by the DECLARE keyword. Each variable declaration is ended with a semicolon.
After declaring variables, the main body of the code block is started with the BEGIN keyword. The code block’s statements should appear after the BEGIN keyword.
The END keyword designates the end of the code block. The main block of a PL/pgSQL function should return a value of its specified return type and end any sub-blocks (code blocks started within another code block) before its END keyword is reached.
4
Declarations (1)
Declaring PL/pgSQL variable
Declarations (2)
Declaring PL/pgSQL variable and assigning values
The NOT NULL keywords indicate that a variable cannot be set as NULL.
The DEFAULT keyword allows you to provide a default value for a variable. Alternatively, you can use the := operator without specifying the DEFAULT keyword, to the same effect.
6
Declarations (3)
Declaring Function Parameters
(1) directly give a name to the parameter in the command
(2) name ALIAS FOR $n;
7
Declarations (4)
Directly using argument variables
Declarations (5)
Attributes
%TYPE attribute
Declarations (6)
Attributes
%ROWTYPE attribute
Comment syntax
Single-line comments
Block comments
Single line comments begin with two dashes (- -) and have no end-character. The parser interprets all characters on the same line after the two dashes as part of the comment.
The second type of comment is the multiline or block comment, which should be familiar to most anyone who has worked with programming languages before. Block comments begin with the forward slash and asterisk characters (/*) and end with the asterisk and forward slash characters (*/). Block comments can span multiple lines, and any text between the opening /* and closing */ is considered a comment. Example 11-7 shows the correct usage of a block comment.
11
Basic Statements (1)
Assignment
Executing a Command with NO RESULT – PERFORM
Basic Statements (2)
Executing a Command with a Single-row result
If the STRICT option is specified, the query must return exactly one row or a run-time error will be reported, either NO_DATA_FOUND (no rows) or TOO_MANY_ROWS (more than one row). You can use an exception block if you wish to catch the error, for example:
where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields
If STRICT is not specified in the INTO clause, then target will be set to the first row returned by the query, or to nulls if the query returned no rows. (Note that “the first row” is not well-defined unless you’ve used ORDER BY.) Any result rows after the first row are discarded.
13
Basic Statements (3)
Example
Basic Statements (4)
Basic Statements (5)
FOUND – Boolean variable
Use the special FOUND Boolean variable directly after a SELECT INTO statement to check whether or not the statement successfully inserted a value into the specified variable
16
Control Structures(1)
RETURN expression
Control Structures(2)
IF statements
IF … THEN
IF … THEN … ELSE
IF … THEN … ELSIF … THEN … ELSE
Control Structures(3)
CASE statements
CASE … WHEN … THEN … ELSE … END CASE
CASE WHEN … THEN … ELSE … END CASE
Control Structures(4)
LOOP
EXIT
LOOP defines an unconditional loop that is repeated indefinitely until terminated by an EXIT or RETURN statement. The optional label can be used by EXIT and CONTINUE statements within nested loops to specify which loop those statements refer to.
If no label is given, the innermost loop is terminated and the statement following END LOOP is executed next. If label is given, it must be the label of the current or some outer level of nested loop or block. Then the named loop or block is terminated and control continues with the statement after the loop’s/block’s corresponding END.
If WHEN is specified, the loop exit occurs only if boolean-expression is true. Otherwise, control passes to the statement after EXIT.
EXIT can be used with all types of loops; it is not limited to use with unconditional loops.
When used with a BEGIN block, EXIT passes control to the next statement after the end of the block. Note that a label must be used for this purpose; an unlabelled EXIT is never considered to match a BEGIN block.
20
Control Structures(5)
CONTINUE
WHILE
Control Structures(6)
FOR (Integer Variant)
Control Structures(7)
FOR (Looping through query results)
Control Structures(8)
Trapping Errors
http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html#ERRCODES-TABLE
If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement afterEND. But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END. If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.
24
Cursors (1)
A pgSQL cursor allows us to encapsulate a query and process each individual row at a time. We use cursors when we want to divide a large result set into parts and process each part individually.
First, declare a cursor.
Next, open the cursor.
Then, fetch rows from the result set into a target.
After that, check if there is more row left to fetch. If yes, go to step 3, otherwise go to step 5.
Finally, close the cursor.
25
Cursors (2)
Declaring Cursor Variables
DECLARE
my_cursor REFCURSOR;
PostgreSQL provides us with a special type called REFCURSOR to declare a cursor variable
cursor_name [ [NO] SCROLL ] CURSOR [( name datatype, name data type, …)] FOR query;
Declare a cursor that bounds to a query
First, you specify a variable name for the cursor.
Next, you specify whether the cursor can be scrolled backward using the SCROLL. If you use NO SCROLL, the cursor cannot be scrolled backward.
Then, you put the CURSOR keyword followed by a list of comma-separated arguments ( name datatype) that defines parameters for the query. These arguments will be substituted by values when the cursor is opened.
After that, you specify a query following the FOR keyword. You can use any valid SELECT statement here.
26
Cursors (3)
Examples:
DECLARE
cur_films CURSOR FOR SELECT * FROM film;
cur_films2 CURSOR (year integer) FOR SELECT * FROM film WHERE release_year = year;
The cur_films is a cursor that encapsulates all rows in the film table.
The cur_films2 is a cursor that encapsulates film with a particular release year in the film table.
This provides an efficient way to return large row sets from functions.
Rather than executing a whole query at once, it is possible to set up a cursor that encapsulates the query, and then read the query result a few rows at a time
create a cursor variable is just to declare it as a variable of type refcursor
All three of these variables have the data type refcursor, but the first can be used with any query, while the second has a fully specified query already bound to it, and the last has a parameterized query bound to it.
Before a cursor can be used to retrieve rows, it must be opened. (This is the equivalent action to the SQL command DECLARE CURSOR.) PL/pgSQL has three forms of the OPENstatement, two of which use unbound cursor variables while the third uses a bound cursor variable.
27
Cursors (4)
Cursors must be opened before they can be used to query rows.
Opening unbound cursors
OPEN unbound_cursor_variable [ [ NO ] SCROLL ] FOR query;
Because unbound cursor variable is not bounded to any query when we declared it, we have to specify the query when we open it.
Example:
OPEN my_cursor FOR SELECT * FROM city WHERE counter = p_country;
Opening bound cursors
OPEN cursor_variable[ (name:=value,name:=value,…)];
Just need to pass the arguments to the query;
Example:
OPEN cur_films(year:=2005);
This provides an efficient way to return large row sets from functions.
Rather than executing a whole query at once, it is possible to set up a cursor that encapsulates the query, and then read the query result a few rows at a time
create a cursor variable is just to declare it as a variable of type refcursor
All three of these variables have the data type refcursor, but the first can be used with any query, while the second has a fully specified query already bound to it, and the last has a parameterized query bound to it.
Before a cursor can be used to retrieve rows, it must be opened. (This is the equivalent action to the SQL command DECLARE CURSOR.) PL/pgSQL has three forms of the OPENstatement, two of which use unbound cursor variables while the third uses a bound cursor variable.
28
Cursors (5)
Using Cursors–After opening a cursor, we can manipulate it using FETCH, MOVE, UPDATE, or DELETE statement.
FETCH
The FETCH statement gets the next row from the cursor and assign it a target_variable
Example: FETCH cur_films INTO row_film;
FETCH LAST FROM row_film INTO title, release_year;
NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
FORWARD
BACKWORD
The FETCH statement gets the next row from the cursor and assign it a target_variable, which could be a record, a row variable, or a comma-separated list of variables. If no more row found, the target_variable is set to NULL(s).
29
Cursors (6)
Moving the cursor
MOVE [ direction { FROM | IN } ] cursor_variable;
If you want to move the cursor only without retrieving any row, you use the MOVE statement.
Examples: MOVE cur_films2;
MOVE LAST FROM cur_films;
MOVE RELATIVE -1 FROM cur_films;
MOVE FORWARD 3 FROM cur_films;
CLOSE closes the portal underlying an open cursor. This can be used to release resources earlier than end of transaction, or to free up the cursor variable to be opened again
30
Cursors (7)
Deleting or updating row
Once a cursor is positioned, we can delete or update row identifying by the cursor
UPDATE table_name
SET column = value, …
WHERE CURRENT OF cursor_variable;
DELETE FROM table_name
WHERE CURRENT OF cursor_variable;
Example: UPDATE film SET release_year = p_year
WHERE CURRENT OF cur_films;
CLOSE closes the portal underlying an open cursor. This can be used to release resources earlier than end of transaction, or to free up the cursor variable to be opened again
31
Cursors (8)
To close an opening cursor, we use CLOSE statement as follows:
CLOSE cursor_variable;
The CLOSE statement releases resources or frees up cursor variable to allow it to be opened again using OPEN statement.
An integrated example can be found in :
http://www.postgresqltutorial.com/plpgsql-cursor/
get_film_titles(integer)
The cursor variable must have been bound to some query when it was declared, and it cannot be open already. The FOR statement automatically opens the cursor, and it closes the cursor again when the loop exits. A list of actual argument value expressions must appear if and only if the cursor was declared to take arguments. These values will be substituted in the query, in just the same way as during an OPEN.
The variable recordvar is automatically defined as type record and exists only inside the loop (any existing definition of the variable name is ignored within the loop). Each row returned by the cursor is successively assigned to this record variable and the loop body is executed.
32
Errors and Messages
RAISE
Example
Reference
PostgreSQL Manuals PostgreSQL 9.1
http://www.postgresql.org/docs/9.1/static/index.html
Practical PostgreSQL
http://www.faqs.org/docs/ppbook/c19610.htm
COST in stored procedures: A positive number giving the estimated execution cost for the
function, in units of cpu_operator_cost. If the function returns a
set, this is the cost per returned row. If the cost is not specified,
1 unit is assumed for C-language and internal functions, and 100 units
for functions in all other languages. Larger values cause the planner
to try to avoid evaluating the function more often than necessary. ”
34
Stored Procedure in PgAdmin
1
2
3
Stored Procedure in PgAdmin
/docProps/thumbnail.jpeg