Skip to content

Commit

Permalink
Fix SQL query for MySQL/Postgres on user profile (#424)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomiceli authored Feb 3, 2025
1 parent c14380f commit 87ae60c
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 12 deletions.
11 changes: 2 additions & 9 deletions internal/db/gist.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,6 @@ func GetAllGistsFromSearch(currentUserId uint, query string, offset int, sort st
}

func gistsFromUserStatement(fromUserId uint, currentUserId uint) *gorm.DB {
return db.
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
Joins("join users on gists.user_id = users.id")
}

func gistsFromUserStatementWithPreloads(fromUserId uint, currentUserId uint) *gorm.DB {
return db.Preload("User").Preload("Forked.User").Preload("Topics").
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
Expand All @@ -185,7 +178,7 @@ func GetAllGistsFromUser(fromUserId uint, currentUserId uint, title string, lang
var gists []*Gist
var count int64

baseQuery := gistsFromUserStatementWithPreloads(fromUserId, currentUserId).Model(&Gist{})
baseQuery := gistsFromUserStatement(fromUserId, currentUserId).Model(&Gist{})

if title != "" {
baseQuery = baseQuery.Where("gists.title like ?", "%"+title+"%")
Expand Down Expand Up @@ -220,7 +213,7 @@ func GetAllGistsFromUser(fromUserId uint, currentUserId uint, title string, lang

func CountAllGistsFromUser(fromUserId uint, currentUserId uint) (int64, error) {
var count int64
err := gistsFromUserStatementWithPreloads(fromUserId, currentUserId).Model(&Gist{}).Count(&count).Error
err := gistsFromUserStatement(fromUserId, currentUserId).Model(&Gist{}).Count(&count).Error
return count, err
}

Expand Down
8 changes: 5 additions & 3 deletions internal/db/gist_language.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ func GetGistLanguagesForUser(fromUserId, currentUserId uint) ([]struct {
Count int64
}

err := gistsFromUserStatement(fromUserId, currentUserId).Model(&GistLanguage{}).
err := db.Model(&GistLanguage{}).
Select("language, count(*) as count").
Joins("JOIN gists ON gists.id = gist_languages.gist_id").
Where("gists.user_id = ?", fromUserId).
Joins("JOIN users ON gists.user_id = users.id").
Where("((gists.private = 0) or (gists.private > 0 and gists.user_id = ?))", currentUserId).
Where("users.id = ?", fromUserId).
Group("language").
Order("count DESC").
Limit(15). // Added limit of 15
Limit(15).
Find(&results).Error

return results, err
Expand Down

0 comments on commit 87ae60c

Please sign in to comment.