Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How to create in SQLAlchemy model row with random string when Postgresql is under?

I need to convert from MySQL where I can do like this.

Column(uuid_generator.GUID(), default=uuid.uuid4, nullable=False, unique=True)

import uuid

class GUID(types.TypeDecorator):
    '''Platform-independent GUID type, Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as stringified hex values.'''
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value)
            else:
                # hexstring
                return "%.32x" % value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)
share|improve this question
    
Can you clarify what you mean by "Is under"? Do you mean when you are using PostgreSQL as your database backend? –  Mark Hildreth Nov 21 '13 at 18:01
    
You can do the same for Postgresql, as uuid.uuid4 is actually a python function, and not RDBMS specific. –  van Nov 21 '13 at 19:15
    
@van I got error ProgrammingError type binary does not exist, BINARY(16) NOT NULL, but it works for mysql –  Damir Nov 21 '13 at 19:54
    
Have you read about and tried to use native Postgresql UUID type? –  van Nov 21 '13 at 21:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.