UUID and PostgreSQL

June 2nd, 2011 Blog 0 Comments

I often use UUID values as secondary identifiers for my domain objects. This is usually generated for my domain entity very simply as follows:


and set directly either as a field variable on instantiation or sometimes in an interceptor on save.

On a recent project we had to migrate some data across some new entities and needed something outside the application to generate the UUID values for each record. I knew that PostgreSQL supported UUID generation – though I had never used this before – and even has a UUID data type. Getting to the function itself proved a little more challenging as it isn’t actually included on a typical installation and is found within the postgres-contrib package. So, to install…

apt-get install postgresql-contrib
sudo su -c "psql pdrivers < /usr/share/postgresql/8.4/contrib/uuid-ossp.sql" postgres

The above installs the relevant contrib package, and creates the UUID functions from the script within the unpacked contrib directory (substitute version as required). We are also installing the function as a superuser (postgres in this case) as we need a user with the ability to install functions using C code.

To generate UUID values execute as follows:

SELECT uuid_generate_v1();


Some good references on the available functions can be found here with some further info on the package OSSP UUID pages here.

VirtualBox update woes
RIP Steve Jobs

About Takis Diakoumis

I am a software developer from Melbourne, Australia. I promote and support open source software and release whatever I can of my own work under the GPL license.

» has written 30 posts

No Comments