Python django.db.models.sql.where.WhereNode() Examples

The following are 22 code examples of django.db.models.sql.where.WhereNode(). 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 django.db.models.sql.where , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_full_handling_conjunction(self):
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()])
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', [])) 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_nodes(self):
        compiler = WhereNodeTest.MockCompiler()
        empty_w = WhereNode()
        w = WhereNode(children=[empty_w, empty_w])
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w.negate()
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.connector = 'OR'
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[empty_w, NothingNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[empty_w, NothingNode()], connector='AND')
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection) 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_empty_full_handling_conjunction(self):
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()])
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', [])) 
Example #4
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_empty_nodes(self):
        if django.VERSION < (1, 11, 0):
            self.skipTest("does not work on older Django")
        compiler = WhereNodeTest.MockCompiler()
        empty_w = WhereNode()
        w = WhereNode(children=[empty_w, empty_w])
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w.negate()
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.connector = 'OR'
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[empty_w, NothingNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[empty_w, NothingNode()], connector='AND')
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection) 
Example #5
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_empty_full_handling_disjunction(self):
        if django.VERSION < (1, 11, 0):
            self.skipTest("does not work on older Django")
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()], connector='OR')
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('dummy', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) 
Example #6
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_empty_full_handling_conjunction(self):
        if django.VERSION < (1, 11, 0):
            self.skipTest("does not work on older Django")
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()])
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()])
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', [])) 
Example #7
Source File: fields.py    From cleanerversion with Apache License 2.0 6 votes vote down vote up
def get_extra_restriction(self, where_class, alias, remote_alias):
        """
        Overrides ForeignObject's get_extra_restriction function that returns
        an SQL statement which is appended to a JOIN's conditional filtering
        part

        :return: SQL conditional statement
        :rtype: WhereNode
        """
        historic_sql = '''{alias}.version_start_date <= %s
                            AND ({alias}.version_end_date > %s
                                OR {alias}.version_end_date is NULL )'''
        current_sql = '''{alias}.version_end_date is NULL'''
        # How 'bout creating an ExtraWhere here, without params
        return where_class([VersionedExtraWhere(historic_sql=historic_sql,
                                                current_sql=current_sql,
                                                alias=alias,
                                                remote_alias=remote_alias)]) 
Example #8
Source File: utils.py    From django-cachalot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _find_subqueries_in_where(children):
    for child in children:
        child_class = child.__class__
        if child_class is WhereNode:
            for grand_child in _find_subqueries_in_where(child.children):
                yield grand_child
        elif child_class is ExtraWhere:
            raise IsRawQuery
        elif child_class is NothingNode:
            pass
        else:
            rhs = child.rhs
            rhs_class = rhs.__class__
            if rhs_class is Query:
                yield rhs
            elif rhs_class is QuerySet:
                yield rhs.query
            elif rhs_class is Subquery or rhs_class is Exists:
                try:
                    yield rhs.query
                except:
                    yield rhs.queryset.query
            elif rhs_class in UNCACHABLE_FUNCS:
                raise UncachableQuery 
Example #9
Source File: related_lookups.py    From python2017 with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            # For multicolumn lookups we need to build a multicolumn where clause.
            # This clause is either a SubqueryConstraint (for values that need to be compiled to
            # SQL) or a OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
            from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR

            root_constraint = WhereNode(connector=OR)
            if self.rhs_is_direct_value():
                values = [get_normalized_value(value, self.lhs) for value in self.rhs]
                for value in values:
                    value_constraint = WhereNode()
                    for source, target, val in zip(self.lhs.sources, self.lhs.targets, value):
                        lookup_class = target.get_lookup('exact')
                        lookup = lookup_class(target.get_col(self.lhs.alias, source), val)
                        value_constraint.add(lookup, AND)
                    root_constraint.add(value_constraint, OR)
            else:
                root_constraint.add(
                    SubqueryConstraint(
                        self.lhs.alias, [target.column for target in self.lhs.targets],
                        [source.name for source in self.lhs.sources], self.rhs),
                    AND)
            return root_constraint.as_sql(compiler, connection)
        else:
            if (getattr(self.rhs, '_forced_pk', False) and
                    not getattr(self.lhs.field.target_field, 'primary_key', False)):
                self.rhs.clear_select_clause()
                if (getattr(self.lhs.output_field, 'primary_key', False) and
                        self.lhs.output_field.model == self.rhs.model):
                    # A case like Restaurant.objects.filter(place__in=restaurant_qs),
                    # where place is a OneToOneField and the primary key of
                    # Restaurant.
                    target_field = self.lhs.field.name
                else:
                    target_field = self.lhs.field.target_field.name
                self.rhs.add_fields([target_field], True)
            return super(RelatedIn, self).as_sql(compiler, connection) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_empty_full_handling_disjunction(self):
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()], connector='OR')
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('dummy', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_empty_full_handling_disjunction(self):
        compiler = WhereNodeTest.MockCompiler()
        w = WhereNode(children=[NothingNode()], connector='OR')
        with self.assertRaises(EmptyResultSet):
            w.as_sql(compiler, connection)
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('', []))
        w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', []))
        w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR')
        self.assertEqual(w.as_sql(compiler, connection), ('dummy', []))
        w.negate()
        self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) 
Example #12
Source File: related_lookups.py    From python2017 with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            assert self.rhs_is_direct_value()
            self.rhs = get_normalized_value(self.rhs, self.lhs)
            from django.db.models.sql.where import WhereNode, AND
            root_constraint = WhereNode()
            for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
                lookup_class = target.get_lookup(self.lookup_name)
                root_constraint.add(
                    lookup_class(target.get_col(self.lhs.alias, source), val), AND)
            return root_constraint.as_sql(compiler, connection)
        return super(RelatedLookupMixin, self).as_sql(compiler, connection) 
Example #13
Source File: related_lookups.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            assert self.rhs_is_direct_value()
            self.rhs = get_normalized_value(self.rhs, self.lhs)
            from django.db.models.sql.where import WhereNode, AND
            root_constraint = WhereNode()
            for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
                lookup_class = target.get_lookup(self.lookup_name)
                root_constraint.add(
                    lookup_class(target.get_col(self.lhs.alias, source), val), AND)
            return root_constraint.as_sql(compiler, connection)
        return super(RelatedLookupMixin, self).as_sql(compiler, connection) 
Example #14
Source File: related_lookups.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            # For multicolumn lookups we need to build a multicolumn where clause.
            # This clause is either a SubqueryConstraint (for values that need to be compiled to
            # SQL) or a OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
            from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR

            root_constraint = WhereNode(connector=OR)
            if self.rhs_is_direct_value():
                values = [get_normalized_value(value, self.lhs) for value in self.rhs]
                for value in values:
                    value_constraint = WhereNode()
                    for source, target, val in zip(self.lhs.sources, self.lhs.targets, value):
                        lookup_class = target.get_lookup('exact')
                        lookup = lookup_class(target.get_col(self.lhs.alias, source), val)
                        value_constraint.add(lookup, AND)
                    root_constraint.add(value_constraint, OR)
            else:
                root_constraint.add(
                    SubqueryConstraint(
                        self.lhs.alias, [target.column for target in self.lhs.targets],
                        [source.name for source in self.lhs.sources], self.rhs),
                    AND)
            return root_constraint.as_sql(compiler, connection)
        else:
            return super(RelatedIn, self).as_sql(compiler, connection) 
Example #15
Source File: related_lookups.py    From python with Apache License 2.0 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            assert self.rhs_is_direct_value()
            self.rhs = get_normalized_value(self.rhs, self.lhs)
            from django.db.models.sql.where import WhereNode, AND
            root_constraint = WhereNode()
            for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
                lookup_class = target.get_lookup(self.lookup_name)
                root_constraint.add(
                    lookup_class(target.get_col(self.lhs.alias, source), val), AND)
            return root_constraint.as_sql(compiler, connection)
        return super(RelatedLookupMixin, self).as_sql(compiler, connection) 
Example #16
Source File: related_lookups.py    From python with Apache License 2.0 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            # For multicolumn lookups we need to build a multicolumn where clause.
            # This clause is either a SubqueryConstraint (for values that need to be compiled to
            # SQL) or a OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
            from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR

            root_constraint = WhereNode(connector=OR)
            if self.rhs_is_direct_value():
                values = [get_normalized_value(value, self.lhs) for value in self.rhs]
                for value in values:
                    value_constraint = WhereNode()
                    for source, target, val in zip(self.lhs.sources, self.lhs.targets, value):
                        lookup_class = target.get_lookup('exact')
                        lookup = lookup_class(target.get_col(self.lhs.alias, source), val)
                        value_constraint.add(lookup, AND)
                    root_constraint.add(value_constraint, OR)
            else:
                root_constraint.add(
                    SubqueryConstraint(
                        self.lhs.alias, [target.column for target in self.lhs.targets],
                        [source.name for source in self.lhs.sources], self.rhs),
                    AND)
            return root_constraint.as_sql(compiler, connection)
        else:
            if (getattr(self.rhs, '_forced_pk', False) and
                    not getattr(self.lhs.field.target_field, 'primary_key', False)):
                self.rhs.clear_select_clause()
                if (getattr(self.lhs.output_field, 'primary_key', False) and
                        self.lhs.output_field.model == self.rhs.model):
                    # A case like Restaurant.objects.filter(place__in=restaurant_qs),
                    # where place is a OneToOneField and the primary key of
                    # Restaurant.
                    target_field = self.lhs.field.name
                else:
                    target_field = self.lhs.field.target_field.name
                self.rhs.add_fields([target_field], True)
            return super(RelatedIn, self).as_sql(compiler, connection) 
Example #17
Source File: base.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_filters_from_where_node(self, where_node, check_only=False):
        # Check if this is a leaf node
        if isinstance(where_node, Lookup):
            field_attname = where_node.lhs.target.attname
            lookup = where_node.lookup_name
            value = where_node.rhs

            # Ignore pointer fields that show up in specific page type queries
            if field_attname.endswith('_ptr_id'):
                return

            # Process the filter
            return self._process_filter(field_attname, lookup, value, check_only=check_only)

        elif isinstance(where_node, SubqueryConstraint):
            raise FilterError('Could not apply filter on search results: Subqueries are not allowed.')

        elif isinstance(where_node, WhereNode):
            # Get child filters
            connector = where_node.connector
            child_filters = [self._get_filters_from_where_node(child) for child in where_node.children]

            if not check_only:
                child_filters = [child_filter for child_filter in child_filters if child_filter]
                return self._connect_filters(child_filters, connector, where_node.negated)

        else:
            raise FilterError('Could not apply filter on search results: Unknown where node: ' + str(type(where_node))) 
Example #18
Source File: related_lookups.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            assert self.rhs_is_direct_value()
            self.rhs = get_normalized_value(self.rhs, self.lhs)
            from django.db.models.sql.where import WhereNode, AND
            root_constraint = WhereNode()
            for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
                lookup_class = target.get_lookup(self.lookup_name)
                root_constraint.add(
                    lookup_class(target.get_col(self.lhs.alias, source), val), AND)
            return root_constraint.as_sql(compiler, connection)
        return super().as_sql(compiler, connection) 
Example #19
Source File: related_lookups.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            # For multicolumn lookups we need to build a multicolumn where clause.
            # This clause is either a SubqueryConstraint (for values that need to be compiled to
            # SQL) or an OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
            from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR

            root_constraint = WhereNode(connector=OR)
            if self.rhs_is_direct_value():
                values = [get_normalized_value(value, self.lhs) for value in self.rhs]
                for value in values:
                    value_constraint = WhereNode()
                    for source, target, val in zip(self.lhs.sources, self.lhs.targets, value):
                        lookup_class = target.get_lookup('exact')
                        lookup = lookup_class(target.get_col(self.lhs.alias, source), val)
                        value_constraint.add(lookup, AND)
                    root_constraint.add(value_constraint, OR)
            else:
                root_constraint.add(
                    SubqueryConstraint(
                        self.lhs.alias, [target.column for target in self.lhs.targets],
                        [source.name for source in self.lhs.sources], self.rhs),
                    AND)
            return root_constraint.as_sql(compiler, connection)
        else:
            if (not getattr(self.rhs, 'has_select_fields', True) and
                    not getattr(self.lhs.field.target_field, 'primary_key', False)):
                self.rhs.clear_select_clause()
                if (getattr(self.lhs.output_field, 'primary_key', False) and
                        self.lhs.output_field.model == self.rhs.model):
                    # A case like Restaurant.objects.filter(place__in=restaurant_qs),
                    # where place is a OneToOneField and the primary key of
                    # Restaurant.
                    target_field = self.lhs.field.name
                else:
                    target_field = self.lhs.field.target_field.name
                self.rhs.add_fields([target_field], True)
            return super().as_sql(compiler, connection) 
Example #20
Source File: fields.py    From django-composite-foreignkey with GNU General Public License v3.0 5 votes vote down vote up
def get_extra_restriction(self, where_class, alias, related_alias):
        constraint = WhereNode(connector=AND)
        for remote, local in self._raw_fields.items():
            lookup = local.get_lookup(self, self.related_model._meta.get_field(remote), alias)
            if lookup:
                constraint.add(lookup, AND)
        if constraint.children:
            return constraint
        else:
            return None 
Example #21
Source File: related_lookups.py    From bioforum with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            assert self.rhs_is_direct_value()
            self.rhs = get_normalized_value(self.rhs, self.lhs)
            from django.db.models.sql.where import WhereNode, AND
            root_constraint = WhereNode()
            for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
                lookup_class = target.get_lookup(self.lookup_name)
                root_constraint.add(
                    lookup_class(target.get_col(self.lhs.alias, source), val), AND)
            return root_constraint.as_sql(compiler, connection)
        return super().as_sql(compiler, connection) 
Example #22
Source File: related_lookups.py    From bioforum with MIT License 5 votes vote down vote up
def as_sql(self, compiler, connection):
        if isinstance(self.lhs, MultiColSource):
            # For multicolumn lookups we need to build a multicolumn where clause.
            # This clause is either a SubqueryConstraint (for values that need to be compiled to
            # SQL) or an OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
            from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR

            root_constraint = WhereNode(connector=OR)
            if self.rhs_is_direct_value():
                values = [get_normalized_value(value, self.lhs) for value in self.rhs]
                for value in values:
                    value_constraint = WhereNode()
                    for source, target, val in zip(self.lhs.sources, self.lhs.targets, value):
                        lookup_class = target.get_lookup('exact')
                        lookup = lookup_class(target.get_col(self.lhs.alias, source), val)
                        value_constraint.add(lookup, AND)
                    root_constraint.add(value_constraint, OR)
            else:
                root_constraint.add(
                    SubqueryConstraint(
                        self.lhs.alias, [target.column for target in self.lhs.targets],
                        [source.name for source in self.lhs.sources], self.rhs),
                    AND)
            return root_constraint.as_sql(compiler, connection)
        else:
            if (not getattr(self.rhs, 'has_select_fields', True) and
                    not getattr(self.lhs.field.target_field, 'primary_key', False)):
                self.rhs.clear_select_clause()
                if (getattr(self.lhs.output_field, 'primary_key', False) and
                        self.lhs.output_field.model == self.rhs.model):
                    # A case like Restaurant.objects.filter(place__in=restaurant_qs),
                    # where place is a OneToOneField and the primary key of
                    # Restaurant.
                    target_field = self.lhs.field.name
                else:
                    target_field = self.lhs.field.target_field.name
                self.rhs.add_fields([target_field], True)
            return super().as_sql(compiler, connection)