Chapter 7 Database Integrity and Transactions Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Accessing data Transactions. Agenda Questions from last class? Transactions concurrency Locking rollback.
Transaction Processing. Objectives After completing this lesson, you should be able to do the following: –Define transactions effectively for an application.
Data and Database Administration Chapter 12. Outline What is Concurrency Control? Background Serializability  Locking mechanisms.
ICOM 6005 – Database Management Systems Design Dr. Manuel Rodríguez-Martínez Electrical and Computer Engineering Department Lecture 16 – Intro. to Transactions.
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 7 Database Integrity.
Database Administration Chapter Six DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Transaction Management and Concurrency Control
Chapter 15 Transaction Management. McGraw-Hill/Irwin © 2004 The McGraw-Hill Companies, Inc. All rights reserved. Outline Transaction basics Concurrency.
Chapter 8 : Transaction Management. u Function and importance of transactions. u Properties of transactions. u Concurrency Control – Meaning of serializability.
1 Transaction Management Database recovery Concurrency control.
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
Jerry Post McGraw-Hill/Irwin Copyright © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. Database Management Systems Chapter 7 Database Integrity.
Transaction Management WXES 2103 Database. Content What is transaction Transaction properties Transaction management with SQL Transaction log DBMS Transaction.
COMP 5138 Relational Database Management Systems Semester 2, 2007 Lecture 8A Transaction Concept.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
INTRODUCTION TO TRANSACTION PROCESSING CHAPTER 21 (6/E) CHAPTER 17 (5/E)
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.
Advanced Database Technologies Lecture 6: Transactions and Database Recovery.
Triggers and Transactions Making Decisions behind the scene.
DBSQL 7-1 Copyright © Genetic Computer School 2009 Chapter 7 Transaction Management, Database Security and Recovery.
1 Transactions BUAD/American University Transactions.
1099 Why Use InterBase? Bill Todd The Database Group, Inc.
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 Concepts. 1. Introduction To transaction Processing 1.1 Single User VS Multi User Systems One criteria to classify Database is.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
DATABASE TRANSACTION. Transaction It is a logical unit of work that must succeed or fail in its entirety. A transaction is an atomic operation which may.
1 IT420: Database Management and Organization Session Control Managing Multi-user Databases 24 March 2006 Adina Crăiniceanu
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,...)
Database structure and space Management. Database Structure An ORACLE database has both a physical and logical structure. By separating physical and logical.
Database structure and space Management. Segments The level of logical database storage above an extent is called a segment. A segment is a set of extents.
© 2002 by Prentice Hall 1 Database Administration David M. Kroenke Database Concepts 1e Chapter 6 6.
The Relational Model1 Transaction Processing Units of Work.
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
MBA 664 Database Management Dave Salisbury ( )
© 2006 ITT Educational Services Inc. Course Name: IT390 Business Database Administration Unit 8 Slide 1 IT 390 Business Database Administration Unit 8:
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Mr.Prasad Sawant, MIT Pune India Introduction to DBMS.
Transaction Management Transparencies. ©Pearson Education 2009 Chapter 14 - Objectives Function and importance of transactions. Properties of 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.
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.
3 Database Systems: Design, Implementation, and Management CHAPTER 9 Transaction Management and Concurrency Control.
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.
ICOM 6005 – Database Management Systems Design Dr. Manuel Rodríguez-Martínez Electrical and Computer Engineering Department Lecture 16 – Intro. to Transactions.
SQL Triggers, Functions & Stored Procedures Programming Operations.
In this session, you will learn to: Implement triggers Implement transactions Objectives.
MULTIUSER DATABASES : Concurrency and Transaction Management.
COMP 430 Intro. to Database Systems Transactions, concurrency, & ACID.
Creating Database Triggers
Database structure and space Management
LAB: Web-scale Data Management on a Cloud
DB Integrity & Transactions Part 1
DB Integrity & Transactions Part 2
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Database Management Systems
Prof. Arfaoui. COM390 Chapter 9
Triggers 7/11/2019 See scm-intranet.
Presentation transcript:

Chapter 7 Database Integrity and Transactions Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica Updated 2015

DBSYSTEMS 2 of 20 Outline  Code in DB system  Triggers  Transactions  Concurrent Access  Locks & Deadlocks  ACID Transactions  Keys creation  DB cursor

DBSYSTEMS 3 of 20 DB System Code as Part of DB System  Create code  As triggers = procedures that support biz processes;  In forms and reports (localized effects)  Functions combined with queries (embedded SQL)  User-defined functions Tables Forms & Reports Triggers If (Click) Then MsgBox... End If If inventory < Minimum Then CREATE POrder End If C++ code: Programs combined with SQL statements if (...) { // embedded SQL SELECT … }

DBSYSTEMS 4 of 20 User-Defined Functions* CREATE FUNCTION IncreaseSalary (EmpID INTEGER, Amt CURRENCY) BEGIN INPUT EmpID, Amt IF (Amt > 50000) THEN RETURN -1-- error flag, data validation ELSE UPDATE Employee SET Salary = Salary + Amt WHERE EmployeeID = EmpID; PRINT New Salary END * Function is the code (program) that returns a result of processing. A program for increasing a salary for a certain amount (pseudo code).

DBSYSTEMS 5 of 20 Events and Triggers (Expanding the topic) Example on slide 4: BEFORE UPDATE on Salary column, run a trigger that checks if a salary ceiling is respected. An event fires (initiates) a trigger (program, code): Common events: SQL-based on rows: INSERT, DELETE, UPDATE SQL-based on tables: ALTER, CREATE, DROP LOGOFF, LOGON – user’s action SERVERERROR, SHUTDOWN, STARTUP – server’s action

DBSYSTEMS 6 of 20 Table and Row Triggers time Before Update on a table (all rows) After Update on the table Before Update of a row After Update of the row Update point SQL events support triggers at two points in time - - BEFORE and AFTER Table Row

DBSYSTEMS 7 of 20 An After Row Trigger Example CREATE TRIGGER LogSalaryChanges AFTER UPDATE OF Salary ON Employee REFERENCINGOLD ROW As oldrow NEW ROW As newrow FOR EACH ROW INSERT INTO tblSalaryChanges (EmpID, ChangeDate, UserID, OldValue, NewValue) VALUES (newrow.EmployeeID, CURRENT_TIMESTAMP, CURRENT_USER, oldrow.Salary, newrow.Salary); The trigger logs employee ID, date, user’s ID, old salary, and new salary into table SalaryChanges, after each update on the salary column in the Employee table. Useful for auditing.

DBSYSTEMS 8 of 20 Cascading Triggers Sale(SaleID, SaleDate, …) OrderItem(OrderID, ItemID, Quantity, …) Order(OrderID, OrderDate, …) Inventory(ItemID, QOH, …) SaleItem(SaleID, ItemID, Quantity, …) AFTER INSERT UPDATE Inventory SET Inventory.QOH=Inventory.QOH – newrow.Quantity AFTER UPDATE WHEN Inventory.QOH < minQuantity INSERT {new order} INSERT {new OrderItem} Increase scope of automation. Take care of dependencies.

DBSYSTEMS 9 of 20 Transactions  Definition: Transaction is a sequence of processing tasks (a process) that succeed or fail altogether.  Each task results in a database change but all must be completed for data change to be valid.  Reason: to protect data accuracy against system failures.  Example on right: 1. customer starts transferring money from savings account to checking account. 2. System crashes after subtracting amount from Savings and the amount is not added to Checking. Transaction 1. Subtract $1000 from Savings. (Then, system crashes) 2. Add $1000 to Checking. (Money not added) SavingsAccount Joe Doe Bal.: Subtract: New Bal.: $1000 subtracted from Savings but Balance in Checking not increased! Checking Account Joe Doe Bal.: Transfer Fails Checking Account Joe Doe Bal.: Add: 1000 x

DBSYSTEMS 10 of 20 Designing Transactions  Transactions are programmed  Mark a transaction start - START TRANSACTION  Determine a point of temporary saving of data changes  Mark a transaction end - COMMIT end-result of processing to database, permanent save.

DBSYSTEMS 11 of 20 Designing Transactions: SAVEPOINT START TRANSACTION; SELECT … UPDATE tblCustomer.record SAVEPOINT StartOptional; UPDATE tblOrder.newrecord UPDATE tblInventory.QOH IF error THEN ROLLBACK TO SAVEPOINT StartOptional; END IF COMMIT; time start Run tasks SAVEPOINT StartOptional Risky tasks COMMIT Partial ROLLBACK

DBSYSTEMS 12 of 20 Concurrent Access  Concurrent Access  Multiple transactions competing for the same data at the same time.  If Order process reads Balance before Payment process ends, the end balance will be incorrect. $950 is the end balance instead of $750 ( ). Customer at loss. Table AccountPayable read and update 1) Read Balance800 2) Subtract pmt-200 3) Read balance800 4) Save new bal.600 5) Add order150 6) Write balance950 Order transaction Payment transaction

DBSYSTEMS 13 of 20 Pessimistic Locks (Serialization)  One answer to problems of concurrent access is to disable it by forcing transactions into a sequence one after another.  A transaction places a SERIALIZABLE lock on data so that no other transaction can access it before the first transaction is completed. 3) Order transaction locked out; System’s message : “Table is locked”. Order transaction, trying to interfere with Payment at step 3 SET TRANSACTION SERIALIZABLE, READ WRITE 1) Read balance800 2) Subtract pmt-200 3) Save new bal.600 Payment transaction

DBSYSTEMS 14 of 20 Deadlock  Deadlock = problem with serialized locks: When different transactions use multiple tables concurrently. T1 locks tbl A and requests access to tbl B, while tbl B is locked by T2 that, in turn, requests access to T1. Neither transaction can be completed. 1) Lock tbl A 2) Read tbl B 1) Lock tbl B 2) Update tbl A Transaction 1 (T1) Transaction 2 (T2) Transactions lock out each other, create “deadly embrace” (another name for deadlock). Solution 1 to deadlock: Each transaction waits random time, tries again, releases locks if unsuccessful, and runs itself all over again. Tbl ATbl B

DBSYSTEMS 15 of 20 Solution 2 to Deadlock: Lock Manager A closed lock-wait loop that blocks all processes. Lock Manager (part of DBMS) monitors all processes. Temporarily disables some processes to clear the blockage.

DBSYSTEMS 16 of 20 Optimistic Locks  Opposite to serialization lock (pessimistic lock); a solution against deadlocks.  Logic:  Assuming that collisions are rare  Record state of DB at READ time of any transaction (no locks)  When a transaction tries to write a new value, system reads data again (current data), and compares it with record at start.  If there is a difference, system sends error message and calls the transaction to execute itself again.

DBSYSTEMS 17 of 20 ACID Transactions  Atomicity: all changes succeed or fail together.  Consistency: all data remain internally consistent (when new data is committed, transactions fully executed) and can be validated (e.g., referential integrity).  Isolation: system gives each transaction the perception that it is running in isolation. There are no concurrent access problems (locks do the job).  Durability: When a transaction is committed, all changes are permanently saved even if there is a hardware or system failure (use a master log file for new data).

DBSYSTEMS 18 of 20 Methods to Generate Keys 1.The DBMS can generate key values automatically whenever a row is inserted into a table (surrogate key). Drawback: concurrent access to DB system can mix up keys that are generated at the same time (e.g., CustomerID In Customer table, which needs to be reused in the Order table). 2.A separate key generator is called by a programmer to create a new key for a specified table. Prevents mix-ups but requires that programmers write code to generate a key for every table and each row insertion.

DBSYSTEMS 19 of 20 Key Generator Create an order for a new customer: (1) Create new key for CustomerID (2) INSERT row into Customer (3) Create key for new OrderID (4) INSERT row into Order Customer Table CustomerID, Name, … Order Table OrderID, CustomerID, …

DBSYSTEMS 20 of 20 Database Cursor  Cursor = A type of variable (memory space) that holds entire records. A relic from old DB systems ( Declare Cursor… Close Cursor ) – no relationship with screen cursor (user interface).  Purposes: Complex calculations on rows Comparisons between rows YearSales Diff , , , ,736 A cursor would read values of sales for the current and previous year, and calculate the difference.