def setup_mappers(cls): global Session Session = scoped_session(sessionmaker()) mapper(User, users, properties={'addresses' : relationship(Address, backref='user', order_by=addresses.c.id)}) mapper(Address, addresses) compile_mappers()
def init_model(engine): """Call me before using any of the tables or classes in the model""" sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine) meta.engine = engine meta.Session = orm.scoped_session(sm) orm.compile_mappers()
def safunc(meta, Alaba, Balama): table_A = Table( 'Alaba', meta, Column( 'name', String, ), Column( 'atype', type_=String, ), Column( 'db_id', primary_key=True, type_=Integer, ), ) table_B = Table( 'Balama', meta, Column( 'dataB', String, ), Column( 'db_id', Integer, ForeignKey('Alaba.db_id', ), primary_key=True, ), ) meta.create_all() mapper_A = mapper( Alaba, table_A, polymorphic_identity='Alaba', polymorphic_on=table_A.c.atype, select_table=outerjoin( table_A, table_B, table_B.c.db_id == table_A.c.db_id, ), ) mapper_B = mapper( Balama, table_B, inherit_condition=table_B.c.db_id == table_A.c.db_id, inherits=mapper_A, polymorphic_identity='Balama', ) compile_mappers()
def setup_mappers(cls): global Session Session = scoped_session(sessionmaker()) mapper(User, users, properties={ 'addresses': relationship(Address, backref='user', order_by=addresses.c.id) }) mapper(Address, addresses) compile_mappers()
def map(self): for table in self.tables: if table in self.mappers: continue props = {} if table in self.models and self.models[table] in self.relations: model = self.models[table] props = {} for rel in self.relations[model]: props[rel.field.name] = relation( self.mo_map[rel.field.rel.to], **rel.props( self.tables, self.mt_map ) ) if len( props ) > 0: mapper(self.objects[table],self.tables[table],properties=props) else: mapper(self.objects[table],self.tables[table]) compile_mappers()
def safunc( meta, Alaba,Balama ): table_A = Table( 'Alaba', meta, Column( 'name', String, ), Column( 'atype', type_= String, ), Column( 'db_id', primary_key= True, type_= Integer, ), ) table_B = Table( 'Balama', meta, Column( 'dataB', String, ), Column( 'db_id', Integer, ForeignKey( 'Alaba.db_id', ), primary_key= True, ), ) meta.create_all() mapper_A = mapper( Alaba, table_A, polymorphic_identity= 'Alaba', polymorphic_on= table_A.c.atype, select_table= outerjoin( table_A, table_B, table_B.c.db_id == table_A.c.db_id, ), ) mapper_B = mapper( Balama, table_B, inherit_condition= table_B.c.db_id == table_A.c.db_id, inherits= mapper_A, polymorphic_identity= 'Balama', ) compile_mappers()
class Groups(Base): __tablename__ = "groups" groupcode = Column(Integer, primary_key=True) groupname = Column(Text, nullable=False) groupdesc = Column(Text) def __init__(self, groupname, groupdesc): self.groupname = groupname self.groupdesc = groupdesc groups_table = Groups.__table__ class subGroups(Base): __tablename__ = "subgroups" subgroupcode = Column(Integer, primary_key=True) groupcode = Column(Integer, ForeignKey("groups.groupcode"), nullable=False) subgroupname = Column(Text) def __init__(self, groupcode, subgroupname): self.groupcode = groupcode self.subgroupname = subgroupname subgroups_table = subGroups.__table__ orm.compile_mappers()
question = Column(Integer) answer = Column(String) login_time = Column(Text) logout_time = Column(Text) def __init__(self,username, userpassword,gender,userrole,question,answer,login_time,logout_time): self.userid = None self.username = username self.userpassword = userpassword self.gender = gender self.userrole = userrole self.question = question self.answer = answer self.login_time = login_time self.logout_time = logout_time users_table = Users.__table__ class ProfitLoss(Base): __tablename__='profit_loss' plid = Column(Integer, primary_key=True) net_flag = Column(String) opening_balance = Column(Numeric(13, 2)) def __init__(self,net_flag,opening_balance): self.plid = None self.net_flag = net_flag self.opening_balance = opening_balance profit_loss = ProfitLoss.__table__ orm.compile_mappers()
def main(daemon_name, argv, init, bootstrap=None, bootstrapper=BootStrapper, cls=ServiceDaemon): """A typical main function for daemons. :param daemon_name: Daemon name. :param argv: A sequence of command line arguments. :param init: A callable that returns the init dict. :param bootstrap: A callable that bootstraps daemon's environment. It's deprecated in favor of bootstrapper. :param bootstrapper: A factory for a callable that bootstraps daemon's environment. This is supposed to be run once for every new deployment. :param cls: Daemon class :return: Exit code of the daemon as int. """ config = cls.parse_config(daemon_name, argv) if config.name is None: config.name = daemon_name # FIXME: Any better ideas? has_services = hasattr(config, '_services') has_stores = hasattr(config, '_stores') services = None if has_services: services = list(config._services) stores = None if has_stores: stores = list(config._stores) try: retval = _inner_main(config, init, bootstrap, bootstrapper) # if _inner_main did something other than initializing daemons if retval is not None: return retval finally: if not isfile(config.config_file): config.do_write_config() logger.info("Writing configuration to: '%s'", config.config_file) elif has_services and services != config._services: config.do_write_config() logger.info("Updating configuration file because new services were " "detected") elif has_stores and stores != config._stores: config.do_write_config() logger.info("Updating configuration file because new stores were " "detected") # FIXME: could someone need these during bootstrap above? if config.uuid is None: config.uuid = config.gen_uuid() config.do_write_config() logger.info("Updating configuration file because new uuid was " "generated") if config.secret is None: config.secret = config.gen_secret() config.do_write_config() logger.info("Updating configuration file because new secret was " "generated") logger.info("Compiling object mappers...") from sqlalchemy.orm import compile_mappers compile_mappers() # at this point it's safe to import the reactor (or anything else from # twisted) because the decision to fork or not to fork is already made. from twisted.internet import reactor from twisted.internet.task import deferLater gc.collect() logger.info("Starting reactor... Max. RSS: %f", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000.0) deferLater(reactor, 0, _set_reactor_thread) return reactor.run()
def setUp(me): me.backrefs() from sqlalchemy.orm import mapper, relation, compile_mappers, backref from sqlalchemy import Table, Column, ForeignKey meta = MetaData('sqlite:///') #meta.bind.echo=True twork = Table( 'work', meta, Column( 'name', Integer, ), Column('id', Integer, primary_key=True), ) tclub = Table( 'club', meta, Column( 'name', Integer, ), Column('id', Integer, primary_key=True), ) tpapa = Table('papa', meta, Column( 'name', Integer, ), Column('id', Integer, primary_key=True), Column('mama_id', Integer, ForeignKey('mama.id'))) tmama = Table( 'mama', meta, Column( 'name', Integer, ), Column('id', Integer, primary_key=True), Column('work_id', Integer, ForeignKey('work.id', )), Column('friend_id', Integer, ForeignKey('mama.id', use_alter=True, name='ma2ma')), Column('papa_id', Integer, ForeignKey('papa.id', use_alter=True, name='ma2pa')), ) tclubmama = Table( 'clubmama', meta, Column('club_id', Integer, ForeignKey('club.id', )), Column('mama_id', Integer, ForeignKey('mama.id', )), ) tkid = Table( 'kid', meta, Column( 'name', Integer, ), Column('id', Integer, primary_key=True), Column('mama_id', Integer, ForeignKey('mama.id', )), ) # meta.create_all() class Base(object): def __init__(me, **kargs): for k, v in kargs.items(): setattr(me, k, v) class Club(Base): pass class Papa(Base): pass class Work(Base): pass class Mama(Base): pass class Kid(Base): pass mapper(Mama, tmama, properties={ 'kids': relation( Kid, backref=me.backref_kids, ), 'club': relation(Club, backref=me.backref_club, secondary=tclubmama), 'work': relation( Work, backref=me.backref_work, ), 'friend': relation( Mama, post_update=True, uselist=False, lazy=True, ), 'papa': relation( Papa, uselist=False, primaryjoin=tmama.c.papa_id == tpapa.c.id, backref=me.backref_papa and backref( me.backref_papa, primaryjoin=tpapa.c.mama_id == tmama.c.id, uselist=False, ), ), }) mapper(Kid, tkid) mapper(Club, tclub) mapper(Work, twork) pa = mapper(Papa, tpapa) if not me.backref_papa: pa.add_property( 'mama', relation( Mama, primaryjoin=tpapa.c.mama_id == tmama.c.id, uselist=False, )) compile_mappers() #or populate() me.backref_kids2 = me.backref_kids or 'mama_id' me.Mama = Mama me.Kid = Kid me.Club = Club me.Work = Work me.Papa = Papa
def initMappings(): a = sqlalchemy s = Schema def eventstampedMapper(class_, local_table, **kwargs): props = kwargs.setdefault('properties', {}) props['creationEvent'] = orm.relation(Event) props['eventId'] = local_table.c.event_id return orm.mapper(class_, local_table, **kwargs) orm.mapper(Event, s.event, properties={ 'eventId' : s.event.c.event_id, 'eventTimestamp' : s.event.c.event_timestamp, }) transactionMapper = eventstampedMapper( Transaction, s.statementItem, properties={ 'date' : s.statementItem.c.dtposted, 'amount' : s.statementItem.c.trnamt, }) isLikelyInvoiceable = a.exists([1], s.statementItem.c.memo.ilike(s.likelyInvoiceable.c.pattern)) \ .correlate(s.statementItem) \ .label('isLikelyInvoiceable') isInvoiceable = a.exists([1], s.statementItem.c.fitid == s.invoiceableItem.c.fitid) \ .label('isInvoiceable') isLikelyPayment = ((s.statementItem.c.trnamt > 0) & (s.statementItem.c.trnamt <= MAXIMUM_LIKELY_PAYMENT)) \ .label('isLikelyPayment') isPayment = a.exists([1], s.statementItem.c.fitid == s.paymentStatementEvidence.c.fitid) \ .label('isPayment') transactionListSelect = a.select([ s.statementItem, isLikelyInvoiceable, isInvoiceable, isLikelyPayment, isPayment, ]).alias('transactionSelect') global transactionListMapper transactionListMapper = orm.mapper(Transaction, transactionListSelect, properties={ 'date' : s.statementItem.c.dtposted, 'amount' : s.statementItem.c.trnamt, }, non_primary=True) eventstampedMapper(ImportedStatement, s.importedStatement, properties={ 'beginDate' : s.importedStatement.c.begin_date, 'endDate' : s.importedStatement.c.end_date, }) orm.mapper(Person, s.person, properties={ 'personId' : s.person.c.person_id, 'givenName' : s.person.c.given_name, 'familyName' : s.person.c.family_name, 'tenancies' : orm.relation(Tenancy, backref='person', cascade='all, delete-orphan'), 'payments' : orm.relation(Payment, backref='personFrom', cascade='all, delete-orphan'), 'invoices' : orm.relation(Invoice, backref='personTo', cascade='all, delete-orphan'), }) eventstampedMapper(Tenancy, s.personTenancy, properties={ 'tenancyId' : s.personTenancy.c.tenancy_id, 'personId' : s.personTenancy.c.person_id, 'dateMovedIn' : s.personTenancy.c.date_moved_in, 'dateMovedOut' : s.personTenancy.c.date_moved_out, }) paymentJoin = orm.polymorphic_union( { 'paymentWithStatementEvidence' : s.personPayment.join(s.paymentStatementEvidence), 'paymentWithOtherEvidence' : s.personPayment.join(s.paymentOtherEvidence), }, None, 'paymentjoin') paymentMapper = eventstampedMapper(Payment, s.personPayment, polymorphic_on=s.personPayment.c.evidence_type, properties={ 'paymentId' : s.personPayment.c.payment_id, 'personId' : s.personPayment.c.person_id, 'paymentDate' : s.personPayment.c.payment_date, 'evidenceType' : s.personPayment.c.evidence_type, }) orm.mapper(PaymentWithStatementEvidence, s.paymentStatementEvidence, inherits=paymentMapper, polymorphic_identity='statement', properties={ 'transaction' : orm.relation(Transaction) }) orm.mapper(PaymentWithOtherEvidence, s.paymentOtherEvidence, inherits=paymentMapper, polymorphic_identity='other') eventstampedMapper(InvoiceableItem, s.invoiceableItem, properties={ 'transaction' : orm.relation(Transaction), }) eventstampedMapper(Invoice, s.personInvoice, properties={ 'invoiceId' : s.personInvoice.c.invoice_id, 'personId' : s.personInvoice.c.person_id, 'invoiceDate' : s.personInvoice.c.invoice_date, 'amount' : s.personInvoice.c.amount, }) orm.mapper(LikelyInvoiceable, s.likelyInvoiceable) orm.compile_mappers()
from sqlalchemy import __version__ if __version__.split('.') < MIN_SA_VERSION.split('.'): raise ImportError('Version %s or later of SQLAlchemy required' % MIN_SA_VERSION) from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm.properties import SynonymProperty from sqlalchemy.orm import compile_mappers, object_session, class_mapper from sqlalchemy.orm.session import Session from sqlalchemy.orm.scoping import ScopedSession from sqlalchemy.orm.dynamic import DynamicAttributeImpl from sqlalchemy.util import OrderedDict import fields, fatypes compile_mappers() # initializes InstrumentedAttributes try: # 0.5 from sqlalchemy.orm.attributes import manager_of_class def _get_attribute(cls, p): manager = manager_of_class(cls) return manager[p.key] except ImportError: # 0.4 def _get_attribute(cls, p): return getattr(cls, p.key) def prettify(text):
def test(): if not OUT: class Text(o2r.Type): pass class Alaba(Base): name = Text() DBCOOK_inheritance = 'joined' #for subclasses - this(base) one is always concrete anyway DBCOOK_has_instances = True #by default only class-tree leaves have instances class Balama(Alaba): alaba = Text() fieldtypemap = { Text: dict(type=String, ), } # map attr-types to sql-column-types else: Alaba = A0 Balama = B0 fieldtypemap = fieldtypemap0 meta = MetaData(create_engine('sqlite:///', echo='echo' in sys.argv)) assert what in 'sa safunc dbcook'.split() TBL = 0 if what == 'sa' or TBL: table_A = Table( 'Alaba', meta, Column( 'name', String, ), Column( 'atype', type_=String, ), Column( 'db_id', primary_key=True, type_=Integer, ), ) table_B = Table( 'Balama', meta, Column( 'dataB', String, ), Column( 'db_id', Integer, ForeignKey('Alaba.db_id', ), primary_key=True, ), ) #tables = { Alaba:table_A, Balama:table_B} #else: tables = () if what == 'sa': meta.create_all() mapper_A = mapper( Alaba, table_A, polymorphic_identity='Alaba', polymorphic_on=table_A.c.atype, select_table=outerjoin( table_A, table_B, table_B.c.db_id == table_A.c.db_id, ), ) mapper( Balama, table_B, inherit_condition=table_B.c.db_id == table_A.c.db_id, inherits=mapper_A, polymorphic_identity='Balama', ) compile_mappers() elif what == 'safunc': safunc(meta, Alaba, Balama) else: print 'dbcook' mybuild = o2r.Builder( meta, dict(Alaba=Alaba, Balama=Balama ), #just scan anything here that looks like subclass of Base fieldtypemap, base_klas=Base, #tables = tables, ) # del mybuild if 10: def populate(): a = Alaba() a.name = 'anna' b = Balama() b.name = 'x' return locals() session = create_session() #anything off Base, go to db for x in populate().values(): if isinstance(x, Base) and not isinstance(x, type): session.save(x) session.flush() session = create_session() all = session.query(Alaba).all() assert len(all) == 2 for q in all: print 'o', q clear_mappers() return meta
class ActivityOffered(Base): __tablename__ = 'activity_offered' __table_args__ = {'autoload' : True} class ActivitySought(Base): __tablename__ = 'activity_sought' __table_args__ = {'autoload' : True} # ------------- # Relationships # ------------- # --------------------------------------------------------- # Test that all relationships/mappings are self-consistent. # --------------------------------------------------------- from sqlalchemy.orm import compile_mappers try: compile_mappers() except RuntimeError, error: print """ An error occurred when verifying the relationships between the database tables. Most likely this is an error in the definition of the SQLAlchemy relationships - see the error message below for details. """ print "Error type: %s" % sys.exc_info()[0] print "Error value: %s" % sys.exc_info()[1] print "Error trace: %s" % sys.exc_info()[2] sys.exit(1)
def setUp( me): me.backrefs() from sqlalchemy.orm import mapper, relation, compile_mappers, backref from sqlalchemy import Table, Column, ForeignKey meta = MetaData( 'sqlite:///') #meta.bind.echo=True twork = Table('work', meta, Column('name', Integer, ), Column('id', Integer, primary_key=True), ) tclub = Table('club', meta, Column('name', Integer, ), Column('id', Integer, primary_key=True), ) tpapa = Table('papa', meta, Column('name', Integer, ), Column('id', Integer, primary_key=True), Column('mama_id', Integer, ForeignKey('mama.id')) ) tmama = Table('mama', meta, Column('name', Integer, ), Column('id', Integer, primary_key=True), Column('work_id', Integer, ForeignKey('work.id',)), Column('friend_id', Integer, ForeignKey('mama.id', use_alter=True, name='ma2ma')), Column('papa_id', Integer, ForeignKey('papa.id', use_alter=True, name='ma2pa')), ) tclubmama = Table('clubmama', meta, Column('club_id', Integer, ForeignKey('club.id',)), Column('mama_id', Integer, ForeignKey('mama.id',)), ) tkid = Table('kid', meta, Column('name', Integer, ), Column('id', Integer, primary_key=True), Column('mama_id', Integer, ForeignKey('mama.id',)), ) # meta.create_all() class Base(object): def __init__( me, **kargs): for k,v in kargs.items(): setattr( me,k,v) class Club( Base):pass class Papa( Base):pass class Work( Base):pass class Mama( Base): pass class Kid( Base): pass mapper( Mama, tmama, properties={ 'kids': relation( Kid, backref= me.backref_kids,), 'club': relation( Club, backref= me.backref_club, secondary=tclubmama), 'work': relation( Work, backref= me.backref_work,), 'friend': relation( Mama, post_update=True, uselist=False, lazy=True, ), 'papa': relation( Papa, uselist=False, primaryjoin= tmama.c.papa_id == tpapa.c.id, backref= me.backref_papa and backref( me.backref_papa, primaryjoin= tpapa.c.mama_id == tmama.c.id, uselist=False, ), ), }) mapper( Kid, tkid) mapper( Club, tclub) mapper( Work, twork) pa=mapper( Papa, tpapa) if not me.backref_papa: pa.add_property( 'mama', relation( Mama, primaryjoin= tpapa.c.mama_id == tmama.c.id, uselist=False, )) compile_mappers() #or populate() me.backref_kids2 = me.backref_kids or 'mama_id' me.Mama = Mama me.Kid = Kid me.Club = Club me.Work = Work me.Papa = Papa
def test(): if not OUT: class Text( o2r.Type): pass class Alaba( Base): name = Text() DBCOOK_inheritance = 'joined' #for subclasses - this(base) one is always concrete anyway DBCOOK_has_instances = True #by default only class-tree leaves have instances class Balama( Alaba): alaba = Text() fieldtypemap = { Text: dict( type= String, ), }# map attr-types to sql-column-types else: Alaba=A0 Balama=B0 fieldtypemap = fieldtypemap0 meta = MetaData( create_engine('sqlite:///', echo= 'echo' in sys.argv )) assert what in 'sa safunc dbcook'.split() TBL = 0 if what == 'sa' or TBL: table_A = Table( 'Alaba', meta, Column( 'name', String, ), Column( 'atype', type_= String, ), Column( 'db_id', primary_key= True, type_= Integer, ), ) table_B = Table( 'Balama', meta, Column( 'dataB', String, ), Column( 'db_id', Integer, ForeignKey( 'Alaba.db_id', ), primary_key= True, ), ) #tables = { Alaba:table_A, Balama:table_B} #else: tables = () if what == 'sa': meta.create_all() mapper_A = mapper( Alaba, table_A, polymorphic_identity= 'Alaba', polymorphic_on= table_A.c.atype, select_table= outerjoin( table_A, table_B, table_B.c.db_id == table_A.c.db_id, ), ) mapper( Balama, table_B, inherit_condition= table_B.c.db_id == table_A.c.db_id, inherits= mapper_A, polymorphic_identity= 'Balama', ) compile_mappers() elif what=='safunc': safunc( meta, Alaba, Balama) else: print 'dbcook' mybuild = o2r.Builder( meta, dict( Alaba=Alaba, Balama=Balama), #just scan anything here that looks like subclass of Base fieldtypemap, base_klas=Base, #tables = tables, ) # del mybuild if 10: def populate(): a = Alaba() a.name = 'anna' b = Balama() b.name = 'x' return locals() session = create_session() #anything off Base, go to db for x in populate().values(): if isinstance( x, Base) and not isinstance( x, type): session.save( x) session.flush() session = create_session() all = session.query( Alaba).all() assert len(all)==2 for q in all: print 'o', q clear_mappers() return meta