Download presentation
Presentation is loading. Please wait.
1
CSC 453 Database Systems Lecture
Tanu Malik College of CDM DePaul University
2
Transactions Motivated by two independent requirements
Concurrent database access Resilience to system failures
3
Transactions Concurrent Access: Attribute-level Inconsistency
Select enrollment from College Where cName = ‘DePaul’ Update College Set enrollment = enrollment Where cName = ‘DePaul’ concurrent with … C2 Select enrollment from College Where cName = ‘DePaul’ Update College Set enrollment = enrollment Where cName = ‘DePaul’
4
Transactions Transactions Solution for both concurrency and failures
A transaction is a sequence of one or more SQL operations treated as a unit Transactions appear to run in isolation If the system fails, each transaction’s changes are reflected either entirely or not at all Transactions
5
Transactions SQL standard:
Transaction begins with a Begin Transaction statement On “commit” transaction ends and new one begins Current transaction ends on session termination “Autocommit” turns each statement into transaction
6
Transactions A Atomicity all-or-nothing 3
Every time a DBMS encounters a begin transaction—commit block, the DBMS software guarantees the following ACID Properties Meaning Order A Atomicity all-or-nothing 3 C Consistency consistent DB state 4 I Isolation appear to act in isolation 1 D Durability commits are persistent 2
7
Internal Representation of SQL statements
Create Table X ( x int, y int , check (y = x) ) Select x from X Read(x) Select * from X Read(x);Read(Y) Insert into X values (5,5) Write(x);Write(y) Insert into X values (6,6) Write(x);Write(y) Update X set x = x*2 Read(x);Write(x) Update X set y = y*2 Read(y);Write(y)
8
SQL Statements Concurrent Access: Attribute-level Inconsistency
Select enrollment from College Where cName = ‘DePaul’ Update College Set enrollment = enrollment Where cName = ‘DePaul’ concurrent with … Select enrollment from College Where cName = ‘DePaul’ Update College Set enrollment = enrollment Where cName = ‘DePaul’
9
Transactions: Internal Representation of SQL statements
READ(enrollment, cName) WRITE(enrollment) concurrent with … C2 READ(enrollment, cName) WRITE(enrollment)
10
Read/Write Temporary variables are visible only within a transaction
Read implies read into memory from disk Subsequent reads (across all transactions) are from memory Write implies write into memory (across all txns) Often an attribute is written from a temporary variable Temporary variables are visible only within a transaction Commit implies flush to disk
11
Transactions: Durability
Begin Transaction READ(enrollment, cName) enrollment gets updated here WRITE(enrollment) Commit concurrent with … C2 Begin Transaction READ(enrollment, cName) WRITE(enrollment) Commit
12
Transactions: Atomicity
(all or nothing) Begin Transaction READ(enrollment, cName) enrollment gets updated here WRITE(enrollment) Commit
13
Transactions: Consistency
Create Table X ( x int, y int , check (y = x) ) Insert into X values (5,5) W(x);W(y) Insert into X values (6,6) W(x);W(y) Select x from X R(x) Select * from X R(x);R(Y) Update X set x = x*2 R(x);W(x) Update X set y = y*2 R(y);W(y)
14
Transactions: Consistency
Create Table X ( x int, y int , check (y >= x) ) Insert into X values (5,5); W(x);W(y) Insert into X values (6,6); W(x);W(y) Select x from X R(x) Select * from X R(x);R(Y) Update X set y = x+y; Update X set x = x+y;
15
Transactions Transaction Rollback (= Abort)
Undoes partial effects of transaction Can be system- or client-initiated Each transaction is “all-or-nothing,” never left half done Begin Transaction; <get input from user> SQL commands based on input <confirm results with user> If ans=‘ok’ Then Commit; Else Rollback;
16
Transactions . . . DBMS (ACID Properties) Isolation Serializability
Serializability Operations may be interleaved, but execution must be equivalent to some sequential (serial) order of all transactions DBMS Data
17
Serializability Basic Assumption– Each transaction preserves database consistency. Thus, serial execution of a set of transactions preserves database consistency. A (possibly concurrent) schedule is serializable if it is equivalent to a serial schedule.
18
Schedules Schedules– a sequences of instructions that specify the chronological order in which instructions of concurrent transactions are executed A schedule for a set of transactions must consist of all instructions of those transactions Must preserve the order in which the instructions appear in each individual transaction. A transaction that successfully completes its execution will have a commit instructions as the last statement A transaction that fails to successfully complete its execution will have an abort instruction as the last statement
19
Schedule 1 Let T1 transfer $50 from A to B, and T2 transfer 10% of the balance from A to B. An example of a serial schedule in which T1 is followed by T2 :
20
Schedule 2 A serial schedule in which T2 is followed by T1 :
21
Schedule 3 Let T1 and T2 be the transactions defined previously. The following schedule is not a serial schedule, but it is equivalent to Schedule 1. commit Note -- In schedules 1, 2 and 3, the sum “A + B” is preserved.
22
Schedule 4 The following concurrent schedule does not preserve the sum of “A + B” commit
23
Transactions Overhead Concurrency Consistency Guarantees . . .
(ACID Properties) Isolation Weaker “Isolation Levels” Read Uncommitted Read Committed Repeatable Read Strongest “Isolation Levels” Serilizable order DBMS Overhead Concurrency Data Consistency Guarantees
24
Transactions Set Transaction Isolation Level Read Uncommitted
Begin Transaction Select GPA from Student Where sizeHS > 2500 Update Student Set GPA = (1.1) GPA Where sizeHS > 2500 Commit concurrent with … Set Transaction Isolation Level Repeatable Read Begin Transaction Select Avg(GPA) From Student Commit
25
Transactions . . . Isolation Levels DBMS Per transaction
“In the eye of the beholder” Affect applies to read statements My transaction is Read Uncommitted My transaction is Repeatable Read DBMS Data
26
Transactions Dirty Reads
“Dirty” data item: written by an uncommitted transaction Select enrollment from College Where cName = ‘DePaul’ Update College Set enrollment = enrollment Where cName = ‘DePaul’ concurrent with … Enrollment is dirty over here. It is updated by the update stmt, but not committed by the txn. Select Avg(enrollment) From College
27
Transactions Dirty Reads
“Dirty” data item: written by an uncommitted transaction Update Student Set GPA = (1.1) GPA Where sizeHS > 2500 concurrent with … Select GPA From Student Where sID = 123 concurrent with … Update Student Set sizeHS = 2600 Where sID = 234
28
Transactions Isolation Level Read Uncommitted
A transaction may perform dirty reads Select GPA from Student Where sizeHS > 2500 Update Student Set GPA = (1.1) GPA Where sizeHS > 2500 concurrent with … Set Transaction Isolation Level Read Uncommitted; Select Avg(GPA) From Student;
29
Transactions Isolation Level Read Committed
A transaction will not perform dirty reads Only reads commited values of other transactions Still does not guarantee global serializability Select GPA From Student Where sizeHS > 2500 Update Student Set GPA = (1.1) GPA Where sizeHS > 2500 concurrent with … Set Transaction Isolation Level Read Committed; Select Avg(GPA) From Student; Select Max(GPA) From Student;
30
Transactions Isolation Level Repeatable Read
A transaction may not perform dirty reads An item read multiple times cannot change value Still does not guarantee global serializability Update Student Set GPA = (1.1) GPA; Update Student Set sizeHS = 1500 Where sID = 123; concurrent with … Set Transaction Isolation Level Repeatable Read; Select Avg(GPA) From Student; Select Avg(sizeHS) From Student;
31
Transactions Isolation Level Repeatable Read
A transaction may not perform dirty reads An item read multiple times cannot change value But a relation can change: “phantom” tuples Insert Into Student [ 100 new tuples ] concurrent with … Set Transaction Isolation Level Repeatable Read; Select Avg(GPA) From Student; Select Max(GPA) From Student;
32
Transactions Isolation Level Repeatable Read
A transaction may not perform dirty reads An item read multiple times cannot change value But a relation can change: “phantom” tuples Delete From Student [ 100 tuples ] concurrent with … Set Transaction Isolation Level Repeatable Read; Select Avg(GPA) From Student; Select Max(GPA) From Student;
33
Transactions Read Only transactions Helps system optimize performance
Independent of isolation level Set Transaction Read Only; Set Transaction Isolation Level Repeatable Read; Select Avg(GPA) From Student; Select Max(GPA) From Student;
34
Transactions Serializable Strongest isolation level SQL Default
Read Uncommitted A data item is dirty if it is written by an uncommitted transaction. Problem of reading dirty data written by another uncommitted transaction: what if that transaction eventually aborts?
35
Transactions Read Committed
Cannot read dirty data written by other uncommitted transactions. But read-committed is still not necessarily serializable Repeatable Read If a tuple is read once, then the same tuple must be retrieved again if query is repeated. Still not serilizable; may see phantom tuples—tuples inserted by other concurrent transactions.
36
Transactions Isolation Levels: Summary dirty reads nonrepeatable reads
phantoms Read Uncommitted Read Committed Repeatable Read Serializable
37
Transactions Isolation Levels: Summary Weaker isolation levels
Standard default: Serializable Weaker isolation levels Increased concurrency + decreased overhead = increased performance Weaker consistency guarantees Some systems have default Repeatable Read Isolation level per transaction and “eye of the beholder” Each transaction’s reads must conform to its isolation level
38
Example Consider a relation R(A) containing {(5),(6)} and two transactions: T1: Update R set A = A+1; T2: Update R set A = 2*A. Suppose both transactions are submitted under the isolation and atomicity properties. Which of the following is NOT a possible final state of R? (10,12);(11,13);(11,12);(12,14)
39
Example Consider a table R(A) containing {(1),(2)} and two transactions: T1: Update R set A = 2*A; T2: Select avg(A) from R. If transaction T2 executes using "read uncommitted", what are the possible values it returns?
40
Example Consider tables R(A) and S(B), both containing {(1),(2)}.
T1: Update R set A = 2*A; update S set B = 2*B T2: Select avg(A) from R; select avg(B) from S. If transaction T2 executes using "read committed", is it possible for T2 to return two different values?
41
Example 5 Consider table R(A) containing {(1),(2)}.
T1:Update T set A=2*A; insert into R values (6); T2: Select avg(A) from R; select avg(A) from R; If transaction T2 executes using "repeatable read", what are the possible values returned by its SECOND statement?
43
PL/SQL A general-purpose procedural programming that includes SQL commands PL/SQL can create and issue SQL statements store and process the results of queries define procedures to respond to database events
44
Basic Structure of Code
Simplest form is an anonymous block: declare -- variable and subprogram declarations -- every statement must end with a ; begin -- PL/SQL statements to execute --every statement must end with a ; --statements can be nested with another B/E exception -- exception handling (optional) end;
45
Output To display output: RAISE NOTICE ‘string %’, arguments;
Output buffer displayed in DBMS Output tab Use View Dbms Output and ‘+’ to open tab Single line comments with – Multi-line with /* */
46
Data Types Numeric Character Boolean Datetime
Data types are not case sensitive DECLARE num1 INTEGER; num2 REAL; num3 DOUBLE PRECISION; BEGIN null; END; /
47
Declaring Variables All variables must be declared:
varName [CONSTANT] dataType [NOT NULL] [:= initialValue]; Assignments use :=, and PL/SQL has typical arithmetic operations
48
Scoping DECLARE BEGIN / -- Global variables num1 number := 95;
dbms_output.put_line('Outer Variable num1: ' || num1); dbms_output.put_line('Outer Variable num2: ' || num2); -- Local variables num1 number := 195; num2 number := 185; dbms_output.put_line('Inner Variable num1: ' || num1); dbms_output.put_line('Inner Variable num2: ' || num2); END; /
49
Declaring Variables Only one variable can be declared per line, but variable types can be given in terms of the domain of another variable or attribute: varName otherVar%type; varName TABLE.Attribute%type;
50
Operators Arithmetic operators Relational operators
Comparison operators LIKE, BETWEEN, IN, IS NULL Logical operators String operators
51
Branching if-then: if condition then
…’true’ statements… end if; if-else: if condition then …’true’ statements… else …’false’ statements… end if;
52
Branching if-elsif: if condition1 then … ‘true’ statements… elsif condition2 then … ‘false-true’ statements… elsif condition3 then … ‘false-false-true’ statements… (… as many times as needed…) else … ‘all false’ statements… end if;
53
Case Statement CASE [ expression ] WHEN condition_1 THEN result_1
... WHEN condition_n THEN result_n ELSE result END
54
Case Statement expression condition_1, condition_2, ... condition_n
Optional. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n) condition_1, condition_2, ... condition_n The conditions that must all be the same datatype. The conditions are evaluated in the order listed. Once a condition is found to be true, the CASE statement will return the result and not evaluate the conditions any further. result_1, result_2, ... result_n Results that must all be the same datatype. This is the value returned once a condition is found to be true.
55
Case Statement If no condition is found to be true, then the CASE statement will return the value in the ELSE clause. If the ELSE clause is omitted and no condition is found to be true, then the CASE statement will return NULL.
56
Case Statement -- Multiple if-then-else better expressed by CASE DECLARE grade CHAR(1); BEGIN grade := 'B'; CASE grade WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent'); WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good'); WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good'); WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair'); WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor'); ELSE DBMS_OUTPUT.PUT_LINE('No such grade'); END CASE; END; /
57
Loops General loop: loop …loop body… end loop;
Repeats until exit; is executed in loop body While loop: while condition loop …loop body… end loop; Repeats until condition is false
58
Loops For loop: for variable in [reverse] lower..upper loop …loop body… end loop; Can only increment/decrement by one lower always appears before upper in header
59
Incorporating SQL Queries
Result of a query can be stored in a set of variables by adding INTO clause to query: SELECT list of attributes INTO list of variables FROM list of tables … Variable types must match attribute types
60
Procedures (In Oracle)
CREATE [OR REPLACE] PROCEDURE name (paramName IN [OUT] paramType …) AS …declarations… BEGIN …body of procedure… END; / ‘IN’ parameters are passed by value, for input only, read-only parameters ‘OUT’ parameters are passed by reference ‘IN OUT’ parameters are passed by reference, to return results to the calling sub-program
61
Functions CREATE [OR REPLACE] FUNCTION mode {IN|OUT|INOUT} name …) RETURNS returnType AS $$ …declarations… BEGIN …body of function… return returnValue; END; $$ language plpgsql; ‘IN’ parameters are default Specify return type and return value instead
62
Executing Procedures and Functions
A standalone procedure Using the EXECUTE keyword Calling the name of the procedure from a PL/SQL block A standalone function Calling the name of the function from a PL/SQL block Calling the name of the function in a SQL query
63
Cursors A cursor represents a pointer into a set of records returned by a query declare name cursor for query; cursor name can be used to iterate through the records returned by query
64
Cursor Commands/Expressions
open name; -- initializes to beginning of set fetch name into variableList; -- reads the next record into the variables close name; -- closes the cursor
65
Parameterized Cursors
Can supply a parameter in cursor declaration and query declare name (parameter in type) cursor for query; Each time cursor is opened, value of parameter is specified in parentheses to complete the query
66
Implicit Cursors for DML statements
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. INSERT operations: the cursor holds the data that needs to be inserted. UPDATE and DELETE operations: the cursor identifies the rows that would be affected.
67
Records Data structure to hold data items of different kinds
Table-based Records: Can create a record with same structure as the row of a table (fields are table attributes): recordName TABLE%rowtype; Can select a row of a table directly into a record, and access individual fields with recordName.Attribute
68
Records Cursor-based records: Assign rowtype from a query in cursor
User-defined Records: Declare a new data type and a table of records: create type newType ( attr1 datatype, attr2 datatype )
69
Exceptions DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling goes here > WHEN exception1 THEN exception1-handling-statements WHEN exception2 THEN exception2-handling-statements WHEN exception3 THEN exception3-handling-statements WHEN others THEN exception3-handling-statements END;
70
Case Statement SELECT LastName, FirstName,
(CASE Career WHEN 'UGRD' THEN 'Undergraduate' WHEN 'GRD' THEN 'Graduate' WHEN ' SAL' THEN 'Student At Large' END) AS Career FROM student; UPDATE employee SET salary = (CASE WHEN salary < THEN 50000 WHEN salary < THEN salary * 1.05 ELSE salary * 1.1 END);
71
Database Active Elements
Checks Assertions Triggers
72
Why Active Elements Other wise application programs have to include checks with every DML statement to preserve data integrity. Better to store checks in DBMS and let DBMS administer the checks.
73
Check User-defined, verified when a tuple is added or updated
Attribute-level: CHECK within an attribute, can only involve that attribute Verified when a tuple is inserted/updated in that attribute Tuple-level: A separate CONSTRAINT, can involve any attributes Verified when a tuple is inserted/updated in any attribute
74
Attribute-level Check
create table enrolled ( StudentID number(5), CourseID number(4), Quarter varchar(6) CHECK(quarter in ('Fall','Winter','Spring')), Year number(4), … create table memberof ( GroupName varchar(40), Joined number(4) CHECK(Joined >= (SELECT Started FROM student WHERE studentID = SID)), ... has to be true (compare WHERE)
attribute checks get evaluated when an attribute is modified i.e. when row is inserted/updated
subqueries not allowed in Oracle checks
75
Tuple-level CHECK create table course ( CID number(4), CourseName varchar(40), Department varchar(4), CourseNr char(3), primary key (CID), check (department <> 'CSC' OR CourseNR > 100) ); same as attribute level check, just involves any number of attributes and different placement
76
Assertion Boolean value SQL expression that is true at all times
Hard to implement CREATE ASSERTION joined CHECK (NOT EXISTS (SELECT * FROM student, memberof WHERE SID = StudentID and Joined < Started)); not supported by anybody
can be mimicked using materialized views and/or triggers
77
Triggers Triggers allow general responses to changes in the database state: Enforcement of business rules Notification of events Maintenance of derived information Maintenance of replicated data Implementation of cross-table constraints
78
Event-Condition-Action Model
An event causes the trigger to fire Before or after an insertion, deletion, or update A condition is tested to see whether or not the trigger will respond (optional…) May depend on original state or modified state An action may be executed in response May be sequence of SQL statements or some stored procedure
79
Oracle Trigger Syntax CREATE [OR REPLACE] TRIGGER Name BEFORE/AFTER INSERT/DELETE/UPDATE [OF Attribute] ON Table [REFERENCING OLD AS OldName NEW AS NewName] [FOR EACH ROW] WHEN (condition) BEGIN …PL/SQL statements or stored procedure… END; /
80
Oracle Trigger Syntax BEFORE/AFTER
Indicates whether queries on TABLE will be performed on the original state of the table, or the modified state INSERT/DELETE/UPDATE [OF Attribute] ON TABLE Indicates what operation(s) will cause the trigger to fire
81
Oracle Trigger Syntax REFERENCING OLD AS OldName, NEW AS NewName
Re-names old and new row states (only allowed if trigger is row-level…) FOR EACH ROW If included, the trigger fires once for each row that is modified (row-level); if not, the trigger fires just once for the entire table (statement-level)
82
Oracle Trigger Syntax WHEN (condition) PL/SQL statements
Condition tested to see if the trigger action will actually execute – can refer to new and old row states PL/SQL statements The code that is executed when trigger fires and condition is satisfied; may call other stored procedures/functions
83
Trigger Restrictions new and old can only refer to row states, so they can only be used for row-level triggers Use new and old in WHEN condition, :new and :old elsewhere Subqueries are not allowed in WHEN PL/SQL block in a row-level trigger cannot query or modify the table that triggered the action
84
BEFORE vs AFTER Order of trigger execution
All BEFORE execute in arbitrary order …but before all AFTER triggers Cannot modify :new values after UPDATE/INSERT
85
Triggers for Other Events
Trigger attached to DDL commands E.g., BEFORE/AFTER DROP ON username.SCHEMA Trigger attached to Views INSTEAD OF INSERT ON [View] Allows updates where they cannot be done automatically Triggers attached to other events CREATE TRIGGER log_errors AFTER SERVERERROR ON DATABASE
86
Triggers CREATE OR REPLACE TRIGGER started
BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; / SET SERVEROUTPUT ON; UPDATE student SET Started = 2001; SELECT * FROM student;
87
Triggers Create trigger CREATE OR REPLACE TRIGGER started
BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; / triggering event attribute/table row trigger trigger restriction old: row before update new: row after update trigger action (in PL/SQL)
88
Triggering Events When do we trigger: before after instead of
CREATE OR REPLACE TRIGGER started BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; / When do we trigger: before after instead of (only for views) What is doing the triggering: insert, update, delete system events
89
row/statement trigger
WHEN only for row-level triggers CREATE OR REPLACE TRIGGER started BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; / :new/:old only for row-level triggers vs CREATE OR REPLACE TRIGGER started AFTER UPDATE ON student BEGIN DBMS_OUTPUT.PUT_LINE(Student Table updated'); END; /
90
Restriction (WHEN) old (before change) new (after change)
CREATE OR REPLACE TRIGGER started BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; / old (before change) new (after change)
91
Trigger Action BEGIN pl/sql block END; / :old, :new variables
dbms_output CREATE OR REPLACE TRIGGER started BEFORE UPDATE OF started ON student FOR EACH ROW WHEN (new.started < old.started) BEGIN :new.started := :old.started; DBMS_OUTPUT.PUT_LINE('Rejected change of started'); END; /
92
Trigger Restrictions new and old can only refer to row states, so they can only be used for row-level triggers Use new and old in WHEN condition, :new and :old elsewhere Subqueries are not allowed in WHEN PL/SQL block in a row-level trigger cannot query or modify the table that triggered the action
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.