0% found this document useful (0 votes)
2 views

Lab4

This document outlines a lab focused on managing transactions in a bank database system, including procedures for deposits, transfers, and withdrawals, as well as a loan assessment system. It details the creation of transaction procedures, data integrity triggers, and a loan eligibility function, alongside concurrency control mechanisms such as locking and transaction isolation levels. The document provides SQL code examples for implementing these functionalities and emphasizes the importance of maintaining data consistency and integrity in a multi-user environment.

Uploaded by

walidlabied2002
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)
2 views

Lab4

This document outlines a lab focused on managing transactions in a bank database system, including procedures for deposits, transfers, and withdrawals, as well as a loan assessment system. It details the creation of transaction procedures, data integrity triggers, and a loan eligibility function, alongside concurrency control mechanisms such as locking and transaction isolation levels. The document provides SQL code examples for implementing these functionalities and emphasizes the importance of maintaining data consistency and integrity in a multi-user environment.

Uploaded by

walidlabied2002
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/ 11

Data security

Lab 4: Managing Transactions in a Bank


Database System
Overview:

In this lab, you will continue building on the bank database by integrating advanced transaction
management and loan assessment functionalities. This involves creating procedures for essential
banking operations—such as depositing, transferring, and withdrawing money—and designing a
comprehensive loan assessment system. You will utilize a previously developed loan assessment
function to determine if a person is eligible for a loan and the maximum loan they can receive.

Part 1: Transaction Procedures

A. Create Procedures for Transactions

Objective: Develop three procedures to handle core banking transactions, with appropriate
logging and validation mechanisms.

1. Deposit Procedure (dep_proc):


o Description: This procedure allows a deposit to be made into a customer's
account.
o Input: account_number, amount.
o Action: Increase the balance of the specified account by the deposited amount.
o Log: Insert the deposit action in the operations table.
2. Transfer Procedure (tran_proc):
o Description: This procedure facilitates transferring funds from one account to
another within the same bank.
o Input: source_account, target_account, amount.
o Action: Decrease the source account's balance and increase the target
account's balance by the transferred amount.
o Log: Record the transfer action in the operations table.
3. Withdraw Procedure (wid_proc):
o Description: This procedure handles withdrawal operations for a customer's
account.
o Input: account_number, amount.
o Action: Decrease the specified account’s balance by the withdrawn amount.
o Log: Record the withdrawal action in the operations table.

B. Implement Data Integrity Trigger

• Objective: Create a trigger that prevents any updates that would lead to a negative
balance.
• Trigger: Use an AFTER UPDATE trigger to check if a balance becomes negative during
a transaction. If so, roll back the transaction and raise an error.

1
Solution.

A. Create Procedures for Transactions

Before you begin, verify the structure of these tables using:

DESCRIBE accounts ;
DESCRIBE operations ;

Creating Procedures

Procedure 1: Deposit Money

DELIMITER //
CREATE PROCEDURE dep_proc(
IN acc_num varchar(50) ,
IN deposit_amount double
)
BEGIN
-- Update account balance
UPDATE person
SET balance = balance + ABS(deposit_amount)
WHERE account_number = acc_num;

-- branch name
set @branch_name = (SELECT branch_name FROM person WHERE account_number =
acc_num );

-- Log the operation


INSERT INTO operations (account_number, operation_type,
branch_name,amount, operation_time,target_account_number)
VALUES (acc_num, 'deposit', @branch_name,ABS(deposit_amount),
NOW(),acc_num);
END //
DELIMITER ;

Verification: Test the procedure by calling:

call dep_proc('A-001', 1000);


select * from person;
select * from operations;

Procedure 2: Transfer Money Between Accounts

DELIMITER //
CREATE PROCEDURE tran_proc(
IN source_acc varchar(50) ,
IN target_acc varchar(50) ,
IN transfer_amount double

2
)
BEGIN
-- branch name
set @branch_name = (SELECT branch_name FROM person WHERE account_number =
source_acc );

-- Decrease source account balance


UPDATE person
SET balance = balance - ABS(transfer_amount)
WHERE account_number = source_acc;

-- Increase target account balance


UPDATE person
SET balance = balance + ABS(transfer_amount)
WHERE account_number = target_acc;

-- Log the operations


INSERT INTO operations (account_number, operation_type,
branch_name,amount, operation_time,target_account_number)
VALUES (source_acc, 'transfer', @branch_name,ABS(transfer_amount),
NOW(),target_acc);
END //
DELIMITER ;

Verification: Test the procedure by calling:

call tran_proc('A-001', 'A-005', 1540);


select * from person;
select * from operations;

Procedure 3: Withdraw Money

DELIMITER //
CREATE PROCEDURE wid_proc(
IN acc_num varchar(50) ,
IN deposit_amount double
)
BEGIN
-- Update account balance
UPDATE person
SET balance = balance - ABS(deposit_amount)
WHERE account_number = acc_num;

-- branch name
set @branch_name = (SELECT branch_name FROM person WHERE account_number =
acc_num );

-- Log the operation

3
INSERT INTO operations (account_number, operation_type,
branch_name,amount, operation_time,target_account_number)
VALUES (acc_num, 'withdraw', @branch_name,ABS(deposit_amount),
NOW(),acc_num);
END //
DELIMITER ;

Verification: Test the procedure by calling:

call wid_proc('A-001', 960);


select * from person;
select * from operations;

B. Implement Data Integrity Trigger

DELIMITER //
CREATE TRIGGER balance_check_trigger
BEFORE UPDATE ON person
FOR EACH ROW
BEGIN
-- Check if the new balance is negative
IF NEW.balance < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Error: Balance cannot be negative.';
END IF;
END //
DELIMITER ;

Verification:

-- Example withdrawal that exceeds balance


CALL wid_proc('A-001', 1000.00);

Some well-known types of signal errors:

SIGNAL SQLSTATE '22012' --> division par 0


SIGNAL SQLSTATE '45000' --> general error
SIGNAL SQLSTATE '01000' --> warning occurred

4
Part 2: Loan Management System

A. Create the Loan Assessment Function

1. Function: loan_eligibility
o Input: account_number, requested_loan_amount.
o Output: Returns either the maximum loan amount that can be approved or a
denial message.
2. Criteria:
o Individual Eligibility: The person should have a minimum balance threshold
(you may define a logical threshold, e.g., 10% of the requested loan amount).
o Bank Capacity: The loan should not exceed a specific percentage of the
bank's total assets. Set a reasonable limit, such as 20% of the total balance
held in the bank.

B. Create a Loan Procedure Using the Function

Objective: Design a procedure called loan_proc that leverages the loan_eligibility


function to process loan requests.

1. Procedure: loan_proc
o Input: account_number, requested_loan_amount.
o Action:
▪ Use the loan_eligibility function to evaluate if the requested loan
is feasible.
▪ If the loan is approved, increase the account's balance by the approved
loan amount.
▪ Log the loan approval or denial in the operations table.
2. Implementation:
o Call the loan_eligibility function within the procedure.
o If approved, execute the deposit of the loan amount into the customer’s
account.
o If denied, provide an appropriate message explaining the reason.

Solution.

A. Create the Loan Assessment Function

Before we begin, if this was our first time developing a stored function in MySQL, we
need to check a global variable and change its values to 1 if it turns out to be 0, and that is:

SET GLOBAL log_bin_trust_function_creators = 1;

This variable applies when binary logging is enabled and it controls whether stored function
creators can be trusted not to create stored functions that may cause unsafe events to be written
to the binary log.

5
If set to 0 (the default), users are not permitted to create or alter stored functions unless they
have the SUPER privilege. A setting of 0 also enforces the restriction that a function must be
declared with the DETERMINISTIC characteristic. If the variable is set to 1, MySQL does
not enforce these restrictions on stored function creation.

DELIMITER //
CREATE FUNCTION loan_eligibility(
acc_number varchar(50),
requested_loan_amount double
) RETURNS VARCHAR(255)
NOT DETERMINISTIC
BEGIN
DECLARE individual_balance double;
DECLARE total_bank_balance double;
DECLARE min_required_balance double;
DECLARE max_loan_amount double;
DECLARE result_message VARCHAR(255);

-- Get the total balance of the bank, attention not to use the information
from the table person. Here, I used the information from the table operations
SELECT (Deposit - Withdraw) INTO total_bank_balance FROM
(SELECT SUM(amount) as Deposit FROM operations WHERE operation_type =
'deposit' ) as a,
(SELECT SUM(amount) as Withdraw FROM operations WHERE operation_type =
'withdraw' ) as b;

-- Calculate the maximum allowable loan based on bank capacity


SET max_loan_amount = total_bank_balance * 0.20;

-- Get the individual's current balance


SET max_loan_amount = (SELECT balance FROM person WHERE account_number =
acc_number);

-- Calculate the minimum required balance for the requested loan


SET min_required_balance = requested_loan_amount * 0.10;

-- Check if individual balance meets the minimum requirement


IF individual_balance < min_required_balance THEN SET result_message =
'Denied: Insufficient individual balance.';
ELSEIF requested_loan_amount > max_loan_amount THEN SET result_message =
CONCAT('Denied: Exceeds bank''s capacity. Maximum allowable loan is ',
FORMAT(max_loan_amount, 2));
ELSE SET result_message = CONCAT('Approved: You are eligible for up to ',
FORMAT(LEAST(requested_loan_amount, max_loan_amount), 2), ' loan.');
END IF;

RETURN result_message;
END //

6
DELIMITER ;

Verification: Test the function by:

SELECT loan_eligibility('A-001', 50000);


SELECT *, loan_eligibility(account_number, 50000) AS loan FROM person;

B. Create a Loan Procedure Using the Function

DELIMITER $$
CREATE PROCEDURE loan_proc(
IN acc_num varchar(50),
IN requested_loan_amount double
)
BEGIN
DECLARE eligibility_message VARCHAR(255);
DECLARE approved_amount double;

-- branch name
set @branch_name = (SELECT branch_name FROM person WHERE account_number =
acc_num );

-- Call the loan_eligibility function


SET eligibility_message = (SELECT loan_eligibility(acc_num,
requested_loan_amount));

-- Check if the loan was approved based on the message returned


IF LEFT(eligibility_message, 8) = 'Approved' THEN
-- Extract the approved amount from the eligibility message
SET approved_amount = requested_loan_amount;

-- Update the account's balance


UPDATE person SET balance = balance + approved_amount
WHERE account_number = account_number;

INSERT INTO operations (account_number, operation_type,


branch_name,amount, operation_time,target_account_number)
VALUES (acc_num, 'loan', @branch_name,approved_amount, NOW(),acc_num);

SELECT eligibility_message ;
ELSE
SELECT eligibility_message ;
END IF;
END $$
DELIMITER ;

7
Verification: Test the procedure by calling:

call loan_proc('A-001', 50000);


select * from person;
select * from operations;

Part 3: Multi-User Concurrency and Transaction Isolation

Overview:

In a real-world banking environment, multiple users might interact with the database
simultaneously. To handle such situations effectively, it is crucial to understand and implement
concurrency control mechanisms, such as locks and transaction isolation levels. These
mechanisms will help maintain data consistency and integrity, ensuring that concurrent
transactions do not interfere with one another.

A. Implement Locking Mechanisms

Objective: Learn to use locks to ensure data consistency during concurrent transactions,
particularly for critical operations like money transfers.

1. Table-Level Locking:
o Implement table-level locks when accessing shared resources, like modifying
account balances.
o Example:
▪ Use LOCK TABLES accounts WRITE before performing multiple
account updates to ensure exclusive access.
▪ Release the lock with UNLOCK TABLES after completing the operation.
2. Row-Level Locking:
o Implement row-level locks for greater granularity, allowing more
concurrency.
o Use the SELECT ... FOR UPDATE statement to lock specific rows during a
transfer, withdrawal, or deposit operation.
o Example:
▪ Lock an account’s row when updating its balance, ensuring no other
transaction can modify the same row until the operation completes.

B. Transaction Isolation Levels

Objective: Explore how different isolation levels impact the visibility of transactions and the
potential for conflicts in a multi-user environment.

1. Transaction Isolation Levels :


o Read Uncommitted: Transactions can read uncommitted changes from other
transactions (allowing dirty reads).

8
oRead Committed: Transactions only see changes that have been committed
(no dirty reads allowed).
o Repeatable Read: Transactions see a consistent view of the database from the
start of the transaction (no non-repeatable reads).
o Serializable: Transactions are completely isolated from each other, behaving
as if they were executed sequentially.
2. Exercise:

Procedure Adjustment:

o Modify the tran_proc to use Repeatable Read isolation, ensuring that the
balance remains consistent during a transfer.
o Apply a Serializable level to the loan procedure to avoid issues with
concurrent loan assessments.

Testing:

o Simulate a scenario with multiple users performing deposits, withdrawals, and


transfers.
o Verify that the isolation level maintains integrity without sacrificing
performance.

Solution.

There are two types of table locking (session locking):

LOCK TABLE person READ ;


LOCK TABLE person write ;

• Any tables related by a foreign key constraint are opened and locked implicitly.
• Any tables used in triggers are also locked implicitly.
• A session holding a WRITE lock can perform table-level operations such as DROP
TABLE or TRUNCATE TABLE.
• For sessions holding a READ lock, DROP TABLE and TRUNCATE TABLE
operations are not permitted.

To unlock we use the statement:

UNLOCK TABLES ;

There are two types of row locking (transaction locking):

SELECT * FROM person where account_number='A-004' FOR UPDATE;


SELECT * FROM person where account_number='A-004' FOR SHARE;

9
• Any lock placed with the `FOR UPDATE` will not allow other transactions to read,
update or delete the row.
• Any lock placed with `FOR SHARE ` will allow other transaction to read the locked
row but it will not allow other transaction to update or delete the row.

There are four types of transaction isolation level (transaction locking):

set session transaction isolation level read uncommitted;


set session transaction isolation level read committed;
set session transaction isolation level REPEATABLE READ;
set session transaction isolation level SERIALIZABLE;

Procedure Adjustment:

o Modify the tran_proc to use Repeatable Read isolation, ensuring that the
balance remains consistent during a transfer.

Solution.

Nothing to do here, since the Repeatable Read is the default isolation mode in innodb.

o Apply a Serializable level to the loan procedure to avoid issues with


concurrent loan assessments.

DELIMITER $$
CREATE PROCEDURE loan_proc(
IN acc_num varchar(50),
IN requested_loan_amount double
)
BEGIN
DECLARE eligibility_message VARCHAR(255);
DECLARE approved_amount double;

set session transaction isolation level SERIALIZABLE;


start transaction ;
-- branch name
set @branch_name = (SELECT branch_name FROM person WHERE account_number
= acc_num );

-- Call the loan_eligibility function


SET eligibility_message = (SELECT loan_eligibility(acc_num,
requested_loan_amount));

-- Check if the loan was approved based on the message returned


IF LEFT(eligibility_message, 8) = 'Approved' THEN
-- Extract the approved amount from the eligibility message
SET approved_amount = requested_loan_amount;

10
-- Update the account's balance
UPDATE person SET balance = balance + approved_amount
WHERE account_number = account_number;

INSERT INTO operations (account_number, operation_type,


branch_name,amount, operation_time,target_account_number)
VALUES (acc_num, 'loan', @branch_name,approved_amount,
NOW(),acc_num);

SELECT eligibility_message ;
ELSE
SELECT eligibility_message ;
END IF;
-- Commit the transaction
COMMIT;
END $$
DELIMITER ;

11

You might also like