Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use covering indexes #592

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 32 additions & 7 deletions core/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ pub struct Index {
pub root_page: usize,
pub columns: Vec<IndexColumn>,
pub unique: bool,
pub index_cover_mapping: HashMap<usize, usize>,
}

#[allow(dead_code)]
Expand All @@ -474,7 +475,11 @@ pub enum Order {
}

impl Index {
pub fn from_sql(sql: &str, root_page: usize) -> Result<Index> {
pub fn from_sql(
sql: &str,
tables: &HashMap<String, Rc<BTreeTable>>,
root_page: usize,
) -> Result<Index> {
let mut parser = Parser::new(sql.as_bytes());
let cmd = parser.next()?;
match cmd {
Expand All @@ -485,24 +490,44 @@ impl Index {
unique,
..
})) => {
let table_name = normalize_ident(&tbl_name.0);
let Some((_, table)) = tables.iter().find(|(t_name, _)| t_name == &&table_name)
else {
crate::bail_corrupt_error!("Parse error: no such table: {}", tbl_name);
};
let mut index_cover_mapping = HashMap::with_capacity(columns.len());
let index_name = normalize_ident(&idx_name.name.0);
let index_columns = columns
.into_iter()
.map(|col| IndexColumn {
name: normalize_ident(&col.expr.to_string()),

let mut index_columns = Vec::with_capacity(columns.len());

for (i, col) in columns.into_iter().enumerate() {
let column_name = normalize_ident(&col.expr.to_string());
// SAFETY: the column in the index must exist in the table
let (pos, _) = table.get_column(&column_name).unwrap();
index_cover_mapping.insert(pos, i);
index_columns.push(IndexColumn {
name: column_name,
order: match col.order {
Some(sqlite3_parser::ast::SortOrder::Asc) => Order::Ascending,
Some(sqlite3_parser::ast::SortOrder::Desc) => Order::Descending,
None => Order::Ascending,
},
})
.collect();
}
if let Some(pos) = table
.columns
.iter()
.position(|column| column.is_rowid_alias)
{
index_cover_mapping.insert(pos, index_cover_mapping.len());
}
Ok(Index {
name: index_name,
table_name: normalize_ident(&tbl_name.0),
table_name,
root_page,
columns: index_columns,
unique,
index_cover_mapping,
})
}
_ => todo!("Expected create index statement"),
Expand Down
105 changes: 74 additions & 31 deletions core/translate/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,34 +664,26 @@ fn init_source(
search,
..
} => {
let table_cursor_id = program.alloc_cursor_id(
Some(table_reference.table_identifier.clone()),
Some(table_reference.table.clone()),
);
let mut is_cover = false;

match mode {
OperationMode::SELECT => {
program.emit_insn(Insn::OpenReadAsync {
cursor_id: table_cursor_id,
root_page: table_reference.table.get_root_page(),
});
program.emit_insn(Insn::OpenReadAwait {});
}
OperationMode::DELETE => {
program.emit_insn(Insn::OpenWriteAsync {
cursor_id: table_cursor_id,
root_page: table_reference.table.get_root_page(),
});
program.emit_insn(Insn::OpenWriteAwait {});
}
_ => {
unimplemented!()
}
}

if let Search::IndexSearch { index, .. } = search {
let index_cursor_id = program
.alloc_cursor_id(Some(index.name.clone()), Some(Table::Index(index.clone())));
if let Search::IndexSearch {
index,
cover_mapping,
..
} = search
{
let index_cursor_id = if cover_mapping.is_some() {
is_cover = true;
program.alloc_cursor_id(
Some(table_reference.table_identifier.clone()),
Some(Table::Index(index.clone())),
)
} else {
program.alloc_cursor_id(
Some(index.name.clone()),
Some(Table::Index(index.clone())),
)
};

match mode {
OperationMode::SELECT => {
Expand All @@ -714,6 +706,33 @@ fn init_source(
}
}

if !is_cover {
let table_cursor_id = program.alloc_cursor_id(
Some(table_reference.table_identifier.clone()),
Some(table_reference.table.clone()),
);

match mode {
OperationMode::SELECT => {
program.emit_insn(Insn::OpenReadAsync {
cursor_id: table_cursor_id,
root_page: table_reference.table.get_root_page(),
});
program.emit_insn(Insn::OpenReadAwait {});
}
OperationMode::DELETE => {
program.emit_insn(Insn::OpenWriteAsync {
cursor_id: table_cursor_id,
root_page: table_reference.table.get_root_page(),
});
program.emit_insn(Insn::OpenWriteAwait {});
}
_ => {
unimplemented!()
}
}
}

Ok(())
}
SourceOperator::Nothing { .. } => Ok(()),
Expand Down Expand Up @@ -921,6 +940,7 @@ fn open_loop(
predicates,
..
} => {
let mut is_index_cover = false;
let table_cursor_id = program.resolve_cursor_id(&table_reference.table_identifier);
let loop_labels = metadata
.loop_labels
Expand All @@ -929,8 +949,21 @@ fn open_loop(
// Open the loop for the index search.
// Rowid equality point lookups are handled with a SeekRowid instruction which does not loop, since it is a single row lookup.
if !matches!(search, Search::RowidEq { .. }) {
let index_cursor_id = if let Search::IndexSearch { index, .. } = search {
Some(program.resolve_cursor_id(&index.name))
let index_cursor_id = if let Search::IndexSearch {
index,
cover_mapping,
..
} = search
{
if let Some(cover_mapping) = &cover_mapping {
program
.table_remapping_cursors
.insert(table_cursor_id, cover_mapping.clone());
is_index_cover = true;
Some(table_cursor_id)
} else {
Some(program.resolve_cursor_id(&index.name))
}
} else {
None
};
Expand Down Expand Up @@ -1069,7 +1102,7 @@ fn open_loop(
_ => {}
}

if let Some(index_cursor_id) = index_cursor_id {
if let (Some(index_cursor_id), false) = (index_cursor_id, is_index_cover) {
program.emit_insn(Insn::DeferredSeek {
index_cursor_id,
table_cursor_id,
Expand Down Expand Up @@ -1459,7 +1492,17 @@ fn close_loop(
return Ok(());
}
let cursor_id = match search {
Search::IndexSearch { index, .. } => program.resolve_cursor_id(&index.name),
Search::IndexSearch {
index,
cover_mapping,
..
} => {
if cover_mapping.is_some() {
program.resolve_cursor_id(&table_reference.table_identifier)
} else {
program.resolve_cursor_id(&index.name)
}
}
Search::RowidSearch { .. } => {
program.resolve_cursor_id(&table_reference.table_identifier)
}
Expand Down
10 changes: 9 additions & 1 deletion core/translate/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1967,7 +1967,14 @@ pub fn translate_expr(
// the table and read the column from the cursor.
TableReferenceType::BTreeTable => {
let cursor_id = program.resolve_cursor_id(&tbl_ref.table_identifier);
if *is_rowid_alias {
if let Some(columns_mapping) = program.table_remapping_cursors.get(&cursor_id) {
// FIXME: row_id is displayed as `column` in explain
program.emit_insn(Insn::Column {
cursor_id,
column: columns_mapping[column],
dest: target_register,
});
} else if *is_rowid_alias {
program.emit_insn(Insn::RowId {
cursor_id,
dest: target_register,
Expand All @@ -1979,6 +1986,7 @@ pub fn translate_expr(
dest: target_register,
});
}

let column = tbl_ref.table.get_column_at(*column);
maybe_apply_affinity(column.ty, target_register, program);
Ok(target_register)
Expand Down
Loading