1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.

Slides:



Advertisements
Similar presentations
1 Constraints, Triggers and Active Databases Chapter 9.
Advertisements

CSE 544 Constraints Lecture #3 Friday, January 13, 2011 Dan Suciu , Winter
Transaction Processing Lecture ACID 2 phase commit.
1 Lecture 04 Entity/Relationship Modelling. 2 Outline E/R model (Chapter 5) From E/R diagrams to relational schemas (Chapter 5) Constraints in SQL (Chapter.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #15 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
1 Introduction to Database Systems CSE 444 Lecture 05: Views, Constraints April 9, 2008.
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.
1 Lecture 06: SQL Friday, January 14, Outline Indexes Defining Views (6.7) Constraints (Chapter 7) We begin E/R diagrams (Chapter 2)
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
1 Lecture 05: SQL Wednesday, October 8, Outline Outer joins (6.3.8) Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes.
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.
Programs with SQL Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program Preprocessor Host.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
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 #15 M.P. Johnson Stern School of Business, NYU Spring, 2005.
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.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
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.
SQL Constraints & Triggers May 10 th, Agenda Big picture –what are constraints & triggers? –where do they appear? –why are they important? In SQL.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 Lecture 6: Views Friday, January 17th, Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department,
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
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.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
© D. Wong Java API for XML Processing (JAXP)  For processing XML data using applications written in Java  JAXP APIs - javax.xml.parsers package.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Introduction to Database Systems CSE 444 Lecture 04: SQL April 7, 2008.
1 Lecture 5: Outerjoins, Schema Creation and Views Wednesday, January 15th, 2003.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003.
1 Lecture 14: Transactions in SQL Wednesday, February 8, 2006.
1 Lecture 06 Data Modeling: E/R Diagrams Wednesday, January 18, 2006.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
1 Lecture 05: SQL Wednesday, October 8, Outline Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes Defining Views (6.7)
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
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.
SQL Environment.
Constraints and Triggers
Remaining Topics in SQL to be covered…
Cse 344 March 2nd – E/r diagrams.
Cse 344 May 14th – Entities.
Transactions Properties.
Lecture 06: SQL Systems Aspects
Lecture 4: Updates, Views, Constraints and Other Fun Features
Lecture 05 Views, Constraints
Unit I-2.
Lecture 17: Systems Aspects of SQL
Lecture 13: Transactions in SQL
Lecture 15: Transactions
Lecture 06: SQL Monday, October 11, 2004.
Lecture 14: XML Publishing & Storage
CSE544 SQL Monday, April 5, 2004.
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 05: SQL Systems Aspects
-Transactions in SQL -Constraints and Triggers
Lecture 11: Transactions in SQL
Presentation transcript:

1 SQL Constraints and Programming

2 Agenda Constraints in SQL Systems aspects of SQL.

3 Constraints in SQL A constraint = a property that we’d like our database to hold The system will enforce the constraint by taking some actions: –forbid an update –or perform compensating updates

4 Constraints in SQL Constraints in SQL: Keys, foreign keys Attribute-level constraints Tuple-level constraints Global constraints: assertions The more complex the constraint, the harder it is to check and to enforce simplest Most complex

5 Keys OR: CREATE TABLE Product ( name CHAR(30) PRIMARY KEY, category VARCHAR(20)) CREATE TABLE Product ( name CHAR(30) PRIMARY KEY, category VARCHAR(20)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20) PRIMARY KEY (name)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20) PRIMARY KEY (name))

6 Keys with Multiple Attributes CREATE TABLE Product ( name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (name, category)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (name, category))

7 Other Keys CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) There is at most one PRIMARY KEY; there can be many UNIQUE

8 Foreign Key Constraints CREATE TABLE Purchase ( prodName CHAR(30) REFERENCES Product(name), date DATETIME) CREATE TABLE Purchase ( prodName CHAR(30) REFERENCES Product(name), date DATETIME) prodName is a foreign key to Product(name) name must be a key in Product Referential integrity constraints

9 NameCategory Gizmogadget CameraPhoto OneClickPhoto ProdNameStore GizmoWiz CameraRitz CameraWiz ProductPurchase

10 Foreign Key Constraints OR (name, category) must be a PRIMARY KEY CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category) CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category)

11 NameCategory Gizmogadget CameraPhoto OneClickPhoto ProdNameStore GizmoWiz CameraRitz CameraWiz ProductPurchase What happens during updates ? Types of updates: In Purchase: insert/update In Product: delete/update

12 What happens during updates ? SQL has three policies for maintaining referential integrity: Reject violating modifications (default) Cascade: after a delete/update do a delete/update Set-null set foreign-key field to NULL READING ASSIGNEMNT: 7.1.5, 7.1.6

13 Constraints on Attributes and Tuples Constraints on attributes: NOT NULL-- obvious meaning... CHECK condition-- any condition ! Constraints on tuples CHECK condition

14 CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) What is the difference from Foreign-Key ?

15 General Assertions CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200) CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200)

16 Final Comments on Constraints Can give them names, and alter later –Read in the book !!! We need to understand exactly when they are checked We need to understand exactly what actions are taken if they fail

17 Triggers in SQL A trigger contains an event, a condition, an action. Event = INSERT, DELETE, UPDATE Condition = any WHERE condition (may refer to the old and the new values) Action = more inserts, deletes, updates Many, many more bells and whistles... Read in the book (it only scratches the surface...)

18 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

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

20 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

21 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

22 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;

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

24 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); }

25 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; }

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

27 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;

28 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”); }

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

30 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).

31 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

32 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 “:”

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

34 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 ?

35 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 ?

36 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 !

37 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 !

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

39 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

40 Example T1: R(x) R(y) W(x) W(y) T2: R(x) R(z) R(y) W(x) W(y) R(x) R(y) W(x) R(x) R(z) W(y) R(y) W(x) W(y) R(x) R(y) W(x) R(x) R(z) R(y) W(y) W(y) W(x) R(x) R(z) R(y) R(x) R(y) W(x) W(y) W(y) W(x)

41 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

42 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

43 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 Recommended Reading: chapter 8.6