Skip to content

Commit

Permalink
Pre-load meta entries for all chapters for optimization (#432)
Browse files Browse the repository at this point in the history
Load meta entries for all chapters in one query to prevent N+1 queries
  • Loading branch information
martinek authored Oct 30, 2022
1 parent 0fa2834 commit a9e5bc0
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion server/src/main/kotlin/suwayomi/tachidesk/manga/impl/Chapter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ object Chapter {
.associateBy({ it[ChapterTable.url] }, { it })
}

val chapterIds = chapterList.map { dbChapterMap.getValue(it.url)[ChapterTable.id] }
val chapterMetas = getChaptersMetaMaps(chapterIds)

return chapterList.mapIndexed { index, it ->

val dbChapter = dbChapterMap.getValue(it.url)
Expand All @@ -156,7 +159,7 @@ object Chapter {
dbChapter[ChapterTable.pageCount],

chapterList.size,
meta = getChapterMetaMap(dbChapter[ChapterTable.id])
meta = chapterMetas.getValue(dbChapter[ChapterTable.id])
)
}
}
Expand Down Expand Up @@ -193,6 +196,15 @@ object Chapter {
}
}

fun getChaptersMetaMaps(chapterIds: List<EntityID<Int>>): Map<EntityID<Int>, Map<String, String>> {
return transaction {
ChapterMetaTable.select { ChapterMetaTable.ref inList chapterIds }
.groupBy { it[ChapterMetaTable.ref] }
.mapValues { it.value.associate { it[ChapterMetaTable.key] to it[ChapterMetaTable.value] } }
.withDefault { emptyMap<String, String>() }
}
}

fun getChapterMetaMap(chapter: EntityID<Int>): Map<String, String> {
return transaction {
ChapterMetaTable.select { ChapterMetaTable.ref eq chapter }
Expand Down

0 comments on commit a9e5bc0

Please sign in to comment.