Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 7 Database Integrity.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
1 Lecture 11: Transactions: Concurrency. 2 Overview Transactions Concurrency Control Locking Transactions in SQL.
Transaction Management: Concurrency Control CS634 Class 17, Apr 7, 2014 Slides based on “Database Management Systems” 3 rd ed, Ramakrishnan and Gehrke.
Transaction Processing. Objectives After completing this lesson, you should be able to do the following: –Define transactions effectively for an application.
What is a Transaction? A transaction is a logical logic of work A transaction may have one of two outcomes –When a transaction completes successfully,
Allowing Multi-user Access Grant – GRANT ON TO |WITH GRANT OPTION | –GRANT TO | WITH ADMIN OPTION| – can be PUBLIC or a role – can be ALL Revoke – REVOKE.
Data and Database Administration Chapter 12. Outline What is Concurrency Control? Background Serializability  Locking mechanisms.
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 7 Database Integrity.
Chapter 4B: More Advanced PL/SQL Programming
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
Chapter 8 : Transaction Management. u Function and importance of transactions. u Properties of transactions. u Concurrency Control – Meaning of serializability.
9 Copyright © 2009, Oracle. All rights reserved. Managing Data Concurrency.
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
Transaction Management WXES 2103 Database. Content What is transaction Transaction properties Transaction management with SQL Transaction log DBMS Transaction.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
INTRODUCTION TO TRANSACTION PROCESSING CHAPTER 21 (6/E) CHAPTER 17 (5/E)
Chapter 7 Database Integrity and Transactions Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of.
1 IT420: Database Management and Organization Transactions 31 March 2006 Adina Crăiniceanu
Jerry Post Copyright © 2013 DATABASE Database Management Systems Chapter 7 Database Integrity and Transactions 1.
4 Copyright © 2004, Oracle. All rights reserved. Database Interfaces.
Triggers and Transactions Making Decisions behind the scene.
DBSQL 7-1 Copyright © Genetic Computer School 2009 Chapter 7 Transaction Management, Database Security and Recovery.
Multi-user Database Processing Architectures Architectures Transactions Transactions Security Security Administration Administration.
1 Transactions BUAD/American University Transactions.
Allowing Multi-user Access Grant – GRANT ON TO – |WITH GRANT OPTION / WITH ADMIN OPTION| – can be PUBLIC or a role – can be all Revoke – REVOKE ON FROM.
1099 Why Use InterBase? Bill Todd The Database Group, Inc.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
1 All Powder Board and Ski Oracle 9i Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2003.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Transaction processing Book, chapter 6.6. Problem: With a single user…. you run a query, you get the results, you run the next, etc. But database life.
9 Copyright © 2007, Oracle. All rights reserved. Managing Data and Concurrency.
Chapter 15 Recovery. Topics in this Chapter Transactions Transaction Recovery System Recovery Media Recovery Two-Phase Commit SQL Facilities.
School of Computer & Communication of LNPU 辽宁石油化工大学计算机与通信工程学院 刘旸 1 数据库管理系统 Database Management Systems Chapter 7 Database Integrity and Transactions 第七章.
Triggers. Why Triggers ? Suppose a warehouse wishes to maintain a minimum inventory of each item. Number of items kept in items table Items(name, number,...)
8 Copyright © 2005, Oracle. All rights reserved. Managing Data.
INFO1408 Database Design Concepts Week 16: Introduction to Database Management Systems Continued.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
The Relational Model1 Transaction Processing Units of Work.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
MBA 664 Database Management Dave Salisbury ( )
Giovanni Chierico | May 2012 | Дубна Data Concurrency, Consistency and Integrity.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
CSC 240 (Blum)1 Database Transactions. CSC 240 (Blum)2 Transaction  A transaction is an interaction between a user (or application) and a database. A.
Transactions.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Transactions, Roles & Privileges Oracle and ANSI Standard SQL Lecture 11.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Module 11: Managing Transactions and Locks
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
©Bob Godfrey, 2002, 2005 Lecture 17: Transaction Integrity and Concurrency BSA206 Database Management Systems.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
© Copyright EnterpriseDB Corporation, All Rights Reserved.1 Isolation Levels in PostgreSQL Kevin Grittner | | PgConf.Russia 2016.
COMP 430 Intro. to Database Systems Transactions, concurrency, & ACID.
SYSTEMS IMPLEMENTATION TECHNIQUES TRANSACTION PROCESSING DATABASE RECOVERY DATABASE SECURITY CONCURRENCY CONTROL.
User-defined functions, Procedures, Triggers and Transactions
DB Integrity & Transactions Part 1
DB Integrity & Transactions Part 2
Transactions Properties.
Ch 21: Transaction Processing
Introduction of Week 13 Return assignment 11-1 and 3-1-5
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Transactions and Concurrency
Database Management Systems
Prof. Arfaoui. COM390 Chapter 9
DB Concurrency ITEC 340 Database I Dr. Ian Barland
Presentation transcript:

Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 7 Database Integrity and Transactions

DATABASE 2 User-Defined Function CREATE FUNCTION EstimateCosts (ListPrice Currency, ItemCategory VarChar) RETURNS Currency BEGIN IF (ItemCategory = ‘Clothing’) THEN RETURN ListPrice * 0.5 ELSE RETURN ListPrice * 0.75 END IF END

DATABASE 3 Function to Perform Conditional Update CREATE FUNCTION IncreaseSalary (EmpID INTEGER, Amt CURRENCY) RETURNS CURRENCY BEGIN IF (Amt > 50000) THEN RETURN -1-- error flag END UPDATE Employee SET Salary = Salary + Amt WHERE EmployeeID = EmpID; RETURN Amt END

DATABASE 4 Looking Up Data CREATE FUNCTION IncreaseSalary (EmpID INTEGER, Amt CURRENCY) RETURNS CURRENCY DECLARE CURRENCY MaxAmount; BEGIN SELECT MaxRaise INTO MaxAmount FROM CompanyLimits WHERE LimitName = ‘Raise’; IF (Amt > 50000) THEN RETURN -1-- error flag END UPDATE Employee SET Salary = Salary + Amt WHERE EmployeeID = EmpID; RETURN Amt; END

DATABASE 5 Data Trigger Events  Oracle additions:  TablesALTER, CREATE, DROP  UserLOGOFF, LOGON  DatabaseSERVERERROR, SHUTDOWN, STARTUP INSERT DELETE UPDATE BEFOREAFTER

DATABASE 6 Statement v. Row Triggers UPDATE Employee SET Salary = Salary WHERE EmployeeID=442 OR EmployeeID=558 SQL time Before Update On table After Update On table Before Update Row 442 After Update Row 442 Update Row 442 … other rows Triggers for overall table Triggers for each row

DATABASE 7 Data Trigger Example CREATE TRIGGER LogSalaryChanges AFTER UPDATE OF Salary ON Employee REFERENCINGOLD ROW as oldrow NEW ROW AS newrow FOR EACH ROW INSERT INTO SalaryChanges (EmpID, ChangeDate, User, OldValue, NewValue) VALUES (newrow.EmployeeID, CURRENT_TIMESTAMP, CURRENT_USER, oldrow.Salary, newrow.Salary);

DATABASE 8 Canceling Data Changes in Triggers CREATE TRIGGER TestDeletePresident BEFORE DELETE ON Employee REFERENCING OLD ROW AS oldrow FOR EACH ROW WHEN (oldrow.Title = ‘President’) SIGNAL _CANNOT_DELETE_PRES;

DATABASE 9 Cascading Triggers Sale(SaleID, SaleDate, …) OrderItem(OrderID, ItemID, Quantity, …) Order(OrderID, OrderDate, …) Inventory(ItemID, QOH, …) SaleItem(SaleID, ItemID, Quantity, …) AFTER INSERT UPDATE Inventory SET QOH = QOH – newrow.Quantity AFTER UPDATE WHEN newrow.QOH < newrow.Reorder INSERT {new order} INSERT {new OrderItem}

DATABASE 10 Trigger Loop Employee(EID, Salary) BonusPaid(EID, BonusDate, Amount) StockOptions(EID, OptionDate, Amount, SalaryAdj) AFTER UPDATE IF newrow.Salary > THEN Add Bonus END AFTER UPDATE Or INSERT IF newrow.Bonus > THEN Reduce Bonus Add Options END AFTER UPDATE Or INSERT IF newrow.Amount > THEN Reduce Salary END

DATABASE 11 Transactions  Some transactions result in multiple changes.  These changes must all be completed successfully, or the group must fail.  Protection for hardware and communication failures.  example: bank customer transfers money from savings account to checking account. Decrease savings balance Increase checking balance Problem if one transaction and machine crashes.  Possibly: give users a chance to reverse/undo a transaction.  Performance gain by executing transactions as a block. Savings Accounts Inez: Checking Accounts Inez: Transaction 1. Subtract $1000 from savings. (machine crashes) 2. Add $1000 to Checking. (money disappears) $1000

DATABASE 12 Defining Transactions  The computer needs to be told which changes must be grouped into a transaction.  Turn on transaction processing.  Signify a transaction start.  Signify the end. Success: save all changes Failure: cancel all changes  Must be set in module code  Commit  Rollback

DATABASE 13 SQL Transaction Code CREATE FUNCTION TransferMoney(Amount Currency, AccountFrom Number, AccountTo Number) RETURNS NUMBER curBalance Currency; BEGIN DECLARE HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; Return -2;-- flag for completion error END; START TRANSACTION;-- optional SELECT CurrentBalance INTO curBalance FROM Accounts WHERE (AccountID = AccountFrom); IF (curBalance < Amount) THEN RETURN -1;-- flag for insufficient funds END IF UPDATE Accounts SET CurrentBalance = CurrentBalance – Amount WHERE AccountID = AccountFrom; UPDATE Accounts SET CurrentBalance = CurrentBalance + Amount WHERE AccountID = AccountTo; COMMIT; RETURN 0;-- flag for success END;

DATABASE 14 SAVEPOINT START TRANSACTION; SELECT … UPDATE … SAVEPOINT StartOptional; UPDATE … If error THEN ROLLBACK TO SAVEPOINT StartOptional; END IF COMMIT; time start Required elements SAVEPOINT StartOptional Risky steps commit Partial rollback

DATABASE 15 Concurrent Access  Concurrent Access  Multiple users or processes changing the same data at the same time.  Final data will be wrong!  Force sequential  Locking  Delayed, batch updates  Two processes  Receive payment ($200)  Place new order ($150)  Initial balance $800  Result should be $ = $750  Interference result is either $600 or $950 IDBalance Jones$800 $600 $950 Customers 1) Read balance800 2) Subtract pmt-200 4) Save new bal.600 3) Read balance800 5) Add order150 6) Write balance950 Receive PaymentPlace New Order

DATABASE 16 Pessimistic Locks: Serialization  One answer to concurrent access is to prevent it.  When a transaction needs to alter data, it places a SERIALIZABLE lock on the data used, so no other transactions can even read the data until the first transaction is completed. IDBalance Jones$800 $600 Customers 1) Read balance800 2) Subtract pmt-200 4) Save new bal.600 3) Read balance Receive error message that it is locked. Receive PaymentPlace New Order SET TRANSACTION SERIALIZABLE, READ WRITE

DATABASE 17 SQL Pessimistic Lock CREATE FUNCTION ReceivePayment ( AccountID NUMBER, Amount Currency) RETURNS NUMBER BEGIN DECLARE HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RETURN -2; END SET TRANSACTION SERIALIZABLE, READ WRITE; UPDATE Accounts SET AccountBalance = AccountBalance - Amount WHERE AccountNumber = AccountID; COMMIT; RETURN 0; END

DATABASE 18 Deadlock  Deadlock  Two (or more) processes have placed locks on data and are waiting for the other’s data.  Many solutions  Random wait time  Global lock manager  Two-phase commit - messages Data AData B 1) Lock Data A 3) Wait for Data B 2) Lock Data B 4) Wait for Data A

DATABASE 19 Lock Manager

DATABASE 20 Optimistic Locks  Assume that collisions are rare  Improved performance, fewer resources  Allow all code to read any data (no locks)  When code tries to write a new value  Check to see if the existing value is different from the one you were given earlier  If it is different, someone changed the database before you finished, so it is a collision--raise an error  Reread the value and try again

DATABASE 21 Optimistic Locks for Simple Update (1) Read the balance (2) Add the new order value (3) Write the new balance (4) Check for errors (5) If there are errors, go back to step (1).

DATABASE 22 Optimistic Locks with SQL CREATE FUNCTION ReceivePayment ( AccountID NUMBER, Amount Currency) RETURNS NUMBER oldAmount Currency; testEnd Boolean = FALSE; BEGIN DO UNTIL testEnd = TRUE BEGIN SELECT Amount INTO oldAmount WHERE AccountNumber = AccountID; … UPDATE Accounts SET AccountBalance = AccountBalance - Amount WHERE AccountNumber = AccountID AND Amount = oldAmount; COMMIT; IF SQLCODE = 0 and nrows > 0 THEN testEnd = TRUE; RETURN 0; END IF -- keep a counter to avoid infinite loops END