"""Column sets of the attached host engine's tables, probed once per connection."""
from __future__ import annotations
import threading
from typing import Any, Dict, FrozenSet, Tuple
# id(conn) -> (conn, table, columns). The connection is held so its id cannot
# be reused by another while cached (sqlite3 connections take no weakref).
_CACHE: Dict[Tuple[int, str], Tuple[Any, FrozenSet[str]]] = {}
_LOCK = threading.Lock()
[docs]def table_columns(conn: Any, table: str) -> FrozenSet[str]:
"""The column names of `table` on `conn`, from PRAGMA table_info on first use."""
key = (id(conn), table)
with _LOCK:
hit = _CACHE.get(key)
if hit is not None and hit[0] is conn:
return hit[1]
cols = frozenset(str(r[1]) for r in conn.execute(f"PRAGMA table_info({table})").fetchall())
with _LOCK:
_CACHE[key] = (conn, cols)
return cols