Is there a way to define a column (primary key) as uuid in sqlalchemy if using postgresql?

+2  A: 

You could try writing a custom type, for instance:

import sqlalchemy.types as types

class UUID(types.TypeEngine):
    def get_col_spec(self):
        return "uuid"

    def bind_processor(self, dialect):
        def process(value):
            return value
        return process

    def result_processor(self, dialect):
        def process(value):
            return value
        return process

table = Table('foo', meta,
    Column('id', UUID(), primary_key=True),
Florian Bösch
This doesn't even work, it's just a cut-and-paste job from the dummy type example from the docs. Tom Willis' answer below is much better.
Jesse Dhillon
+1  A: 

In addition to Florian's answer, there's also this blog entry. It looks similar except that it subclasses types.TypeDecorator instead of types.TypeEngine. Does either approach have an advantage or disadvantage over the other one?

Jacob Gabrielson
+6  A: 

I wrote this

Unless I'm missing something the above solution will work if the underlying database has a UUID type. If it doesn't, you would likely get errors when the table is created. The solution I came up with I was targeting MSSqlServer originally and then went MySql in the end, so I think my solution is a little more flexible as it seems to work fine on mysql and sqlite. Haven't bothered checking postgres yet.

Tom Willis
This should have been chosen as the answer, I guess you posted it much later.
Jesse Dhillon
yeah I posted it after I saw referrals from Jacob's answer.
Tom Willis
Note that if you're using version 0.6 or greater, the MSBinary import statement in Tom's solution should be changed to "from sqlalchemy.dialects.mysql.base import MSBinary". Source:[email protected]/msg18397.html
Cal Jacobson