| 1 |
from django.contrib.gis.db import models |
| 2 |
from django.db import connection |
| 3 |
from django.db.models import Index |
| 4 |
from django.test import TransactionTestCase |
| 5 |
from django.test.utils import isolate_apps |
| 6 |
|
| 7 |
from .models import City |
| 8 |
|
| 9 |
|
| 10 |
class SchemaIndexesTests(TransactionTestCase): |
| 11 |
available_apps = [] |
| 12 |
models = [City] |
| 13 |
|
| 14 |
def get_indexes(self, table): |
| 15 |
with connection.cursor() as cursor: |
| 16 |
constraints = connection.introspection.get_constraints(cursor, table) |
| 17 |
return { |
| 18 |
name: constraint["columns"] |
| 19 |
for name, constraint in constraints.items() |
| 20 |
if constraint["index"] |
| 21 |
} |
| 22 |
|
| 23 |
def has_spatial_indexes(self, table): |
| 24 |
if connection.ops.mysql: |
| 25 |
with connection.cursor() as cursor: |
| 26 |
return connection.introspection.supports_spatial_index(cursor, table) |
| 27 |
elif connection.ops.oracle: |
| 28 |
# Spatial indexes in Meta.indexes are not supported by the Oracle |
| 29 |
# backend (see #31252). |
| 30 |
return False |
| 31 |
return True |
| 32 |
|
| 33 |
def test_using_sql(self): |
| 34 |
if not connection.ops.postgis: |
| 35 |
self.skipTest("This is a PostGIS-specific test.") |
| 36 |
index = Index(fields=["point"]) |
| 37 |
editor = connection.schema_editor() |
| 38 |
self.assertIn( |
| 39 |
"%s USING " % editor.quote_name(City._meta.db_table), |
| 40 |
str(index.create_sql(City, editor)), |
| 41 |
) |
| 42 |
|
| 43 |
@isolate_apps("gis_tests.geoapp") |
| 44 |
def test_namespaced_db_table(self): |
| 45 |
if not connection.ops.postgis: |
| 46 |
self.skipTest("PostGIS-specific test.") |
| 47 |
|
| 48 |
class SchemaCity(models.Model): |
| 49 |
point = models.PointField() |
| 50 |
|
| 51 |
class Meta: |
| 52 |
app_label = "geoapp" |
| 53 |
db_table = 'django_schema"."geoapp_schema_city' |
| 54 |
|
| 55 |
index = Index(fields=["point"]) |
| 56 |
editor = connection.schema_editor() |
| 57 |
create_index_sql = str(index.create_sql(SchemaCity, editor)) |
| 58 |
self.assertIn( |
| 59 |
"%s USING " % editor.quote_name(SchemaCity._meta.db_table), |
| 60 |
create_index_sql, |
| 61 |
) |
| 62 |
self.assertIn( |
| 63 |
'CREATE INDEX "geoapp_schema_city_point_9ed70651_id" ', |
| 64 |
create_index_sql, |
| 65 |
) |
| 66 |
|
| 67 |
def test_index_name(self): |
| 68 |
if not self.has_spatial_indexes(City._meta.db_table): |
| 69 |
self.skipTest("Spatial indexes in Meta.indexes are not supported.") |
| 70 |
index_name = "custom_point_index_name" |
| 71 |
index = Index(fields=["point"], name=index_name) |
| 72 |
with connection.schema_editor() as editor: |
| 73 |
editor.add_index(City, index) |
| 74 |
indexes = self.get_indexes(City._meta.db_table) |
| 75 |
self.assertIn(index_name, indexes) |
| 76 |
self.assertEqual(indexes[index_name], ["point"]) |
| 77 |
editor.remove_index(City, index) |