1 / 31

End of SQL: Triggers, Impedance Mismatch and Transactions

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)

Download Presentation

End of SQL: Triggers, Impedance Mismatch and Transactions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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!

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

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

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

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

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

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

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

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

  11. 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;

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

  13. 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); }

  14. 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 SQL SELECT price INTO :p FROM Product WHERE Product.name = :n; return p; }

  15. Cursors • Declare the cursor • Open the cursor • Fetch tuples one by one • Close the cursor

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

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

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

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

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

  21. 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 “:”

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

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

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

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

  26. 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 !

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

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

  29. Serializability • Enforced with locks, like in Operating Systems ! • But this is not enough: User 1 User 2 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 time What is wrong ?

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

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

More Related