Skip to content

Commit b330252

Browse files
authored
Merge pull request #1430 from mattn/fix-vtable-estimated-cost
Do not clobber SQLite's default cost estimates in BestIndex
2 parents 3babc1f + 2897b83 commit b330252

1 file changed

Lines changed: 17 additions & 2 deletions

File tree

sqlite3_opt_vtable.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -485,8 +485,23 @@ func goVBestIndex(pVTab unsafe.Pointer, icp unsafe.Pointer) *C.char {
485485
if res.AlreadyOrdered {
486486
info.orderByConsumed = C.int(1)
487487
}
488-
info.estimatedCost = C.double(res.EstimatedCost)
489-
info.estimatedRows = C.sqlite3_int64(res.EstimatedRows)
488+
// SQLite pre-initializes estimatedCost and estimatedRows with sensible
489+
// defaults; overwriting them with the Go zero value would make every
490+
// candidate plan look free and break query planning, so only pass
491+
// values the implementation actually set.
492+
if res.EstimatedCost > 0 {
493+
info.estimatedCost = C.double(res.EstimatedCost)
494+
}
495+
if res.EstimatedRows > 0 {
496+
var rows int64
497+
if res.EstimatedRows >= float64(math.MaxInt64) {
498+
rows = math.MaxInt64
499+
} else if rows = int64(res.EstimatedRows); rows < 1 {
500+
// A positive fractional estimate must not truncate to 0.
501+
rows = 1
502+
}
503+
info.estimatedRows = C.sqlite3_int64(rows)
504+
}
490505

491506
return nil
492507
}

0 commit comments

Comments
 (0)