Purpose: The trigger is designed to generate a unique id for each new company record inserted into the company table. The id is composed of the company's country code, a combination of letters derived from the company's name, and a random number.
Trigger Timing:
BEFORE INSERT: The trigger activates before a new record is inserted into the company table.
Trigger Events:
The trigger is fired for each row that is being inserted.
Trigger Logic:
Variable Declarations:
trimmed_company_name: Stores the company's name after trimming any leading or trailing spaces.
space_count: Stores the count of spaces in the trimmed company name.
name_length: Stores the length of the trimmed company name.
Initial Setup:
Trims the NEW.name to remove any leading or trailing spaces.
Calculates the number of spaces in the trimmed company name.
Calculates the length of the trimmed company name.
Generates a random number between 100000 and 999999 and stores it in @random_number.
Handling Short Names (less than 3 characters):
If the company name is less than 3 characters long, it pads the name with 'X's to make it 3 characters long.
Combines the country code, the padded name, and the random number to form the id.
Generating id Based on Space Count in Company Name:
No Spaces (space_count = 0):
Takes the first 3 characters of the trimmed company name.
Combines the country code, these 3 characters, and the random number to form the id.
One Space (space_count = 1):
Extracts the first word and its first letter.
Extracts the second word and its first two letters.
Combines the country code, these letters, and the random number to form the id.
Two or More Spaces (space_count > 1):
Extracts the first word and its first letter.
Extracts the second word and its first letter.
Extracts the third word and its first letter.
Combines the country code, these letters, and the random number to form the id.
Ensuring Generated Letters are at Least 3 Characters Long:
If the generated combination of letters is less than 3 characters long, it pads the combination with 'X's to make it 3 characters long.
Forms the final id using the country code, the padded letters, and the random number.
Type and Timing
Type: This is a BEFORE INSERT trigger.
Timing: It executes before a new record is inserted into the company table.
Functionality
Purpose: The trigger's main purpose is to automatically set the country_code of a new company record based on the city_id provided during the insertion.
Logic:
When a new record is being inserted into the company table (BEFORE INSERT), the trigger checks if the city_id field in the new record (NEW.city_id) is not null.
If city_id is provided, the trigger looks up the corresponding country_code by joining the city and country tables where the country_code in the city table matches the code in the country table and where the city.id matches the city_id of the new company record.
The found country_code is then assigned to the country_code field of the new company record (NEW.country_code).
Type and Timing
Type: This is an AFTER INSERT trigger.
Timing: It executes after a new record is inserted into the company table.
Functionality
Purpose: The trigger's main purpose is to create a log entry whenever a new company record is added to the company table. This is crucial for maintaining an audit trail and monitoring changes in the database.
Logic:
When a new record is inserted into the company table, the trigger activates.
It then calls a stored procedure named activity_log_auto, passing four parameters:
Event Type ('INSERT'): Indicates the nature of the activity, which in this case is an insertion.
Entity ('Company'): Specifies the entity or table affected by the activity.
Key Attribute (NEW.name): The name of the company that was added. NEW.name refers to the value of the name field in the newly inserted record.
Description (CONCAT('New row added with ID: ', NEW.id)): A descriptive string for the log entry. It includes the ID of the newly added company, concatenated with a message. NEW.id refers to the value of the id field in the new record.
Type and Timing
Type: This is an AFTER DELETE trigger.
Timing: It executes after a record is deleted from the company table.
Functionality
Purpose: The trigger is designed to create a log entry whenever a company record is deleted from the company table. This is important for audit trails and tracking changes in the database.
Logic:
When a record is deleted from the company table, the trigger activates.
It calls a stored procedure named activity_log_auto, passing four parameters:
Event Type ('DELETE'): Indicates the nature of the activity, which is a deletion in this case.
Entity ('Company'): Specifies the entity or table affected by the activity.
Key Attribute (OLD.name): The name of the company that was deleted. OLD.name refers to the value of the name field in the deleted record.
Description (CONCAT('Deleted Row with ID: ', OLD.id)): A string that provides a description of the activity. It includes the ID of the deleted company, concatenated with a descriptive message. OLD.id refers to the value of the id field in the deleted record.
Type and Timing
Type: BEFORE INSERT
Timing: Executes before a new record is inserted into the crew_info table.
Purpose and Functionality
Goal: To ensure that any crew member added to a film is actually an employee of the company that produced the film. This is a data integrity check to maintain consistency in the database where multiple entities (employees, films, companies) interact closely.Â
Logic:
Variables Declaration: Two variables, film_company and crew_company, are declared to store the company_id from the film and employee tables, respectively.
Retrieve Film's Company ID:
A SELECT statement retrieves the company_id of the film (identified by movie_code from the new row being inserted) and stores it in the film_company variable.
Retrieve Crew Member's Company ID:
Another SELECT statement retrieves the company_id for the employee (identified by employee_id from the new row) and stores it in the crew_company variable.
Validation Check:
The trigger compares the two company IDs. If they do not match (i.e., the crew member's company is different from the film's production company), the trigger raises an error using SIGNAL SQLSTATE '45000'. This stops the insertion of the new record and returns the message 'Crew member does not belong to the company that produced this film'.
Error Handling: The use of SIGNAL SQLSTATE '45000' is a method to throw a custom error and halt the insertion process if the validation fails.
Type and Timing
Type: BEFORE INSERT
Timing: Executes before a new record is inserted into the employee table.
Purpose and Functionality
Goal: To ensure that the role assigned to a new employee exists either in the role table (for film production roles) or in the department table (for administrative roles). This validation is crucial for maintaining data integrity and ensuring consistency in the database.
Logic:
Variables Declaration:
role_exists: A variable to check if the given role exists in the role table.
department_exists: A variable to check if the given role exists in the department table.
Check Role Existence:
The first SELECT statement counts entries in the role table where the name matches NEW.employee_role. The count is stored in role_exists.
Check Department Existence:
The second SELECT statement counts entries in the department table where the name matches NEW.employee_role. The count is stored in department_exists.
Validation:
If both role_exists and department_exists are 0, it means the role specified for the new employee does not exist in either table. In this case, the trigger raises an error using SIGNAL SQLSTATE '45000' and sets the error message to 'Invalid employee role'. This stops the insertion of the new record.
Error Handling: The use of SIGNAL SQLSTATE '45000' is an effective way to enforce data validation rules and halt the insertion process if the role is not valid.
Type and Timing
Type: AFTER INSERT
Timing: Executes after a new record is inserted into the employee table.
Purpose and Functionality
Goal: The primary objective of this trigger is to categorize new employees as either crew or staff based on their role and then insert corresponding entries into the crew or staff tables.
Logic:
Categorizing as Staff:
If the employee_role of the new employee matches a name in the department table, it implies the employee is part of the staff (administrative roles).
In this case, the trigger inserts a new record into the staff table with the new employee's id and the corresponding department_id.
Categorizing as Crew:
If the employee_role matches a name in the role table, it indicates the employee is part of the production crew.
Here, the trigger inserts a new record into the crew table, linking the new employee's id with the appropriate role_id.
The trigger uses subqueries within the INSERT statements to find the correct department_id or role_id based on the employee_role.
Trigger Name: employee_email_generator
Trigger Event: BEFORE INSERT on the employee table.
Purpose: To generate a unique email address for each new employee based on their personal information and the company they are associated with.
Construction Logic
Domain Generation - The domain name is derived from the company's name (associated with the new employee via company_id) by removing spaces and converting it to lowercase.
Extension Selection - A random domain extension (.com, .org, .co, .net) is selected to complete the email domain part.
Email Prefix Creation - The email prefix is constructed using the employee's first name, last name, a random three-digit number, the first two letters of the middle name, and the last digit of the date of birth. This combination helps in maintaining uniqueness. All elements are converted to lowercase to adhere to common email address standards.
Final Email Address - The complete email address is a concatenation of the email prefix and the generated domain, separated by an "@" symbol.
This trigger is designed to automatically generate a unique id for each new record inserted into the employee table. The generated id is based on the employee's role, distinguishing between crew members (CR-) and staff members (ST-).
Type and Timing
Type: BEFORE INSERT
Timing: Executes before a new record is inserted into the employee table.
Components
Prefix:
CR- for crew members, indicating a role tied to the role table.
ST- for staff members, indicating a role tied to the department table.
Unique Number: A 8-digit random number ensuring uniqueness among employee IDs.
Initials: The first letters of the employee's first, middle, and last names are concatenated to provide a personal identifier.
Role/Department ID: The ID of the role or department the employee belongs to, derived from the respective tables.
Logic
Role Identification: The trigger first determines whether the employee_role matches any entry in the role table. If a match is found, the employee is identified as a crew member. If no match is found, the employee is considered a staff member, assuming the role exists in the department table.
ID Generation: Based on this identification, an appropriate id is generated for the new employee record before insertion. For crew members, the prefix CR- is used, followed by the unique number and the employee's initials. A similar format is used for staff members with the prefix ST-.
Type and Timing
Type: AFTER INSERT
Timing: Executes after a new record is inserted into the employee table.
Purpose and Functionality
Goal: The main objective of this trigger is to create a log entry every time a new employee record is added to the employee table. This logging is crucial for maintaining an audit trail and for tracking the additions of new employees to the database.
Logic:
When a new record is inserted into the employee table, the trigger activates.
It then invokes a stored procedure named activity_log_auto, passing four parameters:
Event Type ('INSERT'): Specifies the nature of the activity, which in this case is an insertion.
Entity ('Employee'): Indicates the entity or table affected by the activity.
Key Attribute (NEW.email_address): The email address of the newly added employee. NEW.email_address refers to the value of the email_address field in the new record.
Description (CONCAT('New row added with ID: ', NEW.id)): Provides a descriptive string for the log entry, including the ID of the new employee. NEW.id refers to the value of the id field in the new record.
Additional Details
DEFINER: Set as root@localhost, which means the trigger executes with the privileges of the root user on localhost.
Automated Logging Process: The trigger ensures that the addition of new employees is automatically logged, providing a reliable method for tracking changes in employee data.
Type and Timing
Type: AFTER DELETE
Timing: Executes after a record is deleted from the employee table.
Purpose and Functionality
Goal: The primary objective of this trigger is to create a log entry whenever an employee record is deleted from the employee table. This is important for maintaining an audit trail and data transparency in tracking changes in the database.
Logic:
When a record is deleted from the employee table, the trigger activates.
It then calls a stored procedure named activity_log_auto, passing four parameters:
Event Type ('DELETE'): Indicates the nature of the activity, which in this case is a deletion.
Entity ('Employee'): Specifies the entity or table affected by the activity.
Key Attribute (OLD.email_address): The email address of the employee that was deleted. OLD.email_address refers to the value of the email_address field in the deleted record.
Description (CONCAT('Deleted Row with id: ', OLD.id)): A descriptive string for the log entry. It includes the ID of the deleted employee, concatenated with a message. OLD.id refers to the value of the id field in the deleted record.
Type and Timing
Type: AFTER INSERT
Timing: Executes after a new record is inserted into the film table.
Purpose and Functionality
Goal: The primary aim of this trigger is to log every insertion event of a film record in the film table. This logging is essential for maintaining an audit trail and for tracking the additions of new film data to the database.
Logic:
When a new record is inserted into the film table, the trigger activates.
It then invokes a stored procedure named activity_log_auto, passing four parameters:
Event Type ('INSERT'): Specifies that the activity type is an insertion.
Entity ('Film'): Indicates that the affected entity is the film table.
Key Attribute (NEW.title): The title of the new film. NEW.title refers to the value of the title field in the new record.
Description (CONCAT('New row added with movie code: ', NEW.movie_code)): Provides a descriptive string for the log entry, which includes the movie code of the newly added film. NEW.movie_code refers to the value of the movie_code field in the new record.
Type and Timing
Type: AFTER DELETE
Timing: Executes after a record is deleted from the film table.
Purpose and Functionality
Goal: The main objective of this trigger is to log every deletion event of a film record in the film table. This is vital for maintaining an audit trail and tracking the removals of film data from the database.
Logic:
When a record is deleted from the film table, the trigger is activated.
It then calls a stored procedure named activity_log_auto, passing four parameters:
Event Type ('DELETE'): Specifies that the activity type is a deletion.
Entity ('Film'): Indicates that the affected entity is the film table.
Key Attribute (OLD.title): The title of the film that was deleted. OLD.title refers to the value of the title field in the deleted record.
Description (CONCAT('Deleted Row with movie code: ', OLD.movie_code)): A descriptive string for the log entry, which includes the movie code of the deleted film. OLD.movie_code refers to the value of the movie_code field in the deleted record.
Type and Timing
Type: BEFORE INSERT
Timing: Executes before a new record is inserted into the film table.
Purpose and Functionality
Goal: The primary purpose of this trigger is to automatically generate a unique identifier (movie code) for each new film record before it is inserted into the database.
Logic:
The trigger checks if the title of the new film record (NEW.title) is not null.
If NEW.title is provided, the trigger generates a unique identifier using the UUID() function and assigns it to NEW.movie_code.
The UUID() function generates a universally unique identifier (UUID), which ensures that each movie code is distinct across all records in the film table.
Type and Timing
Type: BEFORE INSERT
Timing: Executes before a new record is inserted into the grant_request table.
Purpose and Functionality
Goal: The primary objective of this trigger is to automatically generate a unique identifier for each new grant request record before it's inserted into the database.
Logic:
The trigger first checks if the title, funding_organization, and application_date fields of the new grant request record (NEW.title, NEW.funding_organization, NEW.application_date) are not null.
If these fields are provided, the trigger constructs a unique identifier (id) using the CONCAT function with the following components:
Prefix 'GR-' indicating a grant request.
The first letter of the grant's title, converted to uppercase.
A random number between 100000 and 999999.
The first two letters of the funding organization's name, converted to uppercase.
The last digit of the application date's year.
The resulting string is set as the id for the new grant request record.
Custom ID Creation: This trigger ensures a standardized and unique way of creating IDs for new grant requests, incorporating elements from the grant's title, funding organization, and application date.
Type and Timing
Type: This is an AFTER INSERT trigger.
Timing: It executes after a new record is inserted into the grant_request table.
Functionality
Purpose: The main purpose of this trigger is to automatically log every new insertion into the grant_request table, ensuring that each addition is recorded in the database's logging system.
Logic:
When a new record is being inserted into the grant_request table (AFTER INSERT), the trigger activates.
It calls the activity_log_auto stored procedure, passing relevant information about the new grant request:
The type of event ('INSERT').
The entity involved ('Grant Request').
The title of the new grant request (NEW.title) as a key attribute.
A descriptive log message, which includes the ID of the new grant request record (CONCAT('New row added with ID: ', NEW.id)).
The activity_log_auto procedure then logs these details into an activity_log table, effectively capturing the event.
Type and Timing
Type: This is an AFTER DELETE trigger.
Timing: It executes after a record is deleted from the grant_request table.
Functionality
Purpose: The primary purpose of this trigger is to automatically log each deletion event in the grant_request table, ensuring a comprehensive audit trail for deleted grant requests.
Logic:
Upon the deletion of a record from the grant_request table, this trigger is activated.
It calls the activity_log_auto stored procedure, passing essential information about the deleted grant request:
The type of event ('DELETE').
The entity involved ('Grant Request').
The title of the deleted grant request (OLD.title) as a key attribute.
A descriptive log message, including the ID of the deleted record (CONCAT('Deleted Row with id: ', OLD.id)).
The activity_log_auto procedure then logs these details into the activity_log table, capturing the deletion event.
Type and Timing
Type: This is an AFTER INSERT trigger.
Timing: It executes after a new record is inserted into the shareholder table.
Functionality
Purpose: The main purpose of this trigger is to automatically log each new insertion into the shareholder table, ensuring that every addition is recorded for auditing purposes.
Logic:
When a new shareholder record is inserted into the shareholder table, this trigger is activated.
It calls the log_insert_procedure stored procedure, passing relevant details about the new shareholder entry:
The type of event being logged ('INSERT').
The affected entity in the database ('Shareholder').
A key attribute for identification, in this case, the national insurance number of the new shareholder (NEW.national_insurance_number).
A descriptive log message that includes the ID of the newly added shareholder record (CONCAT('New row added with ID: ', NEW.id)).
This information is then recorded in a log, typically stored in a centralized logging table, by the log_insert_procedure.
Type and Timing
Type: This is an AFTER DELETE trigger.
Timing: It executes after a record is deleted from the shareholder table.
Functionality
Purpose: The primary purpose of this trigger is to automatically log each deletion event in the shareholder table, ensuring a comprehensive audit trail for removed shareholder records.
Logic:
When a record is deleted from the shareholder table, the trigger is activated.
It calls the activity_log_auto stored procedure, passing important information about the deleted shareholder:
The type of event ('DELETE').
The entity involved ('Shareholder').
The national insurance number of the deleted shareholder (OLD.national_insurance_number) as a key attribute for identification.
A descriptive log message, including the ID of the deleted record (CONCAT('Deleted Row with id: ', OLD.id)).
The activity_log_auto procedure then logs these details in a centralized logging table, effectively capturing the deletion event.
reg_body_of_country
Type and Timing
This is an AFTER INSERT trigger.
Timing: It executes before an insert operation on the company table.
Logic
Condition Check: The trigger first checks if the city_id field of the new record (NEW.city_id) is not null. This ensures that the automation only proceeds if there is a city specified for the company, which is essential for determining the appropriate registration body.
Determination of registration_body_id: If the condition is met, the trigger then executes a subquery to find the id of the registration body (r.id) that corresponds to the city and country of the new company. It does this by:
Joining the registration_body (r), country (n), and city (c) tables.
Matching the country code of the city (c.country_code) with that of the country (n.code), and also ensuring that the registration body's country code (r.country_code) matches the same country code.
Selecting the registration body where the city's ID matches the new company's city ID (c.id = NEW.city_id).
Assignment: The result of the subquery (i.e., the appropriate registration_body_id) is then assigned to the registration_body_id field of the new company record (NEW.registration_body_id).
Event: BEFORE INSERT on the phone_number table.
Objective: To automatically generate a standardized phone number for each employee based on their associated company's country ISD code and zip code.
Logic
Fetching ISD Code and Zip Code:
The trigger extracts the ISD code and the zip code by joining the country, company, and employee tables. This ensures that the phone number reflects the geographical and organizational context of the employee.
Random Digit Generation:
Two sets of random digits are generated: one set of three digits and another set of four digits, to be incorporated into the phone number.
Phone Number Construction:
If an employee_id is provided in the new record (indicating a valid employee), the trigger constructs the phone number by combining the ISD code, zip code's last three digits, and the generated random digits in the specified format.
log_salary_insert
Event: AFTER INSERT on the staff_salary table.
Purpose: To log a message in the activity log whenever a new staff salary record is inserted, enhancing traceability and auditability.
Logic
Employee Email Retrieval:
Retrieves the email address of the employee associated with the newly inserted salary record by joining the employee and staff_salary tables. This ensures that the log message can be associated with a specific employee by their email.
Logging the Event:
Calls the stored procedure activity_log_auto, passing 'INSERT' as the log type, 'Staff_Salary' as the entity affected, the staff_id (employee ID) as the key column, and a message indicating that a new payroll record has been added, along with the staff member's email address. This provides a clear, informative log entry for each salary record insertion.
log_salary_delete
Event: AFTER DELETE on the staff_salary table.
Purpose: The trigger's goal is to log a specific message in the activity log upon the deletion of a staff salary record to aid in tracking and auditing database changes related to staff salaries.
Logic
Employee Email Retrieval:
Upon the deletion of a staff salary record, the trigger retrieves the email address of the associated employee by joining the employee and staff_salary tables. This action is performed using the OLD keyword to access the staff ID of the deleted record, ensuring that the log entry can be linked to a specific individual.
Logging the Event:
Utilizes the stored procedure activity_log_auto, providing 'DELETE' as the log type, 'Staff_Salary' as the entity, the staff_id as the key column, and a constructed message that details the deletion of the payroll record along with the staff member's email address. This yields a comprehensible and detailed log entry for the deletion action.
delete_employee_record
Event: BEFORE DELETE on the employee table.
Purpose: To automatically clean up related data from various tables (crew, staff, staff_salary, crew_info, phone_number) when an employee record is deleted, thereby maintaining data consistency and integrity across the database.
Logic
Employee ID Capture - The trigger captures the ID of the employee to be deleted (OLD.id) and stores it in a variable employee_id_to_delete. This is crucial because once the deletion proceeds, the reference to OLD.id would not be accessible in the subsequent steps.
Deletion of Related Records - The trigger performs a cascade of deletions across tables that hold references to the employee ID. Specifically, it deletes records from:
crew where crew_id matches the employee's ID.
staff where staff_id matches the employee's ID.
staff_salary where staff_id matches the employee's ID.
crew_info where crew_id matches the employee's ID.
phone_number where employee_id matches the employee's ID.