def test_3(): """ database - test with elixir & framework render method """ app = App1() filePath = os.path.join(os.path.dirname(__file__), 'helloworld.csv') reader = csv.reader(open(filePath, 'r')) res = {} for row in reader: res[row[0].decode('utf-8')] = row[1].decode('utf-8') Language(id=row[0].decode('utf-8'), label=row[1].decode('utf-8')) session.flush() for language in Language.query.all(): app.add_language(language) h = xml.Renderer() xmlToTest = component.Component(app).render(h).write_xmlstring( xml_declaration=True, pretty_print=True).strip() f = open(os.path.join(os.path.dirname(__file__), 'test_xmlns_1.xml')) xmlToCompare = f.read() f.close() assert xmlToTest == xmlToCompare
def getOrCreate( cls, code, name ): country = Country.query.filter_by( code = code ).first() if not country: from elixir import session country = Country( code = code, name = name ) session.flush( [country] ) return country
def getOrCreate( cls, street1, street2, city ): address = cls.query.filter_by( street1 = street1, street2 = street2, city = city ).first() if not address: from elixir import session address = cls( street1 = street1, street2 = street2, city = city ) session.flush( [address] ) return address
def flush(self, entity_instance): """Flush the pending changes of this entity instance to the backend""" from sqlalchemy.orm.session import Session session = Session.object_session(entity_instance) if session: session.flush([entity_instance])
def test_poc_assocproxy(self): from datetime import datetime article = Article( author='unknown', release=datetime.now(), title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad') session.add(article) session.flush() session.expunge_all() article = Article.get(1) fr = article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade") assert fr is not None session.commit() session.expunge_all() article = Article.get(1) author = article.get_localized('fr').author assert author is not None release = article.get_localized('fr').release assert release is not None
def flush(self, party): from sqlalchemy.orm.session import Session session = Session.object_session( party ) if session: # # make sure the temporary contact mechanisms are added # relational # for cm in party._contact_mechanisms.values(): if not cm: break found = False for party_contact_mechanism in party.contact_mechanisms: mechanism = party_contact_mechanism.contact_mechanism_mechanism if mechanism and mechanism[0] == cm[0]: party_contact_mechanism.contact_mechanism_mechanism = cm found = True break if not found: contact_mechanism = ContactMechanism( mechanism = cm ) party.contact_mechanisms.append( PartyContactMechanism(contact_mechanism=contact_mechanism) ) # # then clear the temporary store to make sure they are not created # a second time # #for party_contact_mechanism in party.contact_mechanisms: # objects.extend([ party_contact_mechanism, party_contact_mechanism.contact_mechanism ]) session.flush() party._contact_mechanisms.clear() party.expire( ['phone', 'email', 'fax'] )
def test_edit_locale(self): fr = self.article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade") session.flush() session.expunge_all() article = Article.get(1) article.edit_locale('fr' , title='Les mille et deux nuits') assert article.get_localized('fr').title == 'Les mille et une nuits'
def __stop__(self): self.log.debug('Attempting to stop machine') self.machine.state(State.SHUTDOWN) self.log.debug('Attempted to stop machine') if self['camTempEnable']: self.getManager().getProxy(self['camera']).stopCooling() session.flush()
def getOrCreate( cls, country, code, name ): city = City.query.filter_by( code = code, country = country ).first() if not city: from elixir import session city = City( code = code, name = name, country = country ) session.flush( [city] ) return city
def getOrCreateAuthentication( cls, username ): authentication = cls.query.filter_by( username = username ).first() if not authentication: authentication = cls( username = username ) from elixir import session session.flush( [authentication] ) return authentication
def commitChanges(self): try: session.commit() session.flush() except IntegrityError as e: session.rollback() raise DatabaseException(e, self.Entity)
def test_get_many_localized(self): ar = self.article.add_locale('ar', title=u'كتاب ألف ليلة وليلة', content=u"قمة الأدب العربى ودرته وتاجه على مر تاريخه" ) fr = self.article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade") session.flush() translations = self.article.get_many_localized(('en','fr','ar')) assert fr in translations assert ar in translations assert self.article in translations
def flush(self, party): from sqlalchemy.orm.session import Session session = Session.object_session( party ) if session: objects = [ party ] for party_contact_mechanism in party.contact_mechanisms: objects.extend([ party_contact_mechanism, party_contact_mechanism.contact_mechanism ]) session.flush( objects ) party.expire( ['phone', 'email'] )
def __set_task(self, computer, task_type, *details): output = '' if len(details) == 0: show_help() computer = Computer.get_by(id=computer_id) details = " ".join(details) output += "Found %s in the database. Requesting %s of %s" % \ (repr(computer), task_type, details) Tasks(computer=computer, action=task_type, details=details) session.flush() return output
def setUp(self): """Method used to build a database""" metadata.bind = engine setup_all() create_all() article = Article(author='unknown', title='A Thousand and one nights', content='It has been related to me, O happy King, said Shahrazad') session.add(article) session.flush() session.expunge_all() self.article = Article.get(1)
def create(locker, hostname, path, requestor=None, purpose=""): if requestor is None: requestor = auth.current_user() t = Ticket(requestor=requestor, hostname=hostname, locker=locker, path=path, state="open", purpose=purpose) session.flush() t.addEvent(type='request', state="open", target='us') return t
def test_delete_locale(self): fr = self.article.add_locale('fr', title='Les mille et une nuits', content=u"J'ai entendu dire, Ô mon roi, dit Scheherazade") assert fr is not None session.flush() session.expunge_all() article = Article.get(1) article.delete_locale('fr') session.flush() session.expunge_all() article = Article.get(1) assert article.get_localized('fr') == None
def test_2(): """ database - simple test with sqlalchemy/elixir unicode test """ filePath = os.path.join(os.path.dirname(__file__), 'helloworld.csv') reader = csv.reader(open(filePath, 'r')) res = {} for row in reader: res[row[0].decode('utf-8')] = row[1].decode('utf-8') Language(id=row[0].decode('utf-8'), label=row[1].decode('utf-8')) session.flush() for language in Language.query.all(): assert language.label == res[language.id]
def flush(self, party): from sqlalchemy.orm.session import Session session = Session.object_session( party ) if session: # # flush all contact mechanism related objects # objects = [party] deleted = ( party in session.deleted ) for party_contact_mechanism in party.contact_mechanisms: if deleted: session.delete( party_contact_mechanism ) objects.extend([ party_contact_mechanism, party_contact_mechanism.contact_mechanism ]) session.flush( objects )
def get_or_create(model, **kwargs): """Helper function to search for an object or create it otherwise, based on the Django's Model.get_or_create() method. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: params = {} for key, val in kwargs.iteritems(): params[key] = val instance = model(**params) session.add(instance) session.flush() return instance, True
def test4(): """ database - test children relation with sqlalchemy/elixir """ f = Father(name=u"Father") c1 = Child(name=u"Child1") c2 = Child(name=u"Child2") f.children.append(c1) f.children.append(c2) assert f is c1.father assert f is c2.father session.flush() assert reduce(operator.__and__, [(elt.father.id == f.id) for elt in Child.query.all()])
def test_1(): """ database - simple test with sqlalchemy/elixir """ Language(id=u"english", label=u"hello world") session.flush() language = Language.query.all()[0] assert language.id == u"english" assert language.label == u"hello world" Language(id=u"french", label=u"bonjour monde") session.flush() language = Language.query.all()[1] assert language.id == u"french" assert language.label == u"bonjour monde"
def create_user(self): user = create_user( uid=u'jcdusse', firstname=u'Jean-Claude', lastname=u'Dusse', email=u'jean-claude.dusse@localhost', work_phone=u'0212345678', mobile_phone=u'0612345678', position=u'Bronzé', corporation=OrganizationData(label=u'PagesJaunes', type=OrganizationType(u'Corporation')), direction=OrganizationData(label=u'Dir. Communication', type=OrganizationType(u'Direction')), service=OrganizationData(label=u'Direction de la Communication', type=OrganizationType(u'Service')), site=OrganizationData(label=u'Sèvres', type=OrganizationType(u'Site')), ) user.photo = self.create_photo() session.flush() return user
def translate_or_register( cls, source, language ): """Translate source to language, if no translation is found, register the source as to be translated and return the source""" if source: source = unicode( source ) translation = cls.translate( source, language ) if not translation: if not cls.query.filter_by( source = source, language = language ).first(): if ( source, language ) not in cls._cache: from elixir import session registered_translation = Translation( source = source, language = language ) cls._cache[( source, language )] = source session.flush( [registered_translation] ) logger.debug( 'registed %s with id %s' % ( source, registered_translation.id ) ) return source return translation return ''
def delete(self, entity_instance): """Delete an entity instance""" from sqlalchemy.orm.session import Session session = Session.object_session(entity_instance) # # new and deleted instances cannot be deleted # if session: if entity_instance in session.new: session.expunge(entity_instance) elif (entity_instance not in session.deleted) and ( entity_instance in session ): # if the object is not in the session, it might allready be deleted history = None # # only if we know the primary key, we can keep track of its history # primary_key = self.mapper.primary_key_from_instance(entity_instance) # # we can only store history of objects where the primary key has only # 1 element # @todo: store history for compound primary keys # if not None in primary_key and len(primary_key) == 1: pk = primary_key[0] # save the state before the update from camelot.model.memento import BeforeDelete # only register the delete when the camelot model is active if hasattr(BeforeDelete, "query"): from camelot.model.authentication import getCurrentAuthentication history = BeforeDelete( model=unicode(self.entity.__name__), primary_key=pk, previous_attributes={}, authentication=getCurrentAuthentication(), ) entity_instance.delete() session.flush([entity_instance]) if history: Session.object_session(history).flush([history])
def translate_or_register(cls, source, language): """Translate source to language, if no translation is found, register the source as to be translated and return the source""" if source: source = unicode(source) translation = cls.translate(source, language) if not translation: if not cls.query.filter_by(source=source, language=language).first(): if (source, language) not in cls._cache: from elixir import session registered_translation = Translation(source=source, language=language) cls._cache[(source, language)] = source session.flush([registered_translation]) logger.debug('registed %s with id %s' % (source, registered_translation.id)) return source return translation return ''
def delete(self, entity_instance): """Delete an entity instance""" from sqlalchemy.orm.session import Session session = Session.object_session(entity_instance) # # new and deleted instances cannot be deleted # if session: if entity_instance in session.new: session.expunge(entity_instance) elif (entity_instance not in session.deleted) and \ (entity_instance in session): # if the object is not in the session, it might allready be deleted history = None # # only if we know the primary key, we can keep track of its history # primary_key = self.mapper.primary_key_from_instance( entity_instance) # # we can only store history of objects where the primary key has only # 1 element # @todo: store history for compound primary keys # if not None in primary_key and len(primary_key) == 1: pk = primary_key[0] # save the state before the update from camelot.model.memento import BeforeDelete # only register the delete when the camelot model is active if hasattr(BeforeDelete, 'query'): from camelot.model.authentication import getCurrentAuthentication history = BeforeDelete( model=unicode(self.entity.__name__), primary_key=pk, previous_attributes={}, authentication=getCurrentAuthentication()) entity_instance.delete() session.flush([entity_instance]) if history: Session.object_session(history).flush([history])
def test_create_other_default(self): movie = Movie(author='Proust', title=u'À la recherche du temps perdu', content=u'Longtemps, je me suis couché de bonne heure.', resume=u'Du côté de chez Swann', default_locale = "fr") movie.add_locale('en', title=u'In Search of Lost Time and Remembrance of Things Past', content=u"For a long time I used to go to bed early.", resume=u'translated into English by C. K. Scott Moncrieff') session.flush() movie = Movie(author='disney',title=u'الأشرار الصغار وألعابهم الجميلة', content=u"يستمتع الكبار قبل الصغار (او بنفس الدرجة على الأقل) بكل فيلم من سلسلة 'توي ستوري' يظهر في", resume=u'ومكتوبة بالتوازن الدقيق الذي', default_locale = 'ar') movie.add_locale('en', title=u'Toy Story', content=u"woody & friends.", resume=u'a nice cartoon') session.commit() session.expunge_all() # Movie.__localized_class__.localquery() # from nose.tools import set_trace; set_trace() retrieved_movie = Movie.query.first() assert retrieved_movie.get_localized('fr').title == u'À la recherche du temps perdu' assert retrieved_movie.get_localized('en').title == 'In Search of Lost Time and Remembrance of Things Past'
def test_3(): """ database - test with elixir & framework render method """ app = App1() filePath = os.path.join(os.path.dirname(__file__), 'helloworld.csv') reader = csv.reader(open(filePath, 'r')) res = {} for row in reader: res[row[0].decode('utf-8')] = row[1].decode('utf-8') Language(id=row[0].decode('utf-8'), label=row[1].decode('utf-8')) session.flush() for language in Language.query.all(): app.add_language(language) h = xml.Renderer() xmlToTest = component.Component(app).render(h).write_xmlstring(xml_declaration=True, pretty_print=True).strip() f = open(os.path.join(os.path.dirname(__file__), 'test_xmlns_1.xml')) xmlToCompare = f.read() f.close() assert xmlToTest == xmlToCompare
def setup_function(_): create_all() Father(name=u"Charles Ingalls") session.flush()
def teardown_request(exception): db_session.flush()
def flush(): session.commit() session.flush()
def _setInterest(tag_count, interest_value): tag_count.interest_factor = interest_value dbsession.flush()
def updateLastLogin(): """Update the last login of the current person to now""" from elixir import session authentication = getCurrentAuthentication() authentication.last_login = datetime.datetime.now() session.flush( [authentication] )
def commit(cls): """ Commite les changements effectués """ session.flush() session.commit()