Skip to content

Commit

Permalink
Merge 'fix: index seek wrong on SeekOp::LT\SeekOp::GT' from Kould
Browse files Browse the repository at this point in the history
data does not match predicate when using index, e.g: `select id, age
from users where age > 90 limit 1;` will return data with age  90
the reason is that the current index seek directly uses record for
comparison, but the record of the index itself is longer than the record
of the key (because it contains the primary key), so Gt is invalid.
since only single-column indexes are currently supported:
#350, only the first value of
the record is currently used for comparison.

Reviewed-by: Jussi Saurio <[email protected]>

Closes #593
  • Loading branch information
jussisaurio committed Jan 3, 2025
2 parents 90d01f4 + a339840 commit 0fefffb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 10 additions & 3 deletions core/storage/btree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ impl BTreeCursor {
/// Move the cursor to the record that matches the seek key and seek operation.
/// This may be used to seek to a specific record in a point query (e.g. SELECT * FROM table WHERE col = 10)
/// or e.g. find the first record greater than the seek key in a range query (e.g. SELECT * FROM table WHERE col > 10).
/// We don't include the rowid in the comparison and that's why the last value from the record is not included.
fn seek(
&mut self,
key: SeekKey<'_>,
Expand Down Expand Up @@ -464,9 +465,15 @@ impl BTreeCursor {
};
let record = crate::storage::sqlite3_ondisk::read_record(payload)?;
let found = match op {
SeekOp::GT => record > *index_key,
SeekOp::GE => record >= *index_key,
SeekOp::EQ => record == *index_key,
SeekOp::GT => {
&record.values[..record.values.len() - 1] > &index_key.values
}
SeekOp::GE => {
&record.values[..record.values.len() - 1] >= &index_key.values
}
SeekOp::EQ => {
&record.values[..record.values.len() - 1] == &index_key.values
}
};
self.stack.advance();
if found {
Expand Down
4 changes: 4 additions & 0 deletions testing/where.test
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,10 @@ do_execsql_test where-age-index-seek-regression-test-2 {
select count(1) from users where age > 0;
} {10000}

do_execsql_test where-age-index-seek-regression-test-3 {
select age from users where age > 90 limit 1;
} {91}

do_execsql_test where-simple-between {
SELECT * FROM products WHERE price BETWEEN 70 AND 100;
} {1|hat|79.0
Expand Down

0 comments on commit 0fefffb

Please sign in to comment.