Download presentation
Presentation is loading. Please wait.
1
CS4222 Principles of Database System
11/30/2018 CS4222 Principles of Database System 13. PL/PgSQL Huiping Guo Department of Computer Science California State University, Los Angeles
2
Introduction PL/pgSQL is a loadable, procedural language.
11/30/2018 Introduction PL/pgSQL is a loadable, procedural language. A procedural language is a programming language used to specify a sequence of steps that are followed to produce an intended programmatic result What PL/PgSQL is used for? extending the server functionality via user-defined functions, triggers, etc Advantages group sequences of SQL and programmatic statements together within a database server reduces network and communications overhead 13. PL/pgSQL CS4222_Su17
3
Adding PL/pgSQL to Database
To add PL/pgSQL you can either use the createlang application from command prompt, or the CREATE LANGUAGE SQL command from within a database client such as psql C:\>createlang -U hpguo -d hpguo plpgsql CREATE LANGUAGE command first requires the creation of the PL/pgSQL call handler, which is the function that actually processes and interprets the PL/pgSQL code. You don’t need to do this unless you installed your own server on your home machine!! 13. PL/pgSQL CS4222_Su17
4
Language Structure PL/pgSQL's structure is similar to other programming languages such as C each portion of code acts as a function all variables must be declared before being used code segments accept arguments when called and return arguments at their end PL/pgSQL functions are case insensitive 13. PL/pgSQL CS4222_Su17
5
Code Blocks PL/pgSQL code is organized in blocks of code (block structured code ) Code blocks are entered within a CREATE FUNCTION CREATE FUNCTION command names the new function states its argument types states the return type 13. PL/pgSQL CS4222_Su17
6
Structure of a PL/pgSQL code block
CREATE FUNCTION funName (arguments) RETURNS type AS ’ DECLARE declaration; BEGIN statement; END; ’ LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
7
Code Blocks (cont.) function's main code block starts with a declaration section variable declaration specifies the variable's name and type the main body of the code block is started with the BEGIN keyword END keyword designates the end of the code block PL/pgSQL function should return a value of its specified return type before its END keyword is reached All strings in the code blocks must be enclosed within ‘‘ ’’ (two single quotes) 13. PL/pgSQL CS4222_Su17
8
Comments C style SQL style /* This is a multiple-line comment. */
-- This is a single line comment. 13. PL/pgSQL CS4222_Su17
9
A simple example Define a function Use the function
CREATE FUNCTION a_function () RETURNS int4 AS ' DECLARE an_integer int4 :=1; BEGIN an_integer := 10 * 10; return an_integer; END; ' LANGUAGE 'plpgsql'; Use the function Select a_function() as output; 13. PL/pgSQL CS4222_Su17
10
Declaration and statement
Declare and/or initialize the variables that will be referenced within the code block. Each declaration is terminated by a semicolon Statement A statement performs an action within PL/pgSQL code such as assignment of a value to a variable the execution of a query, …. Each statement within a block is terminated by a semicolon 13. PL/pgSQL CS4222_Su17
11
Declare a variable myrow sailors%ROWTYPE;
variable_name [ CONSTANT ] data_type [ NOT NULL ] [ { DEFAULT | := } value ]; Ex: subject_id INTEGER; five CONSTANT INTEGER := 5; ten INTEGER NOT NULL := 10; letter CHAR DEFAULT ‘’a’’; myrow sailors%ROWTYPE; myfield tablename.columnname %TYPE; 13. PL/pgSQL CS4222_Su17
12
Declare a variable (cont.)
five CONSTANT INTEGER := 5; The variable five cannot be changed. If you change five in the function, you’ll get run time error ten INTEGER NOT NULL := 10; The variable ten cannot be set to NULL letter CHAR DEFAULT “a”; equivalent to letter CHAR :=’’a’’ 13. PL/pgSQL CS4222_Su17
13
Example CREATE FUNCTION example_function () RETURNS text AS ' DECLARE
five CONSTANT INTEGER := 5; ten INTEGER NOT NULL := 10; letter CHAR DEFAULT ''a''; BEGIN return letter; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
14
Data type SQL type Composite variable type
Aliases for Function Parameters 13. PL/pgSQL CS4222_Su17
15
Commonly used SQL data type
Boolean, bool text char Integer, int, int4 Real, float8 date time 13. PL/pgSQL CS4222_Su17
16
Composite variable type
Row type: used to declare a PL/pgSQL record variable with the same structure as the rows in a table you specify. myrow tablename%ROWTYPE; Attribute type used to declare a variable with the data type of a table column. myfield tablename.columnname%TYPE; Record type Similar to row type, without predefined structure Myrecord RECORD 13. PL/pgSQL CS4222_Su17
17
Aliases for Function Parameters
Parameters passed to functions are named with the identifiers $1, $2, etc. Either the alias or the numeric identifier can then be used to refer to the parameter value. 13. PL/pgSQL CS4222_Su17
18
Aliases for Function Parameters
CREATE FUNCTION sales_tax(REAL) RETURNS REAL AS ' DECLARE subtotal ALIAS FOR $1; BEGIN return subtotal * 0.06; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
19
Aliases for Function Parameters
CREATE FUNCTION instr(VARCHAR,INTEGER) RETURNS INTEGER AS ‘ DECLARE v_string ALIAS FOR $1; index ALIAS FOR $2; BEGIN -- Some computations here END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
20
Statement Assignment Controlling Program Flow Basic assignment
SELECT INTO PEROFRM EXCUTE Controlling Program Flow Conditionals Loops 13. PL/pgSQL CS4222_Su17
21
Basic assignment identifier := expression; Examples: user_id := 20;
tax := subtotal * 0.06; 13. PL/pgSQL CS4222_Su17
22
SELECT INTO Syntax target SELECT target_column [, ...]
INTO target_variable [, ...] FROM table_name WHERE conditions target record variable, a row variable, or a comma-separated list of simple variables and record/row fields. takes the value of the first row returned 13. PL/pgSQL CS4222_Su17
23
SELECT INTO statement Create table Customers (id int primary key, name text); Insert into Customers Values(1, 'Tom'); Insert into Customers Values(2, 'Annie'); CREATE FUNCTION get_customer_id (text) RETURNS integer AS ' DECLARE customer_name ALIAS FOR $1; customer_id INTEGER; BEGIN SELECT id INTO customer_id FROM customers WHERE name = customer_name; RETURN customer_id; END; ' LANGUAGE 'plpgsql'; Use the function: SELECT get_customer_id('Annie'); 13. PL/pgSQL CS4222_Su17
24
SELECT INTO statement CREATE FUNCTION get_customer_name (integer) RETURNS text AS ' DECLARE customer_id ALIAS FOR $1; customer_name TEXT; BEGIN SELECT name INTO customer_name FROM customers WHERE id = customer_id; RETURN customer_name; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
25
Using the FOUND boolean
[...] SELECT id INTO customer_id FROM customers WHERE name = customer_name; IF NOT FOUND THEN return -1; END IF; 13. PL/pgSQL CS4222_Su17
26
Using %ROWTYPE CREATE FUNCTION get_customer (integer) RETURNS text AS ' DECLARE customer_id ALIAS FOR $1; found_customer customers%ROWTYPE; BEGIN SELECT * INTO found_customer FROM customers WHERE id = customer_id; RETURN found_customer.id || '' '' || found_customer.name; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
27
Using %TYPE CREATE FUNCTION get_customer2 (integer) RETURNS text AS '
DECLARE customer_id ALIAS FOR $1; customer_name customers.name%TYPE; BEGIN SELECT name INTO customer_name FROM customers WHERE id = customer_id; RETURN customer_id || '' '' || customer_name; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
28
Contionals IF ... THEN ... ELSIF ... ELSE IF ... THEN
IF ... THEN ... ELSE IF ... THEN ... ELSE IF IF ... THEN ... ELSIF ... ELSE 13. PL/pgSQL CS4222_Su17
29
IF-THEN IF v_user_id <> 0 THEN
UPDATE users SET = v_ WHERE user_id = v_user_id; END IF; 13. PL/pgSQL CS4222_Su17
30
IF-THEN-ELSE IF v_count > 0 THEN INSERT INTO users_count (count)
VALUES (v_count); RETURN ''t''; ELSE RETURN ''f''; END IF; 13. PL/pgSQL CS4222_Su17
31
IF-THEN-ELSE IF IF demo_row.sex = ''m'' THEN pretty_sex := ''man'';
ELSE IF demo_row.sex = ''f'' THEN pretty_sex := ''woman''; END IF; 13. PL/pgSQL CS4222_Su17
32
IF-THEN-ELSIF-ELSE IF number = 0 THEN result := ''zero'';
ELSIF number > 0 THEN result := ''positive''; ELSIF number < 0 THEN result := ''negative''; ELSE result := ''NULL''; END IF; 13. PL/pgSQL CS4222_Su17
33
LOOPS Simple loops While For Looping Through Query Results Exit
13. PL/pgSQL CS4222_Su17
34
Simple loops LOOP statement; [...] EXIT [ WHEN condition ]; END LOOP;
LOOP defines an unconditional loop that is repeated indefinitely until terminated by an EXIT or RETURN statement. The innermost loop is terminated and the statement following END LOOP is executed next. If WHEN is specified, the loop exit occurs only if expression is true. Otherwise, control passes to the statement after EXIT. 13. PL/pgSQL CS4222_Su17
35
Simple loops CREATE FUNCTION square_integer_loop(integer)
RETURNS integer AS ' DECLARE num1 ALIAS FOR $1; result integer; BEGIN result := num1; LOOP result := result * result; EXIT WHEN result >= 10000 END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
36
Exit Ex.1 LOOP IF count > 0 THEN EXIT; -- exit loop END IF;
END LOOP; Ex.2 EXIT WHEN count > 0; -- same result as previous example IF stocks > THEN EXIT; -- invalid; cannot use EXIT outside of LOOP END; 13. PL/pgSQL CS4222_Su17
37
While WHILE condition LOOP statement; [...] END LOOP;
13. PL/pgSQL CS4222_Su17
38
While CREATE FUNCTION while_loop (integer, integer)
RETURNS integer AS ' DECLARE low_number ALIAS FOR $1; high_number ALIAS FOR $2; result INTEGER = low_number; BEGIN WHILE result != high_number LOOP result := result + 1; END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
39
For FOR identifier IN [ REVERSE ] expression1 .. expression2 LOOP
statement; [...] END LOOP; The FOR loop will perform a single iteration for each incremented value of identifier which is in the range of values between, and including, expression1 and expression2. The identifier value will be initialized to the value of expression1, regardless of any prior settings, and incremented by one each iteration. If REVERSE is specified, identifier will be decremented rather than incremented 13. PL/pgSQL CS4222_Su17
40
For FOR i IN 1..10 LOOP -- some computations here END LOOP;
FOR i IN REVERSE 10..1 LOOP -- some computations here 13. PL/pgSQL CS4222_Su17
41
Looping Through Query Results
Method 1 FOR record_or_row IN query LOOP statements END LOOP; Method 2 FOR record_or_row IN EXECUTE text_expression END LOOP 13. PL/pgSQL CS4222_Su17
42
Example CREATE TABLE books ( subject_id integer, title text );
insert into books values(1, 'Book A'); insert into books values(1, 'Tomorrow'); insert into books values(2, 'Book B'); insert into books values(3, 'Book C'); 13. PL/pgSQL CS4222_Su17
43
Looping Through Query Results
CREATE FUNCTION extract_title (integer) RETURNS text AS ' DECLARE sub_id ALIAS FOR $1; text_output TEXT :='' ''; row_data books%ROWTYPE; BEGIN -- Iterate through the results of a query. FOR row_data IN SELECT * FROM books WHERE subject_id = sub_id ORDER BY title LOOP -- Insert the title of a matching book into the text_output variable. text_output := text_output || row_data.title || '' ''; END LOOP; RETURN text_output; END; ' LANGUAGE 'plpgsql'; 13. PL/pgSQL CS4222_Su17
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.