Python sqlalchemy.orm.object_session() Examples

The following are 30 code examples of sqlalchemy.orm.object_session(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sqlalchemy.orm , or try the search function .
Example #1
Source File: stop.py    From gtfsdb with Mozilla Public License 2.0 6 votes vote down vote up
def routes(self):
        """
        return list of routes servicing this stop
        @todo: rewrite the cache to use timeout checking in Base.py
        """
        try:
            self._routes
        except AttributeError:
            from gtfsdb.model.route import Route
            from gtfsdb.model.trip import Trip
            from gtfsdb.model.stop_time import StopTime
            session = object_session(self)
            q = session.query(Route)
            f = ((StopTime.stop_id == self.stop_id) & (StopTime.departure_time != ''))
            q = q.filter(Route.trips.any(Trip.stop_times.any(f)))
            q = q.order_by(Route.route_sort_order)
            self._routes = q.all()
        return self._routes 
Example #2
Source File: test_session.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_explicit_expunge_pending(self):
        users, User = self.tables.users, self.classes.User

        mapper(User, users)
        sess = Session()
        u1 = User(name="x")
        sess.add(u1)

        sess.flush()
        sess.expunge(u1)

        assert u1 not in sess
        assert object_session(u1) is None

        sess.rollback()

        assert u1 not in sess
        assert object_session(u1) is None 
Example #3
Source File: test_session.py    From sqlalchemy with MIT License 6 votes vote down vote up
def test_deleted_auto_expunged(self):
        users, User = self.tables.users, self.classes.User

        mapper(User, users)
        sess = Session()
        sess.add(User(name="x"))
        sess.commit()

        u1 = sess.query(User).first()
        sess.delete(u1)

        assert not was_deleted(u1)
        sess.flush()

        assert was_deleted(u1)
        assert u1 not in sess
        assert object_session(u1) is sess
        sess.commit()

        assert object_session(u1) is None 
Example #4
Source File: test_session.py    From sqlalchemy with MIT License 6 votes vote down vote up
def _test_extra_dirty_state(self):
        users, User = self.tables.users, self.classes.User
        m = mapper(User, users)

        s = Session()

        @event.listens_for(m, "after_update")
        def e(mapper, conn, target):
            sess = object_session(target)
            for entry in list(sess.identity_map.values()):
                entry.name = "5"

        a1, a2 = User(name="1"), User(name="2")

        s.add_all([a1, a2])
        s.commit()

        a1.name = "3"
        return s, a1, a2 
Example #5
Source File: manager.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def tracked_operation(func):
    @wraps(func)
    def wrapper(self, mapper, connection, target):
        if not is_versioned(target):
            return
        session = object_session(target)
        conn = session.connection()
        try:
            uow = self.units_of_work[conn]
        except KeyError:
            try:
                uow = self.units_of_work[conn.engine]
            except KeyError:
                for connection in self.units_of_work.keys():
                    if not connection.closed and connection.connection is conn.connection:
                        uow = self.unit_of_work(session)
                        break  # The ConnectionFairy is the same, this connection is a clone
                else:
                    raise
        return func(self, uow, target)
    return wrapper 
Example #6
Source File: column_properties.py    From dokomoforms with GNU General Public License v3.0 6 votes vote down vote up
def _answer_stat(survey_node: AnswerableSurveyNode,
                 allowable_types: set,
                 func: Function) -> object:
    type_constraint = survey_node.the_type_constraint
    if type_constraint not in allowable_types:
        raise InvalidTypeForOperation(
            (type_constraint, func._FunctionGenerator__names[0])
        )
    answer_cls = ANSWER_TYPES[survey_node.the_type_constraint]
    return (
        object_session(survey_node)
        .scalar(
            sa.select([func(answer_cls.main_answer)])
            .select_from(Answer.__table__.join(
                answer_cls.__table__, Answer.id == answer_cls.id
            ))
            .where(Answer.survey_node_id == survey_node.id)
        )
    ) 
Example #7
Source File: stop.py    From gtfsdb with Mozilla Public License 2.0 6 votes vote down vote up
def headsigns(self):
        """
        Returns a dictionary of all unique (route_id, headsign) tuples used
        at the stop and the number of trips the head sign is used
        """
        if not hasattr(self, '_headsigns'):
            from gtfsdb.model.stop_time import StopTime
            self._headsigns = defaultdict(int)
            session = object_session(self)
            log.info("QUERY StopTime")
            q = session.query(StopTime)
            q = q.options(joinedload_all('trip.route'))
            q = q.filter_by(stop_id=self.stop_id)
            for r in q:
                headsign = r.stop_headsign or r.trip.trip_headsign
                self._headsigns[(r.trip.route, headsign)] += 1
        return self._headsigns 
Example #8
Source File: sql_base.py    From QCFractal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _update_many_to_many(self, table, parent_id_name, child_id_name, parent_id_val, new_list, old_list=None):
        """Perfomr upsert on a many to many association table
        Does NOT commit changes, parent should optimize when it needs to commit
        raises exception if ids don't exist in the DB
        """

        session = object_session(self)

        old_set = {x for x in old_list} if old_list else set()
        new_set = {x for x in new_list} if new_list else set()

        # Update many-to-many relations
        # Remove old relations and apply the new ones
        if old_set != new_set:
            to_add = new_set - old_set
            to_del = old_set - new_set

            if to_del:
                session.execute(
                    table.delete().where(
                        and_(table.c[parent_id_name] == parent_id_val, table.c[child_id_name].in_(to_del))
                    )
                )
            if to_add:
                session.execute(table.insert().values([(parent_id_val, my_id) for my_id in to_add])) 
Example #9
Source File: mixins.py    From sqlalchemy_mptt with MIT License 6 votes vote down vote up
def leftsibling_in_level(self):
        """ Node to the left of the current node at the same level

        For example see
        :mod:`sqlalchemy_mptt.tests.cases.get_tree.test_leftsibling_in_level`
        """  # noqa
        table = _get_tree_table(self.__mapper__)
        session = Session.object_session(self)
        current_lvl_nodes = (
            session.query(table)
            .filter_by(level=self.level)
            .filter_by(tree_id=self.tree_id)
            .filter(table.c.lft < self.left)
            .order_by(table.c.lft)
            .all()
        )
        if current_lvl_nodes:
            return current_lvl_nodes[-1]
        return None 
Example #10
Source File: mixins.py    From sqlalchemy_mptt with MIT License 6 votes vote down vote up
def move_before(self, node_id):
        """ Moving one node of tree before another

        For example see:

        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_function`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_other_tree`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_before_to_top_level`
        """  # noqa
        session = Session.object_session(self)
        table = _get_tree_table(self.__mapper__)
        pk = getattr(table.c, self.get_pk_column().name)
        node = session.query(table).filter(pk == node_id).one()
        self.parent_id = node.parent_id
        self.mptt_move_before = node_id
        session.add(self) 
Example #11
Source File: problem.py    From ml-annotate with MIT License 5 votes vote down vote up
def dataset_count(self):
        from annotator.models import Dataset

        return object_session(self).query(Dataset).filter(
            Dataset.problem == self
        ).count() 
Example #12
Source File: test_session.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_plain_delete(self):
        Address = self.classes.Address

        def evt(mapper, conn, instance):
            object_session(instance).delete(Address(email="x1"))

        self._test(evt, r"Session.delete\(\)") 
Example #13
Source File: test_session.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_object_session_raises(self):
        User = self.classes.User

        assert_raises(orm_exc.UnmappedInstanceError, object_session, object())

        assert_raises(orm_exc.UnmappedInstanceError, object_session, User()) 
Example #14
Source File: test_gmail_auth_credentials.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_token_during_connect(db, patch_access_token_getter,
                                      account_with_single_auth_creds):
    account_id = account_with_single_auth_creds.id

    patch_access_token_getter.revoke_refresh_token(
        account_with_single_auth_creds.auth_credentials[0].refresh_token)
    account_with_single_auth_creds.verify_all_credentials()
    assert len(account_with_single_auth_creds.valid_auth_credentials) == 0
    g_token_manager.clear_cache(account_with_single_auth_creds)

    # connect_account() takes an /expunged/ account object
    # that has the necessary relationships eager-loaded
    object_session(account_with_single_auth_creds).expunge(
        account_with_single_auth_creds)
    assert not object_session(account_with_single_auth_creds)

    account = db.session.query(GmailAccount).options(
        joinedload(GmailAccount.auth_credentials)).get(
        account_id)
    db.session.expunge(account)
    assert not object_session(account)

    g = GmailAuthHandler('gmail')

    with pytest.raises(OAuthError):
        g.connect_account(account)

    invalid_account = db.session.query(GmailAccount).get(account_id)
    for auth_creds in invalid_account.auth_credentials:
        assert not auth_creds.is_valid 
Example #15
Source File: test_session.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_plain_merge(self):
        Address = self.classes.Address

        def evt(mapper, conn, instance):
            object_session(instance).merge(Address(email="x1"))

        self._test(evt, r"Session.merge\(\)") 
Example #16
Source File: imap.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_labels(self, new_labels):
        # TODO(emfree): This is all mad complicated. Simplify if possible?

        # Gmail IMAP doesn't use the normal IMAP \\Draft flag. Silly Gmail
        # IMAP.
        self.is_draft = '\\Draft' in new_labels
        self.is_starred = '\\Starred' in new_labels

        category_map = {
            '\\Inbox': 'inbox',
            '\\Important': 'important',
            '\\Sent': 'sent',
            '\\Trash': 'trash',
            '\\Spam': 'spam',
            '\\All': 'all'
        }

        remote_labels = set()
        for label in new_labels:
            if label in ('\\Draft', '\\Starred'):
                continue
            elif label in category_map:
                remote_labels.add((category_map[label], category_map[label]))
            else:
                remote_labels.add((label, None))

        local_labels = {(l.name, l.canonical_name): l for l in self.labels}

        remove = set(local_labels) - remote_labels
        add = remote_labels - set(local_labels)

        with object_session(self).no_autoflush:
            for key in remove:
                self.labels.remove(local_labels[key])

            for name, canonical_name in add:
                label = Label.find_or_create(object_session(self),
                                             self.account, name,
                                             canonical_name)
                self.labels.add(label) 
Example #17
Source File: test_session.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_plain_add(self):
        Address = self.classes.Address

        def evt(mapper, conn, instance):
            object_session(instance).add(Address(email="x1"))

        self._test(evt, r"Session.add\(\)") 
Example #18
Source File: test_session.py    From sqlalchemy with MIT License 5 votes vote down vote up
def test_expunge_cascade(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User,
        )

        mapper(Address, addresses)
        mapper(
            User,
            users,
            properties={
                "addresses": relationship(
                    Address,
                    backref=backref("user", cascade="all"),
                    cascade="all",
                )
            },
        )

        session = create_session()
        u = session.query(User).filter_by(id=7).one()

        # get everything to load in both directions
        print([a.user for a in u.addresses])

        # then see if expunge fails
        session.expunge(u)

        assert sa.orm.object_session(u) is None
        assert sa.orm.attributes.instance_state(u).session_id is None
        for a in u.addresses:
            assert sa.orm.object_session(a) is None
            assert sa.orm.attributes.instance_state(a).session_id is None 
Example #19
Source File: calendar.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def should_suppress_transaction_creation(self):
        if (self in object_session(self).new or
                self in object_session(self).deleted):
            return False
        obj_state = inspect(self)
        return not (obj_state.attrs.name.history.has_changes() or
                    obj_state.attrs.description.history.has_changes() or
                    obj_state.attrs.read_only.history.has_changes()) 
Example #20
Source File: test_gmail_auth_credentials.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_token_during_connect(db, patch_access_token_getter,
                                      account_with_single_auth_creds):
    account_id = account_with_single_auth_creds.id

    patch_access_token_getter.revoke_refresh_token(
        account_with_single_auth_creds.auth_credentials[0].refresh_token)
    account_with_single_auth_creds.verify_all_credentials()
    assert len(account_with_single_auth_creds.valid_auth_credentials) == 0
    g_token_manager.clear_cache(account_with_single_auth_creds)

    # connect_account() takes an /expunged/ account object
    # that has the necessary relationships eager-loaded
    object_session(account_with_single_auth_creds).expunge(
        account_with_single_auth_creds)
    assert not object_session(account_with_single_auth_creds)

    account = db.session.query(GmailAccount).options(
        joinedload(GmailAccount.auth_credentials)).get(
        account_id)
    db.session.expunge(account)
    assert not object_session(account)

    g = GmailAuthHandler('gmail')

    with pytest.raises(OAuthError):
        g.connect_account(account)

    invalid_account = db.session.query(GmailAccount).get(account_id)
    for auth_creds in invalid_account.auth_credentials:
        assert not auth_creds.is_valid 
Example #21
Source File: column_properties.py    From dokomoforms with GNU General Public License v3.0 5 votes vote down vote up
def answer_mode(survey_node: AnswerableSurveyNode):
    """Get the mode of the answers."""
    type_constraint = survey_node.the_type_constraint
    allowable_types = {
        'text', 'integer', 'decimal', 'date', 'time', 'timestamp', 'location',
        'facility', 'multiple_choice'
    }
    if type_constraint not in allowable_types:
        raise InvalidTypeForOperation((type_constraint, 'mode'))
    answer_cls = ANSWER_TYPES[survey_node.the_type_constraint]
    result = (
        object_session(survey_node)
        .execute(
            sa.text(
                'SELECT MODE() WITHIN GROUP (ORDER BY main_answer)'
                ' FROM {table} JOIN {answer_table} ON'
                ' {table}.id = {answer_table}.id'
                ' WHERE {answer_table}.survey_node_id = :sn_id'.format(
                    table=answer_cls.__table__,
                    answer_table=Answer.__table__,
                )
            ),
            {'sn_id': survey_node.id}
        )
        .scalar()
    )
    if type_constraint == 'multiple_choice' and result:
        result = object_session(survey_node).query(Choice).get(str(result))
    return result 
Example #22
Source File: place.py    From osm-wikidata with GNU General Public License v3.0 5 votes vote down vote up
def covers(self, item):
        ''' Is the given item within the geometry of this place. '''
        q = (select([func.ST_Covers(Place.geom, item['location'])])
                .where(Place.place_id == self.place_id))
        return object_session(self).scalar(q) 
Example #23
Source File: base.py    From gtfsdb with Mozilla Public License 2.0 5 votes vote down vote up
def session(self):
        #import pdb; pdb.set_trace()
        ret_val = None
        try:
            ret_val = object_session(self)
        except:
            log.warning("can't get a session from object")
        return ret_val 
Example #24
Source File: events.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def before_delete(self, mapper, connection, instance):
        session = object_session(instance)
        self.instances[session].discard(instance)
        mptt_before_delete(mapper, connection, instance) 
Example #25
Source File: events.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def before_update(self, mapper, connection, instance):
        session = object_session(instance)
        self.instances[session].add(instance)
        mptt_before_update(mapper, connection, instance) 
Example #26
Source File: events.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def before_insert(self, mapper, connection, instance):
        session = object_session(instance)
        self.instances[session].add(instance)
        mptt_before_insert(mapper, connection, instance) 
Example #27
Source File: mixins.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def _base_query_obj(self, session=None):
        if not session:
            session = object_session(self)
        return self._base_query(session) 
Example #28
Source File: mixins.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def move_after(self, node_id):
        """ Moving one node of tree after another

        For example see :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_after_function`
        """  # noqa
        session = Session.object_session(self)
        self.parent_id = self.parent_id
        self.mptt_move_after = node_id
        session.add(self) 
Example #29
Source File: mixins.py    From sqlalchemy_mptt with MIT License 5 votes vote down vote up
def move_inside(self, parent_id):
        """ Moving one node of tree inside another

        For example see:

        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_function`
        * :mod:`sqlalchemy_mptt.tests.cases.move_node.test_move_inside_to_the_same_parent_function`
        """  # noqa
        session = Session.object_session(self)
        self.parent_id = parent_id
        self.mptt_move_inside = parent_id
        session.add(self) 
Example #30
Source File: test_session.py    From sqlalchemy with MIT License 4 votes vote down vote up
def test_duplicate_update(self):
        users, User = self.tables.users, self.classes.User

        mapper(User, users)
        Session = sessionmaker()
        sess = Session()

        u1 = User(name="u1")
        sess.add(u1)
        sess.flush()
        assert u1.id is not None

        sess.expunge(u1)

        assert u1 not in sess
        assert Session.object_session(u1) is None

        u2 = sess.query(User).get(u1.id)
        assert u2 is not None and u2 is not u1
        assert u2 in sess

        assert_raises_message(
            sa.exc.InvalidRequestError,
            "Can't attach instance <User.*?>; another instance "
            "with key .*? is already "
            "present in this session.",
            sess.add,
            u1,
        )

        sess.expunge(u2)
        assert u2 not in sess
        assert Session.object_session(u2) is None

        u1.name = "John"
        u2.name = "Doe"

        sess.add(u1)
        assert u1 in sess
        assert Session.object_session(u1) is sess

        sess.flush()

        sess.expunge_all()

        u3 = sess.query(User).get(u1.id)
        assert u3 is not u1 and u3 is not u2 and u3.name == u1.name