Skip to content

Commit

Permalink
Use index hint for idx_contracts_fcid_timestamp, MySQL does not sel…
Browse files Browse the repository at this point in the history
…ect it otherwise (#1059)

I was still seeing `SLOW SQL` warnings for `SELECT * FROM contracts
WHERE contracts.timestamp >= 1709984700000 AND contracts.timestamp <
1710071100000 AND contracts.fcid = '<binary>' LIMIT 1`, after
`EXPLAIN`ing I found that `MySQL` doesn't use the index we added.
  • Loading branch information
ChrisSchinnerl authored Mar 19, 2024
2 parents 4945ce9 + c7a8ef1 commit c3bdef6
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion stores/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -555,11 +555,16 @@ func (s *SQLStore) findAggregatedContractPeriods(ctx context.Context, start time
return fmt.Errorf("failed to fetch distinct contract ids: %w", err)
}

var indexHint string
if !isSQLite(tx) {
indexHint = "USE INDEX (idx_contracts_fcid_timestamp)"
}

for intervalStart := start; intervalStart.Before(end); intervalStart = intervalStart.Add(interval) {
intervalEnd := intervalStart.Add(interval)
for _, fcid := range fcids {
var metrics []dbContractMetric
err := tx.Raw("SELECT * FROM contracts WHERE contracts.timestamp >= ? AND contracts.timestamp < ? AND contracts.fcid = ? LIMIT 1", unixTimeMS(intervalStart), unixTimeMS(intervalEnd), fileContractID(fcid)).
err := tx.Raw(fmt.Sprintf("SELECT * FROM contracts %s WHERE contracts.timestamp >= ? AND contracts.timestamp < ? AND contracts.fcid = ? LIMIT 1", indexHint), unixTimeMS(intervalStart), unixTimeMS(intervalEnd), fileContractID(fcid)).
Scan(&metrics).Error
if err != nil {
return fmt.Errorf("failed to fetch contract metrics: %w", err)
Expand Down

0 comments on commit c3bdef6

Please sign in to comment.