Skip to content

Commit

Permalink
Add an index on tracks (album_id)
Browse files Browse the repository at this point in the history
use subqueries instead of a left join
  • Loading branch information
lomereiter committed May 25, 2024
1 parent 259be0e commit 7e39221
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
7 changes: 7 additions & 0 deletions db/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func (db *DB) Migrate(ctx MigrationContext) error {
construct(ctx, "202311072309", migrateAlbumInfo),
construct(ctx, "202311082304", migrateTemporaryDisplayAlbumArtist),
construct(ctx, "202312110003", migrateAddExtraIndexes),
construct(ctx, "202405251900", migrateTrackAddIndexOnAlbumID),
}

return gormigrate.
Expand Down Expand Up @@ -813,3 +814,9 @@ func migrateAddExtraIndexes(tx *gorm.DB, _ MigrationContext) error {
CREATE INDEX idx_artist_appearances_album_id ON "artist_appearances" (album_id);
`).Error
}

func migrateTrackAddIndexOnAlbumID(tx *gorm.DB, _ MigrationContext) error {
return tx.Exec(`
CREATE INDEX idx_tracks_album_id ON "tracks" (album_id, length);
`).Error
}
5 changes: 3 additions & 2 deletions server/ctrlsubsonic/handlers_by_folder.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,9 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
// TODO: think about removing this extra join to count number
// of children. it might make sense to store that in the db
q.
Select("albums.*, count(tracks.id) child_count, sum(tracks.length) duration").
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Select(`albums.*,
(SELECT count(*) FROM tracks WHERE album_id = albums.id) child_count,
(SELECT sum(length) FROM tracks WHERE album_id = albums.id) duration`).
Group("albums.id").
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
Offset(params.GetOrInt("offset", 0)).
Expand Down
2 changes: 1 addition & 1 deletion server/ctrlsubsonic/handlers_internet_radio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func runTestCase(t *testing.T, h handlerSubsonic, q url.Values, admin bool) *spe
}

var jsonUnmarshalTypeError *json.UnmarshalTypeError
if errors.As(err, &jsonSyntaxError) {
if errors.As(err, &jsonUnmarshalTypeError) {
t.Fatalf("invalid type at offset %v\n %s <--", jsonUnmarshalTypeError.Offset, body[0:jsonUnmarshalTypeError.Offset])
}

Expand Down

0 comments on commit 7e39221

Please sign in to comment.