diff --git a/src/calibre/db/cache.py b/src/calibre/db/cache.py index 4c270e586b..dfcc4c2df8 100644 --- a/src/calibre/db/cache.py +++ b/src/calibre/db/cache.py @@ -1075,6 +1075,20 @@ class Cache: return {aid:af.author_data(aid) for aid in af.table.id_map} return {aid:af.author_data(aid) for aid in author_ids if aid in af.table.id_map} + @read_api + def author_sorts(self, author_ids=None) -> dict[int, str]: + ''' + Return author sorts for specified authors. + + If no authors with the specified ids are found an empty dictionary is + returned. If author_ids is None, data for all authors is returned. + ''' + af = self.fields['authors'] + m = af.table.asort_map + if author_ids is None: + return m.copy() + return {aid:m[aid] for aid in author_ids if aid in m} + @read_api def format_hash(self, book_id, fmt): ''' Return the hash of the specified format for the specified book. The diff --git a/src/calibre/db/tests/writing.py b/src/calibre/db/tests/writing.py index 748ed85771..d06e4751fc 100644 --- a/src/calibre/db/tests/writing.py +++ b/src/calibre/db/tests/writing.py @@ -789,6 +789,8 @@ class WritingTest(BaseTest): 'Setting the author link to the same value as before, incorrectly marked some books as dirty') sdata = {aid:f'{aid}, changed' for aid in adata} self.assertEqual({1,2,3}, cache.set_sort_for_authors(sdata)) + self.assertEqual(sdata, cache.author_sorts()) + self.assertEqual(sdata, cache.author_sorts(sdata)) for bid in (1, 2, 3): self.assertIn(', changed', cache.field_for('author_sort', bid)) sdata = {aid:f'{aid*2 if aid == max(adata) else aid}, changed' for aid in adata} diff --git a/src/calibre/gui2/library/bookshelf_view.py b/src/calibre/gui2/library/bookshelf_view.py index 8962faef6f..7be537f147 100644 --- a/src/calibre/gui2/library/bookshelf_view.py +++ b/src/calibre/gui2/library/bookshelf_view.py @@ -805,15 +805,15 @@ def get_grouped_iterator(db: Cache, book_ids_iter: Iterable[int], field_name: st return case 'authors': field_id_map = db.get_id_map('authors') - author_sort_map = db.author_data(field_id_map) + author_sort_map = db.author_sorts() def gas(aid: int, au: str) -> str: try: - return author_sort_map[aid]['sort'] - except Exception: + return author_sort_map[aid] + except KeyError: return au - sort_field_map = {au: gas(aid, au) for aid, au in field_id_map.items()} - sort_key = lambda x: sort_field_map[x] # noqa: E731 + sort_key = {au: gas(aid, au) for aid, au in field_id_map.items()}.__getitem__ get_field_id_map = lambda: field_id_map # noqa: E731 + del gas case 'languages': lm = lang_map() formatter = lambda x: lm.get(x, x) # noqa: E731