SIBD W05 - H4 - PSMs - Part II - Triggers and Views
SIBD W05 - H4 - PSMs - Part II - Triggers and Views
• 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
4
ti
fi
ti
Never use oa ng-point
Cursors data types for money
$$
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'
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)
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>
• Removing a Trigger
DROP TRIGGER trigger_name ON tbl_name [IF EXISTS]
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
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
Depositor Borrower
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
• 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
• 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'
physical
model T1 T2 T3 T4 T5 T6
logical model V1 V2 V3
physical model T1 T2 T3 T4 T5
• Removing a user
UPDATE senior_employees
SET birthdate = '01-12-1989' The record will 'disapear’ from the
WHERE eid = 7; result
46
ti
ti
fi
fi
Materialised Views
Large complex views can be materialised to
op mise query performance (over those views)
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)