How to use UUID instead of integers in MySQL DB

I would like to use the python function uuid()to assign my MySQL id instead of integer and AUTOINCREMENT.

However, it would be nice if it uuid()were generated when the object was created. I have not worked with SQL before. So the only way I can do this is to create a new object in python code, run it uuid()and just assign it manually, but that seems unnecessary.

Is there a way to integrate this into a MySQL database?

If so, what data type should I assign to this column? VARCHAR?

+4
source share
1 answer

MySQL UUID - UUID CHAR(32), , , .

SQLAlchemy Python uuid :

from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID
import uuid

class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql 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)

, Postgres , , UUID.

: uuid.uuid4() ; ( UUID) .

+1

All Articles