Presentation is loading. Please wait.

Presentation is loading. Please wait.

PL/pgSQL http://www.commandprompt.com/ppbook/.

Similar presentations


Presentation on theme: "PL/pgSQL http://www.commandprompt.com/ppbook/."— Presentation transcript:

1 PL/pgSQL

2 Definition PL/pgSQL is a loadable, procedural language, similar to the Oracle procedural language, PL/SQL. A procedural language is a programming language used to specify a sequence of steps that are followed to produce an intended programmatic result.

3 Advantages group sequences of SQL and programmatic statements together within a database server reduces network and communications overhead

4 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 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.

5 Example CREATE FUNCTION
CREATE FUNCTION plpgsql_call_handler() RETURNS OPAQUE AS '/postgres_library_path/plpgsql.so' LANGUAGE 'C' postgres_library_path is the absolute system path to the installed PostgreSQL library files. This path, by default, is /usr/local/pgsql/lib

6 Adding Language Previous example only creates the function handler; the language itself must be added with the CREATE LANGUAGE command.

7 Syntax to add Language CREATE LANGUAGE 'plpgsql' HANDLER plpgsql_call_handler LANCOMPILER 'PL/pgSQL‘ plpgsql is the name of the language to be created, the plpgsql_call_handler is the name of the call handler function created in the previous example. LANCOMPILER is the keyword and PL/pgSQL is an arbitrary descriptive note

8 Adding PL/pgSQL with CREATE LANGUAGE
CREATE LANGUAGE 'plpgsql' HANDLER plpgsql_call_handler LANCOMPILER 'PL/pgSQL'; The name following the HANDLER keyword should be the same name which is used to create the call handler

9 Example createlang Using createlang as a database superuser
$ cd /usr/local/pgsql/bin booktown=# createlang plpgsql booktown Explicitly passing a superuser account name to createlang $ cd /usr/local/pgsql/bin/ $ createlang plpgsql -U manager booktown The createlang program will return you to a shell prompt upon successful execution

10 Language Structure PL/pgSQL's structure is similar to other programming languages such as C ach 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

11 Code Blocks PL/pgSQL code is organized in blocks of code (block structured code ) Code blocks are entered within a SQL CREATE FUNCTION CREATE FUNCTION command names the new function states its argument types states the return type

12 Code Blocks (contd.) function's main code block starts with a declaration section variables are declared and optionally initialized to a default value variable declaration specifies the variable's name and type the main body of the code block is started with the BEGIN keyword

13 Code Blocks (contd.) 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

14 The structure of a code block
CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declaration; [...] BEGIN statement; END; ' LANGUAGE 'plpgsql'; PL/pgSQL code can contain an unlimited amount of sub-blocks

15 Comments Using single-line comments Using block comments
-- This will be interpreted as a single-line comment Using block comments /* *This is a *block *comment. */

16 Statements and Expressions
PL/pgSQL code is composed of statements and expressions Most of your code will be made of statements Expressions are essential to certain types of data manipulation

17 Statements statement performs an action within PL/pgSQL code
assignment of a value to a variable execution of a query Most of the statements will be placed in the main operation located after the BEGIN keyword and before the END keyword declarative statements appear in the declaration section (after the DECLARE keyword)

18 Expressions Expressions are calculations or operations Example
return their results as one of PostgreSQL's base data types Example x := a + b adds the variables a and b, then assigns the result to the variable x

19 Example CREATE FUNCTION a_function () RETURNS int4 AS ' DECLARE
an_integer int4; BEGIN an_integer := 10 * 10; return an_integer; END; ' LANGUAGE 'plpgsql'; Output booktown=# SELECT a_function() AS output; output 100 (1 row)

20 Example CREATE FUNCTION add_shipment (integer, text) RETURNS timestamp AS ' DECLARE -- Declare aliases for function arguments. customer_id ALIAS FOR $1; isbn ALIAS FOR $2; -- Declare a variable to hold the shipment ID number and -- the current time. shipment_id INTEGER; right_now timestamp; BEGIN -- Set the current time variable to the string ''now''. right_now := ''now''; -- Order the existing shipments by their ID numbers, beginning -- with the highest number, then insert the first ID number into -- the shipment_id variable. SELECT INTO shipment_id id FROM shipments ORDER BY id DESC; -- Add one to the shipment_id variable. shipment_id := shipment_id + 1;

21 Example (contd.) -- Insert a shipment record into the shipments table. The -- right_now variable will be typecast to a timestamp at -- run-time, causing constant value now to be interpreted as -- the timestamp each time the function is run. INSERT INTO shipments VALUES ( shipment_id, customer_id, isbn, right_now ); -- Return a timestamp using the constant value now. RETURN right_now; END; ' LANGUAGE 'plpgsql';

22 The IF/THEN statement CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] END IF; END; ' LANGUAGE 'plpgsql'; More Examples -

23 Example CREATE FUNCTION stock_amount (integer, integer) RETURNS integer AS ' DECLARE -- Declare aliases for function arguments. b_id ALIAS FOR $1; b_edition ALIAS FOR $2; -- Declare variable to store the ISBN number. b_isbn TEXT; -- Declare variable to store the stock amount. stock_amount INTEGER; BEGIN -- This SELECT INTO statement retrieves the ISBN number of the row in -- the editions table that had both the book ID number and edition number -- that were provided as function arguments. SELECT INTO b_isbn isbn FROM editions WHERE book_id = b_id AND edition = b_edition;

24 Example (contd.) -- Check to see if the ISBN number retrieved is NULL. This will -- happen if there is not an existing book with both the ID number -- and edition number specified in the function arguments. If the -- ISBN is null, the function returns a value of -1 and ends. IF b_isbn IS NULL THEN RETURN -1; END IF; -- Retrieve the amount of books available from the stock table -- and record the number in the stock_amount variable. SELECT INTO stock_amount stock FROM stock WHERE isbn = b_isbn; -- Return the amount of books available. RETURN stock_amount; END; ' LANGUAGE 'plpgsql';

25 The IF/THEN/ELSE statement
CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] ELSE END IF; END; ' LANGUAGE 'plpgsql';

26 Example CREATE FUNCTION in_stock (integer,integer) RETURNS boolean AS ' DECLARE -- Declare aliases for function arguments. b_id ALIAS FOR $1; b_edition ALIAS FOR $2; -- Declare a text variable to hold the ISBN of the book -- once found. b_isbn TEXT; -- Declare an integer variable to hold the amount of stock. stock_amount INTEGER; BEGIN -- This SELECT INTO statement retrieves the ISBN number of -- the row in the editions table that had both the book ID -- number and edition number that were provided as function -- arguments. SELECT INTO b_isbn isbn FROM editions WHERE book_id = b_id AND edition = b_edition; -- Check to see if the ISBN number retrieved is NULL. This

27 Example (contd.) -- will happen if there is not an existing book with both the -- ID number and edition number specified in the function -- arguments. If the ISBN is null, the function returns a -- FALSE value and ends. IF b_isbn IS NULL THEN RETURN FALSE; END IF; -- Retrieve the amount of books available from the stock -- table and record the number in the stock_amount variable. SELECT INTO stock_amount stock FROM stock WHERE isbn = b_isbn; -- Use an IF/THEN/ELSE check to see if the amount of books -- available is less than or equal to 0. If so, return FALSE. -- If not, return TRUE. IF stock_amount <= 0 THEN ELSE RETURN TRUE; END; ' LANGUAGE 'plpgsql';

28 The IF/THEN/ELSE/IF statement
CREATE FUNCTION identifier (arguments) RETURNS type AS ' DECLARE declarations BEGIN IF condition THEN statement; [...] ELSE IF condition END IF; END; ' LANGUAGE 'plpgsql';

29 Example CREATE FUNCTION books_by_subject (text) RETURNS text AS '
DECLARE -- Declare an alias for user input, which should be either all -- or the name of a subject. sub_title ALIAS FOR $1; -- Declare an integer to store the subject ID in, and a text -- variable to store the list of found books. The text variable -- is set to a blank string. sub_id INTEGER; found_text TEXT :=''''; BEGIN -- Retrieve the subject ID number for the book matching the -- title supplied by the user.

30 Example (contd.) SELECT INTO sub_id id FROM subjects WHERE subject = sub_title; -- Check to see if the function was given all as the the subject -- name. If so, execute the SELECT INTO statement and return -- the found_text variable. IF sub_title = ''all'' THEN found_text extract_all_titles(); RETURN found_text; -- If the function was NOT sent all as the name of the subject, -- check to see the subject ID number turned out to be within -- the valid range of subjects. If it did, execute the -- extract_title() function with the subject ID number as its -- argument, then assign the result to the found_text variable. ELSE IF sub_id >= 0 THEN found_text := extract_title(sub_id); RETURN ''\n'' || sub_title || '':\n'' || found_text;

31 Example (contd.) -- If the subject ID number was NULL, return a message telling -- the user that the subject specified could not be found. ELSE IF sub_id IS NULL THEN RETURN ''Subject not found.''; END IF; RETURN ''An error occurred. .''; END; ' LANGUAGE 'plpgsql';

32 Loops an unconditional loop will execute the statements within its body until an EXIT statement is reached the EXIT keyword can be accompanied by WHEN, followed by and an expression to specify when the loop should exit the expression should be a Boolean expression LOOP statement; [...] END LOOP;

33 Loops (contd.) When terminating a loop with EXIT, you may optionally specify a label and/or a condition on which the loop should exit from A label is an arbitrary identifier, prefixed with a pair of less-than symbols (<<) and suffixed with a pair of greater-than symbols (>>) <<label_name>> LOOP […] END LOOP;

34 Loops (contd.) By providing a label, you can specify which loop to exit when you have several loops nested inside each other the use of labels in EXIT will only work if you have specified a label for the loop you are attempting to terminate [ <<label>> ] LOOP statement; [...] EXIT [ label ] [ WHEN condition ]; END LOOP;

35 Example CREATE FUNCTION square_integer_loop (integer) RETURNS integer AS ' DECLARE -- Declare aliases for function argument. num1 ALIAS FOR $1; -- Declare an integer to hold the result. result integer; BEGIN -- Assign the user input number to the result variable. result := num1; LOOP result := result * result; EXIT WHEN result >= 10000; END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql';

36 The WHILE loop The WHILE loop is used to loop through a block of statements until a specified condition becomes false [ <<label>> ] WHILE condition LOOP statement; [...] END LOOP;

37 Example CREATE FUNCTION add_two_loop (integer, integer) RETURNS integer AS ' DECLARE -- Declare aliases for function arguments. low_number ALIAS FOR $1; high_number ALIAS FOR $2; -- Declare a variable to hold the result. result INTEGER = 0; BEGIN -- Add one to the variable result until the value of result is -- equal to high_number. WHILE result != high_number LOOP result := result + 1; END LOOP; RETURN result; END; ' LANGUAGE 'plpgsql';

38 The FOR loop The structure of a FOR loop in PL/pgSQL is similar to FOR loops in other procedural languages [ <<label>> ] FOR identifier IN [ REVERSE ] expression1 .. expression2 LOOP statement; [...] END LOOP;

39 Example CREATE FUNCTION extract_all_titles2 () RETURNS text AS '
DECLARE -- Declare a variable for the subject ID number. sub_id INTEGER; -- Declare a variable to hold the list of titles. text_output TEXT = '' ''; -- Declare a variable to hold the subject title. sub_title TEXT; -- Declare a variable to hold records from the books table. row_data books%ROWTYPE; BEGIN -- Outer FOR loop: loop through the body of this loop until the -- variable i equals 15. Start the looping at 0. Essentially, --loop the following statements 16 times (once for each subject). FOR i IN LOOP

40 Example (contd.) -- Retrieve the subject name of the subject with an ID number -- that matches the variable i. SELECT INTO sub_title subject FROM subjects WHERE id = i; -- Insert the subject name, a colon, and a new line into the -- text_output variable. text_output = text_output || ''\n'' || sub_title || '':\n''; -- Loop through all records in the books table with a subject ID FOR row_data IN SELECT * FROM books WHERE subject_id = i LOOP -- Insert the title of a matching book into the text_output -- variable, followed by a newline. text_output := text_output || row_data.title || ''\n''; END LOOP; -- Return the list. RETURN text_output; END; ' LANGUAGE 'plpgsql';


Download ppt "PL/pgSQL http://www.commandprompt.com/ppbook/."

Similar presentations


Ads by Google