Python sqlalchemy.sql.expression.and_() Examples

The following are 30 code examples of sqlalchemy.sql.expression.and_(). 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.sql.expression , or try the search function .
Example #1
Source File: relations.py    From blitzdb with MIT License 7 votes vote down vote up
def append(self,obj):
        with self.obj.backend.transaction(implicit = True):

            #if the object is not yet in a DB, we save it first.

            if obj.pk is None:
                self.obj.backend.save(obj)

            relationship_table = self.params['relationship_table']
            condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
                             relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
            s = select([func.count(text('*'))]).where(condition)
            result = self.obj.backend.connection.execute(s)
            cnt = result.first()[0]
            if cnt:
                return #the object is already inside
            values = {
                self.params['pk_field_name'] : self.obj.pk,
                self.params['related_pk_field_name'] : obj.pk
            }
            insert = relationship_table.insert().values(**values)
            self.obj.backend.connection.execute(insert)
            self._queryset = None 
Example #2
Source File: opds.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def feed_shelf(book_id):
    off = request.args.get("offset") or 0
    if current_user.is_anonymous:
        shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1,
                                                  ub.Shelf.id == book_id).first()
    else:
        shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id),
                                                           ub.Shelf.id == book_id),
                                                      and_(ub.Shelf.is_public == 1,
                                                           ub.Shelf.id == book_id))).first()
    result = list()
    # user is allowed to access shelf
    if shelf:
        books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == book_id).order_by(
            ub.BookShelf.order.asc()).all()
        for book in books_in_shelf:
            cur_book = calibre_db.get_book(book.book_id)
            result.append(cur_book)
    pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page,
                            len(result))
    return render_xml_template('feed.xml', entries=result, pagination=pagination) 
Example #3
Source File: models.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
def get_last_trades(session, since = None, page_size = None, offset = None, sort_column = None, sort_order='ASC'):
        if since is not None:
          if since > 1000000000:
            since = datetime.utcfromtimestamp(since)
            filter_obj  = and_(Trade.created >= since)
          else:
            filter_obj  = and_(Trade.id > int(since))
        else:
          today = datetime.now()
          since = today - timedelta(days=1)
          filter_obj  = and_(Trade.created >= since)

        trades = session.query(Trade).filter(filter_obj).order_by( Trade.id.desc())

        if page_size:
            trades = trades.limit(page_size)
        if offset:
            trades = trades.offset(offset)
        if sort_column:
            if sort_order == 'ASC':
                trades = trades.order(sort_column)
            else:
                trades = trades.order(sort_column).desc()

        return trades 
Example #4
Source File: models.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
def prepare_filter_query(session, filter_list):
    q = session.query(Order)
    if filter_list:
      for f in filter_list:
        filter_data = f.split(" ")
        if len(filter_data) == 3:
          if filter_data[0] == "user_id" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.user_id == int(filter_data[2])))
          elif filter_data[0] == "account_id" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.account_id == int(filter_data[2])))
          elif filter_data[0] == "has_cum_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_cum_qty == int(filter_data[2])))
          elif filter_data[0] == "has_leaves_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_leaves_qty == int(filter_data[2])))
          elif filter_data[0] == "has_cxl_qty" and filter_data[1] == "eq":
            q =  q.filter(and_(Order.has_cxl_qty == int(filter_data[2])))
    return q 
Example #5
Source File: __init__.py    From gamification-engine with MIT License 6 votes vote down vote up
def subject_add_to_parent(request, *args, **kw):
    context = request.context
    parent_row = context.subject_row

    if not request.has_perm(perm_global_manage_subjects):
        raise APIError(403, "forbidden")

    q = t_subjects_subjects.select().where(and_(
        t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
        t_subjects_subjects.c.part_of_id == parent_row["id"],
    ))

    r = DBSession.execute(q).fetchone()

    if not r:
        q = t_subjects_subjects.insert({
            'subject_id': request.validated_params.body["subject_id"],
            'part_of_id': parent_row["id"],
        })

        update_connection().execute(q)

    return r_status.output({
        "status": "ok"
    }) 
Example #6
Source File: __init__.py    From gamification-engine with MIT License 6 votes vote down vote up
def subject_remove_from_parent(request, *args, **kw):
    context = request.context
    parent_row = context.subject_row

    if not request.has_perm(perm_global_manage_subjects):
        raise APIError(403, "forbidden")

    q = t_subjects_subjects.select().where(and_(
        t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
        t_subjects_subjects.c.part_of_id == parent_row["id"],
    ))

    r = DBSession.execute(q).fetchone()

    if r:
        q = t_subjects_subjects.delete().where(and_(
            t_subjects_subjects.c.subject_id == request.validated_params.body["subject_id"],
            t_subjects_subjects.c.part_of_id == parent_row["id"],
        ))

        update_connection().execute(q)

    return r_status.output({
        "status": "ok"
    }) 
Example #7
Source File: filter.py    From py-mongosql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sql_anded_together(conditions):
        """ Take a list of conditions and AND then together into an SQL expression

            In a few places in the code, we keep conditions in a list without wrapping them
            explicitly into a Boolean expression: just to keep it simple, easy to go through.

            This method will put them together, as required.
        """
        # No conditions: just return True, which is a valid sqlalchemy expression for filtering
        if not conditions:
            return True

        # AND them together
        cc = and_(*conditions)
        # Put parentheses around it, if necessary
        return cc.self_group() if len(conditions) > 1 else cc 
Example #8
Source File: account_limit.py    From rucio with Apache License 2.0 6 votes vote down vote up
def get_rse_account_usage(rse_id, session=None):
    """
    Returns the account limit and usage for all for all accounts on a RSE.

    :param rse_id:   The id of the RSE.
    :param session:  Database session in use.
    :return:         List of dictionaries.
    """
    result = []
    query = session.query(models.AccountUsage.account, models.AccountUsage.files, models.AccountUsage.bytes, models.AccountLimit.bytes, models.RSE.rse)
    query = query.filter(models.RSE.id == models.AccountUsage.rse_id)
    query = query.outerjoin(models.AccountLimit, and_(models.AccountUsage.account == models.AccountLimit.account, models.AccountUsage.rse_id == models.AccountLimit.rse_id)).filter(models.AccountUsage.rse_id == rse_id)
    account_limits_tmp = query.all()
    for row in account_limits_tmp:
        result.append({'rse_id': rse_id, 'rse': row[4], 'account': row[0], 'used_files': row[1], 'used_bytes': row[2], 'quota_bytes': row[3]})
    return result 
Example #9
Source File: db.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def get_search_results(self, term):
        term.strip().lower()
        self.session.connection().connection.connection.create_function("lower", 1, lcase)
        q = list()
        authorterms = re.split("[, ]+", term)
        for authorterm in authorterms:
            q.append(Books.authors.any(func.lower(Authors.name).ilike("%" + authorterm + "%")))
        return self.session.query(Books).filter(self.common_filters(True)).filter(
            or_(Books.tags.any(func.lower(Tags.name).ilike("%" + term + "%")),
                Books.series.any(func.lower(Series.name).ilike("%" + term + "%")),
                Books.authors.any(and_(*q)),
                Books.publishers.any(func.lower(Publishers.name).ilike("%" + term + "%")),
                func.lower(Books.title).ilike("%" + term + "%")
                )).order_by(Books.sort).all()

    # Creates for all stored languages a translated speaking name in the array for the UI 
Example #10
Source File: base.py    From mautrix-python with Mozilla Public License 2.0 6 votes vote down vote up
def _make_simple_select(cls: Type[T], *args: ClauseElement) -> Select:
        """
        Create a simple ``SELECT * FROM table WHERE <args>`` statement.

        Args:
            *args: The WHERE clauses. If there are many elements, they're joined with AND.

        Returns:
            The SQLAlchemy SELECT statement object.
        """
        if len(args) > 1:
            return cls.t.select().where(and_(*args))
        elif len(args) == 1:
            return cls.t.select().where(args[0])
        else:
            return cls.t.select() 
Example #11
Source File: api.py    From karbor with Apache License 2.0 6 votes vote down vote up
def scheduled_operation_log_delete_oldest(context, operation_id,
                                          retained_num, excepted_states):
    table = models.ScheduledOperationLog
    session = get_session()
    with session.begin():
        result = model_query(context, table, session=session).filter_by(
            operation_id=operation_id).order_by(
            expression.desc(table.created_at)).limit(retained_num).all()

        if not result or len(result) < retained_num:
            return
        oldest_create_time = result[-1]['created_at']

        if excepted_states and isinstance(excepted_states, list):
            filters = expression.and_(
                table.operation_id == operation_id,
                table.created_at < oldest_create_time,
                table.state.notin_(excepted_states))
        else:
            filters = expression.and_(
                table.operation_id == operation_id,
                table.created_at < oldest_create_time)

        model_query(context, table, session=session).filter(
            filters).delete(synchronize_session=False) 
Example #12
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def bookmark(book_id, book_format):
    bookmark_key = request.form["bookmark"]
    ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id),
                                              ub.Bookmark.book_id == book_id,
                                              ub.Bookmark.format == book_format)).delete()
    if not bookmark_key:
        ub.session.commit()
        return "", 204

    lbookmark = ub.Bookmark(user_id=current_user.id,
                            book_id=book_id,
                            format=book_format,
                            bookmark_key=bookmark_key)
    ub.session.merge(lbookmark)
    ub.session.commit()
    return "", 201 
Example #13
Source File: api.py    From orchestration with Apache License 2.0 5 votes vote down vote up
def get_wf_sd(service_def_id):
    with session_scope() as session:

        query = session.query(models.Workflow, models.Service) \
            .join(models.Service, and_(
                models.Workflow.service_id == models.Service.id)).filter(
                models.Service.service_definition_id == service_def_id)

    return [] if not query else query.all() 
Example #14
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def toggle_read(book_id):
    if not config.config_read_column:
        book = ub.session.query(ub.ReadBook).filter(and_(ub.ReadBook.user_id == int(current_user.id),
                                                         ub.ReadBook.book_id == book_id)).first()
        if book:
            if book.read_status == ub.ReadBook.STATUS_FINISHED:
                book.read_status = ub.ReadBook.STATUS_UNREAD
            else:
                book.read_status = ub.ReadBook.STATUS_FINISHED
        else:
            readBook = ub.ReadBook(user_id=current_user.id, book_id = book_id)
            readBook.read_status = ub.ReadBook.STATUS_FINISHED
            book = readBook
        if not book.kobo_reading_state:
            kobo_reading_state = ub.KoboReadingState(user_id=current_user.id, book_id=book_id)
            kobo_reading_state.current_bookmark = ub.KoboBookmark()
            kobo_reading_state.statistics = ub.KoboStatistics()
            book.kobo_reading_state = kobo_reading_state
        ub.session.merge(book)
        ub.session.commit()
    else:
        try:
            calibre_db.update_title_sort(config)
            book = calibre_db.get_filtered_book(book_id)
            read_status = getattr(book, 'custom_column_' + str(config.config_read_column))
            if len(read_status):
                read_status[0].value = not read_status[0].value
                calibre_db.session.commit()
            else:
                cc_class = db.cc_classes[config.config_read_column]
                new_cc = cc_class(value=1, book=book_id)
                calibre_db.session.add(new_cc)
                calibre_db.session.commit()
        except (KeyError, AttributeError):
            log.error(u"Custom Column No.%d is not exisiting in calibre database", config.config_read_column)
        except OperationalError as e:
            calibre_db.session.rollback()
            log.error(u"Read status could not set: %e", e)

    return "" 
Example #15
Source File: initializedb.py    From gamification-engine with MIT License 5 votes vote down vote up
def create_user(DBSession, user, password):
    from gengine.app.model import (
        AuthUser,
        Subject,
        AuthRole,
        AuthRolePermission,
        SubjectType,
        t_auth_roles_permissions
    )
    with transaction.manager:
        subjecttype_user = DBSession.query(SubjectType).filter_by(name="User").first()
        if not subjecttype_user:
            subjecttype_user = SubjectType(name="User")
            DBSession.add(subjecttype_user)

        existing = DBSession.query(AuthUser).filter_by(email=user).first()
        DBSession.flush()
        if not existing:
            user1 = Subject(lat=10, lng=50, timezone="Europe/Berlin", subjecttype_id=subjecttype_user.id)
            DBSession.add(user1)
            DBSession.flush()

            auth_user = AuthUser(subject=user1, email=user, password=password, active=True)
            DBSession.add(auth_user)

            auth_role = get_or_create_role(DBSession=DBSession, name="Global Admin")

            for perm in yield_all_perms():
                if not exists_by_expr(t_auth_roles_permissions, and_(
                    t_auth_roles_permissions.c.auth_role_id == auth_role.id,
                    t_auth_roles_permissions.c.name == perm[0]
                )):
                    DBSession.add(AuthRolePermission(role=auth_role, name=perm[0]))

            auth_user.roles.append(auth_role)

            DBSession.add(auth_user)

            DBSession.flush() 
Example #16
Source File: leaderboard.py    From gamification-engine with MIT License 5 votes vote down vote up
def forward(cls, subjecttype_id, from_date, to_date, whole_time_required):
        q = select([t_subjects.c.id, ]).where(t_subjects.c.subjecttype_id == subjecttype_id)
        if from_date != None and to_date != None:
            if whole_time_required:
                q = q.where(and_(
                    t_subjects.c.created_at <= from_date
                    #or_(
                    #    t_subjects.c.deleted_at == None,
                    #    t_subjects.c.deleted_at >= to_date
                    #)
                ))
            else:
                q = q.where(or_(
                    and_(
                        t_subjects.c.created_at <= from_date,
                        #or_(
                        #    t_subjects.c.deleted_at >= from_date,
                        #    t_subjects.c.deleted_at == None,
                        #)
                    ),
                    and_(
                        t_subjects.c.created_at >= from_date,
                        t_subjects.c.created_at <= to_date,
                    )
                ))
        return [x.id for x in DBSession.execute(q).fetchall()]

    #@classmethod
    #def reverse(cls):
    #    return cls.forward() 
Example #17
Source File: views.py    From gamification-engine with MIT License 5 votes vote down vote up
def set_messages_read(request):
    try:
        doc = request.json_body
    except:
        raise APIError(400, "invalid_json", "no valid json body")

    subject_id = int(request.matchdict["subject_id"])

    if asbool(get_settings().get("enable_user_authentication", False)):
        may_read_messages = request.has_perm(perm_global_read_messages) or request.has_perm(
            perm_own_read_messages) and str(request.subject.id) == str(subject_id)
        if not may_read_messages:
            raise APIError(403, "forbidden", "You may not read the messages of this subject.")

    if not exists_by_expr(t_subjects, t_subjects.c.id == subject_id):
        raise APIError(404, "set_messages_read.subject_not_found", "There is no subject with this id.")

    message_id = doc.get("message_id")
    q = select([t_subject_messages.c.id,
        t_subject_messages.c.created_at], from_obj=t_subject_messages).where(and_(t_subject_messages.c.id==message_id,
                                                                       t_subject_messages.c.subject_id==subject_id))
    msg = DBSession.execute(q).fetchone()
    if not msg:
        raise APIError(404, "set_messages_read.message_not_found", "There is no message with this id.")

    uS = update_connection()
    uS.execute(t_subject_messages.update().values({
        "is_read" : True
    }).where(and_(
        t_subject_messages.c.subject_id == subject_id,
        t_subject_messages.c.created_at <= msg["created_at"]
    )))

    return {
        "status" : "ok"
    } 
Example #18
Source File: relations.py    From blitzdb with MIT License 5 votes vote down vote up
def remove(self,obj):
        """
        Remove an object from the relation
        """
        relationship_table = self.params['relationship_table']
        with self.obj.backend.transaction(implicit = True):
            condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk,
                             relationship_table.c[self.params['pk_field_name']] == self.obj.pk)
            self.obj.backend.connection.execute(delete(relationship_table).where(condition))
            self._queryset = None 
Example #19
Source File: base.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def _constraint_to_clause(self, constraint: Constraint) -> ClauseElement:
        return and_(*[column == self.__dict__[name]
                      for name, column in constraint.columns.items()]) 
Example #20
Source File: filter.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def compile_expression(self):
        # So, this is what we expect here
        # self.operator_str: $and, $or, $nor, $not
        # self.value: list[FilterExpressionBase], or just FilterExpressionBase for $not
        #   This means `value` is a list of (column, operator, value), wrapped into an object.
        #   For example: (`age`, ">=", 18)
        #   And the current boolean clause puts it together.

        if self.operator_str == '$not':
            # This operator accepts a FilterExpressionBase, not a list.
            criterion = self.sql_anded_together([
                c.compile_expression()
                for c in self.value
            ])
            return not_(criterion)
        else:
            # Those operators share some steps, so they've been put into one section

            # Their argument (self.value) is a list[FilterExpressionBase].
            # Compile it
            criteria = [self.sql_anded_together([c.compile_expression() for c in cs])
                        for cs in self.value]

            # Build an expression for the boolean operator
            if self.operator_str in ('$or', '$nor'):
                cc = or_(*criteria)
                # for $nor, it will be negated later
            elif self.operator_str == '$and':
                cc = and_(*criteria)
            else:
                raise NotImplementedError('Unknown operator: {}'.format(self.operator_str))

            # Put parentheses around it when there are multiple clauses
            cc = cc.self_group() if len(criteria) > 1 else cc

            # for $nor, we promised to negate the result
            if self.operator_str == '$nor':
                return ~cc
            # Done
            return cc 
Example #21
Source File: models.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hyb_big_id(cls):
        return and_(cls.id > 1000)


# Test how MongoSQL deals with inheritance and polymorphic identity
# MongoSQL shall have no trouble working with inherited fields 
Example #22
Source File: models.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hybrid(cls):
        return and_(cls.id > 10, cls.user.has(User.age > 18)) 
Example #23
Source File: account_limit.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get_local_account_limits(account, rse_ids=None, session=None):
    """
    Returns the account limits for the account on the list of rses.

    :param account:  Account to check the limit for.
    :param rse_ids:  List of RSE ids to check the limit for.
    :param session:  Database session in use.
    :return:         Dictionary {'rse_id': bytes, ...}.
    """

    account_limits = {}
    if rse_ids:
        rse_id_clauses = []
        for rse_id in rse_ids:
            rse_id_clauses.append(and_(models.AccountLimit.rse_id == rse_id, models.AccountLimit.account == account))
        rse_id_clause_chunks = [rse_id_clauses[x:x + 10] for x in range(0, len(rse_id_clauses), 10)]
        for rse_id_chunk in rse_id_clause_chunks:
            tmp_limits = session.query(models.AccountLimit).filter(or_(*rse_id_chunk)).all()
            for limit in tmp_limits:
                if limit.bytes == -1:
                    account_limits[limit.rse_id] = float("inf")
                else:
                    account_limits[limit.rse_id] = limit.bytes
    else:
        account_limits_tmp = session.query(models.AccountLimit).filter(models.AccountLimit.account == account).all()
        for limit in account_limits_tmp:
            if limit.bytes == -1:
                account_limits[limit.rse_id] = float("inf")
            else:
                account_limits[limit.rse_id] = limit.bytes
    return account_limits 
Example #24
Source File: helper.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def tags_filters():
    negtags_list = current_user.list_denied_tags()
    postags_list = current_user.list_allowed_tags()
    neg_content_tags_filter = false() if negtags_list == [''] else db.Tags.name.in_(negtags_list)
    pos_content_tags_filter = true() if postags_list == [''] else db.Tags.name.in_(postags_list)
    return and_(pos_content_tags_filter, ~neg_content_tags_filter)


# checks if domain is in database (including wildcards)
# example SELECT * FROM @TABLE WHERE  'abcdefg' LIKE Name;
# from https://code.luasoftware.com/tutorials/flask/execute-raw-sql-in-flask-sqlalchemy/ 
Example #25
Source File: db.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def check_exists_book(self, authr, title):
        self.session.connection().connection.connection.create_function("lower", 1, lcase)
        q = list()
        authorterms = re.split(r'\s*&\s*', authr)
        for authorterm in authorterms:
            q.append(Books.authors.any(func.lower(Authors.name).ilike("%" + authorterm + "%")))

        return self.session.query(Books)\
            .filter(and_(Books.authors.any(and_(*q)), func.lower(Books.title).ilike("%" + title + "%"))).first()

    # read search results from calibre-database and return it (function is used for feed and simple search 
Example #26
Source File: db.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def common_filters(self, allow_show_archived=False):
        if not allow_show_archived:
            archived_books = (
                ub.session.query(ub.ArchivedBook)
                    .filter(ub.ArchivedBook.user_id == int(current_user.id))
                    .filter(ub.ArchivedBook.is_archived == True)
                    .all()
            )
            archived_book_ids = [archived_book.book_id for archived_book in archived_books]
            archived_filter = Books.id.notin_(archived_book_ids)
        else:
            archived_filter = true()

        if current_user.filter_language() != "all":
            lang_filter = Books.languages.any(Languages.lang_code == current_user.filter_language())
        else:
            lang_filter = true()
        negtags_list = current_user.list_denied_tags()
        postags_list = current_user.list_allowed_tags()
        neg_content_tags_filter = false() if negtags_list == [''] else Books.tags.any(Tags.name.in_(negtags_list))
        pos_content_tags_filter = true() if postags_list == [''] else Books.tags.any(Tags.name.in_(postags_list))
        if self.config.config_restricted_column:
            pos_cc_list = current_user.allowed_column_value.split(',')
            pos_content_cc_filter = true() if pos_cc_list == [''] else \
                getattr(Books, 'custom_column_' + str(self.config.config_restricted_column)). \
                    any(cc_classes[self.config.config_restricted_column].value.in_(pos_cc_list))
            neg_cc_list = current_user.denied_column_value.split(',')
            neg_content_cc_filter = false() if neg_cc_list == [''] else \
                getattr(Books, 'custom_column_' + str(self.config.config_restricted_column)). \
                    any(cc_classes[self.config.config_restricted_column].value.in_(neg_cc_list))
        else:
            pos_content_cc_filter = true()
            neg_content_cc_filter = false()
        return and_(lang_filter, pos_content_tags_filter, ~neg_content_tags_filter,
                    pos_content_cc_filter, ~neg_content_cc_filter, archived_filter)

    # Fill indexpage with all requested data from database 
Example #27
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def toggle_archived(book_id):
    archived_book = ub.session.query(ub.ArchivedBook).filter(and_(ub.ArchivedBook.user_id == int(current_user.id),
                                                                  ub.ArchivedBook.book_id == book_id)).first()
    if archived_book:
        archived_book.is_archived = not archived_book.is_archived
        archived_book.last_modified = datetime.utcnow()
    else:
        archived_book = ub.ArchivedBook(user_id=current_user.id, book_id=book_id)
        archived_book.is_archived = True
    ub.session.merge(archived_book)
    ub.session.commit()
    return "" 
Example #28
Source File: filter.py    From py-mongosql with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def compile_statement(self):
        """ Create an SQL statement

        :rtype: sqlalchemy.sql.elements.BooleanClauseList
        """
        # The list of conditions that will be created by parsing the Query object.
        # In the end, those will be ANDed together
        conditions = []

        # Alright, first we have to handle conditions applied to relationships
        # We have to handle them separately because we want to group filters on the same
        # relationship. If we don't, it may generate duplicate subqueries, for every condition.
        # This would've been not good.
        # So what we do here is we split `expressions` into two groups:
        # 1. Column expressions
        # 2. Relationship expressions, grouped by relation name
        column_expressions = []
        relationship_expressions = {}
        for e in self.expressions:
            if isinstance(e, FilterRelatedColumnExpression):
                relationship_expressions.setdefault(e.relation_name, [])
                relationship_expressions[e.relation_name].append(e)
            else:
                column_expressions.append(e)

        # Compile column expressions. Easy
        conditions.extend(e.compile_expression() for e in column_expressions)

        # Compile related column expressions, grouped by their relation name
        for rel_name, expressions in relationship_expressions.items():
            # Compile
            rel_conditions = [e.compile_expression() for e in expressions]

            # Now, build one query for the whole relationship
            relationship = self.bags.relations[rel_name]
            if self.bags.relations.is_relationship_array(rel_name):
                conditions.append(relationship.any(and_(*rel_conditions)))
            else:
                conditions.append(relationship.has(and_(*rel_conditions)))

        # Convert the list of conditions to one final expression
        return self._BOOLEAN_EXPRESSION_CLS.sql_anded_together(conditions)

    # Not Implemented for this Query Object handler 
Example #29
Source File: push.py    From gamification-engine with MIT License 4 votes vote down vote up
def send_push_message(
        subject_id,
        text="",
        custom_payload={},
        title="Gamification-Engine",
        android_text=None,
        ios_text=None):

    message_count = DBSession.execute(select([func.count("*").label("c")],from_obj=t_subject_messages).where(and_(
        t_subject_messages.c.subject_id == subject_id,
        t_subject_messages.c.is_read == False
    ))).scalar()

    data = dict({"title": title,
                 "badge": message_count}, **custom_payload)

    settings = get_settings()

    if not ios_text:
        ios_text = text

    if not android_text:
        android_text = text

    rows = DBSession.execute(select([t_subject_device.c.push_id, t_subject_device.c.device_os], from_obj=t_subject_device).distinct().where(t_subject_device.c.subject_id==subject_id)).fetchall()

    for device in rows:

        if "ios" in device.device_os.lower():
            identifier = random.getrandbits(32)

            if custom_payload:
                payload = Payload(alert=ios_text, custom=data, badge=message_count, sound="default")
            else:
                payload = Payload(alert=ios_text, custom=data, badge=message_count, sound="default")

            log.debug("Sending Push message to User (ID: %s)", subject_id)

            if device.push_id.startswith("prod_"):
                get_prod_apns().gateway_server.send_notification(device.push_id[5:], payload, identifier=identifier)
            elif device.push_id.startswith("dev_"):
                get_dev_apns().gateway_server.send_notification(device.push_id[4:], payload, identifier=identifier)

        if "android" in device.device_os.lower():

            log.debug("Sending Push message to User (ID: %s)", subject_id)
            push_id = lstrip_word(device.push_id, "dev_")
            push_id = lstrip_word(push_id, "prod_")

            response = get_gcm().json_request(registration_ids=[push_id, ],
                                              data={"message": android_text, "data": data, "title": title},
                                              restricted_package_name=os.environ.get("GCM_PACKAGE", settings.get("gcm.package","")),
                                              priority='high',
                                              delay_while_idle=False)
            if response:
                gcm_feedback(response) 
Example #30
Source File: tasksystem.py    From gamification-engine with MIT License 4 votes vote down vote up
def __call__(self, wrapped):
        """Attach the decorator with Venusian"""

        from gengine.app.registries import get_task_registry
        get_task_registry().register(self.name, wrapped, self.description, self.config_scheme, self.default_config, self.default_cron)

        if self.default_activated:
            import transaction
            from .model import t_tasks
            from ..metadata import DBSession

            if hasattr(DBSession, "target"):
                sess = DBSession()
            else:
                sess = DBSession

            with transaction.manager:

                sess.execute("LOCK TABLE tasks IN ACCESS EXCLUSIVE MODE")
                db_task = sess.execute(t_tasks.select().where(and_(
                    t_tasks.c.task_name.like(self.name),
                    t_tasks.c.is_auto_created == True,
                ))).fetchone()

                if not db_task:
                    # We are not setting config and cron, as we can get the defaults when executing

                    mark_changed(sess, transaction.manager, True)

                    sess.execute(t_tasks.insert().values({
                        'entry_name': self.name,
                        'task_name': self.name,
                        'config': None,
                        'cron': None,
                        'is_removed': False,
                        'is_manually_modified': False,
                        'is_auto_created': True,
                    }))

                    sess.flush()
                sess.commit()
        return wrapped