How to insert UUID automatically in a MySQL colum?

1

Is there any way to insert a UUID automatically into a table field, just as it does with a field of type AUTO_INCREMENT ?

In a framework for PHP, CakePHP, when we set the primary key to VARCHAR(40) , it inserts a UUID automatically, as if it were the auto increment of the table.

Is there a way to do this directly through MySQL? Or do we always have to set the UUID at the time of INSERT ?

Example:

Usuarios
 - uuid
 - nome
 - senha
    
asked by anonymous 25.02.2015 / 19:56

1 answer

5
Since the auto-increment needs static constant data and the UUID would have to be generated dynamically, I think the only way is to create a trigger, something like this:

CREATE TRIGGER before_insert_usuarios
    BEFORE INSERT ON usuarios
    FOR EACH ROW
    SET new.uuid = uuid();
    
25.02.2015 / 20:03