Python django.db.NotSupportedError() Examples

The following are 30 code examples of django.db.NotSupportedError(). 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 , or try the search function .
Example #1
Source File: models.py    From django-sitemessage with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_dispatches_for_update(filter_kwargs: dict) -> Optional[List['Dispatch']]:
    """Distributed friendly version using ``select for update``."""

    dispatches = Dispatch.objects.prefetch_related('message').filter(
        **filter_kwargs

    ).select_for_update(
        **GET_DISPATCHES_ARGS[1]

    ).order_by('-message__time_created')

    try:
        dispatches = list(dispatches)

    except NotSupportedError:
        return None

    except DatabaseError:  # Probably locked. That's fine.
        return []

    return dispatches 
Example #2
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subtract_temporals(self):
        duration_field = DurationField()
        duration_field_internal_type = duration_field.get_internal_type()
        msg = (
            'This backend does not support %s subtraction.' %
            duration_field_internal_type
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.subtract_temporals(duration_field_internal_type, None, None) 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geodetic_area_raises_if_not_supported(self):
        with self.assertRaisesMessage(NotSupportedError, 'Area on geodetic coordinate systems not supported.'):
            Zipcode.objects.annotate(area=Area('poly')).get(code='77002') 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_make_line(self):
        """
        Testing the `MakeLine` aggregate.
        """
        if not connection.features.supports_make_line_aggr:
            with self.assertRaises(NotSupportedError):
                City.objects.all().aggregate(MakeLine('point'))
            return

        # MakeLine on an inappropriate field returns simply None
        self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline'])
        # Reference query:
        # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
        ref_line = GEOSGeometry(
            'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,'
            '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,'
            '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)',
            srid=4326
        )
        # We check for equality with a tolerance of 10e-5 which is a lower bound
        # of the precisions of ref_line coordinates
        line = City.objects.aggregate(MakeLine('point'))['point__makeline']
        self.assertTrue(
            ref_line.equals_exact(line, tolerance=10e-5),
            "%s != %s" % (ref_line, line)
        ) 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_length(self):
        """
        Test the `Length` function.
        """
        # Reference query (should use `length_spheroid`).
        # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
        #   AUTHORITY["EPSG","7030"]]');
        len_m1 = 473504.769553813
        len_m2 = 4617.668

        if connection.features.supports_length_geodetic:
            qs = Interstate.objects.annotate(length=Length('path'))
            tol = 2 if oracle else 3
            self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
            # TODO: test with spheroid argument (True and False)
        else:
            # Does not support geodetic coordinate systems.
            with self.assertRaises(NotSupportedError):
                list(Interstate.objects.annotate(length=Length('path')))

        # Now doing length on a projected coordinate system.
        i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
        self.assertAlmostEqual(len_m2, i10.length.m, 2)
        self.assertTrue(
            SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
        )
        # Length with an explicit geometry value.
        qs = Interstate.objects.annotate(length=Length(i10.path))
        self.assertAlmostEqual(qs.first().length.m, len_m2, 2) 
Example #6
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subtract_temporals(self):
        duration_field = DurationField()
        duration_field_internal_type = duration_field.get_internal_type()
        msg = (
            'This backend does not support %s subtraction.' %
            duration_field_internal_type
        )
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.subtract_temporals(duration_field_internal_type, None, None) 
Example #7
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_distinct_on_fields(self):
        msg = 'DISTINCT ON fields is not supported by this database backend'
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.distinct_sql(['a', 'b'], None) 
Example #8
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_window_frame_raise_not_supported_error(self):
        msg = 'This backend does not support window expressions.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.window_frame_rows_start_end() 
Example #9
Source File: test_explain.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_message(self):
        msg = 'This backend does not support explaining query execution.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            Tag.objects.filter(name='test').explain() 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_postgresql_illegal_range_frame_end(self):
        msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            list(Employee.objects.annotate(test=Window(
                expression=Sum('salary'),
                order_by=F('hire_date').asc(),
                frame=ValueRange(end=1),
            ))) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_postgresql_illegal_range_frame_start(self):
        msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            list(Employee.objects.annotate(test=Window(
                expression=Sum('salary'),
                order_by=F('hire_date').asc(),
                frame=ValueRange(start=-1),
            ))) 
Example #12
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_geodetic_area_raises_if_not_supported(self):
        with self.assertRaisesMessage(NotSupportedError, 'Area on geodetic coordinate systems not supported.'):
            Zipcode.objects.annotate(area=Area('poly')).get(code='77002') 
Example #13
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_make_line(self):
        """
        Testing the `MakeLine` aggregate.
        """
        if not connection.features.supports_make_line_aggr:
            with self.assertRaises(NotSupportedError):
                City.objects.all().aggregate(MakeLine('point'))
            return

        # MakeLine on an inappropriate field returns simply None
        self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline'])
        # Reference query:
        # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
        ref_line = GEOSGeometry(
            'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,'
            '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,'
            '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)',
            srid=4326
        )
        # We check for equality with a tolerance of 10e-5 which is a lower bound
        # of the precisions of ref_line coordinates
        line = City.objects.aggregate(MakeLine('point'))['point__makeline']
        self.assertTrue(
            ref_line.equals_exact(line, tolerance=10e-5),
            "%s != %s" % (ref_line, line)
        ) 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_length(self):
        """
        Test the `Length` function.
        """
        # Reference query (should use `length_spheroid`).
        # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
        #   AUTHORITY["EPSG","7030"]]');
        len_m1 = 473504.769553813
        len_m2 = 4617.668

        if connection.features.supports_length_geodetic:
            qs = Interstate.objects.annotate(length=Length('path'))
            tol = 2 if oracle else 3
            self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
            # TODO: test with spheroid argument (True and False)
        else:
            # Does not support geodetic coordinate systems.
            with self.assertRaises(NotSupportedError):
                list(Interstate.objects.annotate(length=Length('path')))

        # Now doing length on a projected coordinate system.
        i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
        self.assertAlmostEqual(len_m2, i10.length.m, 2)
        self.assertTrue(
            SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
        )
        # Length with an explicit geometry value.
        qs = Interstate.objects.annotate(length=Length(i10.path))
        self.assertAlmostEqual(qs.first().length.m, len_m2, 2) 
Example #15
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_window_frame_raise_not_supported_error(self):
        msg = 'This backend does not support window expressions.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            connection.ops.window_frame_rows_start_end() 
Example #16
Source File: status.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def database_status(self):
        """Collect database connection information.

        :returns: A dict of db connection info.
        """
        try:
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    SELECT datname AS database,
                        numbackends as database_connections
                    FROM pg_stat_database
                    """
                )
                raw = cursor.fetchall()

                # get pg_stat_database column names
                names = [desc[0] for desc in cursor.description]
        except (InterfaceError, NotSupportedError, OperationalError, ProgrammingError) as exc:
            LOG.warning("Unable to connect to DB: %s", str(exc))
            return {"ERROR": str(exc)}

        # transform list-of-lists into list-of-dicts including column names.
        result = [dict(zip(names, row)) for row in raw]

        return result 
Example #17
Source File: test_operations.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_distinct_on_fields(self):
        msg = 'DISTINCT ON fields is not supported by this database backend'
        with self.assertRaisesMessage(NotSupportedError, msg):
            self.ops.distinct_sql(['a', 'b'], None) 
Example #18
Source File: test_explain.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_message(self):
        msg = 'This backend does not support explaining query execution.'
        with self.assertRaisesMessage(NotSupportedError, msg):
            Tag.objects.filter(name='test').explain() 
Example #19
Source File: operations.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def window_frame_range_start_end(self, start=None, end=None):
        start_, end_ = super().window_frame_range_start_end(start, end)
        if (start and start < 0) or (end and end > 0):
            raise NotSupportedError(
                'PostgreSQL only supports UNBOUNDED together with PRECEDING '
                'and FOLLOWING.'
            )
        return start_, end_ 
Example #20
Source File: backend.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, backend, db_alias=None):
        self.backend = backend
        self.name = self.backend.index_name
        self.db_alias = DEFAULT_DB_ALIAS if db_alias is None else db_alias
        self.connection = connections[self.db_alias]
        if self.connection.vendor != 'postgresql':
            raise NotSupportedError(
                'You must select a PostgreSQL database '
                'to use PostgreSQL search.')

        # Whether to allow adding items via the faster upsert method available in Postgres >=9.5
        self._enable_upsert = (self.connection.pg_version >= 90500)

        self.entries = IndexEntry._default_manager.using(self.db_alias) 
Example #21
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def window_frame_range_start_end(self, start=None, end=None):
        start_, end_ = super().window_frame_range_start_end(start, end)
        if (start and start < 0) or (end and end > 0):
            raise NotSupportedError(
                'PostgreSQL only supports UNBOUNDED together with PRECEDING '
                'and FOLLOWING.'
            )
        return start_, end_ 
Example #22
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def explain_query_prefix(self, format=None, **options):
        if not self.connection.features.supports_explaining_query_execution:
            raise NotSupportedError('This backend does not support explaining query execution.')
        if format:
            supported_formats = self.connection.features.supported_explain_formats
            normalized_format = format.upper()
            if normalized_format not in supported_formats:
                msg = '%s is not a recognized format.' % normalized_format
                if supported_formats:
                    msg += ' Allowed formats: %s' % ', '.join(sorted(supported_formats))
                raise ValueError(msg)
        if options:
            raise ValueError('Unknown options: %s' % ', '.join(sorted(options.keys())))
        return self.explain_prefix 
Example #23
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def window_frame_rows_start_end(self, start=None, end=None):
        """
        Return SQL for start and end points in an OVER clause window frame.
        """
        if not self.connection.features.supports_over_clause:
            raise NotSupportedError('This backend does not support window expressions.')
        return self.window_frame_start(start), self.window_frame_end(end) 
Example #24
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def subtract_temporals(self, internal_type, lhs, rhs):
        if self.connection.features.supports_temporal_subtraction:
            lhs_sql, lhs_params = lhs
            rhs_sql, rhs_params = rhs
            return "(%s - %s)" % (lhs_sql, rhs_sql), lhs_params + rhs_params
        raise NotSupportedError("This backend does not support %s subtraction." % internal_type) 
Example #25
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def check_expression_support(self, expression):
        """
        Check that the backend supports the provided expression.

        This is used on specific backends to rule out known expressions
        that have problematic or nonexistent implementations. If the
        expression has a known problem, the backend should raise
        NotSupportedError.
        """
        pass 
Example #26
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def distinct_sql(self, fields, params):
        """
        Return an SQL DISTINCT clause which removes duplicate rows from the
        result set. If any fields are given, only check the given fields for
        duplicates.
        """
        if fields:
            raise NotSupportedError('DISTINCT ON fields is not supported by this database backend')
        else:
            return ['DISTINCT'], [] 
Example #27
Source File: operations.py    From bioforum with MIT License 5 votes vote down vote up
def window_frame_range_start_end(self, start=None, end=None):
        start_, end_ = super().window_frame_range_start_end(start, end)
        if (start and start < 0) or (end and end > 0):
            raise NotSupportedError(
                'PostgreSQL only supports UNBOUNDED together with PRECEDING '
                'and FOLLOWING.'
            )
        return start_, end_ 
Example #28
Source File: compiler.py    From bioforum with MIT License 5 votes vote down vote up
def as_sql(self, with_limits=True, with_col_aliases=False):
        """
        Create the SQL for this query. Return the SQL string and list
        of parameters.  This is overridden from the original Query class
        to handle the additional SQL Oracle requires to emulate LIMIT
        and OFFSET.

        If 'with_limits' is False, any limit/offset information is not
        included in the query.
        """
        # The `do_offset` flag indicates whether we need to construct
        # the SQL needed to use limit/offset with Oracle.
        do_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)
        if not do_offset:
            sql, params = super().as_sql(with_limits=False, with_col_aliases=with_col_aliases)
        elif not self.connection.features.supports_select_for_update_with_limit and self.query.select_for_update:
            raise NotSupportedError(
                'LIMIT/OFFSET is not supported with select_for_update on this '
                'database backend.'
            )
        else:
            sql, params = super().as_sql(with_limits=False, with_col_aliases=True)
            # Wrap the base query in an outer SELECT * with boundaries on
            # the "_RN" column.  This is the canonical way to emulate LIMIT
            # and OFFSET on Oracle.
            high_where = ''
            if self.query.high_mark is not None:
                high_where = 'WHERE ROWNUM <= %d' % (self.query.high_mark,)

            if self.query.low_mark:
                sql = (
                    'SELECT * FROM (SELECT "_SUB".*, ROWNUM AS "_RN" FROM (%s) '
                    '"_SUB" %s) WHERE "_RN" > %d' % (sql, high_where, self.query.low_mark)
                )
            else:
                # Simplify the query to support subqueries if there's no offset.
                sql = (
                    'SELECT * FROM (SELECT "_SUB".* FROM (%s) "_SUB" %s)' % (sql, high_where)
                )

        return sql, params 
Example #29
Source File: operations.py    From bioforum with MIT License 5 votes vote down vote up
def window_frame_rows_start_end(self, start=None, end=None):
        """
        Return SQL for start and end points in an OVER clause window frame.
        """
        if not self.connection.features.supports_over_clause:
            raise NotSupportedError('This backend does not support window expressions.')
        return self.window_frame_start(start), self.window_frame_end(end) 
Example #30
Source File: status.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def database_status(self):
        """Collect database connection information.

        :returns: A dict of db connection info.
        """
        try:
            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    SELECT datname AS database,
                        numbackends as database_connections
                    FROM pg_stat_database
                    """
                )
                raw = cursor.fetchall()

                # get pg_stat_database column names
                names = [desc[0] for desc in cursor.description]
        except (InterfaceError, NotSupportedError, OperationalError, ProgrammingError) as exc:
            LOG.warning("Unable to connect to DB: %s", str(exc))
            return {"ERROR": str(exc)}

        # transform list-of-lists into list-of-dicts including column names.
        result = [dict(zip(names, row)) for row in raw]

        return result