class Result(Base): __tablename__ = 'result' id = db.Column(db.Integer, primary_key=True) job_id = db.Column(db.Integer, db.ForeignKey('group.id')) testcase_id = db.Column(db.Integer, db.ForeignKey('testcase.id')) testcase_name = db.Column(db.Text) groups = db.relationship("Group", secondary='groups_to_results', backref="results") job = db.relation('Group') # , lazy = False) testcase = db.relation('Testcase', backref='results') # , lazy = False)
def _defineMapping(self, tannot): attributes = {} # find all the related tables and infer basic relations, this sort of crude # inference should be optional. for fk in tannot.table.foreign_keys: klass = self.context.getClassFor(table_name=fk.column.table.name) attr_name = tannot.get(fk.column.name).get('attribute', fk.column.table.name) backref = tannot.get(fk.column.name).get('backref', tannot.table.name) attributes[attr_name] = relation(klass, backref=backref) ## # if fk is a primary key then model as inheritance ## if fk.column.primary_key: ## klass = self.getClassFor( fk.column.table.name ) ## raise NotImplemented ## # if fk is to another table and the constraint is not unique ## # if fk is to a mapping table then as a m2m, mapping determined ## # by fk 2 column ratio self.context.defineMapping(tannot, properties=attributes)
def _setup_mappers(self, tables, mappers): """Map the database Tables to SQLAlchemy Mapper objects """ mappers['screening'] = mapper(Screening, tables['screening']) mappers['reservation'] = mapper(Reservation, tables['reservation'], properties = { 'screening' : relation(Screening), })
def process(self, klass, propname, relations): relclass = ActiveMapperMeta.classes[self.classname] if isinstance(self.order_by, str): self.order_by = [self.order_by] if isinstance(self.order_by, list): for itemno in range(len(self.order_by)): if isinstance(self.order_by[itemno], str): self.order_by[itemno] = \ getattr(relclass.c, self.order_by[itemno]) backref = self.create_backref(klass) relations[propname] = relation(relclass.mapper, secondary=self.secondary, backref=backref, private=self.private, lazy=self.lazy, uselist=self.uselist, order_by=self.order_by)
def process(self, klass, propname, relations): relclass = ActiveMapperMeta.classes[self.classname] if isinstance(self.order_by, str): self.order_by = [ self.order_by ] if isinstance(self.order_by, list): for itemno in range(len(self.order_by)): if isinstance(self.order_by[itemno], str): self.order_by[itemno] = \ getattr(relclass.c, self.order_by[itemno]) backref = self.create_backref(klass) relations[propname] = relation(relclass.mapper, secondary=self.secondary, backref=backref, private=self.private, lazy=self.lazy, uselist=self.uselist, order_by=self.order_by)
def process_relationships(klass, was_deferred=False): defer = False for propname, reldesc in klass.relations.items(): if not reldesc.classname in ActiveMapperMeta.classes: if not was_deferred: __deferred_classes__.append(klass) defer = True if not defer: relations = {} for propname, reldesc in klass.relations.items(): relclass = ActiveMapperMeta.classes[reldesc.classname] relations[propname] = relation(relclass, backref=reldesc.backref, private=reldesc.private, lazy=reldesc.lazy, uselist=reldesc.uselist) assign_mapper(klass, klass.table, properties=relations) if was_deferred: __deferred_classes__.remove(klass) if not was_deferred: for deferred_class in __deferred_classes__: process_relationships(deferred_class, was_deferred=True)
def _defineMapping( self, tannot ): attributes = {} # find all the related tables and infer basic relations, this sort of crude # inference should be optional. for fk in tannot.table.foreign_keys: klass = self.context.getClassFor( table_name = fk.column.table.name ) attr_name = tannot.get( fk.column.name ).get('attribute', fk.column.table.name ) backref = tannot.get( fk.column.name ).get('backref', tannot.table.name ) attributes[ attr_name ] = relation( klass, backref=backref ) ## # if fk is a primary key then model as inheritance ## if fk.column.primary_key: ## klass = self.getClassFor( fk.column.table.name ) ## raise NotImplemented ## # if fk is to another table and the constraint is not unique ## # if fk is to a mapping table then as a m2m, mapping determined ## # by fk 2 column ratio self.context.defineMapping( tannot, properties=attributes )
return self.entity.name def set_name(self, name): self.entity.name = name name = property(get_name, set_name) def get_short(self): return self.entity.short def set_short(self, short): self.entity.short = short short = property(get_short, set_short) mapper(Entity, _entity) mapper(Player, _player, properties = {'entity': relation(Entity, lazy=False, cascade="all, delete-orphan")}) def get_players(all=False): if all: return session.query(Player).select() else: return session.query(Player).select_by(current=True) def get_player(name): name = name.lower() query = session.query(Entity) entity = query.get_by(func.lower(Entity.c.name) == name) if entity is None:
"""A Category""" mapper(Category, category_table) task_table = Table('task', meta, SQLAColumn('id', Integer, primary_key=True, autoincrement=True), SQLAColumn('title', String), SQLAColumn('category_id', Integer, ForeignKey('category.id')), SQLAColumn('date', Date), ) class Task(object): """A task""" mapper(Task, task_table, properties=dict( category = relation(Category, backref='tasks'), )) engine = create_engine('sqlite:///') meta.connect(engine) meta.create_all() session = create_session(bind_to=engine) for category in ['Work', 'Home', 'School']: c = Category() c.name=category
def _loadInstance( self, instance ): relation_tables = [] primary_columns = [ rdb.Column( "uid", rdb.String(50), primary_key=True ) ] portal_type = instance.portal_type table_name = self.ident_translate( portal_type ) field_translator = self.translator_factory( self, table_name ) print "Processing Type", portal_type d = {} for field in instance.Schema().fields(): # filter badness from fields with same speling but different captilization. field_name = self.ident_translate( field.getName() ) if field_name in d: continue result = field_translator.visit( field ) if result is None: continue elif isinstance( result, rdb.Column): primary_columns.append( result ) elif isinstance( result, rdb.Table ): relation_tables.append( result ) else: print "Unexpected", result raise RuntimeError d[field_name] = None # define type primary table type_table = rdb.Table( table_name, self.engine, *primary_columns ) # setup a peer factory klass_name = "%s_serializer"%portal_type.lower().replace(' ', '_') type_klass = type( klass_name, (object,), {} ) self._peer_factories[ portal_type ] = type_klass self._tables[ portal_type ] = type_table # setup the reference relations identity = self._peer_factories[ self._identity ] properties = {} for relation_table in relation_tables: print "reference name", relation_table.reference_name for relation_table in relation_tables: properties[ relation_table.reference_name ] = rdb.relation( identity.mapper, relation_table, lazy = False) self._tables[ relation_table.name ] = relation_table kwargs = {'properties':properties} # associate peer to mapper rdb.assign_mapper( type_klass, type_table, **kwargs )
""" Map Domain classes to domain model """ from sqlalchemy import mapper, relation, backref from ore.alchemist.mapper import bind_mapper import schema as app_schema import domain as app_model address_mapper = bind_mapper( app_model.Address, app_schema.AddressTable ) person_mapper = bind_mapper( app_model.Person, app_schema.PersonTable, properties={ 'address' : relation( address_mapper, lazy=True, backref=backref('person', uselist=False)) } )