Skip to content

Instantly share code, notes, and snippets.

@1xch
Last active August 29, 2015 14:02
Show Gist options
  • Save 1xch/b13db0fb953ef7342978 to your computer and use it in GitHub Desktop.
Save 1xch/b13db0fb953ef7342978 to your computer and use it in GitHub Desktop.
closer approximation
"""
This gist provides several mixins to be used on any number of sqlachemy models
1. HasLogMixin, provides a list EntityLog items specific and attached to an instance of the class
2. IsActor or IsReceiver mixins that allow the class to be related to an EntityLog item
as an actor or receiver
The ideal goal is EntityLog items, relatable to specific instances, and queryable by actor/receiver
attachable to any number of items with mixins.
most likely requires something approximating:
http://docs.sqlalchemy.org/en/rel_0_9/_modules/examples/generic_associations/discriminator_on_association.html
but I haven't been able to adapt it
"""
import random
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy import create_engine, Integer, Column, String, ForeignKey, Table
from sqlalchemy.orm import Session, relationship, backref
# from sqlalchemy.ext.associationproxy import association_proxy
@as_declarative()
class Base(object):
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
id = Column(Integer, primary_key=True)
class EntityLog(Base):
info = Column(String)
actor = relationship("Actor", uselist=False, backref="entity_log_actor")
receiver = relationship("Receiver", uselist=False, backref="entity_log_receiver")
def __init__(self, **kwargs):
if kwargs.get('actor'):
self.add_actor(kwargs.pop('actor'))
if kwargs.get('receiver'):
self.add_receiver(kwargs.pop('receiver'))
self.info = str(kwargs)
def add_actor(self, mdl):
a = Actor()
setattr(a, mdl.__tablename__, mdl)
setattr(self, 'actor', a)
def add_receiver(self, mdl):
r = Receiver()
setattr(r, mdl.__tablename__, mdl)
setattr(self, 'receiver', r)
class Actor(Base):
entity_log_id = Column(Integer, ForeignKey("entitylog.id"))
class Receiver(Base):
entity_log_id = Column(Integer, ForeignKey("entitylog.id"))
class IsActorMixin(object):
@declared_attr
def is_actor(cls):
actor_assoc = Table(
"{}_actor_assoc".format(cls.__tablename__),
cls.metadata,
Column("actor_id",
ForeignKey('actor.id'),
primary_key=True),
Column("{}_id".format(cls.__tablename__),
ForeignKey("{}.id".format(cls.__tablename__)),
primary_key=True),
extend_existing=True
)
return relationship("Actor",
backref=backref("{}".format(cls.__tablename__), uselist=False),
secondary=actor_assoc)
class IsReceiverMixin(object):
@declared_attr
def is_receiver(cls):
rec_assoc = Table(
"{}_perf_assoc".format(cls.__tablename__),
cls.metadata,
Column("receiver_id",
ForeignKey('receiver.id'),
primary_key=True),
Column("{}_id".format(cls.__tablename__),
ForeignKey("{}.id".format(cls.__tablename__)),
primary_key=True),
extend_existing=True
)
return relationship("Receiver",
backref=backref("{}".format(cls.__tablename__), uselist=False),
secondary=rec_assoc)
class HasLogMixin(object):
@declared_attr
def log(cls):
log_assoc = Table(
"{}_log".format(cls.__tablename__),
cls.metadata,
Column("entitylogid",
ForeignKey("entitylog.id"),
primary_key=True),
Column("{}_id".format(cls.__tablename__),
ForeignKey("{}.id".format(cls.__tablename__)),
primary_key=True),
)
return relationship("EntityLog", secondary=log_assoc)
class ModelOne(HasLogMixin, IsActorMixin, IsReceiverMixin, Base):
tag = Column(String)
class ModelTwo(HasLogMixin, IsActorMixin, IsReceiverMixin, Base):
tag = Column(String)
engine = create_engine('sqlite://', echo=True)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
session = Session(engine)
a = ModelOne(tag="ONE")
b = ModelTwo(tag="Two")
c = ModelOne(tag="3")
d = ModelTwo(tag="IV")
perf_opts = [a, b, c, d]
a.log.append(EntityLog(actor=a, receiver=random.choice(perf_opts)))
for x in perf_opts:
for i in range(5):
x.log.append(EntityLog(actor=x, receiver=random.choice(perf_opts)))
for i in range(5):
x.log.append(EntityLog(actor=random.choice(perf_opts), receiver=x))
session.add_all([a, b, c, d])
session.commit()
session.query(Actor).filter_by(modelone=a)
# session.query(EntityLog).filter_by(actor=a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment