Debian Codegraph @

docs/sql_queries.rst

raw
1 .. _sql:
2
3 Running SQL queries
4 ===================
5
6 Datasette treats SQLite database files as read-only and immutable. This means it is not possible to execute INSERT or UPDATE statements using Datasette, which allows us to expose SELECT statements to the outside world without needing to worry about SQL injection attacks.
7
8 The easiest way to execute custom SQL against Datasette is through the web UI. The database index page includes a SQL editor that lets you run any SELECT query you like. You can also construct queries using the filter interface on the tables page, then click "View and edit SQL" to open that query in the custom SQL editor.
9
10 Note that this interface is only available if the :ref:`permissions_execute_sql` permission is allowed.
11
12 Any Datasette SQL query is reflected in the URL of the page, allowing you to bookmark them, share them with others and navigate through previous queries using your browser back button.
13
14 You can also retrieve the results of any query as JSON by adding ``.json`` to the base URL.
15
16 .. _sql_parameters:
17
18 Named parameters
19 ----------------
20
21 Datasette has special support for SQLite named parameters. Consider a SQL query like this:
22
23 .. code-block:: sql
24
25 select * from Street_Tree_List
26 where "PermitNotes" like :notes
27 and "qSpecies" = :species
28
29 If you execute this query using the custom query editor, Datasette will extract the two named parameters and use them to construct form fields for you to provide values.
30
31 You can also provide values for these fields by constructing a URL::
32
33 /mydatabase?sql=select...&species=44
34
35 SQLite string escaping rules will be applied to values passed using named parameters - they will be wrapped in quotes and their content will be correctly escaped.
36
37 Values from named parameters are treated as SQLite strings. If you need to perform numeric comparisons on them you should cast them to an integer or float first using ``cast(:name as integer)`` or ``cast(:name as real)``, for example:
38
39 .. code-block:: sql
40
41 select * from Street_Tree_List
42 where latitude > cast(:min_latitude as real)
43 and latitude < cast(:max_latitude as real)
44
45 Datasette disallows custom SQL queries containing the string PRAGMA (with a small number `of exceptions <https://github.com/simonw/datasette/issues/761>`__) as SQLite pragma statements can be used to change database settings at runtime. If you need to include the string "pragma" in a query you can do so safely using a named parameter.
46
47 .. _sql_views:
48
49 Views
50 -----
51
52 If you want to bundle some pre-written SQL queries with your Datasette-hosted database you can do so in two ways. The first is to include SQL views in your database - Datasette will then list those views on your database index page.
53
54 The quickest way to create views is with the SQLite command-line interface::
55
56 $ sqlite3 sf-trees.db
57 SQLite version 3.19.3 2017-06-27 16:48:08
58 Enter ".help" for usage hints.
59 sqlite> CREATE VIEW demo_view AS select qSpecies from Street_Tree_List;
60 <CTRL+D>
61
62 .. _canned_queries:
63
64 Canned queries
65 --------------
66
67 As an alternative to adding views to your database, you can define canned queries inside your ``metadata.json`` file. Here's an example:
68
69 .. code-block:: json
70
71 {
72 "databases": {
73 "sf-trees": {
74 "queries": {
75 "just_species": {
76 "sql": "select qSpecies from Street_Tree_List"
77 }
78 }
79 }
80 }
81 }
82
83 Then run Datasette like this::
84
85 datasette sf-trees.db -m metadata.json
86
87 Each canned query will be listed on the database index page, and will also get its own URL at::
88
89 /database-name/canned-query-name
90
91 For the above example, that URL would be::
92
93 /sf-trees/just_species
94
95 You can optionally include ``"title"`` and ``"description"`` keys to show a title and description on the canned query page. As with regular table metadata you can alternatively specify ``"description_html"`` to have your description rendered as HTML (rather than having HTML special characters escaped).
96
97 .. _canned_queries_named_parameters:
98
99 Canned query parameters
100 ~~~~~~~~~~~~~~~~~~~~~~~
101
102 Canned queries support named parameters, so if you include those in the SQL you will then be able to enter them using the form fields on the canned query page or by adding them to the URL. This means canned queries can be used to create custom JSON APIs based on a carefully designed SQL statement.
103
104 Here's an example of a canned query with a named parameter:
105
106 .. code-block:: sql
107
108 select neighborhood, facet_cities.name, state
109 from facetable
110 join facet_cities on facetable.city_id = facet_cities.id
111 where neighborhood like '%' || :text || '%'
112 order by neighborhood;
113
114 In the canned query metadata (here :ref:`metadata_yaml` as ``metadata.yaml``) it looks like this:
115
116 .. code-block:: yaml
117
118 databases:
119 fixtures:
120 queries:
121 neighborhood_search:
122 sql: |-
123 select neighborhood, facet_cities.name, state
124 from facetable
125 join facet_cities on facetable.city_id = facet_cities.id
126 where neighborhood like '%' || :text || '%'
127 order by neighborhood
128 title: Search neighborhoods
129
130 Here's the equivalent using JSON (as ``metadata.json``):
131
132 .. code-block:: json
133
134 {
135 "databases": {
136 "fixtures": {
137 "queries": {
138 "neighborhood_search": {
139 "sql": "select neighborhood, facet_cities.name, state\nfrom facetable\n join facet_cities on facetable.city_id = facet_cities.id\nwhere neighborhood like '%' || :text || '%'\norder by neighborhood",
140 "title": "Search neighborhoods"
141 }
142 }
143 }
144 }
145 }
146
147 Note that we are using SQLite string concatenation here - the ``||`` operator - to add wildcard ``%`` characters to the string provided by the user.
148
149 You can try this canned query out here:
150 https://latest.datasette.io/fixtures/neighborhood_search?text=town
151
152 In this example the ``:text`` named parameter is automatically extracted from the query using a regular expression.
153
154 You can alternatively provide an explicit list of named parameters using the ``"params"`` key, like this:
155
156 .. code-block:: yaml
157
158 databases:
159 fixtures:
160 queries:
161 neighborhood_search:
162 params:
163 - text
164 sql: |-
165 select neighborhood, facet_cities.name, state
166 from facetable
167 join facet_cities on facetable.city_id = facet_cities.id
168 where neighborhood like '%' || :text || '%'
169 order by neighborhood
170 title: Search neighborhoods
171
172 .. _canned_queries_options:
173
174 Additional canned query options
175 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176
177 Additional options can be specified for canned queries in the YAML or JSON configuration.
178
179 hide_sql
180 ++++++++
181
182 Canned queries default to displaying their SQL query at the top of the page. If the query is extremely long you may want to hide it by default, with a "show" link that can be used to make it visible.
183
184 Add the ``"hide_sql": true`` option to hide the SQL query by default.
185
186 fragment
187 ++++++++
188
189 Some plugins, such as `datasette-vega <https://github.com/simonw/datasette-vega>`__, can be configured by including additional data in the fragment hash of the URL - the bit that comes after a ``#`` symbol.
190
191 You can set a default fragment hash that will be included in the link to the canned query from the database index page using the ``"fragment"`` key.
192
193 This example demonstrates both ``fragment`` and ``hide_sql``:
194
195 .. code-block:: json
196
197 {
198 "databases": {
199 "fixtures": {
200 "queries": {
201 "neighborhood_search": {
202 "sql": "select neighborhood, facet_cities.name, state\nfrom facetable join facet_cities on facetable.city_id = facet_cities.id\nwhere neighborhood like '%' || :text || '%' order by neighborhood;",
203 "fragment": "fragment-goes-here",
204 "hide_sql": true
205 }
206 }
207 }
208 }
209 }
210
211 `See here <https://latest.datasette.io/fixtures#queries>`__ for a demo of this in action.
212
213 .. _canned_queries_writable:
214
215 Writable canned queries
216 ~~~~~~~~~~~~~~~~~~~~~~~
217
218 Canned queries by default are read-only. You can use the ``"write": true`` key to indicate that a canned query can write to the database.
219
220 See :ref:`authentication_permissions_query` for details on how to add permission checks to canned queries, using the ``"allow"`` key.
221
222 .. code-block:: json
223
224 {
225 "databases": {
226 "mydatabase": {
227 "queries": {
228 "add_name": {
229 "sql": "INSERT INTO names (name) VALUES (:name)",
230 "write": true
231 }
232 }
233 }
234 }
235 }
236
237 This configuration will create a page at ``/mydatabase/add_name`` displaying a form with a ``name`` field. Submitting that form will execute the configured ``INSERT`` query.
238
239 You can customize how Datasette represents success and errors using the following optional properties:
240
241 - ``on_success_message`` - the message shown when a query is successful
242 - ``on_success_redirect`` - the path or URL the user is redirected to on success
243 - ``on_error_message`` - the message shown when a query throws an error
244 - ``on_error_redirect`` - the path or URL the user is redirected to on error
245
246 For example:
247
248 .. code-block:: json
249
250 {
251 "databases": {
252 "mydatabase": {
253 "queries": {
254 "add_name": {
255 "sql": "INSERT INTO names (name) VALUES (:name)",
256 "write": true,
257 "on_success_message": "Name inserted",
258 "on_success_redirect": "/mydatabase/names",
259 "on_error_message": "Name insert failed",
260 "on_error_redirect": "/mydatabase"
261 }
262 }
263 }
264 }
265 }
266
267 You can use ``"params"`` to explicitly list the named parameters that should be displayed as form fields - otherwise they will be automatically detected.
268
269 You can pre-populate form fields when the page first loads using a query string, e.g. ``/mydatabase/add_name?name=Prepopulated``. The user will have to submit the form to execute the query.
270
271 .. _canned_queries_magic_parameters:
272
273 Magic parameters
274 ~~~~~~~~~~~~~~~~
275
276 Named parameters that start with an underscore are special: they can be used to automatically add values created by Datasette that are not contained in the incoming form fields or query string.
277
278 These magic parameters are only supported for canned queries: to avoid security issues (such as queries that extract the user's private cookies) they are not available to SQL that is executed by the user as a custom SQL query.
279
280 Available magic parameters are:
281
282 ``_actor_*`` - e.g. ``_actor_id``, ``_actor_name``
283 Fields from the currently authenticated :ref:`authentication_actor`.
284
285 ``_header_*`` - e.g. ``_header_user_agent``
286 Header from the incoming HTTP request. The key should be in lower case and with hyphens converted to underscores e.g. ``_header_user_agent`` or ``_header_accept_language``.
287
288 ``_cookie_*`` - e.g. ``_cookie_lang``
289 The value of the incoming cookie of that name.
290
291 ``_now_epoch``
292 The number of seconds since the Unix epoch.
293
294 ``_now_date_utc``
295 The date in UTC, e.g. ``2020-06-01``
296
297 ``_now_datetime_utc``
298 The ISO 8601 datetime in UTC, e.g. ``2020-06-24T18:01:07Z``
299
300 ``_random_chars_*`` - e.g. ``_random_chars_128``
301 A random string of characters of the specified length.
302
303 Here's an example configuration (this time using ``metadata.yaml`` since that provides better support for multi-line SQL queries) that adds a message from the authenticated user, storing various pieces of additional metadata using magic parameters:
304
305 .. code-block:: yaml
306
307 databases:
308 mydatabase:
309 queries:
310 add_message:
311 allow:
312 id: "*"
313 sql: |-
314 INSERT INTO messages (
315 user_id, message, datetime
316 ) VALUES (
317 :_actor_id, :message, :_now_datetime_utc
318 )
319 write: true
320
321 The form presented at ``/mydatabase/add_message`` will have just a field for ``message`` - the other parameters will be populated by the magic parameter mechanism.
322
323 Additional custom magic parameters can be added by plugins using the :ref:`plugin_hook_register_magic_parameters` hook.
324
325 .. _canned_queries_json_api:
326
327 JSON API for writable canned queries
328 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
329
330 Writable canned queries can also be accessed using a JSON API. You can POST data to them using JSON, and you can request that their response is returned to you as JSON.
331
332 To submit JSON to a writable canned query, encode key/value parameters as a JSON document::
333
334 POST /mydatabase/add_message
335
336 {"message": "Message goes here"}
337
338 You can also continue to submit data using regular form encoding, like so::
339
340 POST /mydatabase/add_message
341
342 message=Message+goes+here
343
344 There are three options for specifying that you would like the response to your request to return JSON data, as opposed to an HTTP redirect to another page.
345
346 - Set an ``Accept: application/json`` header on your request
347 - Include ``?_json=1`` in the URL that you POST to
348 - Include ``"_json": 1`` in your JSON body, or ``&_json=1`` in your form encoded body
349
350 The JSON response will look like this:
351
352 .. code-block:: json
353
354 {
355 "ok": true,
356 "message": "Query executed, 1 row affected",
357 "redirect": "/data/add_name"
358 }
359
360 The ``"message"`` and ``"redirect"`` values here will take into account ``on_success_message``, ``on_success_redirect``, ``on_error_message`` and ``on_error_redirect``, if they have been set.
361
362 .. _pagination:
363
364 Pagination
365 ----------
366
367 Datasette's default table pagination is designed to be extremely efficient. SQL OFFSET/LIMIT pagination can have a significant performance penalty once you get into multiple thousands of rows, as each page still requires the database to scan through every preceding row to find the correct offset.
368
369 When paginating through tables, Datasette instead orders the rows in the table by their primary key and performs a WHERE clause against the last seen primary key for the previous page. For example:
370
371 .. code-block:: sql
372
373 select rowid, * from Tree_List where rowid > 200 order by rowid limit 101
374
375 This represents page three for this particular table, with a page size of 100.
376
377 Note that we request 101 items in the limit clause rather than 100. This allows us to detect if we are on the last page of the results: if the query returns less than 101 rows we know we have reached the end of the pagination set. Datasette will only return the first 100 rows - the 101st is used purely to detect if there should be another page.
378
379 Since the where clause acts against the index on the primary key, the query is extremely fast even for records that are a long way into the overall pagination set.
380
381 .. _cross_database_queries:
382
383 Cross-database queries
384 ----------------------
385
386 SQLite has the ability to run queries that join across multiple databases. Up to ten databases can be attached to a single SQLite connection and queried together.
387
388 Datasette can execute joins across multiple databases if it is started with the ``--crossdb`` option::
389
390 datasette fixtures.db extra_database.db --crossdb
391
392 If it is started in this way, the ``/_memory`` page can be used to execute queries that join across multiple databases.
393
394 References to tables in attached databases should be preceded by the database name and a period.
395
396 For example, this query will show a list of tables across both of the above databases:
397
398 .. code-block:: sql
399
400 select
401 'fixtures' as database, *
402 from
403 [fixtures].sqlite_master
404 union
405 select
406 'extra_database' as database, *
407 from
408 [extra_database].sqlite_master
409
410 `Try that out here <https://latest.datasette.io/_memory?sql=select%0D%0A++%27fixtures%27+as+database%2C+*%0D%0Afrom%0D%0A++%5Bfixtures%5D.sqlite_master%0D%0Aunion%0D%0Aselect%0D%0A++%27extra_database%27+as+database%2C+*%0D%0Afrom%0D%0A++%5Bextra_database%5D.sqlite_master>`__.