How to add many constrains to a mysql database - mysql

I am trying to set up a MySQL database. The final database will consist of approx. 200 columns distributed over 7 tables. Now I’ve got the problem that I’d like to add check constraints to most of the columns. Some columns will only have one constraint, others will have many and/or are affected by columns of different tables.
E.g. rows can only be added to a table if the age is older than 20 years or if the zip code consists of 5 characters and starts with 1 or if the admission date (in table admission) is before the discharge date (in table discharge).
Just three examples. I can think of 1000 more, which is my problem.
I’d like to add these constraints in a more structured way. A trigger with more than 10 constraints will be complex and no one, except for the author will be able to reconstruct all constraints. But if the database will be used for years, many administrators will have to work with the database and maybe add new or remove unnecessary constraints.
DELIMITER $$
CREATE TRIGGER `test``_before_insert` BEFORE INSERT ON `zip`
FOR EACH ROW
BEGIN
IF NEW.zip_id < 5 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint 1';
END IF;
IF NEW.zip_id = 5 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint 2';
END IF;
END $$
DELIMITER ;
That's the way I don't want to handle the problem. 
My question is, if there is a way to declare constraints in a normal-human-readable-way (e.g. one constrain with a nice name per textfile) and add these to the database.

Unfortunately, the check constraint in MySQL does not work. You can learn more at this SO question. Even the accepted answer for this question suggests the use of triggers.
You are on the right track when you decided to use triggers. However you have a few misconceptions.
A trigger is basically defined on an event on a table. As you have 7 tables, you will have 7 separate triggers per table, at least. Read more about triggers in MySQL at MySQL Reference Manual.
It is you and you only that has to find ways to keep the code well organized so that your teammates and even you can understand it well. Everything that you need to do is follow the best practices followed across the software industry. For a few hints you can refer here and here on dba.stackexchange.com.

I have thought about my problem over, and have another argument and solution about the checking of constrains in a trigger.
First, the argument: I probably need at least a BEFORE INSERT and a BEFORE UPDATE trigger to check my data. Both triggers are more or less identical. If a constrain changes over time, I have to submit the change to both triggers or my data can be come inconsistent.
I thought of stored procedures to implement one constrain, which can be called in the INSERT and UPDATE trigger. Now If I change a procedure, it affects both triggers.
DROP TRIGGER IF EXISTS test_before_insert;
DROP PROCEDURE IF EXISTS `procedureLess5`;
DROP PROCEDURE IF EXISTS `procedureEquals5`;
DELIMITER $$
CREATE PROCEDURE `procedureLess5` (IN myInput INT)
BEGIN
IF myInput < 5 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint 1';
END IF;
END $$
CREATE PROCEDURE `procedureEquals5` (IN myInput INT)
BEGIN
IF myInput = 5 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'check constraint 2';
END IF;
END $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON `zip`
FOR EACH ROW
BEGIN
CALL procedureLess5(NEW.zip_id);
CALL procedureEquals5(NEW.zip_id);
END $$
DELIMITER ;
Is this an opportunity?
How about the performance of my database if I have more than 20 called procedures?
Or do you think of another way? I’m not fixed to MySQL, PostgreSQL is also an opportunity. Is it better/faster/more standard to use CHECK CONSTRAINS in PostgreSQL?

Related

MYSQL trigger before delete (instead of deleting rather update

I have two tables, one containing candidate information and the other containing the personal information of everyone considered as a person in the database. However, a candidate should not be deleted from the database, their non-personal data should be kept for record. The deletion of a candidate must result in the deletion of his personal data only. So i am trying to write a before delete trigger on the candidate table that takes the id of the candidate we are trying to delete and sets all their personal info to null. When i run the trigger, it only returns a msg saying candidate was deleted however when i check the personal info table, the row for that candidate still has all the information. what might i be doing wrong?
here is the code for the trigger:
USE `agence_interim`;
DELIMITER $$
DROP TRIGGER IF EXISTS agence_interim.candidat_BEFORE_DELETE$$
USE `agence_interim`$$
CREATE DEFINER = CURRENT_USER TRIGGER `agence_interim`.`candidat_BEFORE_DELETE` BEFORE DELETE ON `candidat` FOR EACH ROW
BEGIN
DECLARE errorMessage VARCHAR(255);
Update personne SET personne.id_personne = null,
personne.nom = null,
personne.prenom = null,
personne.email = null,
personne.telephone =null,
personne.date_naissance =null,
personne.description = null
WHERE personne.id_personne = OLD.id_personne;
SET errorMessage = CONCAT('The personal information for candidate number ',
OLD.id_personne,
' has been deleted');
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = errorMessage;
END$$
DELIMITER ;
I'm afraid this is not possible using a trigger in MySQL.
Using a SIGNAL statement in the trigger body aborts the DELETE action that spawned the trigger, but when the trigger is aborted, this also cancels all subordinate changes executed within the trigger body (and also any actions performed by triggers spawned by those changes, etc.).
There is no support for "instead of" triggers in MySQL. Either all changes succeed, or none of them succeed.
To do what you want, you can't use DELETE from the client.
You must use UPDATE.

Protecting database data

Currently I'm using a MySQL database. Let's say that I have some data regarding last month. When the data has been verified I want to "lock" it, so when my boss asks me if the data is correct, I can answer yes, because I'm certain that the data couldn't have been altered in the mean time.
Is there a way to "lock" data rows or cells from being modified? How could I do that?
Mysql innoDB lock may works, but is not permanent I think (related to transactions). Check yourself here
I would suggest you add an extra column in your table, name it for eg. validated with default value 0. Then when every rows are validated, you change validated value to 1. If so, you can add a trigger to check update on this current table.
delimiter $$
CREATE TRIGGER updateRestrictionOnMyTable
BEFORE UPDATE ON my_table
FOR EACH ROW
BEGIN
IF OLD.validated > 0 THEN
SIGNAL SQLSTATE VALUE '99999'
SET MESSAGE_TEXT = 'You cannot update validated rows';
END IF;
END$$
delimiter ;

Alter a where clause on a update through a trigger or similar

I'm currently building a replication database (for reporting from) for an already existing database and we are wanting to obfuscate/hash certain columns. Both are on AWS RDS platform with the replication set up as a 'read replica' of the source.
One of the issues with using RDS Replication I've found is you cannot specify which columns to ignore (given that RDS read replicas are supposed to be 1:1 this isn't surprising and I fully understand I'm doing something very niche)
The solution to this problem was to set up triggers on updates/inserts to alter these values, like so:
DELIMITER $$
CREATE TRIGGER clients_insert_obfuscate
BEFORE INSERT ON clients
FOR EACH ROW
BEGIN
SET NEW.access_token = NULL, NEW.user_token_ttl = 0;
END$$
DELIMITER ;
However one of the values we want to alter is a primary key (the PKs on this table are used as coupon code redemption numbers).
Which leads me to my question - is there anyway of altering the where clause in a update before its executed from within mysql? So on the replica databse, instead of matching against the unhashed code its matching against the hashed code?
So far I have this:
DELIMITER $$
CREATE TRIGGER insert_obfuscate
BEFORE INSERT ON codes
FOR EACH ROW
BEGIN
SET NEW.code = SHA2(NEW.code, 256);
END$$
DELIMITER ;
DELIMITER $$
CREATE TRIGGER update_obfuscate
BEFORE UPDATE ON codes
FOR EACH ROW
BEGIN
SET NEW.code = SHA2(NEW.code, 256);
END$$
DELIMITER ;
So the insert is fine - but the update trigger is only looking at the params to update - not the where clause.
I understand a trigger might not be the right route to take on this but I'm struggling to find anything else.
Is there anyway of doing this or do I need to look at changing the schema? I would prefer not to change the schema on a production DB though.
Thanks

Preventing the deletion of a specific row in a database

I have a website that is linked to a database. When a user is logged in, they have the ability to delete something called a category. The website creates a prepared statement and removes this category from the database.
I want to be able to prevent the deletion of categories with a specific name or id. This is simple enough to do a check using jquery, but I want to add another layer of security by adding a check within the database. Couple questions...
Trigger or procedure? I have never used procedures before, and from what little trigger experience I have with triggers, I don't know how to go about the issue. Assuming that triggers can be used, how would I get the category being deleted? And then how would I go about stopping that row in the database from being deleted?
As a start, I have the following code for a trigger.
delimiter $$
CREATE TRIGGER category_delete BEFORE DELETE ON categories
FOR EACH ROW
BEGIN
END$$
delimiter ;
Throw an exception from within the trigger to abort the deletion:
delimiter $$
CREATE TRIGGER category_delete BEFORE DELETE ON categories
FOR EACH ROW
BEGIN
IF old.id = 5 THEN -- use whatever condition you need
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'May not delete id 5';
END IF;
END$$
delimiter ;
Just add a trigger and bound it.
Use the power of the database to maintain the business logic and keep it consistent and what is required - despite whatever PHP, JQuery etc. is throwing at it. It is the primary business assert

creating a trigger to lock and unlock a record

I am creating a php script for a MySQL database whereby I call a MySQL trigger..
The trigger should affect a table which is effectively an invoice:
So when I update a field called 'date_invoiced' from its NULL default to a valid date it then locks the whole record from being updated unless you have permission via your MySQL logon to change it back to its default NULL, (effectively 're-opening' the invoice)
No idea how to do this, any help would be great
You can't put a lock on a row. I suggest you use a TRIGGER on update, which makes the update fail if date_invoiced is NOT NULL. Unless username is 'superman'.
I think that you can code what you want following this example.
DELIMITER ||
CREATE TRIGGER upd_lock
BEFORE UPDATE
ON table_name
FOR EACH ROW
BEGIN
IF OLD.date_invoiced IS NOT NULL AND USER() NOT LIKE '\'superman\'#%' THEN
SIGNAL SQLSTATE VALUE '45000' SET MESSAGE_TEXT = '[upd_lock] - Record is locked';
END IF;
END;
||
DELIMITER ;
Adding triggers is essential for the development of complex MySQL databases that retain enforced referential integrity. Foreign keys cannot handle complex cases that perhaps involve more than one column (such as an item_id and item_type_id scenario).
SUPER is required when creating or dropping trigger only when binary logging is turned on.
The reason appears to be related to replication issues (MySQL 5.0 documentation).
RTM.and RTM
Read this link to ... & this threads Applying column permissions for a table over a trigger , Can't create MySQL trigger with TRIGGER privilege on 5.1.32