lecture 8: sql programming and transactions

28
1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003

Upload: abdul-cline

Post on 02-Jan-2016

26 views

Category:

Documents


1 download

DESCRIPTION

Lecture 8: SQL Programming and Transactions. Friday, January 24, 2003. 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? - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lecture 8: SQL Programming and Transactions

1

Lecture 8: SQLProgramming and Transactions

Friday, January 24, 2003

Page 2: Lecture 8: SQL Programming and Transactions

2

Impedance Mismatch

• Example: SQL in C:– C uses int, char[..], pointers, etc– SQL uses tables

• Impedance mismatch = incompatible types

Page 3: Lecture 8: SQL Programming and Transactions

3

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

Page 4: Lecture 8: SQL Programming and Transactions

4

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

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;

Page 5: Lecture 8: SQL Programming and Transactions

5

Example

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

Page 6: Lecture 8: SQL Programming and Transactions

6

Using Shared VariablesVoid 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); }

Page 7: Lecture 8: SQL Programming and Transactions

7

Cursors

1. Declare the cursor

2. Open the cursor

3. Fetch tuples one by one

4. Close the cursor

Page 8: Lecture 8: SQL Programming and Transactions

8

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;

Page 9: Lecture 8: SQL Programming and Transactions

9

Cursorsprintf(“<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”);

}

Page 10: Lecture 8: SQL Programming and Transactions

10

• What is NO_MORE_TUPLES ?

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

Page 11: Lecture 8: SQL Programming and Transactions

11

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

Page 12: Lecture 8: SQL Programming and Transactions

12

In JDBCpublic void doIt(){ try { Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver"); java.sql.Connection c = DriverManager.getConnection("jdbc:odbc:cse444","cse444","cse444"); java.sql.Statement s= c.createStatement(); java.sql.ResultSet rs; rs = s.executeQuery("Select * from beers"); java.sql.ResultSetMetaData md = rs.getMetaData(); while (rs.next()){ area.append("\nTUPLE: |"); for (int i = 1; i <= md.getColumnCount();i++){ area.append(rs.getString(i) + " | "); } } rs.close(); } catch (Exception e){ e.printStackTrace(); System.out.println("something went wrong in database land"); } }

Page 13: Lecture 8: SQL Programming and Transactions

13

Transactions

Address two issues:

• Access by multiple users– Remember the “client-server” architecture: one

server with many clients

• Protection against crashes

Page 14: Lecture 8: SQL Programming and Transactions

14

Flight Reservation get values for :flight, :date, :seat

EXEC SQL SELECT occupied INTO :occ FROM Flight WHERE fltNum = :flight AND fltdt= :date AND fltSeat=:seat if (!occ) { EXEC SQL UPDATE Flights SET occupied = ‘true’ WHERE fltNum= :flight AND fltdt= :date AND fltSeat=:seat /* more code missing */ } else /* notify customer that seat is not available */

Page 15: Lecture 8: SQL Programming and Transactions

15

Problem #1

Customer 1 - finds a seat empty

Customer 2 - finds the same seat empty

Customer 1 - reserves the seat.

Customer 2 - reserves the seat.

Customer 1 will not be happy.

serializability

Page 16: Lecture 8: SQL Programming and Transactions

16

Bank TransfersTransfer :amount from :account1 to :account2

EXEC SQL SELECT balance INTO :balance1 FROM Accounts WHERE accNo = :account1

if (balance1 >= amount) EXEC SQL UPDATE Accounts SET balance = balance + :amount WHERE acctNo = :account2; EXEC SQL UPDATE Accounts SET balance = balance - :amount WHERE acctNo = :account1;

Crash...

Page 17: Lecture 8: SQL Programming and Transactions

17

TransactionsThe user/programmer can group a sequence of commands so that they are executed atomically and in a serializable fashion:

• Transaction commit: all the operations should be done and recorded.

• Transaction abort: none of the operations should be done.

In SQL:

• EXEC SQL COMMIT;

• EXEC SQL ROLLBACK;

Easier said than done...

Page 18: Lecture 8: SQL Programming and Transactions

18

ACIDACID PropertiesAAtomicity: all actions of a transaction happen, or none happen.

CConsistency: if a transaction is consistent, and the database starts from a consistent state, then it will end in a consistent state.

IIsolation: the execution of one transaction is isolated from other transactions.

DDurability: if a transaction commits, its effects persist in the database.

Page 19: Lecture 8: SQL Programming and Transactions

19

How Do We Assure ACID?Concurrency control:

Guarantees consistency and isolation, given atomicity.

Logging and Recovery:

Guarantees atomicity and durability.

If you are going to be in the logging business, one of the thingsthat you’ll have to do is learn about heavy equipment. -- Robert VanNatta Logging History of Columbia County

Page 20: Lecture 8: SQL Programming and Transactions

20

Transactions in SQL

• In “ad-hoc” SQL:– Default: each statement = one transaction

• In “embedded” SQL:BEGIN TRANSACTION

[SQL statements]

COMMIT or ROLLBACK (=ABORT)

Page 21: Lecture 8: SQL Programming and Transactions

21

Transactions: Serializability

Serializability = the technical term for isolation

• An execution is serial if it is completely before or completely after any other transaction’s execution

• An execution is serializable if it equivalent to one that is serial

• DBMS can offer serializability guarantees

Page 22: Lecture 8: SQL Programming and Transactions

22

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 ALOCK B[write B=4]UNLOCK B

LOCK A[write A=3]UNLOCK ALOCK B[write B=4]UNLOCK B

User 1 User 2

What is wrong ?

time

Page 23: Lecture 8: SQL Programming and Transactions

23

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

Page 24: Lecture 8: SQL Programming and Transactions

24

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

Page 25: Lecture 8: SQL Programming and Transactions

25

Database Design

Entity Relationship Diagrams

Page 26: Lecture 8: SQL Programming and Transactions

26

Building an Application with a DBMS

• Requirements modeling (conceptual, pictures)– Decide what entities should be part of the application and

how they should be linked.

• Schema design and implementation– Decide on a set of tables, attributes.

– Define the tables in the database system.

– Populate database (insert tuples).

• Write application programs using the DBMS– way easier now that the data management is taken care of.

Page 27: Lecture 8: SQL Programming and Transactions

27

Database Design

• Why do we need it?– Agree on structure of the database before

deciding on a particular implementation.

• Consider issues such as:– What entities to model– How entities are related– What constraints exist in the domain– How to achieve good designs

Page 28: Lecture 8: SQL Programming and Transactions

28

Database Design Formalisms1. Object Definition Language (ODL):

– Closer in spirit to object-oriented models

2. Entity/Relationship model (E/R):– More relational in nature.

• Both can be translated (semi-automatically) to relational schemas

• ODL to OO-schema: direct transformation (C++ or Smalltalk based system).