From 2308b136fd4ced9227caf5c4e0e326a757d8ce64 Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Mon, 4 May 2020 21:29:58 +1000 Subject: [PATCH] add an index on notes(mid) so we can avoid the tablescan --- pylib/anki/models.py | 1 - pylib/anki/rsbackend.py | 2 +- rslib/src/storage/notetype/get_use_counts.sql | 11 +++++++---- rslib/src/storage/upgrades/schema11_downgrade.sql | 1 + rslib/src/storage/upgrades/schema15_upgrade.sql | 1 + 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/pylib/anki/models.py b/pylib/anki/models.py index 9dfab2eb1..98bc2cbba 100644 --- a/pylib/anki/models.py +++ b/pylib/anki/models.py @@ -317,7 +317,6 @@ class ModelManager: def useCount(self, m: NoteType) -> Any: "Number of note using M." - print("useCount() is slow; prefer all_use_counts()") return self.col.db.scalar("select count() from notes where mid = ?", m["id"]) # Copying diff --git a/pylib/anki/rsbackend.py b/pylib/anki/rsbackend.py index c619e27bf..126fc4d01 100644 --- a/pylib/anki/rsbackend.py +++ b/pylib/anki/rsbackend.py @@ -656,7 +656,7 @@ class RustBackend: json=bjson, preserve_usn_and_mtime=preserve_usn ) ), - release_gil=True + release_gil=True, ).add_or_update_notetype nt["id"] = id diff --git a/rslib/src/storage/notetype/get_use_counts.sql b/rslib/src/storage/notetype/get_use_counts.sql index dce0bdca1..7a00bb99f 100644 --- a/rslib/src/storage/notetype/get_use_counts.sql +++ b/rslib/src/storage/notetype/get_use_counts.sql @@ -1,10 +1,13 @@ select nt.id, nt.name, - count(n.id) + ( + select + count(*) + from notes n + where + nt.id = n.mid + ) from notetypes nt -left join notes n on (n.mid = nt.id) -group by - nt.id order by nt.name \ No newline at end of file diff --git a/rslib/src/storage/upgrades/schema11_downgrade.sql b/rslib/src/storage/upgrades/schema11_downgrade.sql index ec1bd7713..ed7694ad7 100644 --- a/rslib/src/storage/upgrades/schema11_downgrade.sql +++ b/rslib/src/storage/upgrades/schema11_downgrade.sql @@ -6,6 +6,7 @@ drop table templates; drop table notetypes; drop table decks; drop index idx_cards_odid; +drop index idx_notes_mid; update col set ver = 11; \ No newline at end of file diff --git a/rslib/src/storage/upgrades/schema15_upgrade.sql b/rslib/src/storage/upgrades/schema15_upgrade.sql index 5c5e7fec1..a0a5efe33 100644 --- a/rslib/src/storage/upgrades/schema15_upgrade.sql +++ b/rslib/src/storage/upgrades/schema15_upgrade.sql @@ -35,6 +35,7 @@ create table decks ( kind bytes not null ); create unique index idx_decks_name on decks (name); +create index idx_notes_mid on notes (mid); create index idx_cards_odid on cards (odid) where odid != 0;