Debian Codegraph @

django/contrib/gis/db/backends/spatialite/base.py

raw
1 from ctypes.util import find_library
2
3 from django.conf import settings
4 from django.core.exceptions import ImproperlyConfigured
5 from django.db.backends.sqlite3.base import DatabaseWrapper as SQLiteDatabaseWrapper
6
7 from .client import SpatiaLiteClient
8 from .features import DatabaseFeatures
9 from .introspection import SpatiaLiteIntrospection
10 from .operations import SpatiaLiteOperations
11 from .schema import SpatialiteSchemaEditor
12
13
14 class DatabaseWrapper(SQLiteDatabaseWrapper):
15 SchemaEditorClass = SpatialiteSchemaEditor
16 # Classes instantiated in __init__().
17 client_class = SpatiaLiteClient
18 features_class = DatabaseFeatures
19 introspection_class = SpatiaLiteIntrospection
20 ops_class = SpatiaLiteOperations
21
22 def __init__(self, *args, **kwargs):
23 # Trying to find the location of the SpatiaLite library.
24 # Here we are figuring out the path to the SpatiaLite library
25 # (`libspatialite`). If it's not in the system library path (e.g., it
26 # cannot be found by `ctypes.util.find_library`), then it may be set
27 # manually in the settings via the `SPATIALITE_LIBRARY_PATH` setting.
28 self.lib_spatialite_paths = [
29 name
30 for name in [
31 getattr(settings, "SPATIALITE_LIBRARY_PATH", None),
32 "mod_spatialite.so",
33 "mod_spatialite",
34 find_library("spatialite"),
35 ]
36 if name is not None
37 ]
38 super().__init__(*args, **kwargs)
39
40 def get_new_connection(self, conn_params):
41 conn = super().get_new_connection(conn_params)
42 # Enabling extension loading on the SQLite connection.
43 try:
44 conn.enable_load_extension(True)
45 except AttributeError:
46 raise ImproperlyConfigured(
47 "SpatiaLite requires SQLite to be configured to allow "
48 "extension loading."
49 )
50 # Load the SpatiaLite library extension on the connection.
51 for path in self.lib_spatialite_paths:
52 try:
53 conn.load_extension(path)
54 except Exception:
55 if getattr(settings, "SPATIALITE_LIBRARY_PATH", None):
56 raise ImproperlyConfigured(
57 "Unable to load the SpatiaLite library extension "
58 "as specified in your SPATIALITE_LIBRARY_PATH setting."
59 )
60 continue
61 else:
62 break
63 else:
64 raise ImproperlyConfigured(
65 "Unable to load the SpatiaLite library extension. "
66 "Library names tried: %s" % ", ".join(self.lib_spatialite_paths)
67 )
68 return conn
69
70 def prepare_database(self):
71 super().prepare_database()
72 # Check if spatial metadata have been initialized in the database
73 with self.cursor() as cursor:
74 cursor.execute("PRAGMA table_info(geometry_columns);")
75 if cursor.fetchall() == []:
76 if self.ops.spatial_version < (5,):
77 cursor.execute("SELECT InitSpatialMetaData(1)")
78 else:
79 cursor.execute("SELECT InitSpatialMetaDataFull(1)")