sqlalchemy.sql.and_

Here are the examples of the python api sqlalchemy.sql.and_ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

161 Examples 7

3 Source : rels.py
with Apache License 2.0
from amakelov

    def get_call_prov_neighbors(self, call_uids: TSet[str], direction: str = Prov.both, conn: Connection = None) -> pd.DataFrame:
        rs = self.rel_storage
        tableobj = rs.get_tableobj(name=self.PROVENANCE_TABLE)
        if direction == Prov.both:
            condition = tableobj.c[Prov.call_uid].in_(get_in_clause_rhs(call_uids))
        else:
            if direction == Prov.backward:
                is_input = True # go from call back to inputs
            elif direction == Prov.forward:
                is_input = False # go from call to outputs
            else:
                raise NotImplementedError()
            condition = sql.and_(tableobj.c[Prov.call_uid].in_(get_in_clause_rhs(call_uids)), 
                                tableobj.c[Prov.is_input] == is_input)
        query = select(tableobj).where(condition)
        return self._fix_provenance_dtypes(df=rs.fast_select(query=query, conn=conn))
    
    def _filter_vref_backward_neighbors(self, prov_df:pd.DataFrame, method:str) -> pd.DataFrame:

3 Source : compiler.py
with Apache License 2.0
from amakelov

    def __init__(self, select_cols:TList[Column]=None,
                 constraint:BooleanClauseList=None):
        self._select_clause = [] if select_cols is None else select_cols
        self._constraint = sql.and_(True) if constraint is None else constraint
    
    def select_cols(self) -> TList[Column]:

3 Source : characterlookup.py
with GNU General Public License v3.0
from Artikash

    def _getStrokeOrderEntry(self, char, glyph):
        """
        Gets the stroke order sequence for the given character from the
        database's stroke order lookup table.

        :type char: str
        :param char: Chinese character
        :type glyph: int
        :param glyph: *glyph* of the character
        :rtype: str
        :return: string of stroke abbreviations separated by spaces and
            hyphens.
        """
        table = self.db.tables['StrokeOrder']
        return self.db.selectScalar(select([table.c.StrokeOrder],
            and_(table.c.ChineseCharacter == char,
                table.c.Glyph == glyph), distinct=True))

    def _buildStrokeOrder(self, char, glyph, includePartial=False, cache=None):

3 Source : queries.py
with MIT License
from bihealth

    def _build_subquery(self):
        return (
            select([func.count(StructuralVariantComment.sa.id).label("comment_count")])
            .select_from(StructuralVariantComment.sa)
            .where(
                and_(
                    StructuralVariant.sa.sv_type == StructuralVariantComment.sa.sv_type,
                    overlaps(
                        StructuralVariant, StructuralVariantComment, min_overlap=self.MIN_OVERLAP
                    ),
                )
            )
            .alias("subquery_comments_inner")
            .lateral("subquery_comments_outer")
        )

    def extend_fields(self, _query_parts):

3 Source : queries.py
with MIT License
from bihealth

def same_variant(lhs, rhs):
    return and_(
        lhs.sa.release == rhs.sa.release,
        lhs.sa.chromosome == rhs.sa.chromosome,
        lhs.sa.start == rhs.sa.start,
        lhs.sa.end == rhs.sa.end,
        lhs.sa.reference == rhs.sa.reference,
        lhs.sa.alternative == rhs.sa.alternative,
    )


class ExtendQueryPartsDbsnpJoin(ExtendQueryPartsBase):

3 Source : queries.py
with MIT License
from bihealth

    def extend_conditions(self, _query_parts):
        condition = []
        set_ = (
            self.model_set.objects.filter(case=self.case, state="active")
            .order_by("-date_created")
            .first()
        )
        if not set_:
            raise RuntimeError("No variant set to case with id %s found." % self.case.id)
        condition.append(
            and_(self.model.sa.case_id == self.case.id, self.model.sa.set_id == set_.id)
        )
        return [or_(*condition)]

    def extend_selectable(self, query_parts):

3 Source : queries.py
with MIT License
from bihealth

    def _build_full_genotype_term(self, name, gt_list):
        quality_term = self._build_quality_term(name)
        genotype_term = self._build_genotype_term(name, gt_list)
        if self.kwargs.get("%s_fail" % name) == "drop-variant":
            return and_(quality_term, genotype_term)
        elif self.kwargs.get("%s_fail" % name) == "no-call":
            return or_(not_(quality_term), genotype_term)  # implication
        else:  # elif kwargs["%s_fail" % name] == "ignore"
            return genotype_term


class ExtendQueryPartsGenotypeDefaultBase(ExtendQueryPartsGenotypeBase):

3 Source : queries.py
with MIT License
from bihealth

    def extend_conditions(self, _query_parts):
        field = getattr(SmallVariant.sa, "%s_transcript_coding" % self.kwargs["database_select"])
        terms = []
        if not self.kwargs["transcripts_coding"]:
            terms.append(field == False)  # equality from SQL Alchemy
        if not self.kwargs["transcripts_noncoding"]:
            terms.append(field == True)  # equality from SQL Alchemy
        return [and_(*terms)]


class ExtendQueryPartsGeneListsFilter(ExtendQueryPartsBase):

3 Source : queries.py
with MIT License
from bihealth

    def _build_gene_sub_query(self, hgnc_field, gene_list):
        return (
            select([getattr(Hgnc.sa, hgnc_field)])
            .select_from(Hgnc.sa.table)
            .where(
                and_(
                    or_(
                        Hgnc.sa.ensembl_gene_id.in_(gene_list),
                        Hgnc.sa.entrez_id.in_(gene_list),
                        Hgnc.sa.symbol.in_(gene_list),
                    ),
                    getattr(Hgnc.sa, hgnc_field) != None,  # SQL Alchemy forces us to use ``!=``
                )
            )
            .distinct()
        )


class ExtendQueryPartsGenomicRegionFilter(ExtendQueryPartsBase):

3 Source : queries.py
with MIT License
from bihealth

    def extend_conditions(self, _query_parts):
        if self.kwargs["genomic_region"]:
            return [
                or_(
                    *[
                        and_(
                            SmallVariant.sa.chromosome == chrom,
                            (SmallVariant.sa.start >= start) if start else True,
                            (SmallVariant.sa.start   <  = end) if end else True,
                        )
                        for chrom, start, end in self.kwargs["genomic_region"]
                    ]
                )
            ]
        return []


class ExtendQueryPartsLoadPrefetchedBase(ExtendQueryPartsBase):

3 Source : table.py
with MIT License
from bkerler

    def _args_to_clause(self, args, clauses=()):
        clauses = list(clauses)
        for column, value in args.items():
            if not self.has_column(column):
                clauses.append(false())
            elif isinstance(value, (list, tuple)):
                clauses.append(self.table.c[column].in_(value))
            else:
                clauses.append(self.table.c[column] == value)
        return and_(*clauses)

    def _args_to_order_by(self, order_by):

3 Source : passivessldb.py
with GNU Affero General Public License v3.0
from D4-project

    def getRSAModulus(self, hash):
        """ query an RSA Public Keys' modulus from its hash """
        try:
            s = select([self.pkTable.c.modulus]).where(and_(self.pkTable.c.type == 'RSA', self.pkTable.c.hash == hash))
            rows = self.conn.execute(s)
            result = ZZ(rows.fetchone()[0])
            rows.close()
            return result
        except (Exception) as error:
            print(error)

    def getRSAHash(self, modulus):

3 Source : passivessldb.py
with GNU Affero General Public License v3.0
from D4-project

    def getRSAHash(self, modulus):
        """ query an RSA hash from its modulus """
        try:
            s = select([self.pkTable.c.hash]).where(and_(self.pkTable.c.type == 'RSA', self.pkTable.c.modulus == modulus))
            rows = self.conn.execute(s)
            result = ZZ(rows.fetchone()[0])
            rows.close()
            return result
        except (Exception) as error:
            print(error)

    def getRSAHashes(self, moduli):

3 Source : passivessldb.py
with GNU Affero General Public License v3.0
from D4-project

    def getRSAHashes(self, moduli):
        """ query an array of tuple RSA, hash from a list of moduli """
        try:
            s = select([self.pkTable.c.hash]).where(and_(self.pkTable.c.type == 'RSA', self.pkTable.c.modulus == modulus))
            rows = self.conn.execute(s)
            result = ZZ(rows.fetchone()[0])
            rows.close()
            return result
        except (Exception) as error:
            print(error)


    def setRSAPrime(self, match):

3 Source : control_utils.py
with MIT License
from glzjin

    def check_challenge(challenge_id, user_id):
        user = Users.query.filter_by(id=user_id).first()

        if user.type == "admin":
            Challenges.query.filter(
                Challenges.id == challenge_id
            ).first_or_404()
        else:
            Challenges.query.filter(
                Challenges.id == challenge_id,
                and_(Challenges.state != "hidden", Challenges.state != "locked"),
            ).first_or_404()

    @staticmethod

3 Source : d5a224bf5862_change_theme_from_original_to_core.py
with Apache License 2.0
from hebtuerror404

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    connection = op.get_bind()
    connection.execute(
        config_table.update().where(
            and_(config_table.c.key == 'ctf_theme', config_table.c.value == 'original')
        ).values(
            value='core'
        )
    )
    # ### end Alembic commands ###


def downgrade():

3 Source : d5a224bf5862_change_theme_from_original_to_core.py
with Apache License 2.0
from hebtuerror404

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    connection = op.get_bind()
    connection.execute(
        config_table.update().where(
            and_(config_table.c.key == 'ctf_theme', config_table.c.value == 'core')
        ).values(
            value='original'
        )
    )
    # ### end Alembic commands ###

3 Source : users.py
with MIT License
from iit-technology-ambit

    def setTagPriority(self, tag, priority):
        result = self.getTagPriority(tag)

        if result is None:
            self.setNewTag(tag)

        s = userTagJunction.update().\
            values(priority=PriorityType(priority)).\
            where(and_(
                userTagJunction.c.user_id == self.id,
                userTagJunction.c.keyword_id == tag.id))

        db.session.execute(s)
        db.session.commit()

    def getTagPriority(self, tag):

3 Source : users.py
with MIT License
from iit-technology-ambit

    def getTagPriority(self, tag):
        s = select([userTagJunction]).where(and_(
            userTagJunction.c.user_id == self.id,
            userTagJunction.c.keyword_id == tag.id))
        result = list(db.session.execute(s))
        try:
            return result[0]["priority"]
        except IndexError:
            return None

    def savePost(self, post):

3 Source : __init__.py
with BSD 2-Clause "Simplified" License
from limodou

    def filter(self, *condition):
        cond = true()
        for c in condition:
            if c is not None:
                cond = and_(c, cond)
        sub_query = select([self.table.c[self.fielda]], (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & cond)
        condition = self.model_class.c[self.reversed_fieldname].in_(sub_query)
        return condition

    def join_filter(self, *condition):

3 Source : __init__.py
with BSD 2-Clause "Simplified" License
from limodou

    def join_filter(self, *condition):
        cond = true()
        for c in condition:
            if c is not None:
                cond = and_(c, cond)
        return (self.table.c[self.fielda] == self.model_class.c[self.reversed_fieldname]) & (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & cond
        
    def convert_dump(self, value):

3 Source : mail.py
with GNU Affero General Public License v3.0
from man-group

def get_summarised_users(dbsession):
    with transaction.manager:
        period = Period.get_current_period(dbsession)
        return (
            dbsession.query(User)
            .options(joinedload("manager"))
            .join(
                FeedbackForm,
                and_(
                    FeedbackForm.to_username == User.username,
                    FeedbackForm.period_id == period.id,
                    FeedbackForm.is_summary == True,
                ),
            )  # noqa
            .all()
        )


def _build_full_subject(company_name, subject):

3 Source : ban.py
with GNU Affero General Public License v3.0
from OpenQueue

    def __and_statement(self) -> and_:
        return and_(
            ban_table.c.ban_id == self.ban_id,
            ban_table.c.user_id == self.user_id,
            ban_table.c.league_id == self.league_id
        )

    async def get(self) -> BanModel:

3 Source : demo.py
with GNU Affero General Public License v3.0
from OpenQueue

    async def __update_value(self, **kwargs) -> None:
        await Sessions.database.execute(
            scoreboard_total_table.update().values(
                **kwargs
            ).where(
                and_(
                    scoreboard_total_table.c.match_id == self.match.match_id,
                    scoreboard_total_table.c.league_id ==
                    self.match.upper.league_id
                )
            )
        )

    async def upload(self) -> None:

3 Source : match.py
with GNU Affero General Public License v3.0
from OpenQueue

    def __and_statement(self) -> and_:
        return and_(
            scoreboard_total_table.c.match_id == self.match_id,
            scoreboard_total_table.c.league_id == self.upper.league_id
        )

    async def get(self) -> MatchModel:

3 Source : auth.py
with MIT License
from russellromney

def validate_password_key(email, key, engine):
    # email exists
    if not user_exists(email, engine):
        return False

    # there is entry matching key and email
    table = password_change_table()
    statement = select([table.c.email, table.c.password_key, table.c.timestamp]).where(
        and_(table.c.email == email, table.c.password_key == key)
    )
    with engine.connect() as conn:
        resp = list(conn.execute(statement))
        if len(resp) == 1:
            if (resp[0].timestamp - (datetime.now() - timedelta(1))).days   <   1:
                return True
        return False

    # finished with no erros; return True
    return True

3 Source : test_autogen_render.py
with MIT License
from sqlalchemy

    def test_render_check_constraint_sqlexpr(self):
        c = column("c")
        five = literal_column("5")
        ten = literal_column("10")
        eq_ignore_whitespace(
            autogenerate.render._render_check_constraint(
                CheckConstraint(and_(c > five, c   <   ten)),
                self.autogen_context,
                None,
            ),
            "sa.CheckConstraint('c > 5 AND c  <  10')",
        )

    def test_render_check_constraint_literal_binds(self):

3 Source : test_autogen_render.py
with MIT License
from sqlalchemy

    def test_render_check_constraint_literal_binds(self):
        c = column("c")
        eq_ignore_whitespace(
            autogenerate.render._render_check_constraint(
                CheckConstraint(and_(c > 5, c   <   10)),
                self.autogen_context,
                None,
            ),
            "sa.CheckConstraint('c > 5 AND c  <  10')",
        )

    def test_render_unique_constraint_opts(self):

3 Source : test_lambdas.py
with MIT License
from sqlalchemy

    def test_select_whereclause(self):
        t1 = table("t1", column("q"), column("p"))

        x = 10
        y = 5

        def go():
            return select(t1).where(lambda: and_(t1.c.q == x, t1.c.p == y))

        self.assert_compile(
            go(), "SELECT t1.q, t1.p FROM t1 WHERE t1.q = :x_1 AND t1.p = :y_1"
        )

        self.assert_compile(
            go(), "SELECT t1.q, t1.p FROM t1 WHERE t1.q = :x_1 AND t1.p = :y_1"
        )

    def test_global_tracking(self):

3 Source : test_log_delete.py
with GNU General Public License v2.0
from StykMartin

def setUpModule():
    # It makes our tests simpler here if they only need to worry about deleting
    # logs which they themselves have created, rather than ones which might have
    # been left behind from earlier tests in the run.
    with session.begin():
        for job in Job.query.filter(Job.is_expired):
            job.deleted = datetime.datetime.utcnow()
        for job in Job.query.filter(and_(Job.is_deleted, Job.purged == None)):
            job.purged = datetime.datetime.utcnow()


class LogDelete(DatabaseTestCase):

3 Source : config.py
with GNU General Public License v2.0
from StykMartin

    def current_value(self, default=None):
        v = self.values().\
            filter(and_(self.value_class.valid_from   <  = datetime.utcnow(), self.value_class.config_item_id == self.id)).\
            order_by(self.value_class.valid_from.desc()).first()
        if v:
            return v.value
        else:
            return default

    def next_value(self):

3 Source : identity.py
with GNU General Public License v2.0
from StykMartin

    def has_member(cls, user): #pylint: disable=E0213
        return or_(
                and_(cls.membership_type != GroupMembershipType.inverted,
                     cls.user_group_assocs.any(UserGroup.user == user)),
                and_(cls.membership_type == GroupMembershipType.inverted,
                     not_(cls.excluded_user_group_assocs.any(ExcludedUserGroup.user == user)))
                )

    @hybrid_property

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def scheduler_ordering(cls, user, query):
        # Order by:
        #   System Owner
        #   System pools
        #   Single procesor bare metal system
        return query.outerjoin(System.cpu).order_by(
            case([(System.owner==user, 1),
                (and_(System.owner!=user, System.pools != None), 2)],
                else_=3),
                and_(System.hypervisor == None, Cpu.processors == 1))

    @classmethod

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def is_free(cls, user): #pylint: disable=E0213
        cls._ensure_user_is_authenticated(user)
        return and_(cls.user == None,
                or_(cls.loaned == None, cls.loaned == user),
                or_(LabController.disabled == None, LabController.disabled == False))

    @staticmethod

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def excluded_osmajor_byarch(self, arch):
        """
        List excluded osmajor for system by arch
        """
        excluded = ExcludeOSMajor.query.join('system').\
                    join('arch').filter(and_(System.id==self.id,
                                             Arch.id==arch.id))
        return excluded

    def excluded_osversion_byarch(self, arch):

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def excluded_osversion_byarch(self, arch):
        """
        List excluded osversion for system by arch
        """
        excluded = ExcludeOSVersion.query.join('system').\
                    join('arch').filter(and_(System.id==self.id,
                                             Arch.id==arch.id))
        return excluded

    def distros(self, query=None):

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def grants(cls, user, permission): #pylint: disable=E0213
        # need to avoid passing an empty list to in_
        clauses = [SystemAccessPolicyRule.user == user, SystemAccessPolicyRule.everybody]
        if user.groups:
            clauses.append(SystemAccessPolicyRule.group_id.in_(
                    [g.group_id for g in user.groups]))
        return cls.rules.any(and_(SystemAccessPolicyRule.permission == permission,
                or_(*clauses)))

    @hybrid_method

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def by_key_value(cls, system, key, value):
        return cls.query.filter(and_(Key_Value_String.key==key,
                                  Key_Value_String.key_value==value,
                                  Key_Value_String.system==system)).one()


class Key_Value_Int(DeclarativeMappedObject):

3 Source : inventory.py
with GNU General Public License v2.0
from StykMartin

    def by_key_value(cls, system, key, value):
        return cls.query.filter(and_(Key_Value_Int.key==key,
                                  Key_Value_Int.key_value==value,
                                  Key_Value_Int.system==system)).one()

# available in python 2.7+ importlib
def import_module(modname):

3 Source : scheduler.py
with GNU General Public License v2.0
from StykMartin

    def completed_n_days_ago(cls, n):  # pylint: disable=E0213
        # We let cutoff be computed on the SQL side, in case n is also a SQL
        # expression and not a constant.
        cutoff = func.adddate(func.utc_timestamp(), -n)
        return and_(
            cls.is_finished(),
            not_(exists([1], from_obj=Recipe.__table__.join(RecipeSet.__table__),
                        whereclause=and_(RecipeSet.job_id == Job.id,
                                         func.coalesce(Recipe.finish_time,
                                                       RecipeSet.queue_time) >= cutoff)))
        )

    @hybrid_property

3 Source : scheduler.py
with GNU General Public License v2.0
from StykMartin

    def is_expired(cls):  # pylint: disable=E0213
        # We *could* rely on the caller to join Job.retention_tag and then use
        # RetentionTag.expire_in_days directly here, instead of a having this
        # correlated subquery. We have used that approach elsewhere in other
        # hybrids. It produces faster queries too. *BUT* if we did that here,
        # and then the caller accidentally forgot to do the join, this clause
        # would silently result in EVERY JOB being expired which would be
        # a huge disaster.
        expire_in_days_subquery = select([RetentionTag.expire_in_days]) \
            .where(RetentionTag.jobs).correlate(Job).label('expire_in_days')
        return and_(
            Job.deleted == None,
            expire_in_days_subquery > 0,
            Job.completed_n_days_ago(expire_in_days_subquery)
        )

    @classmethod

3 Source : scheduler.py
with GNU General Public License v2.0
from StykMartin

    def cancel_jobs_by_user(cls, user, msg=None):
        jobs = Job.query.filter(and_(Job.owner == user,
                                     Job.status.in_([s for s in TaskStatus if not s.finished])))
        for job in jobs:
            job.cancel(msg=msg)

    def purge(self):

3 Source : sql.py
with GNU General Public License v2.0
from StykMartin

    def __init__(self, table, unique_values, extra_values=()):
        """
        An INSERT statement which will atomically insert a row with the given 
        values if one does not exist, or otherwise do nothing. extra_values are 
        values which do not participate in the unique identity of the row.

        unique_values and extra_values are dicts of (column -> scalar).
        """
        values = dict(unique_values)
        values.update(extra_values)
        super(ConditionalInsert, self).__init__(table, values)
        self.unique_condition = and_(*[col == value
                for col, value in unique_values.iteritems()])

@compiler.compiles(ConditionalInsert)

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_multiple_terms(self):
        clause = lucene_to_sqlalchemy(
                u'user_name:rmancy email_address:[email protected]',
                {'user_name': User.user_name, 'email_address': User.email_address},
                [User.user_name, User.email_address])
        self.assert_clause_equals(clause,
                and_(User.user_name == u'rmancy',
                     User.email_address == u'[email protected]'))

    def test_quoted_term(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_integer_column(self):
        clause = lucene_to_sqlalchemy(u'memory:1024',
                {'memory': System.memory}, [System.memory])
        self.assert_clause_equals(clause, System.memory == 1024)
        # searching invalid numbers against a numeric column is just False
        clause = lucene_to_sqlalchemy(u'memory:much',
                {'memory': System.memory}, [System.memory])
        self.assert_clause_equals(clause, and_(false()))

    def test_numeric_column(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_numeric_column(self):
        clause = lucene_to_sqlalchemy(u'weight:1.2',
                {'weight': LabInfo.weight},
                [LabInfo.weight])
        self.assert_clause_equals(clause, LabInfo.weight == Decimal('1.2'))
        # searching invalid numbers against a numeric column is just False
        clause = lucene_to_sqlalchemy(u'weight:heavy',
                {'weight': LabInfo.weight},
                [LabInfo.weight])
        self.assert_clause_equals(clause, and_(false()))

    def test_datetime_column(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_datetime_column(self):
        clause = lucene_to_sqlalchemy(u'date_added:2014-09-08',
                {'date_added': System.date_added}, [System.date_added])
        self.assert_clause_equals(clause,
                and_(System.date_added >= datetime.datetime(2014, 9, 8, 0, 0),
                     System.date_added   <  = datetime.datetime(2014, 9, 8, 23, 59, 59)))
        # searching invalid dates against a datetime column is just False
        clause = lucene_to_sqlalchemy(u'date_added:fnord',
                {'date_added': System.date_added}, [System.date_added])
        self.assert_clause_equals(clause, and_(false()))

    def test_integer_range(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_integer_exclusive_range(self):
        clause = lucene_to_sqlalchemy(u'memory:{1024 TO 2048]',
                {'memory': System.memory}, [System.memory])
        self.assert_clause_equals(clause,
                and_(System.memory > 1024, System.memory   <  = 2048))
        clause = lucene_to_sqlalchemy(u'memory:[1024 TO 2048}',
                {'memory': System.memory}, [System.memory])
        self.assert_clause_equals(clause,
                and_(System.memory >= 1024, System.memory  <  2048))

    def test_datetime_range(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_datetime_exclusive_range(self):
        clause = lucene_to_sqlalchemy(u'date_added:{2014-08-01 TO 2014-08-31]',
                {'date_added': System.date_added}, [System.date_added])
        self.assert_clause_equals(clause,
                and_(System.date_added > datetime.datetime(2014, 8, 1, 0, 0),
                     System.date_added   <  = datetime.datetime(2014, 8, 31, 23, 59, 59)))
        clause = lucene_to_sqlalchemy(u'date_added:[2014-08-01 TO 2014-08-31}',
                {'date_added': System.date_added}, [System.date_added])
        self.assert_clause_equals(clause,
                and_(System.date_added >= datetime.datetime(2014, 8, 1, 0, 0),
                     System.date_added  <  datetime.datetime(2014, 8, 31, 23, 59, 59)))

    def test_string_range(self):

3 Source : test_search_utility.py
with GNU General Public License v2.0
from StykMartin

    def test_string_range(self):
        clause = lucene_to_sqlalchemy(u'fqdn:[aaa TO zzz]',
                {'fqdn': System.fqdn}, [System.fqdn])
        self.assert_clause_equals(clause,
                and_(System.fqdn >= u'aaa', System.fqdn   <  = u'zzz'))
        clause = lucene_to_sqlalchemy(u'fqdn:[aaa TO *]',
                {'fqdn': System.fqdn}, [System.fqdn])
        self.assert_clause_equals(clause, and_(System.fqdn >= u'aaa', true()))
        clause = lucene_to_sqlalchemy(u'fqdn:[* TO zzz]',
                {'fqdn': System.fqdn}, [System.fqdn])
        self.assert_clause_equals(clause, and_(true(), System.fqdn  < = u'zzz'))
        clause = lucene_to_sqlalchemy(u'fqdn:[* TO *]',
                {'fqdn': System.fqdn}, [System.fqdn])
        self.assert_clause_equals(clause, and_(true(), true()))

    def test_string_exclusive_range(self):

See More Examples