[DDC-451] Add GUID/UUID Id Generator Created: 20/Mar/10  Updated: 13/Aug/12  Resolved: 12/Mar/12

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: ORM
Affects Version/s: 2.0-ALPHA4
Fix Version/s: 2.3
Security Level: All

Type: New Feature Priority: Minor
Reporter: Benjamin Eberlei Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 3
Labels: None


 Description   

We should add an IdGenerator that facilitates the DB Vendors UUID()/GUID() generation facilities.

Although these IdGenerators take more space compared to other Generators there are use-cases which can be only solved with this kind of Id Generator.



 Comments   
Comment by Guilherme Blanco [ 20/Mar/10 ]

Here is a basic GUID generator.

class Guid
{
    /**
     * Generate a GUID
     *
     * @return string
     */
    public static function generate()
    {
        $cpuname     = getenv('COMPUTERNAME');
        $address     = isset($_SERVER['SERVER_ADDR']) ? @$_SERVER['SERVER_ADDR'] : uniqid(hash("md5", time()), true) . time();
        $address     = (trim($cpuname) == '' ? crypt(uniqid(rand(), true)) : $cpuname) . '/' . $address;
        $milisecs        = microtime();
        $randomLong  = (rand(0, 1))? '-':'';
        $randomLong .= rand(1000, 9999).rand(1000, 9999).rand(1000, 9999).rand(100, 999).rand(100, 999);
        
        $string = $address . ':' . $milisecs . ':' . $randomLong;
        $hashString = strtoupper(md5($string));
        
        return substr($hashString, 0, 8).'-'.substr($hashString, 8, 4).'-'.substr($hashString, 12, 4).'-'.substr($hashString, 16, 4).'-'.substr($hashString, 20);
    }
    
    
    /**
     * Verifies if a string is a valid Guid generated acording to this class
     *
     * @param string $guid Guid to be analyzed
     * @return boolean
     */
    public static function match($guid)
    {
        
        $match = preg_match("/^([A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12})$/", $guid);
        
        return $match;
    }
}
Comment by Andy Aja deh [ 12/May/10 ]

I agree, there are some application features that can only be done with GUID.

Comment by Steffen Vogel [ 25/Jul/10 ]

Oh, thats a quite simple implementation of a UUID/GUID generator.

I would prefer something like this:
http://github.com/volkszaehler/volkszaehler.org/blob/master/backend/lib/Util/UUID.php

Its a RFC2144 compatible implementation for UUIDs

Comment by Aigars Gedroics [ 27/Jul/11 ]

Here is complete code how to do this - http://ranskills.wordpress.com/2011/05/26/how-to-add-a-custom-id-generation-strategy-to-doctrine-2-0/.

Comment by Maarten de Keizer [ 23/Nov/11 ]

A couple of months ago I created 2 pull requests for this feature (https://github.com/doctrine/doctrine2/pull/127 and https://github.com/doctrine/dbal/pull/58). It would be nice if the feature is in the next Doctrine release.

Comment by Benjamin Eberlei [ 12/Mar/12 ]

Implemented

Comment by Benjamin Eberlei [ 12/Mar/12 ]

Details: This works with Database provided GUID functionality only for now, the UUID Generator uses the AbstractPlatform#getGuidSqlExpression() function and a SELECT clause to fetch a new guid. A next step might be to add a Platform#supportsGuidGeneration() flag and otherwise fallback to a PHP based generation.

The Id generator in the ORM is pre insert, which makes this very awesome

Comment by Marijn Huizendveld [ 07/Aug/12 ]

There is a nice implementation out there with proper UUID generation and a DBAL datatype.

Comment by Benjamin Eberlei [ 07/Aug/12 ]

starting with 2.3 there are custom id generators and you can do whatever you want. There is also a UUID/GUID type in 2.3 that is using the appropriate vendor database functions to generate those values.

Comment by Menno Holtkamp [ 13/Aug/12 ]

There is also a UUID/GUID type in 2.3 that is using the appropriate vendor database functions to generate those values.

So how would one be able to use this UUID/GUID? Would it be required for the column to be tagged as a @Id and @GeneratedValue with GUID strategy? I would like to have a random string generated which does not act as @Id within Doctrine... The text quoted suggests that it should work out of the box by setting the column type to 'guid', which it does not (2.3.0-RC1).

Simply setting the column type to 'guid' does not trigger the database to generate an ID when INSERTing a row...

Comment by Marco Pivetta [ 13/Aug/12 ]

I'm not sure about PHP's case sensitivity, but as of https://github.com/doctrine/doctrine2/blob/00a5f185444fb5d7c84e445d9ea6d6a68e087f98/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php#L310 I think you should try with "UUID" (uppercase)

Comment by Menno Holtkamp [ 13/Aug/12 ]

Marco, it is indeed 'UUID', but this seems not to kick in when there is no @Id annotation used. I want to use it to come up with an identifier for an Order. It is not a primary key at database level or something like that. I was just wondering whether this new functionality can be used like that. I get the feeling it is not intended to be used like this:

/**
 * Unique Order identifier that acts as reference for an Order even when multiple databases are involved
 * 
 * @var string
 * @ORM\Column(name="order_identifier", type="string", unique=true)
 * @ORM\GeneratedValue(strategy="UUID")
 */
protected $_orderIdentifier;
Comment by Benjamin Eberlei [ 13/Aug/12 ]

Well it is an ID generator. So it has to be with @Id.

Comment by Menno Holtkamp [ 13/Aug/12 ]

Well, yes, that was my question and that is now answered, thanks.

It would be nice though to have UUID generation functionality available for non-database specific IDs as well. For instance for:

  • user account activation tokens
  • payment references
  • invoice reference, etc.

This is now something that has to be implemented at the applciation level. But since we have these generators available, why not re-use it. By adding a @Id annotation, it becomes part of a composite key, which is not the purpose. Maybe I'll dive into the code and see whether this is possible.

Comment by Benjamin Eberlei [ 13/Aug/12 ]

it is available, just take a look at the code.

Comment by Menno Holtkamp [ 13/Aug/12 ]

Well it is an ID generator. So it has to be with @Id.

it is available, just take a look at the code.

Mmm, now I am confused, I think we are mis-communicating.

Maybe using less text and more descriptive examples:

  • is it possible to use Database GUID functionality
    • without using the @Id annotations, to generate values for Entity properties that are not a primary key?
    • note that this Entity unique reference would exist next to a property that does have the @Id annotation

Attempt 1:

/**
 * The Order ID used at database level, which does NOT have any meaning within our domain, solely at database level
 *
 * @var integer
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\SequenceGenerator(sequenceName="orders_id_seq")
 */
protected $_id;

/**
 * The Order reference used at domain level, which DOES have meaning in our domain
 * Typically used to report in emails, printed on Invoices, etc
 *
 * @var string
 * @ORM\Column(name="order_identifier", type="guid")
 */
protected $_orderIdentifier;

Attempt 2:

/**
 * The Order ID used at database level, which does NOT have meaning within our domain, solely at database level
 *
 * @var integer
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\SequenceGenerator(sequenceName="orders_id_seq")
 */
protected $_id;

/**
 * The Order reference used at domain level, which DOES have meaning in our domain
 * Typically used to report in emails, printed on Invoices, etc
 *
 * @var string
 * @ORM\Column(name="order_identifier", type="string", unique=true)
 * @ORM\GeneratedValue(strategy="UUID")
 */
protected $_orderIdentifier;

Based on Benjamin's first answer I guess that this is not possible. Point is, the second answer indicates that it is possible . What is it?

Also note that in Attempt 2, the @GeneratedValue annotation on the second property interferes with the ID generation of the Entity defined at the first property. This is probably to realize composite keys, but can result in unexpected behavior since it replaces the way the primary key is generated?

Comment by Benjamin Eberlei [ 13/Aug/12 ]

Well @GeneratedValue Only works with @Id as I said. But there are low level APIs that you can look up in the UuidGenerator Strategy to use for something like this.

Generated at Wed Jul 23 18:30:33 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.