Week 5
Week 5
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
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.
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
Condition is checked
e.g. Is batch complete? Has student passed?
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
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
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
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;
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
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
table_name.
12
increase_salary_trg BEFORE executing the statement UPDATE of sal column emp table INSERT values INTO sal_hist table
13
14
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
17
Each time a table is accessed, auditing information is recorded against it. Each time a record value is changed the previous value is recorded.
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
continuation
MAX_INS 5 5 MAX_UPD 5 5 0 MAX_DEL 5 0
19
12-SEP-04
10-AUG-04
continuation
OLD_TITL E NULL CLERK NEW_TITLE OLD_SALARY NULL ANALYST SALESMAN 1100 NEW_SALARY 3500 1100
21
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
23
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
ERROR at line 1: ORA-04091: table CGMA2.EMP is mutating, trigger/ function may not see it
25
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
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
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
Structure of the host language remains unchanged Every SQL statement can be embedded
simply prefixed by EXEC SQL
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:
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
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 */
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.
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
<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
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: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');
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
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
<type>: Java data type, <pos>: position of the parameter to be set, <value>: value.
51
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:
In the most recent packages and extensions (IAS, Internet File System Server) the difference between the database and the operating system diminishes.
52