Skip to content

Commit

Permalink
fix slow query bug when order by other fields (#838)
Browse files Browse the repository at this point in the history
* Revert "Optimize slow-query list (#835)"

This reverts commit 585dc7e.

* fix slow query order by

Signed-off-by: crazycs520 <[email protected]>

* add comment

Signed-off-by: crazycs520 <[email protected]>
  • Loading branch information
crazycs520 authored Jan 8, 2021
1 parent 2b3274c commit 4f41dd6
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions pkg/apiserver/slowquery/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,29 @@ func QuerySlowLogList(db *gorm.DB, req *GetListRequest) ([]SlowQuery, error) {
tx = tx.Where("DB IN (?)", req.DB)
}

// more robust
if req.OrderBy == "" {
req.OrderBy = "timestamp"
}

order, err := getProjectionsByFields(req.OrderBy)
if err != nil {
return nil, err
}
// to handle the special case: timestamp
// if req.OrderBy is "timestamp", then the order is "(unix_timestamp(Time) + 0E0) AS timestamp"
if strings.Contains(order[0], " AS ") {
order[0] = req.OrderBy
}
if order[0] == "timestamp" {
// Order by column instead of expression, see related optimization in TiDB: https://github.com/pingcap/tidb/pull/20750
order[0] = "Time"
}

if req.IsDesc {
tx = tx.Order("Time DESC")
tx = tx.Order(fmt.Sprintf("%s DESC", order[0]))
} else {
tx = tx.Order("Time ASC")
tx = tx.Order(fmt.Sprintf("%s ASC", order[0]))
}

if len(req.Plans) > 0 {
Expand Down

0 comments on commit 4f41dd6

Please sign in to comment.