End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.

Slides:



Advertisements
Similar presentations
Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
Advertisements

Transactions (Chapter ). What is it? Transaction - a logical unit of database processing Motivation - want consistent change of state in data Transactions.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Transaction Processing Lecture ACID 2 phase commit.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #15 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #16 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Murali Mani SQL with other Programming Languages.
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
1 A Closer Look Chapter 2. 2 Underlying Concepts of Databases and Transaction Processing.
Lecture #4 October 19, 2000 SQL. Administration Exam date officially moved to December 7 th, 6:30pm, here. Homework #3 – will be on the web site tomorrow.
Dec 15, 2003Murali Mani Transactions and Security B term 2004: lecture 17.
Cs3431 Transactions, Logging and Security. cs3431 Transactions: What and Why? A set of operations on a database must appear as one “unit”. Example: Consider.
Programs with SQL Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program Preprocessor Host.
Embedded SQL Direct SQL is rarely used: usually, SQL is embedded in some application code. We need some method to reference SQL statements. But: there.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #14 M.P. Johnson Stern School of Business, NYU Spring, 2008.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
COMP 5138 Relational Database Management Systems Semester 2, 2007 Lecture 8A Transaction Concept.
Remaining Topics in SQL to be covered… NULL values in SQL Outer joins in SQL Constraints and Triggers in SQL Embedded SQL.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
Lecture #19 May 13 th, Agenda Trip Report End of constraints: triggers. Systems aspects of SQL – read chapter 8 in the book. Going under the lid!
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 10 Transaction Management.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
1 ICS 184: Introduction to Data Management Lecture Note 11: Assertions, Triggers, and Index.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 136 Database Systems I SQL Modifications and Transactions.
Phase 2, Answering queries using views. February 2 nd, 2004.
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
SQL in a Programming Environment CIS 4301 Lecture Notes Lecture /11/2006.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Transactions, Relational Algebra, XML February 11 th, 2004.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Using SQL in PL/SQL Oracle Database PL/SQL 10g Programming Chapter 4.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Advanced Database Concepts Transaction Management and Concurrency Control.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003.
1 Lecture 14: Transactions in SQL Wednesday, February 8, 2006.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
Introduction to SQL Programming Techniques
SQL Environment.
Databases We are particularly interested in relational databases
Remaining Topics in SQL to be covered…
Transactions Properties.
Lecture 06: SQL Systems Aspects
Lecture 4: Updates, Views, Constraints and Other Fun Features
Unit I-2.
Lecture 17: Systems Aspects of SQL
Lecture 13: Transactions in SQL
Lecture 15: Transactions
Lecture 20: Intro to Transactions & Logging II
Chapter 8 Advanced SQL.
Lecture 14: XML Publishing & Storage
CSE544 SQL Monday, April 5, 2004.
Lecture 05: SQL Systems Aspects
-Transactions in SQL -Constraints and Triggers
Assertions and Triggers
Embedded SQL Chapter 8.
Lecture 11: Transactions in SQL
Presentation transcript:

End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004

Triggers Enable the database programmer to specify: when to check a constraint, what exactly to do. A trigger has 3 parts: An event (e.g., update to an attribute) A condition (e.g., a query to check) An action (deletion, update, insertion) When the event happens, the system will check the constraint, and if satisfied, will perform the action. NOTE: triggers may cause cascading effects. Database vendors did not wait for standards with triggers!

Elements of Triggers (in SQL3) Timing of action execution: before, after or instead of triggering event The action can refer to both the old and new state of the database. Update events may specify a particular column or set of columns. A condition is specified with a WHEN clause. The action can be performed either for once for every tuple, or once for all the tuples that are changed by the database operation.

Example: Row Level Trigger CREATE TRIGGER NoLowerPrices AFTER UPDATE OF price ON Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (OldTuple.price > NewTuple.price) UPDATE Product SET price = OldTuple.price WHERE name = NewTuple.name FOR EACH ROW

Statement Level Trigger CREATE TRIGGER average-price-preserve INSTEAD OF UPDATE OF price ON Product REFERENCING OLD_TABLE AS OldStuff NEW_TABLE AS NewStuff WHEN (1000 < (SELECT AVG (price) FROM ((Product EXCEPT OldStuff) UNION NewStuff)) DELETE FROM Product WHERE (name, price, company) IN OldStuff; INSERT INTO Product (SELECT * FROM NewStuff)

Bad Things Can Happen CREATE TRIGGER Bad-trigger AFTER UPDATE OF price IN Product REFERENCING OLD AS OldTuple NEW AS NewTuple WHEN (NewTuple.price > 50) UPDATE Product SET price = NewTuple.price * 2 WHERE name = NewTuple.name FOR EACH ROW

Embedded SQL direct SQL (= ad-hoc SQL) is rarely used in practice: SQL is embedded in some application code SQL code is identified by special syntax

Impedance Mismatch Example: SQL in C: –C uses int, char[..], pointers, etc –SQL uses tables Impedance mismatch = incompatible types

The Impedance Mismatch Problem Why not use only one language? Forgetting SQL: “we can quickly dispense with this idea” [textbook, pg. 351]. SQL cannot do everything that the host language can do. Solution: use cursors

Programs with Embedded SQL Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program Preprocessor Host language compiler Call-level interface (CLI): ODBC,JDBC, ADO

Interface: SQL / Host Language Values get passed through shared variables. Colons precede shared variables when they occur within the SQL statements. EXEC SQL: precedes every SQL statement in the host language. The variable SQLSTATE provides error messages and status reports (e.g., “00000” says that the operation completed with no problem). EXEC SQL BEGIN DECLARE SECTION; char productName[30]; EXEC SQL END DECLARE SECTION; EXEC SQL BEGIN DECLARE SECTION; char productName[30]; EXEC SQL END DECLARE SECTION;

Example Product (pname, price, quantity, maker) Purchase (buyer, seller, store, pname) Company (cname, city) Person(name, phone, city)

Using Shared Variables Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30];/* product-name, company-name */ int p, q;/* price, quantity */ char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for name, price and company somehow */ EXEC SQL INSERT INTO Product(pname, price, quantity, maker) VALUES (:n, :p, :q, :c); } Void simpleInsert() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30];/* product-name, company-name */ int p, q;/* price, quantity */ char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; /* get values for name, price and company somehow */ EXEC SQL INSERT INTO Product(pname, price, quantity, maker) VALUES (:n, :p, :q, :c); }

Single-Row Select Statements int getPrice(char *name) { EXEC SQL BEGIN DECLARE SECTION; char n[20]; int p; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; strcpy(n, name); /* copy name to local variable */ EXEC SQLSELECT price INTO :p FROM Product WHERE Product.name = :n; return p; } int getPrice(char *name) { EXEC SQL BEGIN DECLARE SECTION; char n[20]; int p; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; strcpy(n, name); /* copy name to local variable */ EXEC SQLSELECT price INTO :p FROM Product WHERE Product.name = :n; return p; }

Cursors 1.Declare the cursor 2.Open the cursor 3.Fetch tuples one by one 4.Close the cursor

Cursors void product2XML() { EXEC SQL BEGIN DECLARE SECTION; char n[20], c[30]; int p, q; char SQLSTATE[6]; EXEC SQL END DECLARE SECTION; EXEC SQL DECLARE crs CURSOR FOR SELECT pname, price, quantity, maker FROM Product; EXEC SQL OPEN crs;

Cursors printf(“ \n”); while (1) { EXEC SQL FETCH FROM crs INTO :n, :p, :q, :c; if (NO_MORE_TUPLES) break; printf(“ \n”); printf(“ %s \n”, n); printf(“ %d \n”, p); printf(“ %d \n”, q); printf(“ %s \n”, c); printf(“ \n”); } EXECT SQL CLOSE crs; printf(“ \n”); }

What is NO_MORE_TUPLES ? #define NO_MORE_TUPLES !(strcmp(SQLSTATE,”02000”))

More on Cursors cursors can modify a relation as well as read it. We can determine the order in which the cursor will get tuples by the ORDER BY keyword in the SQL query. Cursors can be protected against changes to the underlying relations. The cursor can be a scrolling one: can go forward, backward +n, -n, Abs(n), Abs(-n).

Dynamic SQL So far the SQL statements were visible to the compiler In dynamic SQL we have an arbitrary string that represents a SQL command Two steps: –Prepare: compiles the string –Execute: executes the compiled string

Dynamic SQL Void someQuery() { EXEC SQL BEGIN DECLARE SECTION; char *command=“UPDATE Product SET quantity=quantity+1 WHERE name=“gizmo” EXEC SQL END DECLARE SECTION; EXEC SQL PREPARE myquery FROM :command; EXEC SQL EXECUTE myquery; } myquery = a SQL variable, does not need to be prefixed by “:”

Transactions Address two issues: Access by multiple users –Remember the “client-server” architecture: one server with many clients Protection against crashes

Multiple users: single statements Client 1: UPDATE Product SET Price = Price – 1.99 WHERE pname = ‘Gizmo’ Client 2: UPDATE Product SET Price = Price*0.5 WHERE pname=‘Gizmo’ Client 1: UPDATE Product SET Price = Price – 1.99 WHERE pname = ‘Gizmo’ Client 2: UPDATE Product SET Price = Price*0.5 WHERE pname=‘Gizmo’ Two managers attempt to do a discount. Will it work ?

Multiple users: multiple statements Client 1:INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 2:SELECT count(*) FROM Product SELECT count(*) FROM SmallProduct Client 1:INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 2:SELECT count(*) FROM Product SELECT count(*) FROM SmallProduct What’s wrong ?

Protection against crashes Client 1: INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 1: INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 What’s wrong ? Crash !

Transactions Transaction = group of statements that must be executed atomically Transaction properties: ACID –ATOMICITY = all or nothing –CONSISTENCY = leave database in consistent state –ISOLATION = as if it were the only transaction in the system –DURABILITY = store on disk !

Transactions in SQL In “ad-hoc” SQL: –Default: each statement = one transaction In “embedded” SQL: BEGIN TRANSACTION [SQL statements] COMMIT or ROLLBACK (=ABORT)

Transactions: Serializability Serializability = the technical term for isolation An execution is serial if it is completely before or completely after any other function’s execution An execution is serializable if it equivalent to one that is serial DBMS can offer serializability guarantees

Serializability Enforced with locks, like in Operating Systems ! But this is not enough: LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B User 1 User 2 What is wrong ? time

Serializability Solution: two-phase locking –Lock everything at the beginning –Unlock everything at the end Read locks: many simultaneous read locks allowed Write locks: only one write lock allowed Insert locks: one per table

Isolation Levels in SQL 1.“Dirty reads” SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 2.“Committed reads” SET TRANSACTION ISOLATION LEVEL READ COMMITTED 3.“Repeatable reads” SET TRANSACTION ISOLATION LEVEL REPEATABLE READ 4.Serializable transactions (default): SET TRANSACTION ISOLATION LEVEL SERIALIZABLE Reading assignment: chapter 8.6