0% found this document useful (0 votes)
40 views

C20.0046: Database Management Systems Lecture #21: M.P. Johnson Stern School of Business, NYU Spring, 2008

This document summarizes a lecture on stored procedures, triggers, transactions, and implementation in database management systems. The lecture covers the use of stored procedures in SQL and PL/SQL, how to write dynamic SQL and use it for data definition language tasks. It also discusses triggers, including the different types of trigger events, when triggers are executed, and an example of a trigger that validates employee data. The lecture concludes with live examples of stored procedures and trigger types.

Uploaded by

sai_ramuk
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)
40 views

C20.0046: Database Management Systems Lecture #21: M.P. Johnson Stern School of Business, NYU Spring, 2008

This document summarizes a lecture on stored procedures, triggers, transactions, and implementation in database management systems. The lecture covers the use of stored procedures in SQL and PL/SQL, how to write dynamic SQL and use it for data definition language tasks. It also discusses triggers, including the different types of trigger events, when triggers are executed, and an example of a trigger that validates employee data. The lecture concludes with live examples of stored procedures and trigger types.

Uploaded by

sai_ramuk
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/ 35

C20.

0046: Database
Management Systems
Lecture #21
M.P. Johnson
Stern School of Business, NYU
Spring, 2008

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 1


Agenda
 Stored procedures?
 Triggers
 Transactions
 RAID?
 Implementation?

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 2


Integration with SQL

DECLARE
DECLARE
l_book_count
l_book_countINTEGER;
INTEGER;
BEGIN
BEGIN
SELECT
SELECTCOUNT(*)
COUNT(*)
INTO
INTOl_book_count
l_book_count
FROM
FROMbooksbooks
WHERE
WHEREauthor
authorLIKE
LIKE'%FEUERSTEIN,
'%FEUERSTEIN,STEVEN%';STEVEN%';
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE((
'Steven
'Stevenhas
haswritten
written(or
(orco-written)
co-written)' '||||l_book_count
l_book_count||||
' 'books.');
books.');
END;
END;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 3


Dynamic PL/SQL
 E.g.: write function to return number rows in
an arbitrary table
CREATE
CREATEOR ORREPLACE
REPLACEFUNCTION
FUNCTIONrowCountrowCount((
tabname
tabnameIN INVARCHAR2)
VARCHAR2)return
returninteger
integer asas
retval
retvalinteger;
integer;
begin
begin
execute
executeimmediate
immediate'select
'select count(*)
count(*) from
from ' '||||tabname
tabnameinto
into
retval;
retval;
return
returnretval;
retval;
end;
end;
//

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 4


Dynamic PL/SQL for DDL
 Ordinarily can’t do DDL in PL/SQL
 But you can in dynamic PL/SQL

 Here’s an e.g.:
CREATE
CREATEOR ORREPLACE
REPLACEprocedure
procedure
dropproc(procname
dropproc(procnameininvarchar2)
varchar2) as
as
begin
begin
execute
executeimmediate
immediate'drop
'dropprocedure
procedure' '||||procname;
procname;
end;
end;
//

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 5


Live examples
 Factorial function:
 http://
pages.stern.nyu.edu/~mjohnson/dbms/plsql/fact.s
ql

 Converting between bases:


 http://pages.stern.nyu.edu/~mjohnson/dbms/plsql/
numsys.sql

 Directory of examples:
 http://pages.stern.nyu.edu/~mjohnson/dbms/plsql/
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 6
SPs in MySQL (5.0)
 Generally similar, though technical diffs
 Need to temporarily redefine ; delimiter

mysql>
mysql> drop
dropprocedure
procedureififexists
existshello;
hello;
myslq>
myslq> delimiter
delimiter//
mysql>
mysql> create
createprocedure
procedurehello()
hello()
->
->begin
begin
->
->select
select'hi';
'hi';
->
->end;
end;
->
->//
mysql>
mysql> delimiter
delimiter;;
mysql>
mysql> call
call hello();
hello();

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 7


New topic: Triggers
 PL/SQL programs that run automatically (are
“triggered”) when a certain event occurs

 E.g.: on insert to some table


 On system start-up
 On delete from table

 Big benefit: need not be called explicitly


 However row in table x is deleted, the trigger
gets called
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 8
Trigger events
 Trigger code may be “triggered” by many kinds of
events:
 Oracle start-up/shut-down
 Triggers may replace initialization scripts

 Data updates:
 Delete: maybe delete related rows
 Inserts
 Updates: maybe make other rows consistent
 Delete: maybe prevent

 DDL statements
 Log creation of all objects, e.g.

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 9


Triggers
 Constraints state what must remain true
 DBMS decides when to check
 Triggers are instructions to perform at explicitly
specified times

 Three aspects:
 An event (e.g., update to an attribute)
 A condition (e.g., a test of that update value)
 An action (the trigger’s effect) (deletion, update, insertion)
 When the event occurs, DBMS checks the
constraint, and if it is satisfied, performs the action

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 10


DML trigger options
 The trigger may be:
 Statement-level (e.g., a DELETE WHERE statement) or
 Row-level (e.g., for each row deleted)

 The trigger may run


 BEFORE
 AFTER or
 INSTEAD OF the statement (in Oracle, not in others)

 It may be triggered by
 INSERTs
 UPDATEs
 DELETEs

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 11


Trigger form
CREATE
CREATE [OR [OR REPLACE]
REPLACE] TRIGGER
TRIGGER trigger
trigger
name
name
{BEFORE
{BEFORE || AFTER AFTER || INSTEAD
INSTEAD OF}
OF}
{INSERT
{INSERT || DELETE
DELETE || UPDATE UPDATE || UPDATE
UPDATE
OF
OF column
column list}
list} ONON table
table name
name
[FOR
[FOR EACHEACH ROW] ROW]
[WHEN
[WHEN (...)](...)]
[DECLARE
[DECLARE ... ... ]]
BEGIN
BEGIN
...
... executable
executable statements
statements ...
...
[EXCEPTION
[EXCEPTION ... ... ]]
END
END [trigger
[trigger name];
name];
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 12
Trigger type examples
 First run copy_tables.sql

1. statement_vs_row.sql
 INSERT INTO to_table SELECT * FROM from_table;

2. before_vs_after.sql
 INSERT INTO to_table SELECT * FROM from_table;

3. one_trigger_per_type.sql
 INSERT INTO to_table VALUES (1);
UPDATE to_table SET col1 = 10;
DELETE to_table;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 13


DML Trigger e.g.
CREATE
CREATE OR OR REPLACE
REPLACE TRIGGER
TRIGGER
validate_employee_changes
validate_employee_changes
BEFORE
BEFORE INSERT
INSERT OROR UPDATE
UPDATE
ON
ON employee
employee
FOR
FOR EACH
EACH ROW
ROW
BEGIN
BEGIN
check_age
check_age (:NEW.date_of_birth);
(:NEW.date_of_birth);
check_resume
check_resume (:NEW.resume);
(:NEW.resume);
END;
END;
 Q: Why is this (maybe) better than client-side
validation?

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 14


Triggers with WHEN
CREATE
CREATEOR ORREPLACE
REPLACETRIGGERTRIGGERcheck_raise
check_raise
AFTER
AFTERUPDATE
UPDATEOF OFsalary,
salary,commission
commission
ON
ONemployee
employee
FOR
FOREACHEACHROW
ROW
WHEN
WHEN((OLD.salary
((OLD.salary!= != NEW.salary
NEW.salaryOROR
(OLD.salary
(OLD.salary IS
IS NULL
NULLAND ANDNEW.salary
NEW.salaryIS
ISNULL))
NULL))
OR
OR(OLD.commission
(OLD.commission!= !=NEW.commission
NEW.commissionOR OR
(OLD.commission
(OLD.commissionIS ISNULL
NULLANDANDNEW.commission
NEW.commission IS
ISNULL)))
NULL)))
BEGIN
BEGIN
...
...
END;
END;
 NB: WHEN applies only to row-level triggers
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 15
Triggers with WHEN
 Parentheses are required
 Can only call built-in functions in when
 Packages like DBMS_OUTPUT are not allowed

CREATE
CREATEOR ORREPLACE
REPLACETRIGGER
TRIGGER
valid_when_clause
valid_when_clause
BEFORE
BEFOREINSERT
INSERT ON
ONframe
frame
FOR
FOREACH
EACHROW
ROW
WHEN
WHEN((TO_CHAR(SYSDATE,'HH24')
TO_CHAR(SYSDATE,'HH24')
BETWEEN
BETWEEN99ANDAND1717 ))
...
...

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 16


Simple trigger example
 R(id, data, last-modified)
 data is a large string
 Last-modified is a newly added date field
 Goal: whenever data is modified, update last-
modified date
 Could modify all scripts/programs that touch this
table CREATE
CREATETRIGGER
TRIGGERUpdateDateTrigger
UpdateDateTrigger
 Bad idea AFTER
AFTERUPDATE
UPDATEOFOFdata
dataON
ONRR
REFERENCING
REFERENCING
 Better: user a trigger NEW
NEWROW
ROWAS ASNewTuple
NewTuple
FOR
FOREACH
EACHROW
ROW
BEGIN
BEGIN
NewTuple.last-modified
NewTuple.last-modified==sysdate;
sysdate;
END;
END;
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 17
Multiple DML actions
 DML actions may be ORed together
CREATE
CREATE OR
OR REPLACE
REPLACE TRIGGER
TRIGGER
 To find actual three_for_the_price_of_one
three_for_the_price_of_one
action, check: BEFORE
BEFOREDELETE DELETEOR ORINSERT
INSERTOR
OR
 INSERTING
UPDATE
UPDATEON ONaccount_transaction
account_transaction
FOR
FOREACH EACHROW ROW
 DELETING
BEGIN
BEGIN
 UPDATING IFIFINSERTING
INSERTING
THEN
THEN
:NEW.created_by
:NEW.created_by:= :=USER;
USER;
:NEW.created_date
:NEW.created_date:= :=SYSDATE;
SYSDATE;
ELSIF
ELSIFDELETING
DELETING
THEN
THEN
audit_deletion(USER,SYSDATE);
audit_deletion(USER,SYSDATE);
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 18
END;
END;
More on UPDATING
 UPDATING may be called for partic. columns
CREATE
CREATEOR ORREPLACE
REPLACETRIGGER
TRIGGERvalidate_update
validate_update
BEFORE
BEFOREUPDATEUPDATEON ONaccount_transaction
account_transaction
FOR
FOREACHEACHROWROW
BEGIN
BEGIN
IF
IFUPDATING
UPDATING ('ACCOUNT_NO')
('ACCOUNT_NO')
THEN
THEN
errpkg.raise('Account
errpkg.raise('Accountnumber
numbercannot
cannot be
beupdated');
updated');
END
ENDIF;IF;
END;
END;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 19


Extended auditing example
 Tables: grades, grades_audit
 Run: grades_tables.sql, grades_audit.sql
 Cases: hacker changes grades, deletes
others UPDATE
UPDATEgrades
grades
SET
SETgrade
grade=='A+'
'A+'
WHERE
WHEREstudent_id
student_id==11
AND
ANDclass_id
class_id== 101;
101;

DELETE
DELETEgrades
grades
WHERE
WHEREstudent_id
student_id==22
AND
ANDclass_id
class_id== 101;
101;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 20


Extended auditing example
 Run: grades_tables.sql, grades_audit2.sql
 Cases: hacker changes student or class ids
UPDATE
UPDATEgrades
gradesSET
SET student_id
student_id== 33
WHERE
WHEREstudent_id
student_id==11AND
ANDclass_id
class_id==101;
101;

UPDATE
UPDATEgrades
gradesSET
SET student_id
student_id== 11
WHERE
WHEREstudent_id
student_id==22AND
ANDclass_id
class_id==101;
101;

UPDATE
UPDATEgrades
gradesSET
SET student_id
student_id== 22
WHERE
WHEREstudent_id
student_id==33AND
ANDclass_id
class_id==101;
101;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 21


DDL Triggers
 Respond to DDL events
 Creating/dropping tables, indices, etc.
 ALTER TABLE etc.
 General form:
CREATE
CREATE[OR [ORREPLACE]
REPLACE]TRIGGER
TRIGGERtrigger
trigger name
name
{BEFORE
{BEFORE||AFTER|
AFTER| {DDL
{DDLevent}
event} ON
ON
{DATABASE
{DATABASE|| SCHEMA}
SCHEMA}
DECLARE
DECLARE
Variable
Variabledeclarations
declarations
BEGIN
BEGIN
...
... some
somecode...
code...
END;
END;
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 22
DDL trigger e.g.
 Town crier examples triggered by creates:

 uninformed_town_crier.sql

 informed_town_crier.sql

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 23


Available DDL events
 CREATE, ALTER, DROP, GRANT, RENAME,
REVOKE, TRUNCATE
 DDL: any DDL event no_create.sql
CREATE
CREATEOR ORREPLACE
REPLACETRIGGER
TRIGGERno_create
no_create
AFTER
AFTERCREATE
CREATEON ONSCHEMA
SCHEMA
BEGIN
BEGIN
RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR(-20000,
(-20000,
'ERROR
'ERROR::Objects
Objectscannot
cannotbe
becreated
createdin
inthe
the
production
productiondatabase.');
database.');
END;
END;
 Q: Does this work??
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 24
DB Event triggers
 Form similar to DDL triggers:
CREATE
CREATE[OR [ORREPLACE]
REPLACE]TRIGGER
TRIGGERtrigger
trigger name
name
{BEFORE
{BEFORE||AFTER}
AFTER} {database
{database event}
event} ONON
{DATABASE
{DATABASE|| SCHEMA}
SCHEMA}
DECLARE
DECLARE
Variable
Variabledeclarations
declarations
BEGIN
BEGIN
...
... some
somecode...
code...
END;
END;
 Triggering events: STARTUP, SHUTDOWN,
SERVERERROR, LOGON, LOGOFF
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 25
DB event restrictions
 Have BEFORE and AFTER as above, but they
don’t always apply:

 No BEFORE STARTUP/LOGON/SERVERERROR

 No AFTER SHUTDOWN/LOGOFF

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 26


DB Trigger e.g.
 Gather stats before shutdown:
CREATE
CREATEOR ORREPLACE
REPLACETRIGGER
TRIGGERon_shutdown
on_shutdown
BEFORE
BEFORESHUTDOWN
SHUTDOWNON ONDATABASE
DATABASE
BEGIN
BEGIN
gather_system_stats;
gather_system_stats;
END;
END;

 Log error messages

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 27


New-old topic: Transactions
 So far, have simply issued commands
 Ignored xacts

 Recall, though: an xact is an operation/set of


ops executed atomically
 In one instant
 ACID test:
 Xacts are atomic
 Each xact (not each statement) must leave the DB
consistent
M.P. Johnson, DBMS, Stern/NYU, Spring 2008 28
Default xact behavior (in Oracle)
 An xact begins upon login
 By default, xact lasts until logoff
 Except for DDL statements
 They automatically commit

 Examples with two views of tbl…


 But with TYPE=innodb !
 mysql> set autocommit = 0

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 29


Direct xact instructions
 At any point, may explicitly COMMIT:
 SQL> COMMIT;
 Saves all statements entered up to now
 Begins new xact

 Conversely, can ROLLBACK


 SQL> ROLLBACK;
 Cancels all statements entered since start of xact

 Example: delete from emp; or delete junk;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 30


Direct xact instructions
 Remember, DDL statements are auto-
committed
  They cannot be rollbacked

drop
drop table
table junk;
junk;
 Examples: rollback;
rollback;
truncate
truncate table
table junk;
junk;
rollback;
rollback;

 Q: Why doesn’t rollback “work”?


M.P. Johnson, DBMS, Stern/NYU, Spring 2008 31
Savepoints
 Xacts are atomic
 Can rollback to beginning of current xact

 But might want to rollback only part way

 Make 10 changes, make one bad change


 Want to: roll back to before last change

 Don’t have Word-like multiple undo


 But do have savepoints

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 32


Savepoints
 Create a savepoint: SAVEPOINT
SAVEPOINT savept_name;
savept_name;

--changes
 emp example: --changes
SAVEPOINT
SAVEPOINT sp1;
sp1;
--changes
 Can skip savepoints --changes
SAVEPOINT
SAVEPOINT sp2;
sp2;
 But can ROLLBACK --changes
--changes
only backwards SAVEPOINT
SAVEPOINT sp3
sp3
 Can ROLLBACK --changes
--changes
only to last COMMIT ROLLBACK
ROLLBACK TO
TO SAVEPOINT
SAVEPOINT sp2;
sp2;
ROLLBACK
ROLLBACK TO
TO SAVEPOINT
SAVEPOINT sp1;
sp1;

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 33


AUTOCOMMIT
 Finally, can turn AUTOCOMMIT on:
 Oralce: SQL> SET AUTOCOMMIT ON;
 Mysql: mysql> SET AUTOCOMMIT=1;
 Can put this in your config file
 Can specify through JDBC, etc.

 Then each statement is auto-committed as its


own xact
 Not just DDL statements

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 34


RAID levels
 RAID level 1: each disk gets a mirror
 RAID level 4: one disk is xor of all others
 Each bit is sum mod 2 of corresponding bits
 E.g.:
 Disk 1: 10110011
 Disk 2: 10101010
 Disk 3: 00111000
 Disk 4:

 How to recover?

 What’s the disadvantage of R4?


 Various other RAID levels in text…

M.P. Johnson, DBMS, Stern/NYU, Spring 2008 35

You might also like