Академический Документы
Профессиональный Документы
Культура Документы
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
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))
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
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?
Preprocessor
Preprocessor
Host language
program 21
Interface: SQL / Host Language
Values get passed through shared variables.
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;
29
More on Cursors
• cursors can modify a relation as well as read it.
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;
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’
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
• 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