On Monday, January 24, 2011 11:11 AM, Artur Reilin wrote:

>> Hi,
>>
>> I have put together a simple uuid generation method in sqlite:
>>
>>   select '{' || hex( randomblob(4)) || '-' || hex( randomblob(2))
>>              || '-' || '4' || substr( hex( randomblob(2)), 2) || '-'
>>              || substr('AB89', 1 + (abs(random()) % 4) , 1)  ||
>>              substr(hex(randomblob(2)), 2) || '-' || hex(randomblob(6)) 
>> ||
>> '}';
>>
>> It's based on the description for v.4 uuid's in wikipedia
>> https://secure.wikimedia.org/wikipedia/en/wiki/Uuid .
>>
>> But I am thinking there may be a better (or another) method to do this
>> in sqlite, without the need to use something external?
>>
>> thanks
>
> http://sqlite.org/lang_corefunc.html
>
> randomblob(N)
> The randomblob(N) function return an N-byte blob containing pseudo-random
> bytes. If N is less than 1 then a 1-byte random blob is returned.
>
> Hint: applications can generate globally unique identifiers using this
> function together with hex() and/or lower() like this:
> hex(randomblob(16))
>
> lower(hex(randomblob(16)))
>

And since this doesn't give the UUID in the form you wish, and failing that 
any other suitable way to do it presents itself to you, you could do worse 
than create a custom function (see 
http://www.sqlite.org/c3ref/create_function.html and 
http://www.sqlite.org/c_interface.html#cfunc) which takes the randomblob 
data and formats it according to the UUID v4 structure.

If you do take this route, then you can create the randomblob data within 
your custom function (hint: have a look at how the randomblob function is 
implemented in the sqlite source code), rather than passing it in as a 
parameter -- the advantage being that you can ensure that you create the 
correct size blob in one go and then split it up appropriately into the 
structure required.

Cheers
Andy



_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to