| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import sqlite3 |
| 4 |
import sys |
| 5 |
from pathlib import Path |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from harlequin.catalog import Catalog, CatalogItem, InteractiveCatalogItem |
| 10 |
from harlequin.exception import HarlequinConfigError, HarlequinConnectionError |
| 11 |
from harlequin_sqlite import HarlequinSqliteAdapter |
| 12 |
|
| 13 |
|
| 14 |
@pytest.fixture |
| 15 |
def extension_path(data_dir: Path) -> Path: |
| 16 |
return data_dir / "adapter_tests" / "sqlite" / "extensions" / "hello0" |
| 17 |
|
| 18 |
|
| 19 |
def test_connect(tiny_sqlite: Path, small_sqlite: Path) -> None: |
| 20 |
tiny = str(tiny_sqlite) |
| 21 |
small = str(small_sqlite) |
| 22 |
assert HarlequinSqliteAdapter([]).connect() |
| 23 |
assert HarlequinSqliteAdapter([":memory:"]).connect() |
| 24 |
assert HarlequinSqliteAdapter([tiny], read_only=False).connect() |
| 25 |
assert HarlequinSqliteAdapter([tiny], read_only=True).connect() |
| 26 |
assert HarlequinSqliteAdapter([tiny], mode="ro").connect() |
| 27 |
assert HarlequinSqliteAdapter([tiny, small, ":memory:"], read_only=False).connect() |
| 28 |
assert HarlequinSqliteAdapter( |
| 29 |
[], |
| 30 |
read_only=False, |
| 31 |
lock_timeout="100", |
| 32 |
isolation_level="EXCLUSIVE", |
| 33 |
check_same_thread=False, |
| 34 |
cached_statements="10", |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
def test_cannot_connect(tmp_path: Path, tiny_sqlite: Path) -> None: |
| 39 |
nonexistent_db = tmp_path / "no.db" |
| 40 |
with pytest.raises(HarlequinConnectionError): |
| 41 |
HarlequinSqliteAdapter((str(nonexistent_db),), read_only=True).connect() |
| 42 |
with pytest.raises(HarlequinConnectionError): |
| 43 |
HarlequinSqliteAdapter( |
| 44 |
(str(nonexistent_db), ":memory:"), read_only=True |
| 45 |
).connect() |
| 46 |
with pytest.raises(HarlequinConnectionError): |
| 47 |
HarlequinSqliteAdapter( |
| 48 |
(str(tiny_sqlite),), read_only=True, mode="rwc" |
| 49 |
).connect() |
| 50 |
|
| 51 |
|
| 52 |
def test_get_databases(tiny_sqlite: Path, tmp_path: Path) -> None: |
| 53 |
new_db = tmp_path / "new.db" |
| 54 |
conn = HarlequinSqliteAdapter((str(tiny_sqlite), str(new_db))).connect() |
| 55 |
assert conn._get_databases() == ["main", "new"] |
| 56 |
|
| 57 |
|
| 58 |
def test_get_tables(tiny_sqlite: Path, small_sqlite: Path) -> None: |
| 59 |
conn = HarlequinSqliteAdapter( |
| 60 |
[str(tiny_sqlite), str(small_sqlite)], read_only=True |
| 61 |
).connect() |
| 62 |
assert conn._get_relations("main") == [("foo", "table")] |
| 63 |
assert conn._get_relations("small") == [("drivers", "table")] |
| 64 |
|
| 65 |
|
| 66 |
def test_get_columns(small_sqlite: Path) -> None: |
| 67 |
conn = HarlequinSqliteAdapter([str(small_sqlite)], read_only=True).connect() |
| 68 |
cols = conn._get_columns(db_name="main", rel_name="drivers") |
| 69 |
assert [(col_name, col_type) for _, col_name, col_type, *_ in cols] == [ |
| 70 |
("driverId", "BIGINT"), |
| 71 |
("driverRef", "VARCHAR"), |
| 72 |
("number", "VARCHAR"), |
| 73 |
("code", "VARCHAR"), |
| 74 |
("forename", "VARCHAR"), |
| 75 |
("surname", "VARCHAR"), |
| 76 |
("dob", "VARCHAR"), |
| 77 |
("nationality", "VARCHAR"), |
| 78 |
("url", "VARCHAR"), |
| 79 |
] |
| 80 |
|
| 81 |
|
| 82 |
def test_get_catalog(tiny_sqlite: Path, small_sqlite: Path) -> None: |
| 83 |
conn = HarlequinSqliteAdapter( |
| 84 |
[str(tiny_sqlite), str(small_sqlite)], read_only=True |
| 85 |
).connect() |
| 86 |
expected = Catalog( |
| 87 |
items=[ |
| 88 |
CatalogItem( |
| 89 |
qualified_identifier='"main"', |
| 90 |
query_name='"main"', |
| 91 |
label="main", |
| 92 |
type_label="db", |
| 93 |
children=[ |
| 94 |
CatalogItem( |
| 95 |
qualified_identifier='"main"."foo"', |
| 96 |
query_name='"main"."foo"', |
| 97 |
label="foo", |
| 98 |
type_label="t", |
| 99 |
children=[ |
| 100 |
CatalogItem( |
| 101 |
qualified_identifier='"main"."foo"."foo_col"', |
| 102 |
query_name='"foo_col"', |
| 103 |
label="foo_col", |
| 104 |
type_label="##", |
| 105 |
) |
| 106 |
], |
| 107 |
) |
| 108 |
], |
| 109 |
), |
| 110 |
CatalogItem( |
| 111 |
qualified_identifier='"small"', |
| 112 |
query_name='"small"', |
| 113 |
label="small", |
| 114 |
type_label="db", |
| 115 |
children=[ |
| 116 |
CatalogItem( |
| 117 |
qualified_identifier='"small"."drivers"', |
| 118 |
query_name='"small"."drivers"', |
| 119 |
label="drivers", |
| 120 |
type_label="t", |
| 121 |
children=[ |
| 122 |
CatalogItem( |
| 123 |
qualified_identifier='"small"."drivers"."driverId"', |
| 124 |
query_name='"driverId"', |
| 125 |
label="driverId", |
| 126 |
type_label="##", |
| 127 |
), |
| 128 |
CatalogItem( |
| 129 |
qualified_identifier='"small"."drivers"."driverRef"', |
| 130 |
query_name='"driverRef"', |
| 131 |
label="driverRef", |
| 132 |
type_label="s", |
| 133 |
), |
| 134 |
CatalogItem( |
| 135 |
qualified_identifier='"small"."drivers"."number"', |
| 136 |
query_name='"number"', |
| 137 |
label="number", |
| 138 |
type_label="s", |
| 139 |
), |
| 140 |
CatalogItem( |
| 141 |
qualified_identifier='"small"."drivers"."code"', |
| 142 |
query_name='"code"', |
| 143 |
label="code", |
| 144 |
type_label="s", |
| 145 |
), |
| 146 |
CatalogItem( |
| 147 |
qualified_identifier='"small"."drivers"."forename"', |
| 148 |
query_name='"forename"', |
| 149 |
label="forename", |
| 150 |
type_label="s", |
| 151 |
), |
| 152 |
CatalogItem( |
| 153 |
qualified_identifier='"small"."drivers"."surname"', |
| 154 |
query_name='"surname"', |
| 155 |
label="surname", |
| 156 |
type_label="s", |
| 157 |
), |
| 158 |
CatalogItem( |
| 159 |
qualified_identifier='"small"."drivers"."dob"', |
| 160 |
query_name='"dob"', |
| 161 |
label="dob", |
| 162 |
type_label="s", |
| 163 |
), |
| 164 |
CatalogItem( |
| 165 |
qualified_identifier='"small"."drivers"."nationality"', |
| 166 |
query_name='"nationality"', |
| 167 |
label="nationality", |
| 168 |
type_label="s", |
| 169 |
), |
| 170 |
CatalogItem( |
| 171 |
qualified_identifier='"small"."drivers"."url"', |
| 172 |
query_name='"url"', |
| 173 |
label="url", |
| 174 |
type_label="s", |
| 175 |
), |
| 176 |
], |
| 177 |
) |
| 178 |
], |
| 179 |
), |
| 180 |
] |
| 181 |
) |
| 182 |
catalog = conn.get_catalog() |
| 183 |
assert [item.label for item in catalog.items] == [ |
| 184 |
item.label for item in expected.items |
| 185 |
] |
| 186 |
for i, database_item in enumerate(catalog.items): |
| 187 |
assert isinstance(database_item, InteractiveCatalogItem) |
| 188 |
assert database_item.children == [] |
| 189 |
schema_items = database_item.fetch_children() |
| 190 |
assert [item.label for item in schema_items] == [ |
| 191 |
item.label for item in expected.items[i].children |
| 192 |
] |
| 193 |
for j, schema_item in enumerate(schema_items): |
| 194 |
assert isinstance(schema_item, InteractiveCatalogItem) |
| 195 |
assert schema_item.children == [] |
| 196 |
relation_items = schema_item.fetch_children() |
| 197 |
assert [(item.label, item.type_label) for item in relation_items] == [ |
| 198 |
(item.label, item.type_label) |
| 199 |
for item in expected.items[i].children[j].children |
| 200 |
] |
| 201 |
for k, relation_item in enumerate(relation_items): |
| 202 |
assert isinstance(relation_item, InteractiveCatalogItem) |
| 203 |
assert relation_item.children == [] |
| 204 |
column_items = relation_item.fetch_children() |
| 205 |
assert [(item.label, item.type_label) for item in column_items] == [ |
| 206 |
(item.label, item.type_label) |
| 207 |
for item in expected.items[i].children[j].children[k].children |
| 208 |
] |
| 209 |
|
| 210 |
|
| 211 |
def test_catalog_items_carry_sqlites_own_type_names(tmp_path: Path) -> None: |
| 212 |
"""The declared type, which sqlite keeps verbatim -- and None for a column |
| 213 |
declared without one, since an empty string is not a type.""" |
| 214 |
conn = HarlequinSqliteAdapter([str(tmp_path / "types.sqlite")]).connect() |
| 215 |
conn.execute("create table t (id bigint, note, total decimal(18,2))") |
| 216 |
conn.execute("create view v as select 1 as n") |
| 217 |
|
| 218 |
(database_item,) = conn.get_catalog().items |
| 219 |
assert isinstance(database_item, InteractiveCatalogItem) |
| 220 |
assert database_item.type_name == "database" |
| 221 |
|
| 222 |
relation_items = database_item.fetch_children() |
| 223 |
assert [(item.label, item.type_name) for item in relation_items] == [ |
| 224 |
("t", "table"), |
| 225 |
("v", "view"), |
| 226 |
] |
| 227 |
|
| 228 |
table_item = relation_items[0] |
| 229 |
assert isinstance(table_item, InteractiveCatalogItem) |
| 230 |
assert [ |
| 231 |
(item.label, item.type_label, item.type_name) |
| 232 |
for item in table_item.fetch_children() |
| 233 |
] == [ |
| 234 |
("id", "##", "bigint"), |
| 235 |
("note", "#.#", None), |
| 236 |
("total", "#.#", "decimal(18,2)"), |
| 237 |
] |
| 238 |
|
| 239 |
|
| 240 |
def test_search_catalog_finds_relations_and_columns(tmp_path: Path) -> None: |
| 241 |
"""One query per attached database, rather than one per relation, and every |
| 242 |
match carries the path that reaches it.""" |
| 243 |
conn = HarlequinSqliteAdapter([str(tmp_path / "search.sqlite")]).connect() |
| 244 |
conn.execute("create table orders (id bigint, customer_id bigint)") |
| 245 |
conn.execute("create view order_summary as select 1 as n") |
| 246 |
conn.execute("create table customers (customer_id bigint)") |
| 247 |
|
| 248 |
assert [ |
| 249 |
(result.parents, result.item.label, result.item.type_name) |
| 250 |
for result in conn.search_catalog("ORDER") |
| 251 |
] == [ |
| 252 |
(("main",), "order_summary", "view"), |
| 253 |
(("main",), "orders", "table"), |
| 254 |
] |
| 255 |
assert [ |
| 256 |
(result.parents, result.item.label, result.item.type_name) |
| 257 |
for result in conn.search_catalog("customer_id") |
| 258 |
] == [ |
| 259 |
(("main", "customers"), "customer_id", "bigint"), |
| 260 |
(("main", "orders"), "customer_id", "bigint"), |
| 261 |
] |
| 262 |
|
| 263 |
|
| 264 |
def test_search_catalog_takes_one_kind_at_a_time(tmp_path: Path) -> None: |
| 265 |
conn = HarlequinSqliteAdapter([str(tmp_path / "kinds.sqlite")]).connect() |
| 266 |
conn.execute("create table orders (orders bigint)") |
| 267 |
|
| 268 |
assert [ |
| 269 |
result.item.type_label for result in conn.search_catalog("orders", "relations") |
| 270 |
] == ["t"] |
| 271 |
assert [ |
| 272 |
result.item.type_label for result in conn.search_catalog("orders", "columns") |
| 273 |
] == ["##"] |
| 274 |
assert len(conn.search_catalog("orders", "all")) == 2 |
| 275 |
|
| 276 |
|
| 277 |
def test_search_catalog_reads_a_wildcard_as_a_character(tmp_path: Path) -> None: |
| 278 |
"""The term is a substring, so a LIKE metacharacter in it matches itself.""" |
| 279 |
conn = HarlequinSqliteAdapter([str(tmp_path / "wild.sqlite")]).connect() |
| 280 |
conn.execute('create table "a%b" (n bigint)') |
| 281 |
conn.execute("create table ab (n bigint)") |
| 282 |
|
| 283 |
assert [result.item.label for result in conn.search_catalog("a%b")] == ["a%b"] |
| 284 |
assert [result.item.label for result in conn.search_catalog("a_b")] == [] |
| 285 |
|
| 286 |
|
| 287 |
def test_search_catalog_covers_every_attached_database( |
| 288 |
tiny_sqlite: Path, small_sqlite: Path |
| 289 |
) -> None: |
| 290 |
conn = HarlequinSqliteAdapter([str(tiny_sqlite), str(small_sqlite)]).connect() |
| 291 |
found = conn.search_catalog("") |
| 292 |
assert {result.parents[0] for result in found if result.parents} == { |
| 293 |
"main", |
| 294 |
"small", |
| 295 |
} |
| 296 |
|
| 297 |
|
| 298 |
def test_search_catalog_matches_every_level(tmp_path: Path) -> None: |
| 299 |
"""A caller searching a catalog does not know its shape, so an attached |
| 300 |
database named like the term is an answer too. SQLite has no schema between |
| 301 |
a database and its relations, which is why this path is one level shorter |
| 302 |
than duckdb's. |
| 303 |
|
| 304 |
Grouped by attached database, since that is what SQLite asks one query per, |
| 305 |
and within each one an item arrives before the items under it. |
| 306 |
""" |
| 307 |
database = tmp_path / "sales.sqlite" |
| 308 |
conn = HarlequinSqliteAdapter([str(database)]).connect() |
| 309 |
conn.execute("create table sales (sales bigint)") |
| 310 |
conn.execute(f"attach database '{database}' as sales") |
| 311 |
|
| 312 |
assert [ |
| 313 |
(result.parents, result.item.label, result.item.type_label) |
| 314 |
for result in conn.search_catalog("sales") |
| 315 |
] == [ |
| 316 |
(("main",), "sales", "t"), |
| 317 |
(("main", "sales"), "sales", "##"), |
| 318 |
((), "sales", "db"), |
| 319 |
(("sales",), "sales", "t"), |
| 320 |
(("sales", "sales"), "sales", "##"), |
| 321 |
] |
| 322 |
|
| 323 |
|
| 324 |
def test_init_script(tiny_sqlite: Path, tmp_path: Path) -> None: |
| 325 |
script = ( |
| 326 |
f".bail on\nselect \n1;\n.bail off\n.open {tiny_sqlite}\n" |
| 327 |
"create table test_init as select 2;" |
| 328 |
) |
| 329 |
commands = HarlequinSqliteAdapter._split_script(script) |
| 330 |
assert len(commands) == 5 |
| 331 |
rewritten = [HarlequinSqliteAdapter._rewrite_init_command(cmd) for cmd in commands] |
| 332 |
assert rewritten[0] == "" |
| 333 |
assert rewritten[1] == commands[1] |
| 334 |
assert rewritten[2] == "" |
| 335 |
assert rewritten[3].startswith(f"attach '{tiny_sqlite}'") |
| 336 |
assert rewritten[4] == commands[4] |
| 337 |
|
| 338 |
with open(tmp_path / "myscript", "w") as f: |
| 339 |
f.write(script) |
| 340 |
|
| 341 |
conn = HarlequinSqliteAdapter( |
| 342 |
[":memory:"], init_path=tmp_path / "myscript" |
| 343 |
).connect() |
| 344 |
cur = conn.execute("select * from test_init") |
| 345 |
assert cur |
| 346 |
assert cur.fetchall() == [(2,)] |
| 347 |
|
| 348 |
|
| 349 |
def test_rewrite_load(extension_path: Path) -> None: |
| 350 |
cmd = f".load {extension_path.as_posix()}" |
| 351 |
rewritten = HarlequinSqliteAdapter._rewrite_init_command(cmd) |
| 352 |
assert rewritten.startswith("select load_extension") |
| 353 |
|
| 354 |
|
| 355 |
@pytest.mark.skipif( |
| 356 |
not hasattr(sqlite3.Connection, "enable_load_extension"), |
| 357 |
reason="Not supported on many Pythons.", |
| 358 |
) |
| 359 |
def test_load_extension(extension_path: Path) -> None: |
| 360 |
conn = HarlequinSqliteAdapter( |
| 361 |
[":memory:"], extension=[extension_path.as_posix()] |
| 362 |
).connect() |
| 363 |
assert conn |
| 364 |
|
| 365 |
|
| 366 |
@pytest.mark.skipif( |
| 367 |
hasattr(sqlite3.Connection, "enable_load_extension"), |
| 368 |
reason="Not supported on many Pythons.", |
| 369 |
) |
| 370 |
def test_load_extension_raises(extension_path: Path) -> None: |
| 371 |
with pytest.raises(HarlequinConfigError) as exc_info: |
| 372 |
_ = HarlequinSqliteAdapter( |
| 373 |
[":memory:"], extension=[extension_path.as_posix()] |
| 374 |
).connect() |
| 375 |
assert "harlequin.sh" in str(exc_info) |
| 376 |
|
| 377 |
|
| 378 |
def test_initialize_adapter_ignores_extra_kwargs() -> None: |
| 379 |
adapter = HarlequinSqliteAdapter((":memory:",), foo="bar") |
| 380 |
assert adapter |
| 381 |
assert adapter.connect() |
| 382 |
|
| 383 |
|
| 384 |
def test_a_query_with_no_rows_still_returns_its_columns() -> None: |
| 385 |
"""A caller handed `None` cannot know what the query selected, so an export |
| 386 |
or a headless render would lose the header. Arrow rather than a dict of |
| 387 |
columns, so duplicate names survive.""" |
| 388 |
import pyarrow as pa |
| 389 |
|
| 390 |
conn = HarlequinSqliteAdapter((":memory:",), no_init=True).connect() |
| 391 |
cur = conn.execute("select 1 as a, 'x' as b where 1=0") |
| 392 |
assert cur is not None |
| 393 |
assert cur.columns() == [("a", "?"), ("b", "?")] |
| 394 |
|
| 395 |
data = cur.fetchall() |
| 396 |
assert isinstance(data, pa.Table) |
| 397 |
assert data.column_names == ["a", "b"] |
| 398 |
assert data.num_rows == 0 |
| 399 |
|
| 400 |
|
| 401 |
def test_duplicate_column_names_survive_an_empty_result() -> None: |
| 402 |
import pyarrow as pa |
| 403 |
|
| 404 |
conn = HarlequinSqliteAdapter((":memory:",), no_init=True).connect() |
| 405 |
cur = conn.execute("select 1 as a, 2 as a where 1=0") |
| 406 |
assert cur is not None |
| 407 |
data = cur.fetchall() |
| 408 |
assert isinstance(data, pa.Table) |
| 409 |
assert data.column_names == ["a", "a"] |
| 410 |
|
| 411 |
|
| 412 |
def test_limit(small_sqlite: Path) -> None: |
| 413 |
adapter = HarlequinSqliteAdapter((str(small_sqlite),)) |
| 414 |
conn = adapter.connect() |
| 415 |
cur = conn.execute("select * from drivers") |
| 416 |
assert cur |
| 417 |
results = cur.fetchall() |
| 418 |
assert len(results) == 857 # type: ignore |
| 419 |
|
| 420 |
cur = conn.execute("select * from drivers") |
| 421 |
assert cur |
| 422 |
cur = cur.set_limit(100) |
| 423 |
results = cur.fetchall() |
| 424 |
assert len(results) == 100 # type: ignore |
| 425 |
|
| 426 |
|
| 427 |
@pytest.mark.parametrize("limit", [0, 1, 2]) |
| 428 |
def test_a_tiny_limit(small_sqlite: Path, limit: int) -> None: |
| 429 |
"""The first row is fetched eagerly, and 0 and 1 are where that shows. |
| 430 |
|
| 431 |
`fetchmany(0)` reads as "all of them" in sqlite3, so a limit of one row is |
| 432 |
a call that must not be made -- and a limit of no rows is a header. |
| 433 |
""" |
| 434 |
conn = HarlequinSqliteAdapter((str(small_sqlite),)).connect() |
| 435 |
cur = conn.execute("select * from drivers") |
| 436 |
assert cur |
| 437 |
results = cur.set_limit(limit).fetchall() |
| 438 |
assert results is not None |
| 439 |
assert len(results) == limit |
| 440 |
|
| 441 |
|
| 442 |
@pytest.mark.py12 |
| 443 |
@pytest.mark.skipif( |
| 444 |
sys.version_info < (3, 12), reason="Transactions only supported on py3.12+" |
| 445 |
) |
| 446 |
def test_transaction_mode() -> None: |
| 447 |
adapter = HarlequinSqliteAdapter((":memory:",)) |
| 448 |
conn = adapter.connect() |
| 449 |
assert conn.transaction_mode is not None |
| 450 |
assert conn.transaction_mode.label == "Auto" |
| 451 |
assert conn.transaction_mode.commit is None |
| 452 |
assert conn.transaction_mode.rollback is None |
| 453 |
new_mode = conn.toggle_transaction_mode() |
| 454 |
assert new_mode |
| 455 |
assert new_mode.label == "Manual" |
| 456 |
assert new_mode.commit is not None |
| 457 |
assert new_mode.rollback is not None |
| 458 |
assert conn.transaction_mode.label == "Manual" |
| 459 |
assert conn.toggle_transaction_mode() |
| 460 |
assert conn.transaction_mode.label == "Auto" |