| 265 | |
| 266 | |
| 267 | 2. Trigger to apply discount to student and child tickets |
| 268 | |
| 269 | When purchasing a ticket, if its a student or a child ticket there exist special discounts. Since the application supports only buying regular tickets (covered by the application use cases), we will present how buying tickets of this type will automatically apply the discounts. |
| 270 | |
| 271 | |
| 272 | {{{ |
| 273 | -- TRIGGER TO CALCULATE TICKET PRICE WITH DISCOUNTS |
| 274 | CREATE OR REPLACE FUNCTION apply_ticket_discount() |
| 275 | RETURNS TRIGGER AS $$ |
| 276 | BEGIN |
| 277 | UPDATE ticket |
| 278 | SET price = tr.base_price - (tr.base_price * NEW.discount / 100) |
| 279 | FROM trip tr |
| 280 | WHERE ticket.ticket_id = NEW.ticket_id AND ticket.trip_id = tr.trip_id; |
| 281 | RETURN NEW; |
| 282 | END; |
| 283 | $$ LANGUAGE plpgsql; |
| 284 | CREATE TRIGGER apply_student_ticket_discount |
| 285 | AFTER INSERT ON student_ticket |
| 286 | FOR EACH ROW EXECUTE FUNCTION apply_ticket_discount(); |
| 287 | |
| 288 | CREATE TRIGGER apply_child_ticket_discount |
| 289 | AFTER INSERT ON child_ticket F |
| 290 | OR EACH ROW EXECUTE FUNCTION apply_ticket_discount(); |
| 291 | }}} |
| 292 | |
| 293 | ''Example'' |
| 294 | If we select the existing child tickets and their appropriate base prices (i.e original prices) using a simple query: |
| 295 | |
| 296 | |
| 297 | {{{ |
| 298 | SELECT |
| 299 | t.ticket_id, |
| 300 | t.price AS discounted_price, |
| 301 | ct.discount, |
| 302 | tr.base_price AS original_price |
| 303 | FROM ticket t |
| 304 | JOIN child_ticket ct ON ct.ticket_id = t.ticket_id |
| 305 | JOIN trip tr ON tr.trip_id = t.trip_id; |
| 306 | }}} |
| 307 | |
| 308 | We will get the following results: |
| 309 | |
| 310 | |
| 311 | |
| 312 | |