Add count helper functions (#291)
authorMarcel van der Veldt <m.vanderveldt@outlook.com>
Sun, 8 May 2022 09:38:57 +0000 (11:38 +0200)
committerGitHub <noreply@github.com>
Sun, 8 May 2022 09:38:57 +0000 (11:38 +0200)
examples/full.py
music_assistant/helpers/database.py
music_assistant/models/media_controller.py

index ef9e1dc68688eebfdb3c86ac07a3b8319913cd42..72a6f5ff89b5af3bb5b23e28f89f20c9904526f3 100644 (file)
@@ -153,14 +153,14 @@ async def main():
         for prov in providers:
             await mass.music.register_provider(prov)
         # get some data
-        artists = await mass.music.artists.library()
-        print(f"Got {len(artists)} artists in library")
-        albums = await mass.music.albums.library()
-        print(f"Got {len(albums)} albums in library")
-        tracks = await mass.music.tracks.library()
-        print(f"Got {len(tracks)} tracks in library")
-        radios = await mass.music.radio.library()
-        print(f"Got {len(radios)} radio stations in library")
+        artists = await mass.music.artists.count()
+        print(f"Got {artists} artists in library")
+        albums = await mass.music.albums.count()
+        print(f"Got {albums} albums in library")
+        tracks = await mass.music.tracks.count()
+        print(f"Got {tracks} tracks in library")
+        radios = await mass.music.radio.count()
+        print(f"Got {radios} radio stations in library")
         playlists = await mass.music.playlists.library()
         print(f"Got {len(playlists)} playlists in library")
         # register a player
index 205b8d7e6446aee3fe9e361edb45262ce2fd3480..b2066cb88f695d7cfc2277d0c020113526a851d9 100755 (executable)
@@ -66,6 +66,21 @@ class Database:
             TABLE_SETTINGS, {"key": key, "value": value}
         )
 
+    async def get_count(
+        self,
+        table: str,
+        match: dict = None,
+        db: Optional[Db] = None,
+    ) -> List[Mapping]:
+        """Get row count for given table/query."""
+        async with self.get_db(db) as _db:
+            sql_query = f"SELECT count() FROM {table}"
+            if match is not None:
+                sql_query += " WHERE " + " AND ".join((f"{x} = :{x}" for x in match))
+            if res := await _db.fetch_one(sql_query, match):
+                return res["count()"]
+            return 0
+
     async def get_rows(
         self,
         table: str,
index 9a9115105abe662e8b1a7dbe1ef0099a0c357f0f..007cd7be73a13daf8f5f67b3c2ff97e0d4617b3c 100644 (file)
@@ -42,6 +42,10 @@ class MediaControllerBase(Generic[ItemCls], metaclass=ABCMeta):
             for db_row in await self.mass.database.get_rows(self.db_table, match)
         ]
 
+    async def count(self) -> int:
+        """Return number of in-library items for this MediaType."""
+        return await self.mass.database.get_count(self.db_table, {"in_library": 1})
+
     async def get(
         self,
         provider_item_id: str,