Вы находитесь на странице: 1из 42

Lecture 07: SQL

Constraints and Programming


Wednesday, January 22, 2003

1
Agenda
• Tales from real database research life
• Constraints in SQL
• Systems aspects of SQL.

2
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

3
Constraints in SQL
Constraints in SQL:
• Keys, foreign keys simplest
• Attribute-level constraints
• Tuple-level constraints
Most
• Global constraints: assertions complex

The more complex the constraint, the harder it is to


check and to enforce
4
Keys
CREATE
CREATETABLE
TABLEProduct
Product((
name
nameCHAR(30)
CHAR(30)PRIMARY
PRIMARYKEY,
KEY,
category
categoryVARCHAR(20))
VARCHAR(20))

OR:
CREATE
CREATETABLE
TABLEProduct
Product((
name
nameCHAR(30),
CHAR(30),
category
categoryVARCHAR(20)
VARCHAR(20)
PRIMARY
PRIMARYKEYKEY(name))
(name))
5
Keys with Multiple Attributes

CREATE
CREATETABLE
TABLE Product
Product ((
name
name CHAR(30),
CHAR(30),
category
category VARCHAR(20),
VARCHAR(20),
price
price INT,
INT,
PRIMARY
PRIMARYKEY KEY (name,
(name, category))
category))

6
Other Keys
CREATE
CREATE TABLE
TABLE Product
Product ((
productID
productID CHAR(10),
CHAR(10),
name
name CHAR(30),
CHAR(30),
category
category VARCHAR(20),
VARCHAR(20),
price
price INT,
INT,
PRIMARY
PRIMARY KEY KEY (productID),
(productID),
UNIQUE
UNIQUE (name,
(name, category))
category))

There is at most one PRIMARY KEY;


there can be many UNIQUE 7
Foreign Key Constraints
Referential
integrity
constraints
CREATE
CREATE TABLE
TABLE Purchase
Purchase ((
prodName
prodName CHAR(30)
CHAR(30)
REFERENCES
REFERENCES Product(name),
Product(name),
date
date DATETIME)
DATETIME)

prodName is a foreign key to Product(name)


name must be a key in Product
8
Product Purchase
Name Category ProdName Store

Gizmo gadget Gizmo Wiz

Camera Photo Camera Ritz

OneClick Photo Camera Wiz

9
Foreign Key Constraints
• OR
CREATE
CREATE TABLE
TABLE Purchase
Purchase ((
prodName
prodName CHAR(30),
CHAR(30),
category
category VARCHAR(20),
VARCHAR(20),
date
date DATETIME,
DATETIME,
FOREIGN
FOREIGN KEY
KEY (prodName,
(prodName, category)
category)
REFERENCES
REFERENCES Product(name,
Product(name, category)
category)
• (name, category) must be a PRIMARY
KEY
10
What happens during updates ?
Types of updates:
• In Purchase: insert/update
• In Product: delete/update
Product Purchase
Name Category ProdName Store

Gizmo gadget Gizmo Wiz

Camera Photo Camera Ritz

OneClick Photo Camera Wiz


11
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


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

13
What
is the difference from
Foreign-Key ?

CREATE
CREATE TABLE
TABLE Purchase
Purchase ((
prodName
prodName CHAR(30)
CHAR(30)
CHECK
CHECK (prodName
(prodName ININ
SELECT
SELECT Product.name
Product.name
FROM
FROM Product),
Product),
date
date DATETIME
DATETIME NOT
NOT NULL)
NULL)

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

15
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

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

17
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

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

19
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


20
Programs with Embedded SQL

Host language + Embedded SQL

Preprocessor
Preprocessor

Host Language + function Call-level


calls interface (CLI):
Host ODBC,JDBC,
Host language
language compiler
compiler
ADO

Host language
program 21
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
EXECSQL
SQL BEGIN
BEGINDECLARE
DECLARESECTION;
SECTION;
char
char productName[30];
productName[30];
EXEC
EXECSQL
SQL END
ENDDECLARE
DECLARESECTION;
SECTION; 22
Example
Product (pname, price, quantity, maker)
Purchase (buyer, seller, store, pname)
Company (cname, city)
Person(name, phone, city)

23
Using Shared Variables
Void
Void simpleInsert()
simpleInsert(){{

EXEC
EXECSQL
SQLBEGIN
BEGINDECLARE
DECLARESECTION;
SECTION;
char
char n[20],
n[20],c[30];
c[30]; /*/*product-name,
product-name,company-name
company-name*/*/
int
int p,p,q;q; /*/*price,
price,quantity
quantity*/*/
char
char SQLSTATE[6];
SQLSTATE[6];
EXEC
EXECSQL
SQLEND
ENDDECLARE
DECLARESECTION;
SECTION;

/*/* get
getvalues
valuesfor
forname,
name,price
priceand
andcompany
company somehow
somehow */*/

EXEC
EXECSQL
SQLINSERT
INSERT INTOINTOProduct(pname,
Product(pname,price,
price,quantity,
quantity,maker)
maker)
VALUES
VALUES (:n,
(:n,:p,
:p,:q,
:q,:c);
:c);
}}

24
Single-Row Select Statements
int
int getPrice(char
getPrice(char*name)
*name){{

EXEC
EXECSQL
SQLBEGIN
BEGINDECLARE
DECLARESECTION;
SECTION;
char
charn[20];
n[20];
int
intp;p;
char
char SQLSTATE[6];
SQLSTATE[6];
EXEC
EXECSQL
SQLEND ENDDECLARE
DECLARESECTION;
SECTION;

strcpy(n,
strcpy(n,name);
name); /*/*copy
copyname
nametotolocal
localvariable
variable*/*/

EXEC
EXECSQL
SQL SELECT
SELECTprice
price INTO
INTO:p:p
FROM
FROM Product
Product
WHERE
WHEREProduct.name
Product.name==:n;:n;
return
returnp;p;
}}
25
Cursors
1. Declare the cursor
2. Open the cursor
3. Fetch tuples one by one
4. Close the cursor

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


27
Cursors
printf(“<allProducts>\n”);
while (1) {
EXEC SQL FETCH FROM crs INTO :n, :p, :q, :c;
if (NO_MORE_TUPLES) break;
printf(“ <product>\n”);
printf(“ <name> %s </name>\n”, n);
printf(“ <price> %d </price>\n”, p);
printf(“ <quantity> %d </quantity>\n”, q);
printf(“ <maker> %s </maker>\n”, c);
printf(“ </product>\n”);
}
EXECT SQL CLOSE crs;
printf(“</allProducts>\n”);
}
28
• What is NO_MORE_TUPLES ?

#define NO_MORE_TUPLES !(strcmp(SQLSTATE,”02000”))

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

30
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

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


Transactions
Address two issues:

• Access by multiple users


– Remember the “client-server” architecture: one
server with many clients
• Protection against crashes

33
Multiple users: single statements
Client
Client1:1:
UPDATE
UPDATEProduct
Product
SET
SETPrice
Price==Price
Price––1.99
1.99
WHERE
WHEREpname
pname==‘Gizmo’
‘Gizmo’

Client
Client2:2:
UPDATE
UPDATEProduct
Product
SET
SETPrice
Price==Price*0.5
Price*0.5
WHERE
WHEREpname=‘Gizmo’
pname=‘Gizmo’

Two managers attempt to do a discount.


Will it work ? 34
Multiple users: multiple
statements
Client
Client1:1: INSERT
INSERTINTO
INTOSmallProduct(name,
SmallProduct(name,price)
price)
SELECT
SELECTpname,
pname,price
price
FROM
FROMProduct
Product
WHERE
WHEREprice
price<=
<=0.99
0.99

DELETE
DELETEProduct
Product
WHERE
WHEREprice
price<=0.99
<=0.99

Client
Client2:2: SELECT
SELECTcount(*)
count(*)
FROM
FROMProduct
Product

SELECT
SELECTcount(*)
count(*)
FROM
FROMSmallProduct
SmallProduct

What’s wrong ? 35
Protection against crashes

Client
Client1:
1:
INSERT
INSERTINTO
INTOSmallProduct(name,
SmallProduct(name,price)
price)
SELECT
SELECTpname,
pname,price
price
FROM
FROMProduct
Product
WHERE
WHEREprice
price<=
<=0.99
0.99
Crash !
DELETE
DELETEProduct
Product
WHERE
WHEREprice
price<=0.99
<=0.99

What’s wrong ? 36
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 !
37
Transactions in SQL
• In “ad-hoc” SQL:
– Default: each statement = one transaction

• In “embedded” SQL:
BEGIN TRANSACTION
[SQL statements]
COMMIT or ROLLBACK (=ABORT)

38
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
39
Serializability
• Enforced with locks, like in Operating Systems !
• But this is not enough:

User 1 LOCK
LOCKAA User 2
[write
[writeA=1]
A=1]
UNLOCK
UNLOCKAA LOCK
LOCKAA
. .. .. . [write
[writeA=3]
A=3]
. .. .. . UNLOCK
UNLOCKAA
. .. .. . LOCK
LOCKBB
. .. .. . [write
[writeB=4]
B=4] time
LOCK
LOCKBB UNLOCK
UNLOCKBB
[write
[writeB=2]
B=2]
UNLOCK
UNLOCKBB 40
What is wrong ?
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
41
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


42

Вам также может понравиться