Public feed #892782

Wolever

public python v1 · immutable
Raw Edit
·published 2008-02-05 18:32 UTC
rendered paste body
#!/usr/bin/env pythonfrom elixir import *from sqlalchemy import *import threadingclass Project(Entity):    has_field('name', Unicode, primary_key=True)class ProjectIdMapperExtension(MapperExtension):    def before_insert(self, mapper, connection, instance):        # If we don't have an ID already,        # grab the next ID in this project        if not instance.id:            # Grab the underlying SQLAlchemy table            ticket_table = instance._descriptor.entity.table            if not hasattr(self, '_thread_local'):                self._thread_local = threading.local()            if not hasattr(self._thread_local, 'projects'):                self._thread_local.projects = {}            project_contexts = self._thread_local.projects            # Check if we already have an entry for this project            if project_contexts.has_key(instance.project_name):                project_contexts[instance.project_name] += 1            else:                # No entry -- query for the next ID                qry = select([func.max(instance.c.id)], instance.c.project_name == instance.project_name)                rproxy = qry.execute()                last_id  = rproxy.fetchone()[0]                if not last_id: last_id = 0                project_contexts[instance.project_name] = last_id + 1            instance.id = project_contexts[instance.project_name]    def after_insert(self, mapper, connection, instance):        # After this insert is over, trash the counter (it may well expire)        if hasattr(self, '_thread_local'):            if hasattr(self._thread_local, 'projects'):                del self._thread_local.projectsfrom elixir.fields import Statement, HasFieldfrom elixir.relationships import BelongsTofrom elixir.options import UsingMapperOptionsclass ProjectId(object):    def __init__(self, entity):        BelongsTo(entity, 'project', of_kind='Project', column_kwargs={"primary_key": True})        HasField(entity, 'id', Integer, default=0, primary_key=True, autoincrement=False)        UsingMapperOptions(entity, extension=ProjectIdMapperExtension())has_project_and_id = Statement(ProjectId)class Milestone(Entity):    has_project_and_id()    has_field('name', Unicode)metadata.connect("sqlite://in_memory")metadata.engine.echo = Truecreate_all()y = Project(name='fizzle')x = Milestone(project=y, name='stuff0')n = Milestone(project=y, name='stuff1')n = Milestone(project=y, name='stuff2')objectstore.flush()