Coverage for downtify/library_listing_store.py: 100%

47 statements  

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

1"""SQLite/PostgreSQL snapshot of ``GET /tracks`` / ``GET /playlists`` / path pairs.""" 

2 

3from __future__ import annotations 

4 

5import json 

6from pathlib import Path 

7from typing import Any, Optional 

8 

9from .db.config import Dialect 

10from .db.core import Database, as_database 

11from .library_metadata_cache import META_VERSION 

12 

13#: Bump when the JSON shape of a snapshot row changes. 

14LISTING_FORMAT = 1 

15 

16 

17class LibraryListingStore: 

18 """Persists a folded library listing so a restart can skip the disk walk.""" 

19 

20 def __init__(self, path_or_db: str | Path | Database) -> None: 

21 self.db = as_database(path_or_db, 'library') 

22 if isinstance(path_or_db, Database): 

23 self._path = str(self.db.path) if self.db.path else None 

24 else: 

25 self._path = str(path_or_db) 

26 self._init_db() 

27 

28 def _connect(self): 

29 return self.db.connect() 

30 

31 def _init_db(self) -> None: 

32 # The Postgres schema is created by migrations; only SQLite needs DDL. 

33 if self.db.dialect is not Dialect.SQLITE: 

34 return 

35 with self._connect() as conn: 

36 conn.execute(""" 

37 CREATE TABLE IF NOT EXISTS library_listing ( 

38 cache_key TEXT PRIMARY KEY, 

39 fingerprint TEXT NOT NULL, 

40 listing_format INTEGER NOT NULL, 

41 meta_version INTEGER NOT NULL, 

42 paths_json TEXT NOT NULL, 

43 playlists_json TEXT NOT NULL, 

44 entries_json TEXT NOT NULL 

45 ) 

46 """) 

47 

48 def load(self, cache_key: str) -> Optional[dict[str, Any]]: 

49 with self._connect() as conn: 

50 row = conn.execute( 

51 """ 

52 SELECT fingerprint, listing_format, meta_version, 

53 paths_json, playlists_json, entries_json 

54 FROM library_listing 

55 WHERE cache_key = ? 

56 """, 

57 (cache_key,), 

58 ).fetchone() 

59 if row is None: 

60 return None 

61 if int(row['listing_format'] or 0) != LISTING_FORMAT: 

62 return None 

63 if int(row['meta_version'] or 0) < META_VERSION: 

64 return None 

65 try: 

66 paths = [ 

67 (str(stored), str(resolved)) 

68 for stored, resolved in json.loads(row['paths_json']) 

69 ] 

70 playlists = json.loads(row['playlists_json']) 

71 entries = json.loads(row['entries_json']) 

72 except (TypeError, ValueError): 

73 return None 

74 if not isinstance(playlists, list) or not isinstance(entries, list): 

75 return None 

76 return { 

77 'fingerprint': str(row['fingerprint'] or ''), 

78 'paths': paths, 

79 'playlists': playlists, 

80 'entries': entries, 

81 } 

82 

83 def save( 

84 self, 

85 cache_key: str, 

86 fingerprint: str, 

87 paths: list[tuple[str, str]], 

88 playlists: list[dict[str, Any]], 

89 entries: list[dict[str, Any]], 

90 ) -> None: 

91 payload = ( 

92 cache_key, 

93 fingerprint, 

94 LISTING_FORMAT, 

95 META_VERSION, 

96 json.dumps(paths), 

97 json.dumps(playlists), 

98 json.dumps(entries), 

99 ) 

100 with self._connect() as conn: 

101 conn.execute( 

102 """ 

103 INSERT INTO library_listing ( 

104 cache_key, fingerprint, listing_format, meta_version, 

105 paths_json, playlists_json, entries_json 

106 ) VALUES (?, ?, ?, ?, ?, ?, ?) 

107 ON CONFLICT(cache_key) DO UPDATE SET 

108 fingerprint = excluded.fingerprint, 

109 listing_format = excluded.listing_format, 

110 meta_version = excluded.meta_version, 

111 paths_json = excluded.paths_json, 

112 playlists_json = excluded.playlists_json, 

113 entries_json = excluded.entries_json 

114 """, 

115 payload, 

116 ) 

117 

118 def clear(self) -> None: 

119 with self._connect() as conn: 

120 conn.execute('DELETE FROM library_listing')