def InitMapper( cls, metadata, Parameter, ParameterType, DesignQuantity ): mapper( cls, inherits = Parameter, polymorphic_identity = ParameterType, properties = { '_quantity' : relation( DesignQuantity, collection_class = attribute_mapped_collection('design')) }) cls.quantity = association_proxy('_quantity', 'quantity', creator = lambda k, v: DesignQuantity( design = k, quantity = v ) )
def test_merge_irregular_collection(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) mapper( User, users, properties={ "addresses": relationship( mapper(Address, addresses), backref="user", collection_class=attribute_mapped_collection("email_address"), ) }, ) u1 = User(id=7, name="fred") u1.addresses["*****@*****.**"] = Address(email_address="*****@*****.**") sess = create_session() sess.merge(u1) sess.flush() assert list(u1.addresses.keys()) == ["*****@*****.**"]
def _variables(cls): # Camelcase the tablename to give the Variable inner class # here a specific class name; necessary for reporting on # classes class_name = \ "".join(x.title() for x in cls.vars_tablename[:-1].split('_')) # Because we are constructing Variable inner class with the # 3-arg `type` function, we need to pull out all SA columns # given that initialization order matters for SA! # # * Defines the primary key with correct ordering # * Captures references, as seen in _repr_columns parent_id = Column(ForeignKey( '%s.id' % cls.__tablename__), primary_key=True) key = Column(String(255), primary_key=True) value = Column(JSONType) Variable = type(class_name, (Base,), { '__tablename__': cls.vars_tablename, 'parent_id': parent_id, 'key': key, 'value': value, '_repr_columns': [key, value]}) # Need a reference for the association proxy to lookup the # Variable class so it can reference cls.variable_class = Variable return relationship( Variable, collection_class=attribute_mapped_collection('key'), cascade='all, delete-orphan', lazy="joined")
def InitMapper( cls, metadata, Parameter, ParameterType, ResourceQuantity ): mapper( cls, inherits = Parameter, polymorphic_identity = ParameterType, properties = { '_quantity' : relation( ResourceQuantity, collection_class = attribute_mapped_collection('resource')) }) cls.quantity = association_proxy('_quantity', 'quantity', creator = lambda k, v: ResourceQuantity( resource = k, **v ) )
def transaction_meta_factory(self): """ Creates TransactionMeta class. """ class TransactionMeta( self.declarative_base, TransactionMetaBase ): __tablename__ = 'transaction_meta' TransactionMeta.transaction_log = sa.orm.relationship( self.transaction_log_cls, backref=sa.orm.backref( 'meta_relation', collection_class=attribute_mapped_collection('key') ), primaryjoin=( '%s.id == TransactionMeta.transaction_id' % self.transaction_log_cls.__name__ ), foreign_keys=[TransactionMeta.transaction_id] ) self.transaction_log_cls.meta = association_proxy( 'meta_relation', 'value', creator=lambda key, value: TransactionMeta(key=key, value=value) ) return TransactionMeta
def test_merge_irregular_collection(self): mapper(User, users, properties={ 'addresses': relationship( mapper(Address, addresses), backref='user', collection_class=attribute_mapped_collection('email_address')), }) u1 = User(id=7, name='fred') u1.addresses['*****@*****.**'] = Address(email_address='*****@*****.**') sess = create_session() sess.merge(u1) sess.flush() assert u1.addresses.keys() == ['*****@*****.**']
def test_validator_bulk_dict_set(self): users, addresses, Address = ( self.tables.users, self.tables.addresses, self.classes.Address, ) class User(fixtures.ComparableEntity): @validates("addresses", include_removes=True) def validate_address(self, key, item, remove): if not remove: assert isinstance(item, str) else: assert isinstance(item, Address) item = Address(email_address=item) return item mapper( User, users, properties={ "addresses": relationship( Address, collection_class=collections.attribute_mapped_collection( "email_address" ), ) }, ) mapper(Address, addresses) u1 = User() u1.addresses["e1"] = "e1" u1.addresses["e2"] = "e2" eq_( u1.addresses, { "e1": Address(email_address="e1"), "e2": Address(email_address="e2"), }, ) u1.addresses = {"e3": "e3", "e4": "e4"} eq_( u1.addresses, { "e3": Address(email_address="e3"), "e4": Address(email_address="e4"), }, )
def setup(): """ Set up ORM. Does not create any database tables, see :py:func:`create_tables` for that. """ global resource_metadata_table if resource_metadata_table is None: log.debug('Defining resource metadata table') resource_metadata_table = Table( RESOURCE_METADATA_TABLE_NAME, metadata, Column('resource_id', types.UnicodeText, ForeignKey('resource.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False, primary_key=True), Column('last_extracted', types.DateTime), Column('last_url', types.UnicodeText), Column('last_format', types.UnicodeText), Column('task_id', types.UnicodeText) ) mapper( ResourceMetadata, resource_metadata_table, properties={ '_meta': relationship(ResourceMetadatum, collection_class= attribute_mapped_collection('key'), cascade='all, delete, delete-orphan'), } ) else: log.debug('Resource metadata table already defined') global resource_metadatum_table if resource_metadatum_table is None: log.debug('Defining resource metadatum table') resource_metadatum_table = Table( RESOURCE_METADATUM_TABLE_NAME, metadata, Column('id', types.Integer, nullable=False, primary_key=True), Column('resource_id', types.UnicodeText, ForeignKey( RESOURCE_METADATA_TABLE_NAME + '.resource_id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('key', types.UnicodeText, nullable=False), Column('value', types.UnicodeText) ) mapper(ResourceMetadatum, resource_metadatum_table) else: log.debug('Resource metadatum table already defined')
def test_attribute_mapped_collection(self): users, addresses = self.tables.users, self.tables.addresses mapper(User, users, properties={ 'addresses': relationship( Address, collection_class=attribute_mapped_collection('email_address') ) }) mapper(Address, addresses) u1 = User() u1.addresses = {"email1": Address(email_address="email1")} for loads, dumps in picklers(): repickled = loads(dumps(u1)) eq_(u1.addresses, repickled.addresses) eq_(repickled.addresses['email1'], Address(email_address="email1"))
def variable_association(cls): name = cls.__name__ discriminator = name.lower() # Defines a polymorphic class to distinguish variables stored # for regions, cells, etc. cls.variable_assoc_cls = assoc_cls = type( "%sVariableAssociation" % name, (VariableAssociation,), { '__tablename__': None, # because mapping into a shared table '__mapper_args__': { 'polymorphic_identity': discriminator } }) def _assoc_creator(kv): assoc = assoc_cls() for key, value in kv.items(): assoc.variables[key] = Variable(key=key, value=value) return assoc cls._variables = association_proxy( 'variable_association', 'variables', creator=_assoc_creator) # Using a composite associative proxy here enables returning the # underlying values for a given key, as opposed to the # Variable object; we need both. cls.variables = association_proxy( 'variable_association', 'values', creator=_assoc_creator) def with_characteristic(self, key, value): return self._variables.any(key=key, value=value) cls.with_characteristic = classmethod(with_characteristic) rel = relationship( assoc_cls, collection_class=attribute_mapped_collection('key'), cascade='all, delete-orphan', lazy='joined', single_parent=True, backref=backref('parent', uselist=False)) return rel
class UserPreferences(Base): """ Contains the user preferences data. """ __tablename__ = 'USER_PREFERENCES' ONLINE_HELP_ACTIVE = "online_help_active" VIEWERS_COLOR_SCHEME = "viewers_color_scheme" PROJECT_STRUCTURE_GROUPING = "project_structure_grouping" fk_user = Column(Integer, ForeignKey('USERS.id'), primary_key=True) key = Column(String, primary_key=True) value = Column(String) user = relationship(User, backref=backref("user_preferences", cascade="all, delete-orphan", lazy='joined', collection_class=attribute_mapped_collection("key"))) def __repr__(self): return 'UserPreferences: %s - %s' % (self.key, self.value)
class Detail(AttributeModel): """ Same as property but use text to store the value in case of large-sized value. """ __alias__ = 'detail' __tablename__ = 'metadash_detail' __collector__ = attribute_mapped_collection("key") __outline__ = "value" id = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=True) key = db.Column(db.String(255), nullable=False, index=True, unique_attribute=True) value = db.Column(db.Text(), nullable=True) def __init__(self, key, value): self.key = key self.value = value def __repr__(self): return '<Detail "{}": "{}" of Entiry({})>'.format(self.key, self.value, self.entity)
class Role(AbstractRole[GlobalPermission], Base): """A role defines the set of global permissions :class:`.Permission` of a :class:`.User`. :ivar ~.Role.name: The name of the global role. """ __tablename__ = 'Role' id = db.Column('id', db.Integer, primary_key=True) name = db.Column('name', db.Unicode, unique=True, nullable=False) _permissions: t.MutableMapping[ GlobalPermission, Permission[GlobalPermission]] = db.relationship( 'Permission', collection_class=attribute_mapped_collection('value'), secondary=roles_permissions, backref=db.backref('roles', lazy='dynamic')) @property def uses_course_permissions(self) -> bool: return False
class Release(db.Model): __tablename__ = "releases" id = db.Column(db.String(24), primary_key=True) app_id = db.Column(db.String(24), db.ForeignKey('apps.id', ondelete='cascade'), index=True) app = db.relationship('App', back_populates='releases') binaries = db.relationship( 'Binary', back_populates='release', collection_class=attribute_mapped_collection('platform')) has_pbw = db.Column(db.Boolean()) capabilities = db.Column(ARRAY(db.String)) js_md5 = db.Column(db.String(32)) published_date = db.Column(db.DateTime) release_notes = db.Column(db.Text) version = db.Column(db.String) compatibility = db.Column(ARRAY(db.Text)) is_published = db.Column(db.Boolean)
def setup(self): class B(object): def __init__(self, key, elem): self.key = key self.elem = elem class A(object): elements = association_proxy("orig", "elem", creator=B) m = MetaData() a = Table('a', m, Column('id', Integer, primary_key=True)) b = Table('b', m, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id'))) mapper(A, a, properties={ 'orig':relationship(B, collection_class=attribute_mapped_collection('key')) }) mapper(B, b) self.A = A self.B = B
class OrderProperties(PropertiesMixin, db.Model): """ Makes a relation from an order to a key value pair. This is used to store any dynamic information that needs to be stored next to the required columns of the :class:`backend.models.Order` model. """ order_number = db.Column(db.Integer, db.ForeignKey('order.order_number', ondelete='CASCADE'), primary_key=True) # The relationship from order to order_properties is set to be usable as # a Python dictionary object order = db.relationship( 'Order', backref=db.backref('properties', collection_class=attribute_mapped_collection('key'), cascade='all, delete-orphan'))
def setup(self): class B(object): def __init__(self, key, elem): self.key = key self.elem = elem class A(object): elements = association_proxy("orig", "elem", creator=B) m = MetaData() a = Table('a', m, Column('id', Integer, primary_key=True)) b = Table('b', m, Column('id', Integer, primary_key=True), Column('aid', Integer, ForeignKey('a.id'))) mapper(A, a, properties={ 'orig':relationship(B, collection_class=attribute_mapped_collection('key')) }) mapper(B, b) self.A = A self.B = B
class DonVi(CommonAdjacencyModel): __tablename__ = 'donvi' #_parent_attr_ = 'captren_id' id = db.Column(db.Integer, primary_key=True) ma = db.Column(db.String(255), nullable=True) ten = db.Column(db.String(255), nullable=False) sodienthoai = db.Column(db.String(63)) diachi = db.Column(db.String(255)) email = db.Column(db.String(255)) ghichu = db.Column(db.String(255)) vungmien = db.Column(db.SmallInteger) # tinhthanh_id = db.Column(db.Integer, db.ForeignKey('tinhthanh.id'), nullable=True) tinhthanh = db.relationship('TinhThanh', viewonly=True) tuyendonvi = db.Column(db.SmallInteger, nullable=False) # la trung tam, hay truong hoc ... coquanchuquan = db.Column(db.String(255)) parent_id = db.Column(db.Integer, db.ForeignKey('donvi.id'), nullable=True) loaidonvi = db.Column(db.SmallInteger) #1: kdyt quocte, 2: kdyt tinhthanh giamdoc = db.Column(db.String) sdtgiamdoc = db.Column(db.String) emailgiamdoc = db.Column(db.String) phogiamdoc = db.Column(db.String) sdtphogiamdoc = db.Column(db.String) emailphogiamdoc = db.Column(db.String) hotline_email = db.Column(db.String()) hotline_sodienthoai = db.Column(db.String()) hotline_fax = db.Column(db.String()) children = relationship("DonVi", # cascade deletions cascade="all, delete-orphan", # many to one + adjacency list - remote_side # is required to reference the 'id' # column in the join condition. backref=backref("parent", remote_side=id, viewonly=True), # children will be represented as a dictionary # on the "id" attribute. collection_class=attribute_mapped_collection('id'), ) def __todict__(self): return {"id":self.id, "ma": self.ma,"ten": self.ten, "parent_id": self.parent_id, "tuyendonvi":self.tuyendonvi}
class Event(ProxiedDictMixin, Base): __tablename__ = 'event' __table_args__ = ( Index('ix_event_message_id', 'message_id'), Index('ix_event_type_id', 'event_type_id'), Index('ix_event_generated', 'generated') ) id = Column(Integer, primary_key=True) message_id = Column(String(50), unique=True) generated = Column(PreciseTimestamp()) event_type_id = Column(Integer, ForeignKey('event_type.id')) event_type = relationship("EventType", backref=backref('event_type')) traits = relationship("Trait", collection_class=attribute_mapped_collection('name')) _proxied = association_proxy("traits", "value", creator=lambda name, value: Trait(name=name, value=value)) @property def event_type_string(self): return self.event_type.desc @property def as_dict(self): d = dict(self._proxied) d['message_id'] = self.message_id d['event_type'] = self.event_type_string d['timestamp'] = self.generated return d def __init__(self, message_id, event_type, generated): self.message_id = message_id self.event_type = event_type self.generated = generated def __repr__(self): return "<Event %s ('Event : %s %s, Generated: %s')>" % (self.id, self.message_id, self.event_type, self.generated)
class SocialNetwork(Base): """Stores the social networks that people might be members of """ __tablename__ = 'social_network' id = sa.Column(sa.types.Integer, primary_key=True) name = sa.Column(sa.types.Text, unique=True, nullable=False) url = sa.Column(sa.types.Text, nullable=False) logo = sa.Column(sa.types.Text, nullable=False) by_person = sa.orm.relation( PersonSocialNetworkMap, collection_class=attribute_mapped_collection('person'), cascade="all, delete-orphan", backref='social_network') people = association_proxy('by_person', 'account_name') # Note: You can't set via the people attribute def __init__(self, **kwargs): super(SocialNetwork, self).__init__(**kwargs) @classmethod def find_by_name(self, name, abort_404=True): result = Session.query(SocialNetwork).filter_by(name=name).first() if result is None and abort_404: abort(404, "No such social network object") return result @classmethod def find_by_id(self, id, abort_404=True): result = Session.query(SocialNetwork).filter_by(id=id).first() if result is None and abort_404: abort(404, "No such social network object") return result @classmethod def find_all(self): return Session.query(SocialNetwork).order_by(SocialNetwork.name).all() def __repr__(self): return '<SocialNetwork id="%s" name="%s">' % (self.id, self.name)
class Notification(db.Model): __tablename__ = 'notifications' id = Column(db.Integer, primary_key=True, autoincrement=True) description = Column(db.String(255), nullable=False) type = Column(db.Integer, nullable=False) user_id = Column(db.Integer, db.ForeignKey('users.id')) enabled = Column(db.Integer, default=1) settings = db.relationship( "NotificationSetting", backref="notification", collection_class=attribute_mapped_collection('name'), cascade="all, delete-orphan") def get_setting(self, name, default=None): if name in self.settings.keys(): return self.settings[name].value return default
class Settings(ImmutableProxiedDictMixin, db.Model, SQLAEvent): id = db.Column(db.Integer, primary_key=True) store = db.relationship( "Setting", collection_class=attribute_mapped_collection("key")) _proxied = association_proxy("store", "value") profile_id = db.Column(db.Integer, db.ForeignKey("settings_profile.id"), nullable=False) def on_init(self): process_func = lambda seq: [Field(**d) for d in seq if type(d) is dict] ready = ((c, process_func(l)) for c, l in current_app.provided_settings) for category, opts in ready: for opt in opts: setting = Setting(key=opt.name) setting.value = opt.default setting.category = str(category) db.session.add(setting) self.store[opt.name] = setting
class PortChain(model_base.BASEV2, model_base.HasId, model_base.HasProject): """Represents a Neutron service function Port Chain.""" __tablename__ = 'sfc_port_chains' chain_id = sa.Column(sa.Integer(), unique=True, nullable=False) name = sa.Column(sa.String(db_const.NAME_FIELD_SIZE)) description = sa.Column(sa.String(db_const.DESCRIPTION_FIELD_SIZE)) chain_group_associations = orm.relationship( ChainGroupAssoc, backref='port_chain', order_by="ChainGroupAssoc.position", collection_class=ordering_list('position'), cascade='all, delete-orphan') chain_classifier_associations = orm.relationship( ChainClassifierAssoc, backref='port_chain', cascade='all, delete-orphan') chain_parameters = orm.relationship( ChainParameter, collection_class=attribute_mapped_collection('keyword'), cascade='all, delete-orphan')
class Judging(BaseModel): id = db.Column(db.Integer, primary_key=True, nullable=False) submission: "Submission" judge: "User" comment = db.Column(db.String, nullable=True) scores = db.relationship( "Score", backref="judging", lazy=True, collection_class=attribute_mapped_collection("criteria.value"), cascade="all,delete,delete-orphan", ) submission_id = db.Column(db.Integer, db.ForeignKey("submission.id"), nullable=False) judge_id = db.Column(db.Integer, db.ForeignKey("users.osu_uid"), nullable=False)
class PortPairGroup(model_base.BASEV2, model_base.HasId, model_base.HasProject): """Represents a port pair group model.""" __tablename__ = 'sfc_port_pair_groups' group_id = sa.Column(sa.Integer(), unique=True, nullable=False) name = sa.Column(sa.String(db_const.NAME_FIELD_SIZE)) description = sa.Column(sa.String(db_const.DESCRIPTION_FIELD_SIZE)) tap_enabled = sa.Column(sa.Boolean(), server_default=sa.sql.false(), nullable=False) port_pairs = orm.relationship( PortPair, backref='port_pair_group' ) port_pair_group_parameters = orm.relationship( PortPairGroupParam, collection_class=attribute_mapped_collection('keyword'), cascade='all, delete-orphan') chain_group_associations = orm.relationship( ChainGroupAssoc, backref='port_pair_groups')
class PortChain(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a Neutron service function Port Chain.""" __tablename__ = 'sfc_port_chains' name = sa.Column(sa.String(NAME_MAX_LEN)) description = sa.Column(sa.String(DESCRIPTION_MAX_LEN)) chain_group_associations = orm.relationship( ChainGroupAssoc, backref='port_chain', order_by="ChainGroupAssoc.position", collection_class=ordering_list('position'), cascade='all, delete-orphan') chain_classifier_associations = orm.relationship( ChainClassifierAssoc, backref='port_chain', cascade='all, delete-orphan') chain_parameters = orm.relationship( ChainParameter, collection_class=attribute_mapped_collection('keyword'), cascade='all, delete-orphan')
class ObservationAttribute(Entities): __tablename__ = "observation_attribute" observation_id = Column(Integer, ForeignKey("observation.id"), primary_key=True) attribute = Column(String) value_id = Column(Integer, ForeignKey("attribute_value.id"), primary_key=True) value = relationship("AttributeValue") observation = relationship( Observation, backref=backref( "observation_attributes", collection_class=attribute_mapped_collection("attribute"), cascade="all, delete-orphan", ), )
class MassShiftToCompoundMassShift(Base): __tablename__ = "MassShiftToCompoundMassShift" compound_id = Column(Integer, ForeignKey(CompoundMassShift.id, ondelete="CASCADE"), index=True, primary_key=True) individual_id = Column(Integer, ForeignKey(MassShift.id, ondelete='CASCADE'), index=True, primary_key=True) individual = relationship(MassShift) compound = relationship( CompoundMassShift, backref=backref( "_counts", collection_class=attribute_mapped_collection("individual"), cascade="all, delete-orphan")) count = Column(Integer)
class Ask(db.Model): id = db.Column(UUID, primary_key=True, default=random_uuid) question_id = db.Column(UUID, db.ForeignKey('question.id'), nullable=False) question = db.relationship('Question', lazy='eager', backref=db.backref('asked', lazy='dynamic', cascade='all')) mandate_id = db.Column(UUID, db.ForeignKey('mandate.id'), nullable=False) mandate = db.relationship('Mandate', backref=db.backref('asked', lazy='dynamic', cascade='all')) match_row = db.relationship('Match', lazy='eager', uselist=False, primaryjoin='Ask.id==foreign(Match.id)', cascade='all') @property def match(self): if self.match_row is None: self.match_row = Match(parent='ask') return self.match_row meta = db.relationship('Meta', collection_class=attribute_mapped_collection('key'), primaryjoin='Ask.id == foreign(Meta.object_id)', cascade='all, delete-orphan') def get_meta(self, key): if key in self.meta: return self.meta[key].value else: return None def set_meta(self, key, value): row = self.meta.setdefault(key, Meta(key=key)) if value is None: del self.meta[key] else: row.value = value def get_meta_dict(self): return {m.key: m.value for m in self.meta.values()}
def InitMapper( cls, metadata, Component, Property ): cls.__table__ = Table( cls.__tablename__, metadata, Column('component_id', Integer, ForeignKey( Component.id ), primary_key = True ), Column('property_id', Integer, ForeignKey( Property.id ), primary_key = True ), Column('value', Text, nullable = False, default = """(lambda (design) 1)""" )) cols = cls.__table__.c Index('ix_%s_component_property' % cls.__tablename__, cols.component_id, cols.property_id) mapper( cls, cls.__table__, properties = { 'component': relation( Component, uselist = False ), 'property': relation( Property, uselist = False ) }) class_mapper( Component ).add_property( '_properties', relation( cls, collection_class = attribute_mapped_collection('property') )) Component.properties = association_proxy('_properties', 'value', creator = lambda k,v: cls( property = k, value = v ) )
class ProcessTask(Model): """A process task.""" class meta: constraints = [UniqueConstraint('process_id', 'task_id', 'phase')] schema = schema tablename = 'process_task' id = Identifier() process_id = ForeignKey('process.id', nullable=False, ondelete='CASCADE') task_id = ForeignKey('scheduled_task.task_id', nullable=False) phase = Enumeration(PROCESS_TASK_ACTIONS, nullable=False) process = relationship( Process, backref=backref('process_tasks', collection_class=attribute_mapped_collection('phase'), cascade='all,delete-orphan', passive_deletes=True)) task = relationship(ScheduledTask, cascade='all,delete-orphan', single_parent=True)
def test_merge_irregular_collection(self): users, Address, addresses, User = (self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User) mapper(User, users, properties={ 'addresses': relationship(mapper(Address, addresses), backref='user', collection_class=attribute_mapped_collection( 'email_address')), }) u1 = User(id=7, name='fred') u1.addresses['*****@*****.**'] = Address(email_address='*****@*****.**') sess = create_session() sess.merge(u1) sess.flush() assert list(u1.addresses.keys()) == ['*****@*****.**']
class FileExtension(db.Model): __tablename__ = 'item_types' id = db.Column(db.Integer, primary_key=True) extension = db.Column(db.String(12), index=True, unique=True, nullable=False) mime_type = db.Column(db.String(128), index=False, unique=False, nullable=False) plugin_id = db.Column(db.Integer, db.ForeignKey('plugins.id')) plugin = db.relationship( 'Plugin', backref=db.backref( '_extensions', collection_class=attribute_mapped_collection('extension'), lazy="joined", cascade="all, delete-orphan"))
class UserPreferences(Base): """ Contains the user preferences data. """ __tablename__ = 'USER_PREFERENCES' ONLINE_HELP_ACTIVE = "online_help_active" fk_user = Column(Integer, ForeignKey('USERS.id'), primary_key=True) key = Column(String, primary_key=True) value = Column(String) user = relationship( User, backref=backref("user_preferences", cascade="all, delete-orphan", lazy='joined', collection_class=attribute_mapped_collection("key"))) def __repr__(self): return 'UserPreferences: %s - %s' % (self.key, self.value)
def assign_translations(self): """ Assigns translations relationship for translatable model. The assigned attribute is a relationship to all translation locales. """ mapper = sa.orm.class_mapper(self.parent_cls) if not mapper.has_property('_translations'): foreign_keys = [ getattr(self.translation_cls, column_key) for column_key in get_primary_keys(self.parent_cls).keys() ] mapper.add_property('_translations', sa.orm.relationship( self.translation_cls, primaryjoin=sa.and_(*self.primary_key_conditions), foreign_keys=foreign_keys, collection_class=attribute_mapped_collection('locale'), comparator_factory=TranslationComparator, cascade='all, delete-orphan', passive_deletes=option(self.parent_cls, 'passive_deletes'), ))
class FlowClassifier(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a v2 neutron flow classifier.""" __tablename__ = 'sfc_flow_classifiers' name = sa.Column(sa.String(255)) ethertype = sa.Column(sa.String(40)) protocol = sa.Column(sa.String(40)) description = sa.Column(sa.String(255)) source_port_range_min = sa.Column(sa.Integer) source_port_range_max = sa.Column(sa.Integer) destination_port_range_min = sa.Column(sa.Integer) destination_port_range_max = sa.Column(sa.Integer) source_ip_prefix = sa.Column(sa.String(255)) destination_ip_prefix = sa.Column(sa.String(255)) logical_source_port = sa.Column( sa.String(UUID_LEN), sa.ForeignKey('ports.id', ondelete='RESTRICT')) logical_destination_port = sa.Column( sa.String(UUID_LEN), sa.ForeignKey('ports.id', ondelete='RESTRICT')) l7_parameters = orm.relationship( L7Parameter, collection_class=attribute_mapped_collection('keyword'), cascade='all, delete-orphan')
def InitMapper( cls, metadata, Design, Component ): cls.__table__ = Table( cls.__tablename__, metadata, Column('design_id', ForeignKey( Design.id ), primary_key = True ), Column('component_id', ForeignKey( Component.id ), primary_key = True ), Column('amount', Integer, nullable = False, default = 1 )) cols = cls.__table__.c Index('ix_%s_design_component' % cls.__tablename__, cols.design_id, cols.component_id) mapper( cls, cls.__table__, properties = { 'design': relation( Design, uselist = False ), 'component': relation( Component, uselist = False ) }) class_mapper( Design ).add_property( '_components', relation( cls, collection_class = attribute_mapped_collection('component') )) Design.components = association_proxy('_components', 'amount', creator = lambda k,v: cls( component = k, amount = v ) )
class TreeNode(Base): __tablename__ = 'tree' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey(id)) name = Column(String(50), nullable=False) children = relationship("TreeNode", # cascade deletions cascade="all", # many to one + adjacency list - remote_side # is required to reference the 'remote' # column in the join condition. backref=backref("parent", remote_side=id), # children will be represented as a dictionary # on the "name" attribute. collection_class=attribute_mapped_collection('name'), ) def __init__(self, name, parent=None): self.name = name self.parent = parent def __repr__(self): return "TreeNode(name=%r, id=%r, parent_id=%r)" % ( self.name, self.id, self.parent_id ) def dump(self, _indent=0): return " " * _indent + repr(self) + \ "\n" + \ "".join([ c.dump(_indent +1) for c in self.children.values()] )
class PlayersGames(db.Model): ''' this maps players to games, and provides the score and placement ''' __tablename = 'playersgames' player_id = db.Column('player_id', db.Integer, db.ForeignKey('player.player_id'), primary_key=True) game_id = db.Column('game_id', db.Integer, db.ForeignKey('game.game_id'), primary_key=True) score = db.Column(db.Integer) penalties = db.Column(db.Integer) place = db.Column(db.Integer) note = db.Column(db.UnicodeText()) player = db.relationship( Player, backref=db.backref( 'played_games', lazy='joined', cascade="all,delete-orphan", ), ) game = db.relationship( Game, backref=db.backref( 'games_players', lazy='dynamic', cascade="all, delete-orphan", collection_class=attribute_mapped_collection("place"), ), ) def __init__(self, player=None, game=None, score=-9999, place=-1): self.player = player self.game = game self.score = score self.place = place
def __init__(self): try: from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import mapper, relationship from sqlalchemy.orm.collections import attribute_mapped_collection except ImportError: raise ImportError('Interaction with SQL based databases requires SQLAlchemy') self.metadata = MetaData() self.framework = Table('framework', self.metadata, Column('id', Integer, primary_key=True), Column('name', String(250))) self.argument = Table('argument', self.metadata, Column('id', Integer, primary_key=True), Column('name', String(250)), Column('framework_id', Integer, ForeignKey('framework.id'))) self.attack= Table('attack', self.metadata, Column('id', Integer, primary_key=True), Column('attacker_id', Integer, ForeignKey('argument.id')), Column('target_id', Integer, ForeignKey('argument.id'))) mapper(al.ArgumentationFramework, self.framework, properties={ 'argument' : relationship(al.Argument, backref='framework'), 'arguments' : relationship(al.Argument, collection_class=attribute_mapped_collection('name'), cascade="all, delete-orphan") }) mapper(al.Argument, self.argument, properties={ 'attacks' : relationship(al.Argument, secondary=self.attack, primaryjoin=self.argument.c.id==self.attack.c.attacker_id, secondaryjoin=self.argument.c.id==self.attack.c.target_id, collection_class=set) })
class Character(Base): __tablename__ = 'characters' name = Column(String) realm_id = Column(Integer, ForeignKey('realms.id')) class_id = Column(Integer, ForeignKey('classes.id')) faction_id = Column(Integer, ForeignKey('factions.id')) race_id = Column(Integer, ForeignKey('races.id')) character_class = relationship('Class') faction = relationship('Faction') race = relationship('Race') gems = relationship('GemSlotAssociation', cascade='all, delete, delete-orphan') for k, v in CHARACTER_HEADER_FIELDS.items(): exec('{} = {}'.format(k, v)) __table_args__ = (UniqueConstraint('realm_id', 'name'), ) years = relationship("Year", backref='character', collection_class=attribute_mapped_collection('year'), cascade='all, delete, delete-orphan') def _creator(k, v): y = Year(k) y.snapshots = v return y snapshots = association_proxy('years', 'snapshots', creator=_creator) def __init__(self, name, **kwargs): self.name = name for k, v in kwargs.items(): if k in CHARACTER_HEADER_FIELDS or \ hasattr(self, k): self.__setattr__(k, v)
class OAuth(Model, OAuthConsumerMixin): __table_args__ = (db.UniqueConstraint("provider", "provider_user_id"), ) provider_user_id = db.Column(db.String(256), nullable=False) provider_user_login = db.Column(db.String(256), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False) user = db.relationship( User, # This `backref` thing sets up an `oauth` property on the User model, # which is a dictionary of OAuth models associated with that user, # where the dictionary key is the OAuth provider name. backref=db.backref( "oauth", collection_class=attribute_mapped_collection("provider"), cascade="all, delete-orphan", ), ) GDPR_EXPORT_COLUMNS = { "provider_user_login": "******", "provider_user_id": "Provider User ID ", "provider": "The provider", "created_at": "When it was created" }
def create_class(self, manager): """ Create TransactionMeta class. """ class TransactionMeta(manager.declarative_base, TransactionMetaBase): __tablename__ = 'transaction_meta' TransactionMeta.transaction = sa.orm.relationship( manager.transaction_cls, backref=sa.orm.backref( 'meta_relation', collection_class=attribute_mapped_collection('key')), primaryjoin=('%s.id == TransactionMeta.transaction_id' % manager.transaction_cls.__name__), foreign_keys=[TransactionMeta.transaction_id]) manager.transaction_cls.meta = association_proxy( 'meta_relation', 'value', creator=lambda key, value: TransactionMeta(key=key, value=value)) return TransactionMeta
class File(Base): """Class to store information about one file submitted within a submission. """ __tablename__ = 'files' __table_args__ = ( UniqueConstraint('submission_id', 'filename'), ) # Auto increment primary key. id = Column( Integer, primary_key=True) # Submission (id and object) owning the file. submission_id = Column( Integer, ForeignKey(Submission.id, onupdate="CASCADE", ondelete="CASCADE"), nullable=False, index=True) submission = relationship( Submission, backref=backref('files', collection_class= attribute_mapped_collection('filename'), cascade="all, delete-orphan", passive_deletes=True)) # Filename and digest of the submitted file. filename = Column( Unicode, FilenameConstraint("filename"), nullable=False) digest = Column( String, DigestConstraint("digest"), nullable=False)
def test_attribute_mapped_collection(self): users, addresses = self.tables.users, self.tables.addresses mapper( User, users, properties={ "addresses": relationship( Address, collection_class=attribute_mapped_collection( "email_address" ), ) }, ) mapper(Address, addresses) u1 = User() u1.addresses = {"email1": Address(email_address="email1")} for loads, dumps in picklers(): repickled = loads(dumps(u1)) eq_(u1.addresses, repickled.addresses) eq_(repickled.addresses["email1"], Address(email_address="email1"))
def InitMapper( cls, metadata, Subject, Parameter, ParameterName ): subject = Subject.__origname__.lower() cls.__table__ = Table( cls.__tablename__, metadata, Column('%s_id' % subject, ForeignKey( Subject.id ), index = True, primary_key = True ), Column('name_id', ForeignKey( ParameterName.id ), index = True, primary_key = True ), Column('param_id', ForeignKey( Parameter.id ), nullable = True )) mapper( cls, cls.__table__, properties = { '_name' : relation( ParameterName, uselist = False ), 'parameter' : relation( Parameter, uselist = False ) }) cls.name = property( lambda self: getattr( self._name, 'name', None ), lambda self, name: setattr( self, '_name', ParameterName.ByName(name) ) ) class_mapper( Subject ).add_property( '_parameters', relation( cls, collection_class = attribute_mapped_collection('name') )) Subject.parameters = association_proxy('_parameters', 'parameter', creator = lambda k, v: cls( name = k, parameter = v ) )
def get_translations_relationship_args(self): foreign_keys = [ getattr(self.translation_cls, column_key) for column_key in get_primary_keys(self.parent_cls).keys() ] relationship_args = copy( self.manager.option( self.parent_cls, 'translations_relationship_args' ) ) defaults = dict( primaryjoin=sa.and_(*self.primary_key_conditions), foreign_keys=foreign_keys, collection_class=attribute_mapped_collection('locale'), comparator_factory=TranslationComparator, cascade='all, delete-orphan', passive_deletes=True, ) for key, value in defaults.items(): relationship_args.setdefault(key, value) return relationship_args
def groupnode(klass, up='super', down='sub', name='node', keyattr='name', cascade="all, delete-orphan"): """ Add Adjacency list attributes to klass. """ uprel = up+name downrel = down+name+'s' idrel = up+name+'_id' _id = Column(Integer, ForeignKey('%s.id' % klass.__tablename__)) remote_id = klass.metadata.tables[klass.__tablename__].columns['id'] setattr(klass, idrel, _id) setattr(klass, downrel, relationship(klass, cascade=cascade, backref=backref(uprel, remote_side=[remote_id]), foreign_keys=[_id], collection_class=attribute_mapped_collection(keyattr), )) # Explicit indicator for root nodes, where remote_id is null setattr(klass, 'is_root'+name, Column(Boolean))
:arg pkg_listing: PackageListing to find the Collection for. :returns: Collection Alias. This is either the branchname or a combination of the collection name and version. This is used to make Branch keys for the dictionary mapping of pkg listings into packages. ''' return pkg_listing.collection.simple_name # # Mappers # mapper(Package, PackageTable, properties={ # listings is here for compatibility. Will be removed in 0.4.x 'listings': relation(PackageListing), 'listings2': relation(PackageListing, backref=backref('package'), collection_class=mapped_collection(collection_alias)) }) mapper(PackageListing, PackageListingTable, properties={ 'people': relation(PersonPackageListing), 'people2': relation(PersonPackageListing, backref=backref('packagelisting'), collection_class = attribute_mapped_collection('username')), 'groups': relation(GroupPackageListing), 'groups2': relation(GroupPackageListing, backref=backref('packagelisting'), collection_class = attribute_mapped_collection('groupname')), })
mapper(StatusTranslation, StatusTranslationTable) mapper(CollectionStatus, CollectionStatusTable, properties={ 'collections': relation(Collection, backref=backref('status')), 'collectionPackages': relation(CollectionPackage, backref=backref('status')), 'translations': relation(StatusTranslation, order_by=StatusTranslationTable.c.language, primaryjoin=StatusTranslationTable.c.statuscodeid \ == CollectionStatusTable.c.statuscodeid, foreign_keys=[StatusTranslationTable.c.statuscodeid]), 'locale': relation(StatusTranslation, primaryjoin=StatusTranslationTable.c.statuscodeid \ == CollectionStatusTable.c.statuscodeid, foreign_keys=[StatusTranslationTable.c.statuscodeid], collection_class=attribute_mapped_collection('language'), backref=backref('cstatuscode', foreign_keys=[StatusTranslationTable.c.statuscodeid], primaryjoin=StatusTranslationTable.c.statuscodeid \ == CollectionStatusTable.c.statuscodeid)), }) mapper(PackageListingStatus, PackageListingStatusTable, properties={ 'listings': relation(PackageListing, backref=backref('status')), 'translations': relation(StatusTranslation, order_by=StatusTranslationTable.c.language, primaryjoin=StatusTranslationTable.c.statuscodeid \ == PackageListingStatusTable.c.statuscodeid, foreign_keys=[StatusTranslationTable.c.statuscodeid]), 'locale': relation(StatusTranslation, order_by=StatusTranslationTable.c.language,
def create_translation_table(_table_name, foreign_class, relation_name, language_class, relation_lazy='select', **kwargs): """Creates a table that represents some kind of data attached to the given foreign class, but translated across several languages. Returns the new table's mapped class. It won't be declarative, but it will have a `__table__` attribute so you can retrieve the Table object. `foreign_class` must have a `__singlename__`, currently only used to create the name of the foreign key column. Also supports the notion of a default language, which is attached to the session. This is English by default, for historical and practical reasons. Usage looks like this: class Foo(Base): ... create_translation_table('foo_bars', Foo, 'bars', name = Column(...), ) # Now you can do the following: foo.name foo.name_map['en'] foo.foo_bars['en'] foo.name_map['en'] = "new name" del foo.name_map['en'] q.options(joinedload(Foo.bars_local)) q.options(joinedload(Foo.bars)) The following properties are added to the passed class: - `(relation_name)`, a relation to the new table. It uses a dict-based collection class, where the keys are language identifiers and the values are rows in the created tables. - `(relation_name)_local`, a relation to the row in the new table that matches the current default language. - `(relation_name)_table`, the class created by this function. Note that these are distinct relations. Even though the former necessarily includes the latter, SQLAlchemy doesn't treat them as linked; loading one will not load the other. Modifying both within the same transaction has undefined behavior. For each column provided, the following additional attributes are added to Foo: - `(column)_map`, an association proxy onto `foo_bars`. - `(column)`, an association proxy onto `foo_bars_local`. Pardon the naming disparity, but the grammar suffers otherwise. Modifying these directly is not likely to be a good idea. For Markdown-formatted columns, `(column)_map` and `(column)` will give Markdown objects. """ # n.b.: language_class only exists for the sake of tests, which sometimes # want to create tables entirely separate from the pokedex metadata foreign_key_name = foreign_class.__singlename__ + '_id' Translations = type(_table_name, (object,), { '_language_identifier': association_proxy('local_language', 'identifier'), 'relation_name': relation_name, }) # Create the table object table = Table(_table_name, foreign_class.__table__.metadata, Column(foreign_key_name, Integer, ForeignKey(foreign_class.id), primary_key=True, nullable=False, info=dict(description="ID of the %s these texts relate to" % foreign_class.__singlename__)), Column('local_language_id', Integer, ForeignKey(language_class.id), primary_key=True, nullable=False, info=dict(description="Language these texts are in")), ) Translations.__table__ = table # Add ye columns # Column objects have a _creation_order attribute in ascending order; use # this to get the (unordered) kwargs sorted correctly kwitems = kwargs.items() kwitems.sort(key=lambda kv: kv[1]._creation_order) for name, column in kwitems: column.name = name table.append_column(column) # Construct ye mapper mapper(Translations, table, properties={ 'foreign_id': synonym(foreign_key_name), 'local_language': relationship(language_class, primaryjoin=table.c.local_language_id == language_class.id, innerjoin=True), }) # Add full-table relations to the original class # Foo.bars_table setattr(foreign_class, relation_name + '_table', Translations) # Foo.bars setattr(foreign_class, relation_name, relationship(Translations, primaryjoin=foreign_class.id == Translations.foreign_id, collection_class=attribute_mapped_collection('local_language'), )) # Foo.bars_local # This is a bit clever; it uses bindparam() to make the join clause # modifiable on the fly. db sessions know the current language and # populate the bindparam. # The 'dummy' value is to trick SQLA; without it, SQLA thinks this # bindparam is just its own auto-generated clause and everything gets # f****d up. local_relation_name = relation_name + '_local' setattr(foreign_class, local_relation_name, relationship(Translations, primaryjoin=and_( Translations.foreign_id == foreign_class.id, Translations.local_language_id == bindparam('_default_language_id', value='dummy', type_=Integer, required=True), ), foreign_keys=[Translations.foreign_id, Translations.local_language_id], uselist=False, #innerjoin=True, lazy=relation_lazy, )) # Add per-column proxies to the original class for name, column in kwitems: getset_factory = None string_getter = column.info.get('string_getter') if string_getter: getset_factory = _getset_factory_factory( column.name, string_getter) # Class.(column) -- accessor for the default language's value setattr(foreign_class, name, LocalAssociationProxy(local_relation_name, name, getset_factory=getset_factory)) # Class.(column)_map -- accessor for the language dict # Need a custom creator since Translations doesn't have an init, and # these are passed as *args anyway def creator(language, value): row = Translations() row.local_language = language setattr(row, name, value) return row setattr(foreign_class, name + '_map', association_proxy(relation_name, name, creator=creator, getset_factory=getset_factory)) # Add to the list of translation classes foreign_class.translation_classes.append(Translations) # Done return Translations
def test_dict_collections(self): class Foo(_base.BasicEntity): pass class Bar(_base.BasicEntity): pass from sqlalchemy.orm.collections import attribute_mapped_collection attributes.register_class(Foo) attributes.register_attribute(Foo, 'someattr', uselist=True, useobject=True, typecallable=attribute_mapped_collection('name')) hi = Bar(name='hi') there = Bar(name='there') old = Bar(name='old') new = Bar(name='new') f = Foo() eq_(attributes.get_history(attributes.instance_state(f), 'someattr'), ((), [], ())) f.someattr['hi'] = hi eq_(attributes.get_history(attributes.instance_state(f), 'someattr'), ([hi], [], [])) f.someattr['there'] = there eq_(tuple([set(x) for x in attributes.get_history(attributes.instance_state(f), 'someattr')]), (set([hi, there]), set(), set())) attributes.instance_state(f).commit(['someattr']) eq_(tuple([set(x) for x in attributes.get_history(attributes.instance_state(f), 'someattr')]), (set(), set([hi, there]), set()))
es_Fit.commandFitDict = association_proxy( "boostedOf", # look at the boostedOf association... "booster_fit", # .. and return the booster fit creator=lambda boosterID, booster_fit: CommandFit(boosterID, booster_fit) ) # These relationships are broken out so that we can easily access it in the events stuff # We sometimes don't want particular relationships to cause a fit modified update (eg: projecting # a fit onto another would 'modify' both fits unless the following relationship is ignored) projectedFitSourceRel = relationship( ProjectedFit, primaryjoin=projectedFits_table.c.sourceID == fits_table.c.ID, backref='source_fit', collection_class=attribute_mapped_collection('victimID'), cascade='all, delete, delete-orphan') boostedOntoRel = relationship( CommandFit, primaryjoin=commandFits_table.c.boosterID == fits_table.c.ID, backref='booster_fit', collection_class=attribute_mapped_collection('boostedID'), cascade='all, delete, delete-orphan') mapper(es_Fit, fits_table, properties={ "_Fit__modules": relation( Module, collection_class=HandledModuleList,
def __str__(self): return self._getstring(0, False) def _getstring(self, level, expand = False): s = (' ' * level) + "%s (%s,%s, %d)" % ( self.name, self.id,self.parent_id,id(self)) + '\n' if expand: s += ''.join([n._getstring(level+1, True) for n in self.children.values()]) return s def print_nodes(self): return self._getstring(0, True) mapper(TreeNode, trees, properties={ 'children': relation(TreeNode, cascade="all", backref=backref("parent", remote_side=[trees.c.id]), collection_class=attribute_mapped_collection('name'), lazy=False, join_depth=3)}) print "\n\n\n----------------------------" print "Creating Tree Table:" print "----------------------------" trees.create() node2 = TreeNode('node2') node2.append('subnode1') node = TreeNode('rootnode') node.append('node1') node.append(node2) node.append('node3') node.children['node2'].append('subnode2')
Column("factionID", Integer), Column("volume", Float), Column("mass", Float), Column("capacity", Float), Column("published", Boolean), Column("marketGroupID", Integer, ForeignKey("invmarketgroups.marketGroupID")), Column("iconID", Integer, ForeignKey("icons.iconID")), Column("groupID", Integer, ForeignKey("invgroups.groupID"), index=True)) from .metaGroup import metatypes_table # noqa from .traits import traits_table # noqa mapper(Item, items_table, properties={ "group" : relation(Group, backref="items"), "icon" : relation(Icon), "_Item__attributes": relation(Attribute, collection_class=attribute_mapped_collection('name')), "effects": relation(Effect, secondary=typeeffects_table, collection_class=attribute_mapped_collection('name')), "metaGroup" : relation(MetaType, primaryjoin=metatypes_table.c.typeID == items_table.c.typeID, uselist=False), "ID" : synonym("typeID"), "name" : synonym("typeName"), "description" : deferred(items_table.c.description), "traits" : relation(Traits, primaryjoin=traits_table.c.typeID == items_table.c.typeID, uselist=False) }) Item.category = association_proxy("group", "category")
Column("raceID", Integer), Column("factionID", Integer), Column("volume", Float), Column("mass", Float), Column("capacity", Float), Column("published", Boolean), Column("marketGroupID", Integer, ForeignKey("invmarketgroups.marketGroupID")), Column("iconID", Integer, ForeignKey("icons.iconID")), Column("groupID", Integer, ForeignKey("invgroups.groupID"), index=True)) from .metaGroup import metatypes_table # noqa from .traits import traits_table # noqa mapper(Item, items_table, properties={"group": relation(Group, backref="items"), "icon": relation(Icon), "_Item__attributes": relation(Attribute, collection_class=attribute_mapped_collection('name')), "effects": relation(Effect, collection_class=attribute_mapped_collection('name')), "metaGroup": relation(MetaType, primaryjoin=metatypes_table.c.typeID == items_table.c.typeID, uselist=False), "ID": synonym("typeID"), "name": synonym("typeName"), "description": deferred(items_table.c.description), "traits": relation(Traits, primaryjoin=traits_table.c.typeID == items_table.c.typeID, uselist=False) }) Item.category = association_proxy("group", "category")
from eos.saveddata.mutator import Mutator from eos.saveddata.fit import Fit modules_table = Table("modules", saveddata_meta, Column("ID", Integer, primary_key=True), Column("fitID", Integer, ForeignKey("fits.ID"), nullable=False, index=True), Column("itemID", Integer, nullable=True), Column("baseItemID", Integer, nullable=True), Column("mutaplasmidID", Integer, nullable=True), Column("dummySlot", Integer, nullable=True, default=None), Column("chargeID", Integer), Column("state", Integer, CheckConstraint("state >= -1"), CheckConstraint("state <= 2")), Column("projected", Boolean, default=False, nullable=False), Column("position", Integer), Column("created", DateTime, nullable=True, default=datetime.datetime.now), Column("modified", DateTime, nullable=True, onupdate=datetime.datetime.now), Column("spoolType", Integer, nullable=True), Column("spoolAmount", Float, nullable=True), CheckConstraint('("dummySlot" = NULL OR "itemID" = NULL) AND "dummySlot" != "itemID"')) mapper(Module, modules_table, properties={ "owner": relation(Fit), "mutators": relation( Mutator, backref="module", cascade="all,delete-orphan", collection_class=attribute_mapped_collection('attrID') ) })
class MediaFullText(object): query = DBSession.query_property() mapper(MediaFullText, media_fulltext) mapper(MediaMeta, media_meta) mapper(MediaFilesMeta, media_files_meta) _media_files_mapper = mapper( MediaFile, media_files, extension=events.MapperObserver(events.MediaFile), properties={ "_meta": relation(MediaFilesMeta, collection_class=attribute_mapped_collection("key"), passive_deletes=True) }, ) _media_mapper = mapper( Media, media, order_by=media.c.title, extension=events.MapperObserver(events.Media), properties={ "fulltext": relation(MediaFullText, uselist=False, passive_deletes=True), "author": composite( Author, media.c.author_name, media.c.author_email, doc="""An instance of :class:`mediacore.model.authors.Author`.
Column("factionID", Integer), Column("volume", Float), Column("mass", Float), Column("capacity", Float), Column("published", Boolean), Column("marketGroupID", Integer, ForeignKey("invmarketgroups.marketGroupID")), Column("iconID", Integer, ForeignKey("icons.iconID")), Column("groupID", Integer, ForeignKey("invgroups.groupID"), index=True)) from .metaGroup import metatypes_table # noqa from .traits import traits_table # noqa mapper(Item, items_table, properties={ "group" : relation(Group, backref="items"), "icon" : relation(Icon), "_Item__attributes": relation(Attribute, cascade='all, delete, delete-orphan', collection_class=attribute_mapped_collection('name')), "effects": relation(Effect, secondary=typeeffects_table, collection_class=attribute_mapped_collection('name')), "metaGroup" : relation(MetaType, primaryjoin=metatypes_table.c.typeID == items_table.c.typeID, uselist=False), "ID" : synonym("typeID"), "name" : synonym("typeName"), "description" : deferred(items_table.c.description), "traits" : relation(Traits, primaryjoin=traits_table.c.typeID == items_table.c.typeID, uselist=False) }) Item.category = association_proxy("group", "category")
""" _property_type = AnimalFact _property_mapping = 'facts' def __init__(self, name): self.name = name def __repr__(self): return '<%s %r>' % (self.__class__.__name__, self.name) mapper(Animal, animals, properties={ 'facts': relationship( AnimalFact, backref='animal', collection_class=attribute_mapped_collection('key')), }) mapper(AnimalFact, facts) engine = create_engine("sqlite://") metadata.create_all(engine) session = Session(bind=engine) stoat = Animal('stoat') stoat['color'] = 'reddish' stoat['cuteness'] = 'somewhat' # dict-like assignment transparently creates entries in the # stoat.facts collection: print(stoat.facts['color'])