Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python's UUID to generate unique IDs, should I still check for duplicates?

I'm using Python's UUID function to create unique IDs for objects to be stored in a database:

>>> import uuid
>>> print uuid.uuid4()
2eec67d5-450a-48d4-a92f-e387530b1b8b

Is it ok to assume that this is indeed a unique ID?

Or should I double-check that this unique ID has not already been generated against my database before accepting it as valid.

like image 539
ensnare Avatar asked Jun 01 '14 18:06

ensnare


Video Answer


2 Answers

I would use uuid1, which has zero chance of collisions since it takes date/time into account when generating the UUID (unless you are generating a great number of UUID's at the same time).

You can actually reverse the UUID1 value to retrieve the original epoch time that was used to generate it.

uuid4 generates a random ID that has a very small chance of colliding with a previously generated value, however since it doesn't use monotonically increasing epoch time as an input (or include it in the output uuid), a value that was previously generated has a (very) small chance of being generated again in the future.

like image 74
14 revs, 12 users 16% Avatar answered Oct 13 '22 19:10

14 revs, 12 users 16%


You should always have a duplicate check, even though the odds are pretty good, you can always have duplicates.

I would recommend just adding a duplicate key constraint in your database and in case of an error retry.

like image 6
Wolph Avatar answered Oct 13 '22 18:10

Wolph