I am struggeling to create a trigger within MySQL, so that everytime I am inserting a value into a column named title a HASH shall be created and stored in the column title_hash. Since I don’t know how this works I found this code while googling:
CREATE TRIGGER insertModelHash
BEFORE
INSERT
ON
products
FOR EACH ROW SET
NEW.model_hash = CONV(RIGHT(MD5(NEW.products_model), 16), 16, 10)
The MySQL-reference tells me, that this means:
- Create a trigger called
insertModelHash… - … before inserting row int table
products… - use the functions
MD5, RIGHT, CONVon the columnproducts_modelin every new row I intend to insert.
The 3. point needs more explanation:
- I guess, that
NEWis some sort of identifier of new rows. SoNEW.products_modelpoints to the columnproducts_modelin the current (new) row. - Then
MD5is issued. Since I want to use SHA-2 it is obvious for me to changeMD5(NEW.products_model), 16)===>SHA2(NEW.products_model), 224). - And now I struggle: Why does this guy use
CONV(RIGHT(...)...)? Is this really necessary?
Additional information: Right now, I am doing
hashlib.sha224(title).hexdigest()
in Python and store this value.
I appreciate any suggestions/explanations!
To answer your three questions:
The
NEWkeyword references the ‘pseudo-table’ for the record that would be inserted. On an updated trigger, you can access both ‘NEW’ and ‘OLD’, and on a delete, just ‘OLD’.Yes, MD5 is used to create the hash. However, in your question, you have part of the parameter to the ‘RIGHT’ function included. It’s only
MD5(NEW.products_model)(there’s no, 16). And yes, you can substitute SHA2 for MD5, if it’s available (it’s only available if MySQL is configured for SSL support).The
RIGHT(string, number)simply takes the right ‘number’ characters from ‘string’.The CONV() function is used to convert a number between bases. The combination of these last two functions takes the right 16 characters of the hash, and converts them from base 16 (hex) to base 10 (decimal).
And the answer is no, you don’t need them if all you want to do is store the hash itself.