Debian Codegraph @

docs/spatialite.rst

raw
1 .. _spatialite:
2
3 ============
4 SpatiaLite
5 ============
6
7 The `SpatiaLite module <https://www.gaia-gis.it/fossil/libspatialite/index>`_ for SQLite adds features for handling geographic and spatial data. For an example of what you can do with it, see the tutorial `Building a location to time zone API with SpatiaLite <https://datasette.io/tutorials/spatialite>`__.
8
9 To use it with Datasette, you need to install the ``mod_spatialite`` dynamic library. This can then be loaded into Datasette using the ``--load-extension`` command-line option.
10
11 Datasette can look for SpatiaLite in common installation locations if you run it like this::
12
13 datasette --load-extension=spatialite --setting default_allow_sql off
14
15 If SpatiaLite is in another location, use the full path to the extension instead::
16
17 datasette --setting default_allow_sql off \
18 --load-extension=/usr/local/lib/mod_spatialite.dylib
19
20 .. _spatialite_warning:
21
22 Warning
23 =======
24
25 .. warning::
26 The SpatiaLite extension adds `a large number of additional SQL functions <https://www.gaia-gis.it/gaia-sins/spatialite-sql-5.0.1.html>`__, some of which are not be safe for untrusted users to execute: they may cause the Datasette server to crash.
27
28 You should not expose a SpatiaLite-enabled Datasette instance to the public internet without taking extra measures to secure it against potentially harmful SQL queries.
29
30 The following steps are recommended:
31
32 - Disable arbitrary SQL queries by untrusted users. See :ref:`authentication_permissions_execute_sql` for ways to do this. The easiest is to start Datasette with the ``datasette --setting default_allow_sql off`` option.
33 - Define :ref:`canned_queries` with the SQL queries that use SpatiaLite functions that you want people to be able to execute.
34
35 The `Datasette SpatiaLite tutorial <https://datasette.io/tutorials/spatialite>`__ includes detailed instructions for running SpatiaLite safely using these techniques
36
37 .. _spatialite_installation:
38
39 Installation
40 ============
41
42 Installing SpatiaLite on OS X
43 -----------------------------
44
45 The easiest way to install SpatiaLite on OS X is to use `Homebrew <https://brew.sh/>`_.
46
47 ::
48
49 brew update
50 brew install spatialite-tools
51
52 This will install the ``spatialite`` command-line tool and the ``mod_spatialite`` dynamic library.
53
54 You can now run Datasette like so::
55
56 datasette --load-extension=spatialite
57
58 Installing SpatiaLite on Linux
59 ------------------------------
60
61 SpatiaLite is packaged for most Linux distributions.
62
63 ::
64
65 apt install spatialite-bin libsqlite3-mod-spatialite
66
67 Depending on your distribution, you should be able to run Datasette something like this::
68
69 datasette --load-extension=/usr/lib/x86_64-linux-gnu/mod_spatialite.so
70
71 If you are unsure of the location of the module, try running ``locate mod_spatialite`` and see what comes back.
72
73 Spatial indexing latitude/longitude columns
74 ===========================================
75
76 Here's a recipe for taking a table with existing latitude and longitude columns, adding a SpatiaLite POINT geometry column to that table, populating the new column and then populating a spatial index:
77
78 .. code-block:: python
79
80 import sqlite3
81
82 conn = sqlite3.connect("museums.db")
83 # Lead the spatialite extension:
84 conn.enable_load_extension(True)
85 conn.load_extension("/usr/local/lib/mod_spatialite.dylib")
86 # Initialize spatial metadata for this database:
87 conn.execute("select InitSpatialMetadata(1)")
88 # Add a geometry column called point_geom to our museums table:
89 conn.execute(
90 "SELECT AddGeometryColumn('museums', 'point_geom', 4326, 'POINT', 2);"
91 )
92 # Now update that geometry column with the lat/lon points
93 conn.execute(
94 """
95 UPDATE museums SET
96 point_geom = GeomFromText('POINT('||"longitude"||' '||"latitude"||')',4326);
97 """
98 )
99 # Now add a spatial index to that column
100 conn.execute(
101 'select CreateSpatialIndex("museums", "point_geom");'
102 )
103 # If you don't commit your changes will not be persisted:
104 conn.commit()
105 conn.close()
106
107 Making use of a spatial index
108 =============================
109
110 SpatiaLite spatial indexes are R*Trees. They allow you to run efficient bounding box queries using a sub-select, with a similar pattern to that used for :ref:`full_text_search_custom_sql`.
111
112 In the above example, the resulting index will be called ``idx_museums_point_geom``. This takes the form of a SQLite virtual table. You can inspect its contents using the following query:
113
114 .. code-block:: sql
115
116 select * from idx_museums_point_geom limit 10;
117
118 Here's a live example: `timezones-api.datasette.io/timezones/idx_timezones_Geometry <https://timezones-api.datasette.io/timezones/idx_timezones_Geometry>`_
119
120 +--------+----------------------+----------------------+---------------------+---------------------+
121 | pkid | xmin | xmax | ymin | ymax |
122 +========+======================+======================+=====================+=====================+
123 | 1 | -8.601725578308105 | -2.4930307865142822 | 4.162120819091797 | 10.74019718170166 |
124 +--------+----------------------+----------------------+---------------------+---------------------+
125 | 2 | -3.2607860565185547 | 1.27329421043396 | 4.539252281188965 | 11.174856185913086 |
126 +--------+----------------------+----------------------+---------------------+---------------------+
127 | 3 | 32.997581481933594 | 47.98238754272461 | 3.3974475860595703 | 14.894054412841797 |
128 +--------+----------------------+----------------------+---------------------+---------------------+
129 | 4 | -8.66890811920166 | 11.997337341308594 | 18.9681453704834 | 37.296207427978516 |
130 +--------+----------------------+----------------------+---------------------+---------------------+
131 | 5 | 36.43336486816406 | 43.300174713134766 | 12.354820251464844 | 18.070993423461914 |
132 +--------+----------------------+----------------------+---------------------+---------------------+
133
134 You can now construct efficient bounding box queries that will make use of the index like this:
135
136 .. code-block:: sql
137
138 select * from museums where museums.rowid in (
139 SELECT pkid FROM idx_museums_point_geom
140 -- left-hand-edge of point > left-hand-edge of bbox (minx)
141 where xmin > :bbox_minx
142 -- right-hand-edge of point < right-hand-edge of bbox (maxx)
143 and xmax < :bbox_maxx
144 -- bottom-edge of point > bottom-edge of bbox (miny)
145 and ymin > :bbox_miny
146 -- top-edge of point < top-edge of bbox (maxy)
147 and ymax < :bbox_maxy
148 );
149
150 Spatial indexes can be created against polygon columns as well as point columns, in which case they will represent the minimum bounding rectangle of that polygon. This is useful for accelerating ``within`` queries, as seen in the Timezones API example.
151
152 Importing shapefiles into SpatiaLite
153 ====================================
154
155 The `shapefile format <https://en.wikipedia.org/wiki/Shapefile>`_ is a common format for distributing geospatial data. You can use the ``spatialite`` command-line tool to create a new database table from a shapefile.
156
157 Try it now with the North America shapefile available from the University of North Carolina `Global River Database <http://gaia.geosci.unc.edu/rivers/>`_ project. Download the file and unzip it (this will create files called ``narivs.dbf``, ``narivs.prj``, ``narivs.shp`` and ``narivs.shx`` in the current directory), then run the following::
158
159 $ spatialite rivers-database.db
160 SpatiaLite version ..: 4.3.0a Supported Extensions:
161 ...
162 spatialite> .loadshp narivs rivers CP1252 23032
163 ========
164 Loading shapefile at 'narivs' into SQLite table 'rivers'
165 ...
166 Inserted 467973 rows into 'rivers' from SHAPEFILE
167
168 This will load the data from the ``narivs`` shapefile into a new database table called ``rivers``.
169
170 Exit out of ``spatialite`` (using ``Ctrl+D``) and run Datasette against your new database like this::
171
172 datasette rivers-database.db \
173 --load-extension=/usr/local/lib/mod_spatialite.dylib
174
175 If you browse to ``http://localhost:8001/rivers-database/rivers`` you will see the new table... but the ``Geometry`` column will contain unreadable binary data (SpatiaLite uses `a custom format based on WKB <https://www.gaia-gis.it/gaia-sins/BLOB-Geometry.html>`_).
176
177 The easiest way to turn this into semi-readable data is to use the SpatiaLite ``AsGeoJSON`` function. Try the following using the SQL query interface at ``http://localhost:8001/rivers-database``:
178
179 .. code-block:: sql
180
181 select *, AsGeoJSON(Geometry) from rivers limit 10;
182
183 This will give you back an additional column of GeoJSON. You can copy and paste GeoJSON from this column into the debugging tool at `geojson.io <https://geojson.io/>`_ to visualize it on a map.
184
185 To see a more interesting example, try ordering the records with the longest geometry first. Since there are 467,000 rows in the table you will first need to increase the SQL time limit imposed by Datasette::
186
187 datasette rivers-database.db \
188 --load-extension=/usr/local/lib/mod_spatialite.dylib \
189 --setting sql_time_limit_ms 10000
190
191 Now try the following query:
192
193 .. code-block:: sql
194
195 select *, AsGeoJSON(Geometry) from rivers
196 order by length(Geometry) desc limit 10;
197
198 Importing GeoJSON polygons using Shapely
199 ========================================
200
201 Another common form of polygon data is the GeoJSON format. This can be imported into SpatiaLite directly, or by using the `Shapely <https://pypi.org/project/Shapely/>`_ Python library.
202
203 `Who's On First <https://whosonfirst.org/>`_ is an excellent source of openly licensed GeoJSON polygons. Let's import the geographical polygon for Wales. First, we can use the Who's On First Spelunker tool to find the record for Wales:
204
205 `spelunker.whosonfirst.org/id/404227475 <https://spelunker.whosonfirst.org/id/404227475/>`_
206
207 That page includes a link to the GeoJSON record, which can be accessed here:
208
209 `data.whosonfirst.org/404/227/475/404227475.geojson <https://data.whosonfirst.org/404/227/475/404227475.geojson>`_
210
211 Here's Python code to create a SQLite database, enable SpatiaLite, create a places table and then add a record for Wales:
212
213 .. code-block:: python
214
215 import sqlite3
216
217 conn = sqlite3.connect("places.db")
218 # Enable SpatialLite extension
219 conn.enable_load_extension(True)
220 conn.load_extension("/usr/local/lib/mod_spatialite.dylib")
221 # Create the masic countries table
222 conn.execute("select InitSpatialMetadata(1)")
223 conn.execute(
224 "create table places (id integer primary key, name text);"
225 )
226 # Add a MULTIPOLYGON Geometry column
227 conn.execute(
228 "SELECT AddGeometryColumn('places', 'geom', 4326, 'MULTIPOLYGON', 2);"
229 )
230 # Add a spatial index against the new column
231 conn.execute("SELECT CreateSpatialIndex('places', 'geom');")
232 # Now populate the table
233 from shapely.geometry.multipolygon import MultiPolygon
234 from shapely.geometry import shape
235 import requests
236
237 geojson = requests.get(
238 "https://data.whosonfirst.org/404/227/475/404227475.geojson"
239 ).json()
240 # Convert to "Well Known Text" format
241 wkt = shape(geojson["geometry"]).wkt
242 # Insert and commit the record
243 conn.execute(
244 "INSERT INTO places (id, name, geom) VALUES(null, ?, GeomFromText(?, 4326))",
245 ("Wales", wkt),
246 )
247 conn.commit()
248
249 Querying polygons using within()
250 ================================
251
252 The ``within()`` SQL function can be used to check if a point is within a geometry:
253
254 .. code-block:: sql
255
256 select
257 name
258 from
259 places
260 where
261 within(GeomFromText('POINT(-3.1724366 51.4704448)'), places.geom);
262
263 The ``GeomFromText()`` function takes a string of well-known text. Note that the order used here is ``longitude`` then ``latitude``.
264
265 To run that same ``within()`` query in a way that benefits from the spatial index, use the following:
266
267 .. code-block:: sql
268
269 select
270 name
271 from
272 places
273 where
274 within(GeomFromText('POINT(-3.1724366 51.4704448)'), places.geom)
275 and rowid in (
276 SELECT pkid FROM idx_places_geom
277 where xmin < -3.1724366
278 and xmax > -3.1724366
279 and ymin < 51.4704448
280 and ymax > 51.4704448
281 );