Debian Codegraph @

tests/test_internals_database.py

raw
1 """
2 Tests for the datasette.database.Database class
3 """
4
5 from datasette.app import Datasette
6 from datasette.database import Database, Results, MultipleValues
7 from datasette.utils.sqlite import sqlite3
8 from datasette.utils import Column
9 from .fixtures import app_client, app_client_two_attached_databases_crossdb_enabled
10 import pytest
11 import time
12 import uuid
13
14
15 @pytest.fixture
16 def db(app_client):
17 return app_client.ds.get_database("fixtures")
18
19
20 @pytest.mark.asyncio
21 async def test_execute(db):
22 results = await db.execute("select * from facetable")
23 assert isinstance(results, Results)
24 assert 15 == len(results)
25
26
27 @pytest.mark.asyncio
28 async def test_results_first(db):
29 assert None is (await db.execute("select * from facetable where pk > 100")).first()
30 results = await db.execute("select * from facetable")
31 row = results.first()
32 assert isinstance(row, sqlite3.Row)
33
34
35 @pytest.mark.asyncio
36 @pytest.mark.parametrize("expected", (True, False))
37 async def test_results_bool(db, expected):
38 where = "" if expected else "where pk = 0"
39 results = await db.execute("select * from facetable {}".format(where))
40 assert bool(results) is expected
41
42
43 @pytest.mark.parametrize(
44 "query,expected",
45 [
46 ("select 1", 1),
47 ("select 1, 2", None),
48 ("select 1 as num union select 2 as num", None),
49 ],
50 )
51 @pytest.mark.asyncio
52 async def test_results_single_value(db, query, expected):
53 results = await db.execute(query)
54 if expected:
55 assert expected == results.single_value()
56 else:
57 with pytest.raises(MultipleValues):
58 results.single_value()
59
60
61 @pytest.mark.asyncio
62 async def test_execute_fn(db):
63 def get_1_plus_1(conn):
64 return conn.execute("select 1 + 1").fetchall()[0][0]
65
66 assert 2 == await db.execute_fn(get_1_plus_1)
67
68
69 @pytest.mark.parametrize(
70 "tables,exists",
71 (
72 (["facetable", "searchable", "tags", "searchable_tags"], True),
73 (["foo", "bar", "baz"], False),
74 ),
75 )
76 @pytest.mark.asyncio
77 async def test_table_exists(db, tables, exists):
78 for table in tables:
79 actual = await db.table_exists(table)
80 assert exists == actual
81
82
83 @pytest.mark.parametrize(
84 "table,expected",
85 (
86 (
87 "facetable",
88 [
89 "pk",
90 "created",
91 "planet_int",
92 "on_earth",
93 "state",
94 "_city_id",
95 "_neighborhood",
96 "tags",
97 "complex_array",
98 "distinct_some_null",
99 "n",
100 ],
101 ),
102 (
103 "sortable",
104 [
105 "pk1",
106 "pk2",
107 "content",
108 "sortable",
109 "sortable_with_nulls",
110 "sortable_with_nulls_2",
111 "text",
112 ],
113 ),
114 ),
115 )
116 @pytest.mark.asyncio
117 async def test_table_columns(db, table, expected):
118 columns = await db.table_columns(table)
119 assert columns == expected
120
121
122 @pytest.mark.parametrize(
123 "table,expected",
124 (
125 (
126 "facetable",
127 [
128 Column(
129 cid=0,
130 name="pk",
131 type="integer",
132 notnull=0,
133 default_value=None,
134 is_pk=1,
135 hidden=0,
136 ),
137 Column(
138 cid=1,
139 name="created",
140 type="text",
141 notnull=0,
142 default_value=None,
143 is_pk=0,
144 hidden=0,
145 ),
146 Column(
147 cid=2,
148 name="planet_int",
149 type="integer",
150 notnull=0,
151 default_value=None,
152 is_pk=0,
153 hidden=0,
154 ),
155 Column(
156 cid=3,
157 name="on_earth",
158 type="integer",
159 notnull=0,
160 default_value=None,
161 is_pk=0,
162 hidden=0,
163 ),
164 Column(
165 cid=4,
166 name="state",
167 type="text",
168 notnull=0,
169 default_value=None,
170 is_pk=0,
171 hidden=0,
172 ),
173 Column(
174 cid=5,
175 name="_city_id",
176 type="integer",
177 notnull=0,
178 default_value=None,
179 is_pk=0,
180 hidden=0,
181 ),
182 Column(
183 cid=6,
184 name="_neighborhood",
185 type="text",
186 notnull=0,
187 default_value=None,
188 is_pk=0,
189 hidden=0,
190 ),
191 Column(
192 cid=7,
193 name="tags",
194 type="text",
195 notnull=0,
196 default_value=None,
197 is_pk=0,
198 hidden=0,
199 ),
200 Column(
201 cid=8,
202 name="complex_array",
203 type="text",
204 notnull=0,
205 default_value=None,
206 is_pk=0,
207 hidden=0,
208 ),
209 Column(
210 cid=9,
211 name="distinct_some_null",
212 type="",
213 notnull=0,
214 default_value=None,
215 is_pk=0,
216 hidden=0,
217 ),
218 Column(
219 cid=10,
220 name="n",
221 type="text",
222 notnull=0,
223 default_value=None,
224 is_pk=0,
225 hidden=0,
226 ),
227 ],
228 ),
229 (
230 "sortable",
231 [
232 Column(
233 cid=0,
234 name="pk1",
235 type="varchar(30)",
236 notnull=0,
237 default_value=None,
238 is_pk=1,
239 hidden=0,
240 ),
241 Column(
242 cid=1,
243 name="pk2",
244 type="varchar(30)",
245 notnull=0,
246 default_value=None,
247 is_pk=2,
248 hidden=0,
249 ),
250 Column(
251 cid=2,
252 name="content",
253 type="text",
254 notnull=0,
255 default_value=None,
256 is_pk=0,
257 hidden=0,
258 ),
259 Column(
260 cid=3,
261 name="sortable",
262 type="integer",
263 notnull=0,
264 default_value=None,
265 is_pk=0,
266 hidden=0,
267 ),
268 Column(
269 cid=4,
270 name="sortable_with_nulls",
271 type="real",
272 notnull=0,
273 default_value=None,
274 is_pk=0,
275 hidden=0,
276 ),
277 Column(
278 cid=5,
279 name="sortable_with_nulls_2",
280 type="real",
281 notnull=0,
282 default_value=None,
283 is_pk=0,
284 hidden=0,
285 ),
286 Column(
287 cid=6,
288 name="text",
289 type="text",
290 notnull=0,
291 default_value=None,
292 is_pk=0,
293 hidden=0,
294 ),
295 ],
296 ),
297 ),
298 )
299 @pytest.mark.asyncio
300 async def test_table_column_details(db, table, expected):
301 columns = await db.table_column_details(table)
302 # Convert "type" to lowercase before comparison
303 # https://github.com/simonw/datasette/issues/1647
304 compare_columns = [
305 Column(
306 c.cid, c.name, c.type.lower(), c.notnull, c.default_value, c.is_pk, c.hidden
307 )
308 for c in columns
309 ]
310 assert compare_columns == expected
311
312
313 @pytest.mark.asyncio
314 async def test_get_all_foreign_keys(db):
315 all_foreign_keys = await db.get_all_foreign_keys()
316 assert all_foreign_keys["roadside_attraction_characteristics"] == {
317 "incoming": [],
318 "outgoing": [
319 {
320 "other_table": "attraction_characteristic",
321 "column": "characteristic_id",
322 "other_column": "pk",
323 },
324 {
325 "other_table": "roadside_attractions",
326 "column": "attraction_id",
327 "other_column": "pk",
328 },
329 ],
330 }
331 assert all_foreign_keys["attraction_characteristic"] == {
332 "incoming": [
333 {
334 "other_table": "roadside_attraction_characteristics",
335 "column": "pk",
336 "other_column": "characteristic_id",
337 }
338 ],
339 "outgoing": [],
340 }
341 assert all_foreign_keys["compound_primary_key"] == {
342 # No incoming because these are compound foreign keys, which we currently ignore
343 "incoming": [],
344 "outgoing": [],
345 }
346 assert all_foreign_keys["foreign_key_references"] == {
347 "incoming": [],
348 "outgoing": [
349 {
350 "other_table": "primary_key_multiple_columns",
351 "column": "foreign_key_with_no_label",
352 "other_column": "id",
353 },
354 {
355 "other_table": "simple_primary_key",
356 "column": "foreign_key_with_blank_label",
357 "other_column": "id",
358 },
359 {
360 "other_table": "simple_primary_key",
361 "column": "foreign_key_with_label",
362 "other_column": "id",
363 },
364 ],
365 }
366
367
368 @pytest.mark.asyncio
369 async def test_table_names(db):
370 table_names = await db.table_names()
371 assert table_names == [
372 "simple_primary_key",
373 "primary_key_multiple_columns",
374 "primary_key_multiple_columns_explicit_label",
375 "compound_primary_key",
376 "compound_three_primary_keys",
377 "foreign_key_references",
378 "sortable",
379 "no_primary_key",
380 "123_starts_with_digits",
381 "Table With Space In Name",
382 "table/with/slashes.csv",
383 "complex_foreign_keys",
384 "custom_foreign_key_label",
385 "units",
386 "tags",
387 "searchable",
388 "searchable_tags",
389 "searchable_fts",
390 "searchable_fts_segments",
391 "searchable_fts_segdir",
392 "searchable_fts_docsize",
393 "searchable_fts_stat",
394 "select",
395 "infinity",
396 "facet_cities",
397 "facetable",
398 "binary_data",
399 "roadside_attractions",
400 "attraction_characteristic",
401 "roadside_attraction_characteristics",
402 ]
403
404
405 @pytest.mark.asyncio
406 async def test_execute_write_block_true(db):
407 await db.execute_write(
408 "update roadside_attractions set name = ? where pk = ?", ["Mystery!", 1]
409 )
410 rows = await db.execute("select name from roadside_attractions where pk = 1")
411 assert "Mystery!" == rows.rows[0][0]
412
413
414 @pytest.mark.asyncio
415 async def test_execute_write_block_false(db):
416 await db.execute_write(
417 "update roadside_attractions set name = ? where pk = ?",
418 ["Mystery!", 1],
419 )
420 time.sleep(0.1)
421 rows = await db.execute("select name from roadside_attractions where pk = 1")
422 assert "Mystery!" == rows.rows[0][0]
423
424
425 @pytest.mark.asyncio
426 async def test_execute_write_script(db):
427 await db.execute_write_script(
428 "create table foo (id integer primary key); create table bar (id integer primary key);"
429 )
430 table_names = await db.table_names()
431 assert {"foo", "bar"}.issubset(table_names)
432
433
434 @pytest.mark.asyncio
435 async def test_execute_write_many(db):
436 await db.execute_write_script("create table foomany (id integer primary key)")
437 await db.execute_write_many(
438 "insert into foomany (id) values (?)", [(1,), (10,), (100,)]
439 )
440 result = await db.execute("select * from foomany")
441 assert [r[0] for r in result.rows] == [1, 10, 100]
442
443
444 @pytest.mark.asyncio
445 async def test_execute_write_has_correctly_prepared_connection(db):
446 # The sleep() function is only available if ds._prepare_connection() was called
447 await db.execute_write("select sleep(0.01)")
448
449
450 @pytest.mark.asyncio
451 async def test_execute_write_fn_block_false(db):
452 def write_fn(conn):
453 with conn:
454 conn.execute("delete from roadside_attractions where pk = 1;")
455 row = conn.execute("select count(*) from roadside_attractions").fetchone()
456 return row[0]
457
458 task_id = await db.execute_write_fn(write_fn, block=False)
459 assert isinstance(task_id, uuid.UUID)
460
461
462 @pytest.mark.asyncio
463 @pytest.mark.parametrize("num_sql_threads", (0, 3))
464 async def test_execute_write_fn_block_false_returns_unique_uuid(num_sql_threads):
465 ds = Datasette([], memory=True, settings={"num_sql_threads": num_sql_threads})
466 db = ds.add_memory_database("test_block_false_{}".format(num_sql_threads))
467 await db.execute_write("create table t (id integer primary key)")
468
469 def write_fn(conn):
470 with conn:
471 conn.execute("insert into t default values")
472
473 first = await db.execute_write_fn(write_fn, block=False)
474 second = await db.execute_write_fn(write_fn, block=False)
475 assert isinstance(first, uuid.UUID)
476 assert isinstance(second, uuid.UUID)
477 assert first != second
478 # A blocking write runs after both queued writes on the same connection.
479 count = await db.execute_write_fn(
480 lambda conn: conn.execute("select count(*) from t").fetchone()[0]
481 )
482 assert count == 2
483
484
485 @pytest.mark.asyncio
486 async def test_execute_write_fn_block_true(db):
487 def write_fn(conn):
488 with conn:
489 conn.execute("delete from roadside_attractions where pk = 1;")
490 row = conn.execute("select count(*) from roadside_attractions").fetchone()
491 return row[0]
492
493 new_count = await db.execute_write_fn(write_fn)
494 assert 3 == new_count
495
496
497 @pytest.mark.asyncio
498 async def test_execute_write_fn_exception(db):
499 def write_fn(conn):
500 assert False
501
502 with pytest.raises(AssertionError):
503 await db.execute_write_fn(write_fn)
504
505
506 @pytest.mark.asyncio
507 @pytest.mark.timeout(1)
508 async def test_execute_write_fn_connection_exception(tmpdir, app_client):
509 path = str(tmpdir / "immutable.db")
510 sqlite3.connect(path).execute("vacuum")
511 db = Database(app_client.ds, path=path, is_mutable=False)
512 app_client.ds.add_database(db, name="immutable-db")
513
514 def write_fn(conn):
515 assert False
516
517 with pytest.raises(AssertionError):
518 await db.execute_write_fn(write_fn)
519
520 app_client.ds.remove_database("immutable-db")
521
522
523 @pytest.mark.asyncio
524 async def test_mtime_ns(db):
525 assert isinstance(db.mtime_ns, int)
526
527
528 def test_mtime_ns_is_none_for_memory(app_client):
529 memory_db = Database(app_client.ds, is_memory=True)
530 assert memory_db.is_memory is True
531 assert None is memory_db.mtime_ns
532
533
534 def test_is_mutable(app_client):
535 assert Database(app_client.ds, is_memory=True).is_mutable is True
536 assert Database(app_client.ds, is_memory=True, is_mutable=True).is_mutable is True
537 assert Database(app_client.ds, is_memory=True, is_mutable=False).is_mutable is False
538
539
540 @pytest.mark.asyncio
541 async def test_attached_databases(app_client_two_attached_databases_crossdb_enabled):
542 database = app_client_two_attached_databases_crossdb_enabled.ds.get_database(
543 "_memory"
544 )
545 attached = await database.attached_databases()
546 assert {a.name for a in attached} == {"extra database", "fixtures"}
547
548
549 @pytest.mark.asyncio
550 async def test_database_memory_name(app_client):
551 ds = app_client.ds
552 foo1 = ds.add_database(Database(ds, memory_name="foo"))
553 foo2 = ds.add_memory_database("foo")
554 bar1 = ds.add_database(Database(ds, memory_name="bar"))
555 bar2 = ds.add_memory_database("bar")
556 for db in (foo1, foo2, bar1, bar2):
557 table_names = await db.table_names()
558 assert table_names == []
559 # Now create a table in foo
560 await foo1.execute_write("create table foo (t text)")
561 assert await foo1.table_names() == ["foo"]
562 assert await foo2.table_names() == ["foo"]
563 assert await bar1.table_names() == []
564 assert await bar2.table_names() == []
565
566
567 @pytest.mark.asyncio
568 async def test_in_memory_databases_forbid_writes(app_client):
569 ds = app_client.ds
570 db = ds.add_database(Database(ds, memory_name="test"))
571 with pytest.raises(sqlite3.OperationalError):
572 await db.execute("create table foo (t text)")
573 assert await db.table_names() == []
574 # Using db.execute_write() should work:
575 await db.execute_write("create table foo (t text)")
576 assert await db.table_names() == ["foo"]