How to insert UUID automatically into a Mysql Database?

Asked

Viewed 1,769 times

1

Is there any way to insert a UUID automatically in a table field, in the same way as with a field of the type AUTO_INCREMENT?

In a framework for PHP, Cakephp, when defining the primary key as VARCHAR(40), he inserts a UUID automatically, as if it were auto table increment.

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

Example:

Usuarios
 - uuid
 - nome
 - senha
  • You need to improve something to accept?

  • @bigown, I was told that on shared servers, this TRIGGER is blocked. Does it proceed? That’s why I hadn’t marked :\

  • As far as I know it is not no, and if it is case by case. I see no reason to be blocked and from my experience, never seen to be. And it’s not so easy to block this, would have to tamper with the Pgsql code.

1 answer

6


Since autoincrement needs static constant data and UUID would have to be generated dynamically, I think the only way is to create a trigger, something like that:

CREATE TRIGGER before_insert_usuarios
    BEFORE INSERT ON usuarios
    FOR EACH ROW
    SET new.uuid = uuid();

I put in the Github for future reference.

  • But that wouldn’t change the uuid all Insert? Even if the record already has one uuid?

  • 1

    But if it’s a insert how would he change anything? Each line will only have one insert. Then you can only do update on the line.

  • True. My mistake.

  • Now that will be useful. I don’t know how to use Rigger, and I will use it in the system :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.