Application Programming Database Lectures for Mathematics Students

Application Programming Database Lectures for Mathematics Students

Application Programming Database lectures for mathematics students Zbigniew Jurkiewicz, Institute of Informatics UW April 23, 2017 Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Functions You can define functions in Postgres with CREATE FUNCTION name(parameter type, ...) RETURNS result-type AS $$ function-body $$ LANGUAGE language-name; For the SQL language the body is a sequence of SQL statements. The function body in older versions was surrounded by single quotes, which was inconvenient, as it lead to doubling any apostrophes inside body (around strings etc.). Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Functions Because in Postgres the statement SELECT can be used for evaluating expressions not connected with any database, e.g. bd> SELECT 2 + 5 AS seven; seven ------ 7 so simple functions can be defined using just SQL: CREATE FUNCTION add7(i int4) RETURNS int4 AS $$ SELECT i + 7; $$ LANGUAGE sql; Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Functions Example call of the above function: bd> SELECT add7(4) AS result; result ----- 11 Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Functions Functions written in SQL return as their value the result from the last statement in the body, this is usually SELECT. If the result is not to be interpreted as a set, the first resulting row will be taken (so take care about possible ORDER BY ;-). If the query result is empty, NULL is returned. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Functions If an SQL function does not return anything reasonable, the result type should be declared as void, and the body may not terminate with SELECT query. CREATE FUNCTION clean () RETURNS void AS $$ DELETE FROM Animals WHERE weight <= 0; $$ LANGUAGE SQL; SELECT clean(); Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students PL/pgSQL Usually the stored database procedures are not defined in SQL, but in procedural languages. In Postgres the default language for database server is PL/pgSQL, similar to PL/SQL from Oracle. The standard languages provided in distribution are installed using the shell script createlang. To install PL/pgSQL in the database template1 it is enough to type createlang plpgsql template1 Removal of a procedural language could be done within SQL using the statement DROP LANGUAGE or by running the script droplang. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students PL/pgSQL PL/pgSQL (Procedural Language/postgresSQL) extends SQL with typical constructs encountered in imperative programming languages. The basic unit in PL/SQL is the block, programs are built from nested blocks. Inside blocks you may use as instructions all SQL data manipulation statement (e.g. SELECT, INSERT, UPDATE, DELETE) and transaction control statements. There is also an extended form of SELECT statement, to move the values found in the database into PL/pgSQL variables. Schema data definition instructions, such as CREATE, DROP or ALTER, are not allowed. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students PL/pgSQL In addition to SQL statements blocks may contain typical instructions like assignments, conditional instructions, loops or procedure calls. PL/pgSQL blocks are usually placed in function bodies, and this functions can be called by using ordinary SELECT for example from psql program. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Blocks The syntax of a PL/pgSQL block is as follows: [DECLARE declarations of variables, constants and local procedures] BEGIN instructions END; (the square brackets mark the optional part, they are not syntax elements). Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Blocks Example block: DECLARE a NUMERIC(5); BEGIN SELECT COUNT(*) INTO a FROM EMP WHERE ENAME LIKE ’A%’; IF a > 0 THEN INSERT INTO TEMP VALUES(a); END IF; RAISE NOTICE ’OK’; END; Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers Triggers are procedures “automagically” called when some event happens, e.g. when inserting a new row into a particular table. Triggers originally were not intended to serve as a mechanism for ensuring the legality of database states (this role was to be played by integrity constraints and assertions), but to ensure the legality of transitions between states. But since no popular DBMS implement assertions (it is not easy, by the way), triggers are most often used to realize complex constraints. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers Trigger definition contains three components Event: modification of some table, e.g. “inserting into Species table”. Condition: Boolean expression in SQL syntax. Actions: instructions to be executed, most often written in SQL or PL/SQL. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Syntax of triggers According to SQL standard, the trigger syntax is as follows: CREATE [OR REPLACE] TRIGGER name fBEFORE | AFTERg INSERT OR DELETE OR UPDATE ON table FOR EACH fROW | STATEMENTg BEGIN instruction ... END; Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Example Let’s try to write a trigger which after removing a row from Species table would set NULLs in the species column for corresponding rows of Animals table. We can of course achieve the same effect more easily just using foreign key constraints — but it may be interesting to see how they can be implemented. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Example CREATE TRIGGER DelSpec AFTER DELETE ON Species FOR EACH ROW EXECUTE UPDATE Animals SET species = NULL WHERE species = OLD.species; Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Other example Let us assume that for each species in the table Species we want to store (in a separate column) the number of animals of this kind. We start by adding the appropriate column ALTER Species ADD howmany INTEGER DEFAULT 0 CHECK (howmany >= 0); Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Other example Time to define triggers CREATE TRIGGER InsAnimals AFTER INSERT ON Animals FOR EACH ROW EXECUTE UPDATE Species SET howmany = howmany + 1 WHERE name = NEW.species; CREATE TRIGGER DelAnimals AFTER DELETE ON Animals FOR EACH ROW EXECUTE UPDATE Species SET howmany = howmany - 1 WHERE name = OLD.species; Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers in Postgres Triggers in PL/pgSQL always contain as their bodies a call to a previously defined procedure. The procedure should be a function with no arguments and should declare that it returns the special type TRIGGER The trigger function receives data not from ordinary functional parameters, but through the structure TriggerData. Trigger procedures should not be called directly (by name). They are called implicitly by trigger, whenever the associated events occur. The event can be one of SQL operations INSERT, DELETE or UPDATE. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers in Postgres For each trigger you must define whether its procedure will be called BEFORE or AFTER the operation proper. Also each trigger should have declared one of two levels: row or statement. The option FOR EACH ROW declares row-level trigger, by default the trigger is statement-level. Statement-level trigger is fired only once for the whole SQL statement, but row-level trigger is independently fired once for each row being modified. Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers in Postgres The trigger definition in PL/pgSQL has the following syntax: CREATE TRIGGER name BEFORE | AFTER INSERT | DELETE | UPDATE [OR ...] ON table [FOR EACH ROW | STATEMENT] EXECUTE PROCEDURE procedure-name(arguments); Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers in Postgres Additional remarks: The trigger function must be defined before creating trigger. The name of a trigger must be unique for a given table and is used when removing the trigger. For a single trigger one can state up to three kinds of events (INSERT, DELETE or UPDATE) activating the trigger (use OR connective between them). Examples: ... INSERT ON R ... ... INSERT OR DELETE OR UPDATE ON R ... Zbigniew Jurkiewicz, Institute of Informatics UW Application Programming Database lectures for mathematics students Triggers in Postgres When removing a trigger it is necessary to give the table name in addition to the trigger name. DROP TRIGGER name ON table; In

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    34 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us