KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: How to generate a UUID
PRODUCT: 4D | VERSION: 11.4 | PLATFORM: Mac & Win
Published On: August 20, 2009

As explained in Wikipedia:

"A Universally Unique Identifier (UUID) is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE). The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve name conflicts."

4D makes extensive use of UUIDs internally. Applications that use the iCalendar format make extensive user of UUIDs to ID calendars and events. Every hard drive in your computer has a UUID. And now you can add UUIDs to your own database elements in 4D v11 SQL.

The routine below, UTIL_NewUUID, returns a version 4 UUID as specified in rfc 4122. Note the UTIL_Random command is from the Tech Tip: A wrapper for Random with added functionality.

'UTIL_NewUUID -> STRING

C_TEXT($0;$UUID_T)
C_LONGINT($Ndx;$Idx;$SOA;$RIS;$Rnd_L;$End_L)
C_TEXT($Chars_T)

`====================== Initialize and Setup ================================

$Chars_T:="0123456789abcdef"
$End_L:=Length($Chars_T)-1

`======================== Method Actions ==================================

`// rfc 4122 requires this format for a version 4 (random number) UUID
$UUID_T:="########-####-4###-####-############"


For ($Ndx;1;Length($UUID_T))
    If ($UUID_T[[$Ndx]]="#")
        $Rnd_L:=UTIL_Random (0;$End_L)
        If ($Ndx=20)
            `Must be a value of 8, 9, a, or b
            $Idx:=($Rnd_L & 0x0003) | 0x0008
        Else
            $Idx:=$Rnd_L
        End if
        $UUID_T[[$Ndx]]:=$Chars_T[[$Idx+1]]
    End if
End for

`======================== Clean up and Exit =================================

$0:=$UUID_T

Commented by Neil Dennis on April 29, 2010 at 1:01 PM
WARNING: Testing the generated UUIDs for uniqueness I was able to generate over 200 million without finding a single duplicate. However the UTIL_Random does not seem to produce sufficiently random numbers after a database restart. I found that after only three database restarts and generating IDs I discovered many duplicate UUIDs.