|
1 | 1 | import copy |
2 | 2 | import json |
3 | 3 | import pickle |
| 4 | +import sqlite3 |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 |
|
@@ -545,3 +546,59 @@ async def test_labels_in_json_and_csv(ds_with_dogs): |
545 | 546 | "1,1,Natalie,3", |
546 | 547 | "2,99,,3", |
547 | 548 | ] |
| 549 | + |
| 550 | + |
| 551 | +@pytest.mark.asyncio |
| 552 | +@pytest.mark.parametrize("method", ("execute_fn", "execute_write_fn")) |
| 553 | +async def test_raw_connections_return_rows(method): |
| 554 | + ds = Datasette(memory=True) |
| 555 | + db = ds.add_memory_database(f"test_raw_connections_{method}") |
| 556 | + await db.execute_write_script(""" |
| 557 | + create table dogs (id integer primary key, name text); |
| 558 | + insert into dogs values (1, 'Cleo'), (2, 'Pancakes'); |
| 559 | + """) |
| 560 | + |
| 561 | + def fetch(conn): |
| 562 | + return conn.execute("select id, name from dogs order by id").fetchall() |
| 563 | + |
| 564 | + rows = await getattr(db, method)(fetch) |
| 565 | + assert all(type(row) is Row for row in rows) |
| 566 | + assert rows[0]["name"] == "Cleo" |
| 567 | + assert rows[1][0] == 2 |
| 568 | + assert rows[0].keys() == ["id", "name"] |
| 569 | + # The rows of one query share their columns |
| 570 | + assert rows[0].columns is rows[1].columns |
| 571 | + |
| 572 | + def reuse_cursor(conn): |
| 573 | + cursor = conn.cursor() |
| 574 | + first = cursor.execute("select 1 as a").fetchone() |
| 575 | + second = cursor.execute("select 2 as b, 3 as c").fetchone() |
| 576 | + return first, second |
| 577 | + |
| 578 | + first, second = await getattr(db, method)(reuse_cursor) |
| 579 | + assert first.keys() == ["a"] |
| 580 | + assert second.keys() == ["b", "c"] |
| 581 | + assert dict(second) == {"b": 2, "c": 3} |
| 582 | + |
| 583 | + def interleave(conn): |
| 584 | + ids = conn.execute("select id from dogs order by id") |
| 585 | + names = conn.execute("select name from dogs order by id") |
| 586 | + return [(ids.fetchone(), names.fetchone()) for _ in range(2)] |
| 587 | + |
| 588 | + pairs = await getattr(db, method)(interleave) |
| 589 | + assert [(dict(id_), dict(name)) for id_, name in pairs] == [ |
| 590 | + ({"id": 1}, {"name": "Cleo"}), |
| 591 | + ({"id": 2}, {"name": "Pancakes"}), |
| 592 | + ] |
| 593 | + |
| 594 | + |
| 595 | +@pytest.mark.asyncio |
| 596 | +async def test_execute_isolated_fn_connection_is_not_configured(tmp_path): |
| 597 | + path = str(tmp_path / "isolated.db") |
| 598 | + sqlite3.connect(path).execute("vacuum") |
| 599 | + ds = Datasette([path]) |
| 600 | + db = ds.get_database("isolated") |
| 601 | + row = await db.execute_isolated_fn( |
| 602 | + lambda conn: conn.execute("select 1 as a").fetchone() |
| 603 | + ) |
| 604 | + assert type(row) is tuple |
0 commit comments