0% found this document useful (0 votes)
23 views51 pages

SIBD W05 - H4 - PSMs - Part II - Triggers and Views

The document discusses advanced concepts in information systems and databases, focusing on Persistent Stored Modules (PSMs) such as cursors, exceptions, triggers, and views. It explains how to create and manage triggers for database operations, including handling exceptions and maintaining data integrity. Additionally, it covers the creation of views for data abstraction and security, emphasizing their role in providing logical independence from the physical data model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views51 pages

SIBD W05 - H4 - PSMs - Part II - Triggers and Views

The document discusses advanced concepts in information systems and databases, focusing on Persistent Stored Modules (PSMs) such as cursors, exceptions, triggers, and views. It explains how to create and manage triggers for database operations, including handling exceptions and maintaining data integrity. Additionally, it covers the creation of views for data abstraction and security, emphasizing their role in providing logical independence from the physical data model.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Information Systems and Databases

Sistemas de Informação e Bases de Dados

W05/H4: PSMs — Part II — Triggers and Views


Prof. Flavio Mar ns
ti
Class Outline

• Cursors
• Excep ons
• Triggers

2
ti
Cursors
Cursors
Abstrac on to read a table with a le seman cs that
can be used within Persistent Stored Modules

• OPEN - Open the cursor (and execute the query


associated to the cursor)

• FETCH - Read the record and advance to the


next

• CLOSE - Close the cursor and free resources

4
ti
fi
ti
Never use oa ng-point
Cursors data types for money

CREATE OR REPLACE FUNCTION average_balance() RETURN

$$
FLOAT AS X
DECLARE balance_var REAL DEFAULT 0.0;
DECLARE sum_balance REAL DEFAULT 0.0; Declares the
DECLARE count_balance INTEGER DEFAULT 0; cursor for a query
DECLARE cursor_account CURSOR FOR
SELECT balance FROM account;
BEGIN Opens the cursor
OPEN cursor_account;
LOOP Reads a record and
FETCH cursor_account INTO balance_var; advances to the
EXIT WHEN NOT FOUND; next record
sum_balance := sum_balance + balance_var;
count_balance := count_balance + 1;
END LOOP; Closes the cursor
CLOSE cursor_account;
RETURN sum_balance / count_balance;
END
$$ de
IST ▪ DEI ▪ Bases LANGUAGE
Dados plpgsql;
5
fl
ti
Excep ons
ti
Raising Excep ons
RAISE EXCEPTION <message>
USING HINT 'text'

CREATE FUNCTION search(uid INT) RETURNS VOID AS


$$
BEGIN Raising an excep on is
IF NOT EXISTS(
SELECT * the same as “viola ng an
FROM users integrity constraint”
WHERE user_id=uid)
THEN
RAISE EXCEPTION 'Nonexistent ID %', user_id
USING HINT = 'Please check your user ID';
END IF;
END;
$$ LANGUAGE plpgsql;
7
ti
ti
ti
Recovering from
Excep ons
CREATE OR REPLACE FUNCTION calc_tax(arg NUMERIC)
RETURNS NUMERIC Some code block
AS $$
DECLARE res INTEGER; that triggers the
BEGIN excep on
DECLARE nome_condition CONDITION
-- main block
FOR SQLSTATE xpto
res := 100 / arg;
RETURN res;

EXCEPTION
WHEN division_by_zero
THEN RETURN 0;
END;
$$ Use the WHEN clause
LANGUAGE plpgsql; to catch the excep on
8
ti
ti
ti
Triggers
Triggers
Are ac ons (procedures) that are
automa cally invoked in response to speci c
database events (opera ons such as INSERTS,
UPDATES, or DELETES)

• Implement complex Integrity Constraints


• Update/change tables (for history or audit
purposes)
• Replicate tables
• Maintain summary tables
10
ti
ti
ti
fi
Triggers E-C-A pa ern
Triggers are speci ed using event-condi on-ac on
(ECA) rules:
• Event: what type of update ac vates the trigger
• Condi on: a ques on or test to see if the
ac on should be taken
• Ac on: a procedure that is executed when the
trigger is ac vated and the previous condi on
is true

11
ti
ti
ti
ti
fi
ti
ti
tt
ti
ti
ti
Syntax
A procedure that is automa cally invoked in response to speci c
database updates
• Crea ng a Trigger
CREATE TRIGGER <trigger_name>
{ BEFORE | AFTER } { INSERT | UPDATE | DELETE }

ON <tbl_name>

WHEN <condition>

FOR EACH { ROW | STATEMENT } EXECUTE PROCEDURE


<proc_name>

• Removing a Trigger
DROP TRIGGER trigger_name ON tbl_name [IF EXISTS]

Triggers are an old concept was only standardised in the SQL


standard: 1999 12
ti
ti
fi
Example: Integrity Constraint
Create a trigger that prevents the balance from being
nega ve or greater than 100
CREATE OR REPLACE FUNCTION chk_balance_interval_proc() In POSTGRES
RETURNS TRIGGER AS
$$ we must
BEGIN create a
IF NEW.balance < 0 OR NEW.balance > 100 THEN
RAISE EXCEPTION 'Withdrawal or deposit past the limits' func on that
END IF; returns a
RETURN NEW; TRIGGER! 🤦
END;
$$ LANGUAGE plpgsql;
This trigger
may fail
CREATE TRIGGER chk_balance_interval_trigger
BEFORE UPDATE OR INSERT ON account
FOR EACH ROW EXECUTE PROCEDURE chk_balance_interval_proc(); POSTGRES
syntax is
UPDATE account Nothing misleading (no
SET balance = balance - 500 should be trigger is being
WHERE account_number = 'A-101'; returned returned)
13
ti
ti
Example: Integrity Constraint
Create a trigger that never lets the balance go
below 0 or above 100
CREATE OR REPLACE FUNCTION chk_balance_interval_proc()
RETURNS TRIGGER AS
$$
BEGIN
IF NEW.balance < 0 THEN This trigger never fails;
NEW.balance := 0; instead, it intercepts
ELSEIF NEW.balance > 100 THEN the updates to balance
NEW.balance := 100;
END IF;

RETURN NEW;
END;
$$ LANGUAGE plpgsql;
All account
-- Code to install the trigger should go here…
values will
remain
between 0
UPDATE account and 100
SET balance = balance - 500
14
BEFORE Trigger Behaviour

• ACTIVATION: A BEFORE trigger is ac vated once


for each row or once for each statement
(depending on how it was speci ed)
• FAILURE: If a BEFORE trigger fails:
A. The opera on on the corresponding row
or table is not performed
B. Any AFTER triggers will not be ac vated

15
ti
fi
ti
ti
AFTER Trigger Behaviour
• ACTIVATION: An AFTER trigger is ac vated once for
each row or once for each statement (depending on
how it was speci ed) if:
A. All BEFORE triggers on the same table and
related to the same opera on are
successfully executed
B. The opera on has been executed sucessfully
• FAILURE: If a AFTER trigger fails, the opera on on the
corresponding row or table is not performed

16
ti
fi
ti
ti
ti
Example: Complex table update
Consider the following new requirements for the Bank
database
1. Whenever a customer withdraws more than the
balance
2. Instead of resul ng in a nega ve balance, the bank:
A. Creates a loan equal to the missing amount
B. Gives the loan the same number as the account
C. Zeroes the account balance
Trigger condi on: an UPDATE that results in a nega ve
IST ▪ DEI ▪ Bases de Dados account balance
17
ti
ti
ti
ti
Example: Complex table
update
Withdrawal of € 800 from the A-102 account

account_number | branch_name | balance


----------------+-------------+----------
A-101 | Downtown | 500.0000
A-215 | Metro | 600.0000
A-102 | Uptown | 700.0000
A-305 | Round Hill | 800.0000
A-201 | Uptown | 900.0000
A-222 | Central | 550.0000
A-217 | University | 650.0000
A-333 | Central | 750.0000
A-444 | Downtown | 850.0000

IST ▪ DEI ▪ Bases de Dados


18
Trigger: Example 2
Withdrawal of € 800 from the A-102 account result
on a loan Loan
Account
loan_number | branch_name | amount
account_number | branch_name | balance
-------------+-------------+-----------
----------------+-------------+----------
L-17 | Downtown | 1000.0000
A-101 | Downtown | 500.0000
L-23 | Central | 2000.0000
A-215 | Metro | 600.0000
L-15 | Uptown | 3000.0000
A-102 | Uptown | 700.0000
L-14 | Downtown | 4000.0000
A-305 | Round Hill | 800.0000
L-93 | Metro | 5000.0000
A-201 | Uptown | 900.0000
L-11 | Round Hill | 6000.0000
A-222 | Central | 550.0000
L-16 | Uptown | 7000.0000
A-217 | University | 650.0000
L-20 | Downtown | 8000.0000
A-333 | Central | 750.0000
L-21 | Central | 9000.0000
A-444 | Downtown | 850.0000
A-102 | UpTown | 100.0000

Depositor Borrower

customer_name | account_number customer_name | loan_number


---------------+---------------- ---------------+-------------
Johnson | A-101 Iacocca | L-17
Brown | A-215 Brown | L-23
Cook | A-102 Cook | L-15
Cook | A-101 Nguyen | L-14
Flores | A-305 Davis | L-93
Johnson | A-201 Brown | L-11
Iacocca | A-217 Gonzalez | L-17
Evans | A-222 Iacocca | L-16
Oliver | A-333 Parker | L-20
Brown | A-444 Brown | L-21
Cook | A-102
IST ▪ DEI ▪ Bases de Dados 19
Trigger: Example 2
CREATE OR REPLACE FUNCTION overdraft_proc()
RETURNS TRIGGER
AS $$
BEGIN
IF NEW.balance < 0 THEN
INSERT INTO loan
VALUES (NEW.account_number,
NEW.branch_name,
- NEW.balance);

INSERT INTO borrower


SELECT customer_name, account_number
FROM depositor
WHERE depositor.account_number = NEW.account_number;

NEW.balance := 0;
END IF; CREATE TRIGGER overdraft_trigger
END BEFORE UPDATE ON account
$$ LANGUAGEFORplpgsql;
EACH ROW EXECUTE PROCEDURE
overdraft_proc();
20
Problems with Triggers
• Complex e ect. Its e ect can be complex and
unpredictable
- Mul ple triggers can be ac vated in a single
opera on
- The ac on of a trigger can ac vate another
trigger (recursive triggers)
• Cycles of events. Chains of endless events.
Very di cult to debug and x.

21
ti
ti
ti
ffi
ff
ff
ti
fi
ti
Problems with Triggers
• Unintended execu ons
- Changes to a table will run triggers even
if that’s not what is intended
• Occurrence of errors
- If the trigger fails, the en re opera on
fails
- Extended undo recovery mes
22
ti
ti
ti
ti
When not to use Triggers
• Summary tables: Use VIEWS instead of
triggers, if possible

• Complex Integrity Constraints: Use


CHECKs whenever possible

• Table replica on: Use DBMS built-in


mechanisms
23
ti
Class Outline

• Crea ng Views
• Logical Independence using Views
• User Management
• Updatable Views
• Materialised Views

24
ti
Crea ng Views
ti
Views
• A view is a virtual table de ned through a query
• Associates a name to a SELECT statement
CREATE VIEW myview AS SELECT …
Once created, it can be used as a rela on but it is not
the same as crea ng a table

Views do not have storage, they are computed, and


their contents will change if the tables involved in the
query change
26
ti
fi
ti
Crea ng Views
Views are database objects that can be
created and removed.
• Crea on of a View
CREATE VIEW myview AS SELECT …

• Removal of a View
DROP VIEW myview

27
ti
ti
Crea ng a View: Example 1
CREATE VIEW account_stats_view(
name, num_accts)
AS
SELECT customer_name, COUNT(*) AS num_accts


FROM depositor
Criação:
GROUP BY customer_name;

SELECT *
FROM account_stats_view;

28
ti
Crea ng a View: Example 2
CREATE VIEW top_employee(
name, salary, department)
AS
SELECT name, salary, department
FROM employee
WHERE salary > 10000

SELECT name
FROM top_employee A view can be queried
WHERE salary >= ALL( like any regular table
SELECT salary
FROM top_employee)
ti
Resolving Queries on Views
SELECT COUNT(*)
FROM top_employee References to a
WHERE department = 'HR' view are replaced
by its de ni on

SELECT COUNT(*)
FROM (SELECT name, salary, department
FROM employee
WHERE salary > 10000)
WHERE department = 'HR'

The technique for evalua ng view queries is known as


View Expansion 30
fi
ti
ti
Views and Logical
Independence
Data Independence Applica ons
only know the
Views (the
APPS Logical Model)
and therefore is
independent
logical from the
V1 V2 V3 Physical Model
model

physical
model T1 T2 T3 T4 T5 T6

• Views map data from tables the physical model to


a new logical model
• Views support logical independence from the
physical model 32
ti
Security
APP A APP B

logical model V1 V2 V3

physical model T1 T2 T3 T4 T5

Views are useful for security context: The DBA can


create views and grant them access to a group of
users (or applica ons).
33
ti
Security
Suppose App A works with VIP customers and
App B works with Regular Customers
CREATE VIEW V1_vip_customer
AS Both V1 and V2
SELECTCREATE
customer_name, customer_city views can be
VIEW V2_regular created based
FROM customer
SELECTccustomer_name, customer_city on the same
WHERE FROM
1000000 <(
customer c base tables
SELECT SUM(balance)
WHERE 1000000 > (
FROM account
SELECT a INNER JOIN depositor d
SUM(balance)
ON a.account_number
FROM account a INNER= d.account_number
JOIN depositor d
AND d.customer_name = c.customer_name
ON a.account_number = d.account_number
AND d.customer_name = c.customer_name

Views can par on a table horizontally or ver cally and give


applica ons the illusion that they are dealing with dis nct tables 34
ti
ti
ti
ti
ti
Security
APP A only sees V1 and
No user/app besides the DB the ‘VIP’ records
administrator can ever see the
account records

account_number | branch_name | balance V1 APP A


----------------+-------------+----------
A-101 | Downtown | 500.0000
A-215 | Metro | 600.0000
A-102 | Uptown | 700.0000
A-305 | Round Hill | 800.0000
A-201 | Uptown | 900.0000
A-222
A-217
| Central | 550.0000
| University | 650.0000
APP B
A-333 | Central | 750.0000 V2
A-444 | Downtown | 850.0000

APP B only sees V2 and


the ‘Regular’ records
35
User Management
User Management
Databases support user management with
dis nct privileges

• Crea on of a new user

CREATE USER 'scott' WITH PASSWORD 'tiger'

• Removing a user

DROP USER [IF EXISTS] 'scott'

Will not work on db.tecnico.ulisboa.pt 37


ti
ti
GRANT and REVOKE
Access privileges are managed with GRANT
and REVOKE
GRANT <privilege_list> | ALL
ON <object_name>
TO <user_or_role_name>

REVOKE <privilege_list> | ALL


ON <object_name>
FROM <user_or_role_name>
• <privilege_list> may contain SELECT, INSERT, UPDATE,
DELETE
• <object_name> can be a table or a view
Will not work on db.tecnico.ulisboa.pt 38
Examples
GRANT SELECT
ON vip_customer_view
TO scott;
GRANT SELECT, INSERT, DELETE
ON user_credentials
TO my_login_app_user;
GRANT ALL
ON vip_customer_view
TO scott;
REVOKE ALL
ON vip_customer_view
FROM scott;
REVOKE DELETE
ON user_credentials
FROM my_login_app_user; 39
Updatable Views
Updatable Views
SQL:1999 dis nguishes between two types of views:
• Updatable Views: Whose rows can be modi ed
- A column of a view can be updated if: At least one column
must be updatable

• (1) it is obtained directly from a base table and


• (2) the primary key of the base table is included in
the columns of the view
• Insertable Views: Where new lines can be inserted
- There must be a one-to-one rela onship between the
rows of the view and those of the respec ve base
tables.
41
ti
ti
ti
fi
Updatable View: Example
This view is updatable

CREATE VIEW senior_employees(eid, emp_name, birthdate)


AS
SELECT e.eid, e.name AS emp_name, e.birthdate
FROM employee e
WHERE birthdate < '01-01-1980';

INSERT INTO senior_employees VALUES (7, 'Grace', '01-12-1979');

SELECT * FROM senior_employees;


The new record will show up in the
result

UPDATE senior_employees
SET birthdate = '01-12-1989' The record will 'disapear’ from the
WHERE eid = 7; result

SELECT * FROM senior_employees;


Non-updatable view: Example
This view is not updatable!

CREATE VIEW senior_managers(emp_name, dep_name, birthdate) AS


SELECT e.name AS emp_name,
d.name AS dep_name,
e.birthdate
FROM employee e
JOIN department d ON e.eid = d.mid
WHERE birthdate < '01-01-1980';

SELECT * FROM senior_managers;

emp_name | dep_name | birthdate Now we cannot insert anymore.


----------+----------+-----------
Caroline | Sales | 1971-04-07 This statement fails because the keys e.eid
and d.mid are not in the view!

INSERT INTO senior_managers VALUES ('Grace', 'Finance',


'08-03-1979');
Non-Updatable Views
The following views are not updatable
• Views with aggregate queries: because they
create a one-to-many rela onship between the
records of the view and the records of the base
table(s)
• Views that join tables: because they cannot
guarantee one-to-one rela onships between the
view and the base table
• Views that project out a ributes: because base
table keys are some mes le out
44
ti
tt
ti
ti
ft
Materialised Views
Materialised Views
Views some mes can be too costly to compute
and need to be op mised using cache:

• Memory cache when the query underlying the


view is complex and the results t in memory
• Disk Cache when the query underlying the view is
complex and the results do not t in memory
In computer science, a CACHE is a temporary
copy of frequently accessed values that is faster

46
ti
ti
fi
fi
Materialised Views
Large complex views can be materialised to
op mise query performance (over those views)

• Materialised views on ORACLE and on Postgres


CREATE MATERIALIZED VIEW account_stats AS SELECT …

• Materialised Query Tables and materialised Summary Tables


on IBM DB2

CREATE TABLE account_stats AS SELECT …

47
ti
Refreshing Materialised
Views
Also known as upda ng views or propaga ng updates
In POSTGRES, views can be refreshed in two ways:
• On-demand
REFRESH MATERIALIZED VIEW account_stats;

• Automa cally
CREATE UNIQUE INDEX idx_account_stats
ON account_stats(name);
REFRESH MATERIALIZED VIEW
CONCURRENTLY account_stats;
48
ti
ti
ti
Resolving Queries over
Materialised Views
Queries over materialised views can be resolved
using the view expansion strategy or using query
rewri ng over views
SELECT name, COUNT(*)
SELECT name, num_accts
FROM depositor
GROUP BY name
HAVING COUNT(*) > 2
⟩⟩ FROM account_stats_view
WHERE num_accts > 2

The DBMS detects that we are doing an aggrega on query and rewrites
the query at the expense of the view (or exis ng materialised views)

A materialised view improves response me


through query rewrite or reduce execu on me. 49
ti
ti
ti
ti
ti
ti
Materialised Views
Useful concepts regarding Materialised Views
• Space: Unlike an ordinary view (which does not
take up any storage space), a materialised view
contains the rows resul ng from the underlying
query.
• Storage: A materialised view can be stored in the
same database as its base tables or in a di erent
database
• Usage: Frequently used for Data Warehousing
(Data Analy cs) or Replica on purposes.
50
ti
ti
ti
ff

You might also like