0% found this document useful (0 votes)
38 views52 pages

Week 5

The document discusses database triggers in SQL. It provides an overview of triggers and their use for information processing. It describes the components of a trigger including the event, condition, and action. It explains how triggers extend the capabilities of a DBMS beyond simple data management. Examples are provided to illustrate auditing operations, tracking changes, maintaining referential integrity, and more. Limitations of triggers related to mutating tables are also discussed.

Uploaded by

reflex24
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views52 pages

Week 5

The document discusses database triggers in SQL. It provides an overview of triggers and their use for information processing. It describes the components of a trigger including the event, condition, and action. It explains how triggers extend the capabilities of a DBMS beyond simple data management. Examples are provided to illustrate auditing operations, tracking changes, maintaining referential integrity, and more. Limitations of triggers related to mutating tables are also discussed.

Uploaded by

reflex24
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

Lecture 5

Triggers Embedded SQL


1

Overview

Limitations of Relational Data Model for performing Information Processing Database Triggers in SQL Using Database Triggers for Information Processing within DBMS Restrictions for Database Triggers Embedded SQL JDBC
2

Limitations of Relational Data Model

Data Bases vs. Information Systems


DBMS manages data regardless of its usage. IS processes information with respect to its usage. Data model does not give interpretation in terms of the application domain
e.g. relational model, hierarchical model, set model.

Data Model vs. System Architecture

IS architecture is developed so that the data can be interpreted as information about a particular applied domain
e.g. HR information, financial information, sales information.
3

ECA

Event occurs in the data base


e.g. insertion, deletion, update.

Condition is checked
e.g. Is batch complete? Has student passed?

Actions are executed if condition is satisfied


e.g. send batch to supplier, congratulate student.
4

Extending Information Processing Capabilities of DBMS using Triggers

Processing of database content, performed by the DBMS engine itself, not by the application client execution of the trigger (Event) Initiated by a specified condition, depending on the type of the trigger firing of the trigger (Condition) All data actions performed by the trigger execute within the same transaction in which the trigger fires, but in a separate session (Action) Triggers are checked for different privileges as necessary for the processed data. Cannot contain transaction control statements (COMMIT, SAVEPOINT, ROLLBACK not allowed). 5

Database Triggers in SQL


Not specified in SQL-92, but standardised in SQL3 (SQL1999) Available in most commercial DBMS (Oracle, IBM DB2, MS SQL server) and some public domain DBMS (Postgres)
but not in smaller desktop (Oracle Lite) or public domain DBMS (MySQL).

Some vendor DBMS permit native extensions to SQL for specifying the triggers
e.g. PL/SQL in Oracle, Transact SQL in MS SQL Server.

Some DBMS also allow use of general purpose programming languages instead of SQL
e.g. C/C++ in Poet, JAVA in Oracle, C#/VB in SQL Server. for example also to views as in Oracle.
6

Some DBMS extend the triggers beyond tables

Types of SQL Triggers

How many times should the trigger body execute when the triggering event takes place? Per statement: The trigger executes once for the triggering event. This is the default. For each row: The trigger executes once FOR EACH ROW affected by the triggering event. When can the trigger be fired? Relative to the execution of an SQL DML statement (BEFORE or AFTER or INSTEAD OF it) Exactly in a situation depending on specific system resources (e.g. signal from the system clock, expiring timer, exhausting memory).
7

Statement and Row Triggers


Example 1: Monitoring Statement Events
SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'EDUCATION', 'NEW YORK');

Execute only once even if multiple rows affected Example 2: Monitoring Row Events
SQL> UPDATE emp 2 SET sal = sal * 1.1 3 WHERE deptno = 30;

Execute for each row of the table affected by the event


8

Firing Sequence of Database Triggers on a Single Row


DEPT table
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON

BEFORE statement trigger

BEFORE row trigger AFTER row trigger

AFTER statement trigger

Firing Sequence of Database Triggers on Multiple Rows


EMP table
EMPNO
7839 7698 7788 BEFORE statement trigger

ENAME
KING BLAKE SMITH

DEPTNO
30 30 30 BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger AFTER statement trigger
10

Syntax for creating triggers in SQL


Trigger name - unique within the data base schema. Timing - depends on the order of controlled events (before or after or instead of). Triggering event the event which fires the trigger (E). Filtering condition - checked when the triggering event occurs (C). Target - table (or view) against which the trigger is fired; they should both be created within the same schema. Trigger Parameters - parameters used to denote the record columns; preceded by colon :OLD , :NEW for old and new values respectively. Trigger action - SQL statements, executed when the trigger fires; surrounded by BEGIN ... END (A).
11

Syntax for Creating Statement Triggers


CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name BEGIN SQL or PL/SQL statements; END;
The trigger body consisting of SQL statements will be executed only once according to the prescribed timing, when the event1 (event2, event3) occurs against the monitored table in question

table_name.

12

Example: Registering Operations


SQL> 2 3 4 5 6 7 8 CREATE TRIGGER increase_salary_trg BEFORE UPDATE OF sal ON emp BEGIN INSERT INTO sal_hist(increased, changedOn) VALUES ('YES', SYSDATE); END; /

Trigger name: Timing: Triggering event: Target: Trigger action:

increase_salary_trg BEFORE executing the statement UPDATE of sal column emp table INSERT values INTO sal_hist table
13

Syntax for Creating Row Triggers


CREATE [OR REPLACE] TRIGGER trigger_name timing event1 [OR event2 OR event3] ON table_name [REFERENCING OLD AS old | NEW AS new] FOR EACH ROW [WHEN condition] BEGIN SQL or PL/SQL statements; END The trigger body consisting of SQL statements will be executed once for each row affected by event1 (event2, event3) in the table named table_name, subject to the additional condition.

14

Example: Calculating Derived Columns


SQL>CREATE OR REPLACE TRIGGER derive_commission_trg 2 BEFORE UPDATE OF sal ON emp 3 FOR EACH ROW 4 WHEN (new.job LIKE 'SALES%') 5 BEGIN 6 :new.comm := :old.comm * (:new.sal/:old.sal); 7 END; 8 /

Trigger name: Timing: Triggering event: Filtering condition: Target: Trigger parameters: Trigger action:

derive_commission_trg BEFORE executing the statement UPDATE of sal column Note: no (colon : ) before new in WHEN job LIKE 'SALES%' emp table old, new calculate the new commission to be updated

15

Trigger Execution order


1. Execute all BEFORE STATEMENT triggers. 2. Disable temporarily all integrity constraints on the table. 3. Loop for each row in the table: 3.1 Execute all BEFORE ROW triggers. 3.2 Execute the SQL statement against the row and perform integrity constraint checking of the data. 3.3 Execute all AFTER ROW triggers. 4. Complete deferred integrity constraint checking against the table. 5. Execute all AFTER STATEMENT triggers.
16

Controlling Triggers using SQL

Disable or Re-enable a data base trigger:


ALTER TRIGGER trigger_name DISABLE | ENABLE

Disable or Re-enable all triggers for a table:


ALTER TABLE table_name DISABLE | ENABLE ALL TRIGGERS

Remove a trigger from the data base:


DROP TRIGGER trigger_name

17

Using Database Triggers for Information Processing

Auditing Table Operations

Each time a table is accessed, auditing information is recorded against it. Each time a record value is changed the previous value is recorded.

Tracking Record Value Changes

Protecting Database Referential Integrity: if a foreign key points to changing records

Referential integrity must be maintained.


e.g. when the factory is closed, all employees become unemployed.

Maintenance of Semantic Integrity

Storing Derived Data

e.g. the number of items in the trolley should correspond to the current session selection.
e.g. checking user privileges when accessing sensitive information.
18

Security Access Control

Auditing Table Operations


USER_NAME SCOTT SCOTT JONES TABLE_NAME COLUMN_NAME EMP EMP SAL EMP INS 1 0 UPD 1 1 0 DEL 1 0

continuation
MAX_INS 5 5 MAX_UPD 5 5 0 MAX_DEL 5 0

19

Example: Counting Statement Execution


SQL> CREATE OR REPLACE TRIGGER audit_emp 2 AFTER DELETE ON emp 3 FOR EACH ROW 4 BEGIN 5 UPDATE audit_table SET del = del + 1 6 WHERE user_name = USER 7 AND table_name = 'EMP'; 7 END; 8 / Whenever an employee record is deleted from the database, the counter in an audit table registering the number of deleted rows for the current user in system variable USER is incremented.
20

Example: Tracing Record Value Changes


USER_NAME EGRAVINA NGREENBE TIMESTAMP

12-SEP-04
10-AUG-04

ID OLD_LAST_NAME NEW_LAST_NAME 7950 NULL HUTTON 7844 MAGEE TURNER

continuation
OLD_TITL E NULL CLERK NEW_TITLE OLD_SALARY NULL ANALYST SALESMAN 1100 NEW_SALARY 3500 1100

21

Example: Recording Changes


SQL>CREATE OR REPLACE TRIGGER audit_emp_values 2 AFTER DELETE OR UPDATE ON emp 3 FOR EACH ROW 4 BEGIN 5 INSERT INTO audit_emp_values (user_name, 6 timestamp, id, old_last_name, new_last_name, 7 old_title, new_title, old_salary, new_salary) 8 VALUES (USER, SYSDATE, :old.empno, :old.ename, 9 :new.ename, :old.job, :new.job, 10 :old.sal, :new.sal); 11 END; 12 /

Whenever some details for an employee are deleted or updated, both the previous and new details are recorded in an audit table to allow tracing the history of changes. An insert operation cannot be recorded with this trigger as :old.empno has no value.

22

Example: Protecting Referential Integrity


SQL>CREATE OR REPLACE TRIGGER cascade_updates 2 AFTER UPDATE OF deptno ON dept 3 FOR EACH ROW 4 BEGIN 5 UPDATE emp 6 SET emp.deptno = :new.deptno 7 WHERE emp.deptno = :old.deptno; 8 END 9 /
Whenever the department number changes, all employee records for this department will automatically be changed as well, so that the employees will continue to work for the same department.

23

Restrictions for Database Triggers


Problem: impossible to determine certain values during execution of a sequence of operations belonging to one and the same transaction. Mutating tables: contain rows which change their values after certain operation and which are used again before the current transaction commits. Preventing table mutation: Should not contain rows which are constrained by rows from other changing tables. Should not contain rows which are updated and read in one and the same operation. Should not contain rows which are updated and read via other operations during the same transaction.
24

Example: Mutating Table


SQL> 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE TRIGGER emp_count AFTER DELETE ON emp FOR EACH ROW DECLARE num INTEGER; BEGIN SELECT COUNT(*) INTO num FROM emp; DBMS_OUTPUT.PUT_LINE(' There are now ' || num || ' employees.'); END; /
Under the bar is code entered in SQL*Plus which triggers cascade_updates in this case. Triggers are not executed directly.

SQL> DELETE FROM emp 2 WHERE deptno = 30;

ERROR at line 1: ORA-04091: table CGMA2.EMP is mutating, trigger/ function may not see it
25

Example: Mutating Table (fixed)


SQL> 2 3 4 5 6 7 8 9 10 CREATE OR REPLACE TRIGGER emp_count AFTER DELETE ON emp Now the trigger becomes a statement trigger FOR EACH ROW and the EMP table is no longer a mutating DECLARE table. num INTEGER; BEGIN SELECT COUNT(*) INTO num FROM emp; DBMS_OUTPUT.PUT_LINE(' There are now ' || num || ' employees.'); END; /

SQL> DELETE FROM emp WHERE deptno = 30;

There are now 13 employees. There are now 8 employees.


6 rows deleted.
26

Rules for Good Practice


Rule 1: Do not change data in the primary key, foreign key, or unique key columns of any table. Rule 2: Do not update records in the same table you read during the same transaction. Rule 3: Do not aggregate over the same table you are updating. Rule 4: Do not read data from a table which is updated during the same transaction. Rule 5: Do not use Data Control Language statements in triggers.
27

Additional Literature on Triggers

P. Atzeni, S. Ceri, S.Paraboschi and R. Torlone. Database Systems, Chapter 12 Active Databases. McGraw-Hill (1999) Oracle Database Server Documentation. Oracle9i Database Concepts, Chapter 17 Triggers. Oracle Database Server Documentation. Oracle9i Application Developer's Guide Fundaments, Chapter 15 Using Triggers.

28

Embedded SQL & JDBC


Coupling Modes between Data Base and Programming Languages:

Extending the data base language with programming constructs (e.g. PL/SQL). Extending programming languages with data base constructs. Persistent programming languages, data base programming languages. Embedding a data base programming language into a programming language: Embedded SQL. Data base access from the programming language with specialised constructs.
29

Embedded SQL

Can embed SQL into various languages such as PASCAL, C, C++ and send command lines to data base Problems with SQL Embedding

Type systems do not fit Set-oriented vs. individual (scalar) variables Mapping of record/attributes to data types of the host language Iterative processing of the result set by a cursor

Practical Solution

Effects on the Host Language

Structure of the host language remains unchanged Every SQL statement can be embedded
simply prefixed by EXEC SQL

How to communicate between application program and data base?


30

Development of Embedded SQL application


Must have a connection established in order to run

31

Establishing a Connection
Application with embedded SQL: data base connection must be established explicitly.
EXEC SQL CONNECT :username IDENTIFIED BY :passwd; username and passwd are host variables of the types CHAR or

VARCHAR2
Strings are not allowed! Not supported by the SQL environment Equivalent:

EXEC SQL CONNECT :uid;


where uid has a value of the form "name/passwd". NOTE: JAVA has problems connecting if the sid of the database has an underscore in the name, e.g. info_db 32

Host Variables (calling program)

Needed for communication between the data base and the application program:

Output variables for communication of values from the database to the application program Data Base Application

Input variables for the communication of values from the application program to the database. Application Data Base

Data types of the data base and programming language must be compatible.
33

Handling multiple row return


Queries to the data base may return multiple rows


these will be lost if not handled correctly.

Cursors
Analogous to PL/SQL Required for processing any result set that may contain more than one row Cursor operations

DECLARE <cname> CURSOR FOR <SQLstatement> OPEN <cname> FETCH <cname> INTO <varlist> CLOSE <cname>

Error Situations Cursor not declared or not opened. No (further) data has been found (incorrect EXIT clause). Cursor has been closed, and not reopened.

34

Example
All SQL commands are preceded by EXEC

Dont panic! You are not expected to understand the code Illustration only!

int main() { EXEC SQL BEGIN DECLARE SECTION; char cityName[25]; /* output host var */ int cityEinw; /* output host var */ char* landID = "D"; /* input host var */ short ind1, ind2; /* indicator var */ char* uid = "/"; EXEC SQL END DECLARE SECTION; EXEC SQL CONNECT :uid; /*connect to DB */ EXEC SQL DECLARE StadtCursor CURSOR FOR SELECT Name, Einwohner FROM Stadt WHERE Code = :landID; EXEC SQL OPEN StadtCursor; /* open cursor */ printf("Stadt Einwohner\n"); while (1) {EXEC SQL FETCH StadtCursor INTO :cityName:ind1 , :cityEinw INDICATOR :ind2; if(ind1 != -1 && ind2 != -1) {printf("%s %d \n", cityName, cityEinw); }}; 35 EXEC SQL CLOSE StadtCursor; } /*close cursor */

PL/SQL - blocking of code

Oracle ProC/C++ precompiler supports PL/SQL blocks:


can be used in place of an SQL statement; reduce communication overhead between client and server.

Frame for communication: EXEC SQL EXECUTE DECLARE ... BEGIN ... END; END-EXEC; This reduces the need for EXEC commands at the start of each line.
36

Transactions

Application programming is regarded as a closed transaction, if it is not divided by COMMIT (or ROLLBACK) commands (it happens in isolation and as one block of code). In Oracle, after leaving a program, COMMIT is executed automatically. COMMIT is executed automatically before each DDL statement. The data base connection is shut down by either EXEC SQL COMMIT RELEASE; or EXEC SQL ROLLBACK RELEASE;
Transaction handling is covered later in the module.
37

Additional .
Savepoints

Transactions can be divided by savepoints. Syntax: EXEC SQL SAVEPOINT <name>; ROLLBACK to an earlier savepoint deletes all savepoints in between.

Exception Handling Mechanism


When you embed code you must handle errors


otherwise the program could crash or hang up.

The WHENEVER statement is the main one used.


38

WHENEVER statement

Specifies actions to be executed automatically by the DBMS in case of an error: EXEC SQL WHENEVER <condition> <action>; <condition> may be: SQLWARNING: the most recent statement caused a warning different from no data found. This corresponds to sqlcode > 0, but <> 1403. SQLERROR: the most recent statement caused a serious error. This corresponds to sqlcode < 0. NOT FOUND: SELECT INTO or FETCH did not return any more answer rows. This corresponds to sqlcode 1403.

39

WHENEVER statement (cont.)

<action> tells the DBMS what to do should an error be encountered during execution, e.g. CONTINUE: the program continues with the subsequent statement. DO <proc_name>: invoke a procedure (error handling); DO BREAK for exiting a loop. GOTO <label>: jump to the given label. STOP: rollback and exit from the program.
40

JAVA and Data Bases


JAVA is platform-independent: If a Java Virtual Machine is available, Java programs can be executed. APIs (Application Programming Interfaces) are collections of classes and interfaces that provide a certain functionality
avoids recoding of common code.

JDBC (Java DataBase Connectivity) is an API for data base access: Interface for (remote) access to a database from Java programs. Applications can be programmed independently of the underlying DBMS
increased flexibility.

Translates the ODBC idea to Java established protocol Common base is the X/Open SQL CLI (Call Level Interface) Standard
conforming to standards improves reliability.
41

JDBC Architecture

42

JDBC API
Flexible: Application can be programmed independently from the underlying DBMS. De facto portability only in the SQL-2 standard (not stored procedures, object-relational features). Low-level: Statements are submitted as strings. In contrast to Embedded SQL, program variables are not allowed in SQL commands. Under development: Embedded SQL for JAVA; Direct mapping of tables and rows to JAVA classes.
43

JDBC functionality

Establishing a connection to the data base (DriverManager, Connection). Submission of SQL statements to the database (statement and subclasses) Processing of the result set (ResultSet)

44

JDBC: establishing a connection

Invocation of the DriverManager:


Connection <name> = DriverManager.getConnection (<jdbc-url>, <user-id>, <passwd>);

Data base is uniquely identified by the JDBCURL:


jdbc:<subprotocol>:<subname> <subprotocol> identifies the driver and access mechanism <subname> identifies the data base
45

jdbc:oracle:<driver-name>: @<IP-Address DB Server>:<Port>:<SID> e.g. String url = 'jdbc:oracle:thin:@132.230.150.11:1521:o901'; Connection conn = DriverManager.getConnection(url,'jdbc_1','jdbc_1');

Returns an opened connection instance, conn. To close the connection: conn.close();


46

Submitting SQL statements


Statement objects: created by invocation of methods of an existing connection: Statement: simple SQL statement without parameters. PreparedStatement: precompiled query, query with parameters. CallableStatement: invocation of a stored PL/SQL procedure.
47

JDBC Data Types

JDBC stands in between Java (object types) and SQL (predefined types). java.sql.types defines generic SQL types which are used by JDBC: If the data types are not supported by SQL-2 then the program cannot use the returned value.
48

Handling result sets (multiple row return)


Information about columns of the result set: ResultSetMetaData <name> = <result-set>.getMetaData(); creates a ResultSetMetaData object that contains information about the result set:

49

Prepared Statements
PreparedStatement <name> = <connection>.prepareStatement(<string>); SQL statement <string> is precompiled.

thus, the statement is contained in the state of the object more efficient than (simple) Statement if it has to be executed several times.

Depending on <string>, one of the (parameterless!) methods <prepared-statement>.executeQuery() <prepared-statement>.executeUpdate() <prepared-statement>.execute() is applicable.
50

Prepared statements + parameters


Input parameters are represented by ? PreparedStatement pstmt = pstmt .setString (1, "D" ); conn.prepareStatement ResultSet rset = pstmt ("SELECT Population .ExecuteQuery (); FROM Country ... WHERE Code = ?");
pstmt .setString (1, "CH" ); ResultSet rset = pstmt (); ?-parameters are assigned to values.ExecuteQuery by

<prepared-statement>.set<type>(<pos>,<value>); before a PreparedStatement is submitted.


<type>: Java data type, <pos>: position of the parameter to be set, <value>: value.
51

Further SQL/Oracle tools

Dynamic SQL:

SQL statements are generated in in PL/SQL at runtime as strings, and are then submitted to the data base. built-in Java Virtual Machine, access to the file system i= internet: XML-interface, Web-Application-Server etc. HTML pages can be generated depending on the data base contents.

ORACLE 8i:

ORACLE-Web Server/Internet Application Server (9i):

In the most recent packages and extensions (IAS, Internet File System Server) the difference between the database and the operating system diminishes.
52

You might also like