Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random ids in sqlalchemy (pylons)

I'm using pylons and sqlalchemy and I was wondering how I could have some randoms ids as primary_key.

like image 543
Cedric Avatar asked Oct 05 '09 18:10

Cedric


3 Answers

the best way is to use randomly generated UUIDs:

import uuid

id = uuid.uuid4()

uuid datatypes are available natively in some databases such as Postgresql (SQLAlchemy has a native PG uuid datatype for this purpose - in 0.5 its called sqlalchemy.databases.postgres.PGUuid). You should also be able to store a uuid in any 16 byte CHAR field (though I haven't tried this specifically on MySQL or others).

like image 169
zzzeek Avatar answered Oct 21 '22 09:10

zzzeek


i use this pattern and it works pretty good. source

from sqlalchemy import types
from sqlalchemy.databases.mysql import MSBinary
from sqlalchemy.schema import Column
import uuid


class UUID(types.TypeDecorator):
    impl = MSBinary
    def __init__(self):
        self.impl.length = 16
        types.TypeDecorator.__init__(self,length=self.impl.length)

    def process_bind_param(self,value,dialect=None):
        if value and isinstance(value,uuid.UUID):
            return value.bytes
        elif value and not isinstance(value,uuid.UUID):
            raise ValueError,'value %s is not a valid uuid.UUID' % value
        else:
            return None

    def process_result_value(self,value,dialect=None):
        if value:
            return uuid.UUID(bytes=value)
        else:
            return None

    def is_mutable(self):
        return False


id_column_name = "id"

def id_column():
    import uuid
    return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)

#usage
my_table = Table('test',metadata,id_column(),Column('parent_id',UUID(),ForeignKey(table_parent.c.id)))

Though zzzeek I believe is the author of sqlalchemy, so if this is wrong he would know, and I would listen to him.

like image 5
Tom Willis Avatar answered Oct 21 '22 10:10

Tom Willis


Or with ORM mapping:

import uuid
from sqlalchemy import Column, Integer, String, Boolean

def uuid_gen():
    return str(uuid.uuid4())

Base = declarative_base()
class Device(Base):
    id = Column(String, primary_key=True, default=uuid_gen)

This stores it as a string providing better database compatibility. However, you lose the database's ability to more optimally store and use the uuid.

like image 2
HypeXR Avatar answered Oct 21 '22 10:10

HypeXR