Coverage for downtify/db/rows.py: 100%

38 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""Row type compatible with ``sqlite3.Row`` for PostgreSQL results.""" 

2 

3from __future__ import annotations 

4 

5from collections.abc import Callable, Sequence 

6from functools import lru_cache 

7from typing import Any 

8 

9 

10@lru_cache(maxsize=256) 

11def _name_index(keys: tuple[str, ...]) -> dict[str, int]: 

12 """Map lower-cased column names to their first index.""" 

13 index: dict[str, int] = {} 

14 for position, name in enumerate(keys): 

15 index.setdefault(name.lower(), position) 

16 return index 

17 

18 

19class Row(tuple): 

20 """Tuple of values that also supports lookup by column name. 

21 

22 Behaves like ``sqlite3.Row``: integer and slice indexing, plus 

23 case-insensitive column name lookup. Iteration, equality and hashing 

24 follow the plain tuple of values. 

25 """ 

26 

27 def __new__(cls, keys: Sequence[str], values: Sequence[Any]) -> Row: 

28 self = super().__new__(cls, values) 

29 self._keys = tuple(keys) 

30 self._index = _name_index(self._keys) 

31 return self 

32 

33 def __getnewargs__(self) -> tuple[tuple[str, ...], tuple[Any, ...]]: 

34 return (self._keys, tuple(self)) 

35 

36 def __getitem__(self, key: Any) -> Any: 

37 if isinstance(key, str): 

38 position = self._index.get(key.lower()) 

39 if position is None: 

40 raise IndexError('No item with that key') 

41 return tuple.__getitem__(self, position) 

42 return tuple.__getitem__(self, key) 

43 

44 def keys(self) -> list[str]: 

45 """Return the column names in their original case.""" 

46 return list(self._keys) 

47 

48 def get(self, key: Any, default: Any = None) -> Any: 

49 """Return the value for ``key`` or ``default`` if it is missing.""" 

50 try: 

51 return self[key] 

52 except (IndexError, TypeError): 

53 return default 

54 

55 

56def pg_row_factory(cursor: Any) -> Callable[[Sequence[Any]], Row]: 

57 """psycopg row factory producing ``Row`` objects. 

58 

59 Column names are read from ``cursor.description`` once per result set. 

60 """ 

61 description = cursor.description or [] 

62 keys = tuple(column.name for column in description) 

63 

64 def make_row(values: Sequence[Any]) -> Row: 

65 return Row(keys, values) 

66 

67 return make_row