diff --git a/docs/features.md b/docs/features.md index 0f2ab69e..93f437c9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -251,6 +251,7 @@ If `unsafe_txdb_checkpoint` is not enabled, `build_rocksdb()` returns an explici - Unique - Normal - Composite +- Prefix: `col(n)` in `UNIQUE` constraints and `CREATE INDEX` indexes the first `n` characters of a string or the first `n` bytes of a binary value. Other types and primary key prefixes are rejected. Prefix indexes cannot cover queries; equality candidates are checked against the full row. ### Supports multiple primary key types - Tinyint diff --git a/src/binder/create_index.rs b/src/binder/create_index.rs index a0345b5b..f015af9e 100644 --- a/src/binder/create_index.rs +++ b/src/binder/create_index.rs @@ -13,14 +13,10 @@ // limitations under the License. use crate::binder::{Binder, Source}; -use crate::catalog::ColumnRef; use crate::errors::DatabaseError; -use crate::planner::operator::create_index::CreateIndexOperator; use crate::planner::operator::table_scan::TableScanOperator; -use crate::planner::operator::Operator; -use crate::planner::{Childrens, LogicalPlan}; +use crate::planner::LogicalPlan; use crate::storage::StorageTransaction; -use crate::types::index::IndexType; use crate::types::LogicalType; impl> Binder<'_, '_, T, A> { @@ -41,33 +37,4 @@ impl> Binder<'_, '_, T, )), } } - - pub(crate) fn bind_create_index( - &mut self, - table_name: &str, - index_name: String, - columns: Vec, - if_not_exists: bool, - is_unique: bool, - input: LogicalPlan, - ) -> Result { - let ty = if is_unique { - IndexType::Unique - } else if columns.len() == 1 { - IndexType::Normal - } else { - IndexType::Composite - }; - - Ok(LogicalPlan::new( - Operator::CreateIndex(CreateIndexOperator { - table_id: self.context.table_id(table_name)?, - columns, - index_name, - if_not_exists, - ty, - }), - Childrens::Only(Box::new(input)), - )) - } } diff --git a/src/binder/create_table.rs b/src/binder/create_table.rs index 63c5c629..3f06a140 100644 --- a/src/binder/create_table.rs +++ b/src/binder/create_table.rs @@ -15,7 +15,7 @@ use super::{is_valid_identifier, Binder}; use crate::catalog::{ColumnCatalog, TableName}; use crate::errors::DatabaseError; -use crate::planner::operator::create_table::CreateTableOperator; +use crate::planner::operator::create_table::{CreateTableOperator, UniqueKey}; use crate::planner::operator::Operator; use crate::planner::{Childrens, LogicalPlan}; use crate::storage::StorageTransaction; @@ -27,7 +27,7 @@ impl> Binder<'_, '_, T, &mut self, table_name: TableName, columns: Vec, - composite_unique_keys: Vec>, + composite_unique_keys: Vec, if_not_exists: bool, ) -> Result { let mut names = HashSet::new(); @@ -68,6 +68,7 @@ mod tests { use crate::binder::BinderContext; use crate::catalog::ColumnDesc; use crate::storage::Storage; + use crate::types::index::IndexValType; use crate::types::value::DataValue; use crate::types::CharLengthUnits; use crate::types::LogicalType; @@ -84,7 +85,7 @@ mod tests { let dialect = crate::dialect::GenericSqlDialect::new(); let sql = "create table t1 (id int primary key default 5 null, \ - name varchar(10) null, unique (name, id))"; + name varchar(10) null, unique (name, id), unique (name(3)))"; let mut binder = Binder::new( BinderContext::new( &names, @@ -104,10 +105,23 @@ mod tests { let mut plan_arena = crate::planner::PlanArena::new(&table_arena); let plan1 = binder.bind(&stmt, &mut plan_arena).unwrap(); + let name_ty = LogicalType::Varchar(Some(10), CharLengthUnits::Characters); match plan1.operator { Operator::CreateTable(op) => { assert_eq!(op.table_name, "t1"); - assert_eq!(op.composite_unique_keys, vec![vec![1, 0]]); + assert_eq!( + op.composite_unique_keys, + vec![ + UniqueKey { + column_positions: vec![1, 0], + index_val_ty: vec![name_ty.clone().into(), LogicalType::Integer.into()], + }, + UniqueKey { + column_positions: vec![1], + index_val_ty: vec![IndexValType::new(name_ty, Some(3))?], + }, + ] + ); let id = &op.columns[0]; assert_eq!(id.name(), "id"); assert!(!id.nullable()); diff --git a/src/binder/parser.rs b/src/binder/parser.rs index c29625a0..fc4ef6c2 100644 --- a/src/binder/parser.rs +++ b/src/binder/parser.rs @@ -35,6 +35,8 @@ use crate::expression::{AliasType, ScalarExpression, TypeCast}; use crate::iter_ext::Itertools; use crate::parser::parse_sql_with_recursion_limit; use crate::planner::operator::alter_table::change_column::{DefaultChange, NotNullChange}; +use crate::planner::operator::create_index::CreateIndexOperator; +use crate::planner::operator::create_table::UniqueKey; use crate::planner::operator::join::{JoinCondition, JoinOperator as LJoinOperator, JoinType}; use crate::planner::operator::mark_apply::MarkApplyQuantifier; use crate::planner::operator::project::ProjectOperator; @@ -44,6 +46,7 @@ use crate::planner::operator::{CommandType, Operator}; use crate::planner::MetaArena; use crate::planner::{Childrens, ExprRef, LogicalPlan, PlanArena}; use crate::storage::{Storage, StorageTransaction}; +use crate::types::index::IndexValType; use crate::types::value::{DataValue, Utf8Type}; use crate::types::{CharLengthUnits, ColumnId, LogicalType}; pub(super) use sqlparser::ast::{ @@ -815,18 +818,41 @@ where for constraint in create.constraints { match constraint { TableConstraint::PrimaryKey(primary) => { - let positions = Self::constraint_columns(&columns, primary.columns)?; - for (i, position) in positions.into_iter().enumerate() { + for (i, part) in primary.columns.iter().enumerate() { + let (position, prefix_len) = Self::constraint_column(&columns, part)?; + if prefix_len.is_some() { + return Err(DatabaseError::UnsupportedStmt( + "PRIMARY KEY index prefixes".into(), + )); + } columns[position].desc_mut().set_primary(Some(i)); } } TableConstraint::Unique(unique) => { Self::check_unique_nulls_option(unique.nulls_distinct)?; - let positions = Self::constraint_columns(&columns, unique.columns)?; - match positions.as_slice() { + match unique.columns.as_slice() { [] => return Err(DatabaseError::InvalidIndex), - [position] => columns[*position].desc_mut().set_unique(), - _ => composite_unique_keys.push(positions), + [part] if matches!(part.column.expr, Expr::Identifier(_)) => { + let (position, _) = Self::constraint_column(&columns, part)?; + columns[position].desc_mut().set_unique(); + } + parts => { + let mut column_positions = Vec::with_capacity(parts.len()); + let mut index_val_ty = Vec::with_capacity(parts.len()); + for part in parts { + let (position, prefix_len) = + Self::constraint_column(&columns, part)?; + column_positions.push(position); + index_val_ty.push(IndexValType::new( + columns[position].datatype().clone(), + prefix_len, + )?); + } + composite_unique_keys.push(UniqueKey { + column_positions, + index_val_ty, + }); + } } } constraint => { @@ -911,30 +937,31 @@ where Ok(()) } - fn constraint_columns( + fn constraint_column( table_columns: &[ColumnCatalog], - index_columns: Vec, - ) -> Result, DatabaseError> { - let mut positions = Vec::with_capacity(index_columns.len()); - for index_column in index_columns { - let Expr::Identifier(ident) = index_column.column.expr else { - return Err(DatabaseError::UnsupportedStmt( - "only identifier columns are supported in `PRIMARY KEY/UNIQUE`".to_string(), - )); - }; - let column_name = lower_ident(&ident); - let position = table_columns - .iter() - .position(|column| column.name() == column_name.as_ref()) - .ok_or_else(|| { - attach_span_if_absent( - DatabaseError::column_not_found(column_name.into_owned()), - ident.span, - ) - })?; - positions.push(position); - } - Ok(positions) + index_column: &IndexColumn, + ) -> Result<(usize, Option), DatabaseError> { + let expr = &index_column.column.expr; + let part = match expr { + Expr::Identifier(ident) => Some((ident, None)), + _ => prefix_key_part(expr).map(|(ident, len)| (ident, Some(len))), + }; + let (ident, prefix_len) = part.ok_or_else(|| { + DatabaseError::UnsupportedStmt( + "only identifier columns are supported in `PRIMARY KEY/UNIQUE`".into(), + ) + })?; + let column_name = lower_ident(ident); + let position = table_columns + .iter() + .position(|column| column.name() == column_name.as_ref()) + .ok_or_else(|| { + attach_span_if_absent( + DatabaseError::column_not_found(column_name.into_owned()), + ident.span, + ) + })?; + Ok((position, prefix_len)) } fn create_index(self, create: CreateIndex) -> Result { @@ -965,9 +992,8 @@ where let input = self .binder .bind_create_index_source(&table_name, self.arena)?; - let mut columns = Vec::with_capacity(create.columns.len()); - - for index_column in create.columns { + let table_id = self.binder.context.table_id(&table_name)?; + let key_parts = create.columns.into_iter().map(|index_column| { if index_column.operator_class.is_some() || index_column.column.options.asc == Some(false) || index_column.column.options.nulls_first.is_some() @@ -977,23 +1003,29 @@ where "CREATE INDEX column options".to_string(), )); } - let expr = self - .binder - .bind_expr(&index_column.column.expr, self.arena)?; - match &expr { - ScalarExpression::ColumnRef { column, .. } => columns.push(*column), - _ => { - return Err(DatabaseError::UnsupportedStmt(format!( - "'CREATE INDEX' by {expr:?}" - ))) - } - } - } + let ast = &index_column.column.expr; + let (expr, prefix_len) = match prefix_key_part(ast) { + Some((ident, len)) => ( + self.binder + .bind_expr(&Expr::Identifier(ident.clone()), self.arena)?, + Some(len), + ), + None => (self.binder.bind_expr(ast, self.arena)?, None), + }; + let ScalarExpression::ColumnRef { column, .. } = expr else { + return Err(DatabaseError::UnsupportedStmt(format!( + "'CREATE INDEX' by {expr:?}" + ))); + }; + let key_ty = + IndexValType::new(self.arena.column(column).datatype().clone(), prefix_len)?; + Ok((column, key_ty)) + }); - self.binder.bind_create_index( - &table_name, + CreateIndexOperator::build( + table_id, index_name, - columns, + key_parts, create.if_not_exists, create.unique, input, @@ -2006,6 +2038,36 @@ fn sql_object_name(name: ObjectName) -> Result { Ok(lower_case_name(&name)?.into_owned()) } +/// A prefix key part `col(n)` parses as a call. +fn prefix_key_part(expr: &Expr) -> Option<(&Ident, u32)> { + let Expr::Function(func) = expr else { + return None; + }; + let [ObjectNamePart::Identifier(ident)] = func.name.0.as_slice() else { + return None; + }; + let FunctionArguments::List(list) = &func.args else { + return None; + }; + let [FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(value)))] = list.args.as_slice() + else { + return None; + }; + let Value::Number(length, false) = &value.value else { + return None; + }; + let length = length.parse::().ok().filter(|len| *len > 0)?; + let is_plain_call = !func.uses_odbc_syntax + && matches!(func.parameters, FunctionArguments::None) + && list.duplicate_treatment.is_none() + && list.clauses.is_empty() + && func.filter.is_none() + && func.null_treatment.is_none() + && func.over.is_none() + && func.within_group.is_empty(); + is_plain_call.then_some((ident, length)) +} + pub(super) fn lower_ident(ident: &Ident) -> Cow<'_, str> { let value = &ident.value; diff --git a/src/catalog/table.rs b/src/catalog/table.rs index 7eb5be15..adb354aa 100644 --- a/src/catalog/table.rs +++ b/src/catalog/table.rs @@ -17,7 +17,7 @@ use crate::errors::DatabaseError; use crate::expression::ScalarExpression; use crate::iter_ext::Itertools; use crate::planner::{ExprRef, MetaArena, PlanArena}; -use crate::types::index::{IndexMeta, IndexMetaRef, IndexType}; +use crate::types::index::{IndexMeta, IndexMetaRef, IndexType, IndexValType}; use crate::types::serialize::TupleValueSerializableImpl; use crate::types::tuple::Schema; use crate::types::{ColumnId, LogicalType}; @@ -205,6 +205,7 @@ impl TableCatalog { &mut self, name: String, column_ids: Vec, + value_ty: Vec, ty: IndexType, arena: &mut (impl MetaArena + ?Sized), ) -> Result { @@ -219,29 +220,11 @@ impl TableCatalog { .last() .map(|index| arena.index(*index).id + 1) .unwrap_or(0); - let pk_ty = self.primary_key_type.clone(); - - let mut val_tys = Vec::with_capacity(column_ids.len()); - for column_id in column_ids.iter() { - let val_ty = self - .get_column_by_id(column_id) - .map(|(_, column)| arena.column(column)) - .ok_or_else(|| DatabaseError::column_not_found(column_id.to_string()))? - .datatype() - .clone(); - val_tys.push(val_ty) - } - let value_ty = if val_tys.len() == 1 { - val_tys.pop().unwrap() - } else { - LogicalType::Tuple(val_tys) - }; - let index = IndexMeta { id: index_id, column_ids, table_id: self.id, - pk_ty, + pk_ty: self.primary_key_type.clone(), value_ty, name, ty, @@ -277,7 +260,7 @@ impl TableCatalog { let (primary_keys, primary_key_indices) = Self::build_primary_keys(&table_catalog.column_refs, arena); - table_catalog.primary_key_type = Self::build_primary_key_type(&primary_keys, arena); + table_catalog.primary_key_type = Self::build_primary_key_type(&primary_keys, arena)?; table_catalog.primary_keys = primary_keys; table_catalog.primary_key_indices = primary_key_indices; @@ -287,17 +270,12 @@ impl TableCatalog { fn build_primary_key_type( primary_keys: &[(usize, ColumnRef)], arena: &(impl MetaArena + ?Sized), - ) -> LogicalType { - if primary_keys.len() == 1 { - arena.column(primary_keys[0].1).datatype().clone() - } else { - LogicalType::Tuple( - primary_keys - .iter() - .map(|(_, column)| arena.column(*column).datatype().clone()) - .collect_vec(), - ) - } + ) -> Result { + LogicalType::from_key_types( + primary_keys + .iter() + .map(|(_, column)| Ok(arena.column(*column).datatype().clone())), + ) } pub(crate) fn reload( @@ -327,7 +305,7 @@ impl TableCatalog { } let indexes = indexes.map(|index| arena.alloc_index(index)).collect(); let (primary_keys, primary_key_indices) = Self::build_primary_keys(&column_refs, arena); - let primary_key_type = Self::build_primary_key_type(&primary_keys, arena); + let primary_key_type = Self::build_primary_key_type(&primary_keys, arena)?; Ok(TableCatalog { id, diff --git a/src/db/program.rs b/src/db/program.rs index f0d4275f..1c111aca 100644 --- a/src/db/program.rs +++ b/src/db/program.rs @@ -343,7 +343,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "pk".into(), ty: IndexType::PrimaryKey { is_multiple: false }, }); @@ -422,7 +422,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "other".into(), ty: IndexType::Normal, }); diff --git a/src/execution/ddl/create_index.rs b/src/execution/ddl/create_index.rs index dd9bbfeb..00f04b60 100644 --- a/src/execution/ddl/create_index.rs +++ b/src/execution/ddl/create_index.rs @@ -24,7 +24,6 @@ use crate::storage::StorageTransaction; use crate::types::index::Index; use crate::types::tuple::Schema; use crate::types::value::DataValue; -use crate::types::ColumnId; pub struct CreateIndex<'a> { op: &'a CreateIndexOperator, @@ -69,6 +68,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for CreateIndex<'a> { table_id, index_name, columns, + index_val_ty, if_not_exists, ty, } = self.op; @@ -86,37 +86,41 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for CreateIndex<'a> { return Ok(()); } - let (column_ids, column_exprs): (Vec, Vec) = columns - .iter() - .copied() - .filter_map(|column| { - plan_arena.column(column).id().and_then(|id| { - self.input_schema - .iter() - .position(|schema_column| schema_column == &column) - .map(|position| (id, ScalarExpression::column_expr(column, position))) - }) - }) - .unzip(); + let mut column_ids = Vec::with_capacity(columns.len()); + let mut column_exprs = Vec::with_capacity(columns.len()); + for &column in columns { + let id = plan_arena + .column(column) + .id() + .ok_or(DatabaseError::InvalidIndex)?; + let position = self + .input_schema + .iter() + .position(|c| *c == column) + .ok_or(DatabaseError::InvalidIndex)?; + column_ids.push(id); + column_exprs.push(ScalarExpression::column_expr(column, position)); + } let index_id_result = { let mut decode = arena.decode_context(); let (transaction, table_codec) = arena.transaction_codec_mut(); - let (table, index_id) = transaction + let (table, index_meta) = transaction .add_index_meta( table_codec, plan_arena, table_catalog.name(), index_name.clone(), column_ids, + index_val_ty.clone(), *ty, &mut decode, ) .await?; let table_id = table.id(); arena.push_ddl_apply(DDLApply::upsert_table(table, false)); - Ok((table_id, index_id)) + Ok((table_id, index_meta)) }; - let (table_id, index_id) = match index_id_result { + let (table_id, index_meta) = match index_id_result { Ok(ids) => ids, Err(DatabaseError::DuplicateIndex(index_name)) => { if *if_not_exists { @@ -138,7 +142,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for CreateIndex<'a> { let mut state = arena.local_state(plan_arena); let (tuple, transaction, table_codec) = state.tuple_transaction_codec_mut(); let tuple_pk = tuple.pk().ok_or(DatabaseError::PrimaryKeyNotFound)?; - let index = Index::new(index_id, tuple, *ty); + let index = Index::from_meta(plan_arena.index(index_meta), tuple); transaction .add_index(table_codec, table_id, index, tuple_pk) .await?; diff --git a/src/execution/dml/analyze.rs b/src/execution/dml/analyze.rs index c8a3fb79..23133603 100644 --- a/src/execution/dml/analyze.rs +++ b/src/execution/dml/analyze.rs @@ -28,11 +28,12 @@ use crate::planner::operator::analyze::AnalyzeOperator; use crate::planner::LogicalPlan; use crate::planner::{ExecMetaArena, MetaArena}; use crate::storage::{table_codec::TableCodec, StorageTransaction}; -use crate::types::index::IndexId; +use crate::types::index::{IndexId, IndexMetaRef}; use crate::types::tuple::TupleLike; use crate::types::value::{DataValue, Utf8Type}; use crate::types::{CharLengthUnits, ColumnId}; use ordered_float::OrderedFloat; +use std::borrow::Cow; use std::fmt::{self, Formatter}; use std::mem; @@ -125,13 +126,14 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Analyze<'a> { .collect::, DatabaseError>>()?; let indexes = table .indexes() - .map(|index| { - let index = plan_arena.index(*index); + .map(|&index_ref| { + let index = plan_arena.index(index_ref); let index_id = index.id; let builder = HistogramBuilder::new(index, relative_error, hll_precision)?; let exprs = index.column_exprs(table).collect::, _>>()?; Ok(State { index_id, + prefix_index: index.has_prefix().then_some(index_ref), exprs, builder, histogram_buckets: self.histogram_buckets, @@ -146,15 +148,25 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Analyze<'a> { for (_, position, builder) in &mut columns { builder.append(tuple.value_at(*position)); } - for State { exprs, builder, .. } in builders.iter_mut() { + for State { + exprs, + builder, + prefix_index, + .. + } in builders.iter_mut() + { let value = match exprs.as_slice() { - [expr] => expr.eval(plan_arena, Some(&tuple))?.into_owned(), + [expr] => expr.eval(plan_arena, Some(&tuple))?, _ => { arena.rewrite(exprs, plan_arena, Some(&tuple))?; - DataValue::Tuple(arena.result_mut().take_values()) + Cow::Owned(DataValue::Tuple(arena.result_mut().take_values())) } }; - builder.append(value)?; + let key = match prefix_index { + Some(index) => plan_arena.index(*index).truncate_key(value)?, + None => value.into_owned(), + }; + builder.append(key)?; } } let mut state = arena.local_state(plan_arena); @@ -178,6 +190,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Analyze<'a> { struct State { index_id: IndexId, + prefix_index: Option, exprs: Vec, builder: HistogramBuilder, histogram_buckets: Option, diff --git a/src/execution/dml/delete.rs b/src/execution/dml/delete.rs index 0fdf9857..e793e9af 100644 --- a/src/execution/dml/delete.rs +++ b/src/execution/dml/delete.rs @@ -85,12 +85,11 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Delete<'a> { IndexType::PrimaryKey { .. } ) }) - .map(|index_meta| { - let index_meta = plan_arena.index(*index_meta); + .map(|&index_meta| { Ok(( - index_meta.id, - index_meta.ty, - index_meta + index_meta, + plan_arena + .index(index_meta) .column_exprs(table) .collect::, _>>()?, )) @@ -104,11 +103,11 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Delete<'a> { let Some(tuple_id) = tuple.pk() else { continue; }; - for (index_id, index_ty, exprs) in index_templates.iter() { + for (index_meta, exprs) in index_templates.iter() { arena.rewrite(exprs, plan_arena, Some(&tuple))?; let mut state = arena.local_state(plan_arena); let (values, transaction, table_codec) = state.tuple_transaction_codec_mut(); - let index = Index::new(*index_id, values, *index_ty); + let index = Index::from_meta(plan_arena.index(*index_meta), values); transaction .del_index(table_codec, table_id, &index, tuple_id) .await?; diff --git a/src/execution/dml/insert.rs b/src/execution/dml/insert.rs index cac6bd0e..86b8d921 100644 --- a/src/execution/dml/insert.rs +++ b/src/execution/dml/insert.rs @@ -114,7 +114,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Insert<'a> { arena.rewrite(exprs, plan_arena, Some(&*tuple))?; let mut state = arena.local_state(plan_arena); let (values, transaction, table_codec) = state.tuple_transaction_codec_mut(); - let index = Index::new(index_meta.id, values, index_meta.ty); + let index = Index::from_meta(index_meta, values); transaction .add_index(table_codec, table.table_id, index, tuple_id) .await?; diff --git a/src/execution/dml/update.rs b/src/execution/dml/update.rs index be4af615..3e114df4 100644 --- a/src/execution/dml/update.rs +++ b/src/execution/dml/update.rs @@ -106,7 +106,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Update<'a> { arena.rewrite(exprs, plan_arena, Some(&tuple))?; let mut state = arena.local_state(plan_arena); let (values, transaction, table_codec) = state.tuple_transaction_codec_mut(); - let old_index = Index::new(index_meta.id, values, index_meta.ty); + let old_index = Index::from_meta(index_meta, values); transaction .del_index(table_codec, table.table_id, &old_index, &old_pk) .await?; @@ -131,7 +131,7 @@ impl<'a, T: StorageTransaction + 'a> ExecutorNode<'a, T> for Update<'a> { arena.rewrite(exprs, plan_arena, Some(&tuple))?; let mut state = arena.local_state(plan_arena); let (values, transaction, table_codec) = state.tuple_transaction_codec_mut(); - let new_index = Index::new(index_meta.id, values, index_meta.ty); + let new_index = Index::from_meta(index_meta, values); transaction .add_index(table_codec, table.table_id, new_index, &new_pk) .await?; diff --git a/src/expression/range_detacher.rs b/src/expression/range_detacher.rs index ed41d712..5f77adb0 100644 --- a/src/expression/range_detacher.rs +++ b/src/expression/range_detacher.rs @@ -636,7 +636,7 @@ impl<'a, A: MetaArena + ?Sized> RangeDetacher<'a, IndexRangeColumn, A> { if prefix_len >= index.column_ids.len() { return Ok(None); } - let composite = matches!(index.value_ty, LogicalType::Tuple(_)); + let composite = index.value_ty.len() > 1; let Range::Scope { min, max } = original else { return Ok(None); }; diff --git a/src/optimizer/core/histogram.rs b/src/optimizer/core/histogram.rs index 33bfbc9d..ef4cf4a2 100644 --- a/src/optimizer/core/histogram.rs +++ b/src/optimizer/core/histogram.rs @@ -155,10 +155,8 @@ impl HistogramBuilder { hll_precision: u8, ) -> Result { let mut meta = HistogramMetaBuilder::new(hll_precision)?; - if let LogicalType::Tuple(fields) = &index_meta.value_ty { - for _ in 1..fields.len() { - meta.hlls.push(HyperLogLog::with_precision(hll_precision)?); - } + for _ in 1..index_meta.value_ty.len() { + meta.hlls.push(HyperLogLog::with_precision(hll_precision)?); } Ok(Self { index_id: index_meta.id, @@ -911,7 +909,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "pk_c1".to_string(), ty: IndexType::PrimaryKey { is_multiple: false }, } @@ -919,7 +917,7 @@ mod tests { fn tuple_index_meta(len: usize) -> IndexMeta { IndexMeta { - value_ty: LogicalType::Tuple(vec![LogicalType::Integer; len]), + value_ty: vec![LogicalType::Integer.into(); len], ty: IndexType::PrimaryKey { is_multiple: true }, ..index_meta() } diff --git a/src/optimizer/core/statistics_meta.rs b/src/optimizer/core/statistics_meta.rs index a2b98204..513c3a44 100644 --- a/src/optimizer/core/statistics_meta.rs +++ b/src/optimizer/core/statistics_meta.rs @@ -176,7 +176,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "pk_c1".to_string(), ty: IndexType::PrimaryKey { is_multiple: false }, }; diff --git a/src/optimizer/rule/implementation/dql/table_scan.rs b/src/optimizer/rule/implementation/dql/table_scan.rs index 901e9c2e..873fe088 100644 --- a/src/optimizer/rule/implementation/dql/table_scan.rs +++ b/src/optimizer/rule/implementation/dql/table_scan.rs @@ -23,6 +23,7 @@ use crate::optimizer::rule::implementation::dql::filter::estimate_predicate_rows use crate::planner::operator::{Operator, PhysicalOption, PlanImpl, RowCountOption, SortOption}; use crate::planner::{LogicalPlan, PlanArena}; use crate::types::index::{IndexLookup, IndexMeta, IndexType}; +use std::borrow::Cow; use std::sync::LazyLock; static TABLE_SCAN_PATTERN: LazyLock = LazyLock::new(|| Pattern { @@ -114,14 +115,30 @@ impl ImplementationRule for IndexScanImplementation { let mut ndv = None; let index_meta = arena.index(index_info.meta); - // A complete, non-NULL unique key can match at most one row. - let counted = loader - .collect_count( - scan_op.table_id, - index_meta.id, - range, - &mut state.histogram_buf, - )? + let stats_range = match (index_meta.has_prefix(), range) { + (false, range) => Some(Cow::Borrowed(range)), + (true, Range::Eq(value)) if !value.has_parameter() => { + Some(Cow::Owned(Range::Eq( + index_meta + .truncate_key(Cow::Borrowed(value.value()?))? + .into(), + ))) + } + _ => None, + }; + let counted = stats_range + .as_deref() + .map(|range| { + loader.collect_count( + scan_op.table_id, + index_meta.id, + range, + &mut state.histogram_buf, + ) + }) + .transpose()? + .flatten() + // A complete, non-NULL unique key can match at most one row. .or_else(|| unique_eq_row_count(index_meta, range).map(|rows| (rows, rows))); if let Some((mut row_count, distinct_count)) = counted { row_count = adjust_index_row_count(index_meta, range, row_count); diff --git a/src/optimizer/rule/normalization/elimination.rs b/src/optimizer/rule/normalization/elimination.rs index 517ac646..69763077 100644 --- a/src/optimizer/rule/normalization/elimination.rs +++ b/src/optimizer/rule/normalization/elimination.rs @@ -1394,7 +1394,7 @@ mod tests { column_ids: (1..=len as ColumnId).collect(), table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx".to_string(), ty: IndexType::PrimaryKey { is_multiple: len > 1, @@ -1483,7 +1483,7 @@ mod tests { column_ids: vec![c1_id], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx".to_string(), ty: IndexType::PrimaryKey { is_multiple: false }, }), diff --git a/src/optimizer/rule/normalization/join_reorder.rs b/src/optimizer/rule/normalization/join_reorder.rs index 57851388..ee5e4611 100644 --- a/src/optimizer/rule/normalization/join_reorder.rs +++ b/src/optimizer/rule/normalization/join_reorder.rs @@ -783,7 +783,7 @@ mod tests { column_ids: vec![0], ty: IndexType::Normal, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], }); let info = IndexInfo { meta, @@ -1067,7 +1067,7 @@ mod tests { for index in [&mut l_index, &mut r_index] { index.column_ids.push(1); index.ty = IndexType::Composite; - index.value_ty = LogicalType::Tuple(vec![LogicalType::Integer, LogicalType::Integer]); + index.value_ty = vec![LogicalType::Integer.into(); 2]; } let ScalarExpression::ColumnRef { column: l_col, .. } = arena.expression(l) else { unreachable!() diff --git a/src/optimizer/rule/normalization/parameterized_index.rs b/src/optimizer/rule/normalization/parameterized_index.rs index af59be6e..7877b421 100644 --- a/src/optimizer/rule/normalization/parameterized_index.rs +++ b/src/optimizer/rule/normalization/parameterized_index.rs @@ -197,7 +197,14 @@ fn parameterize_right_subtree( else { return Ok(None); }; - let key_type = &arena.index(scan.index_infos[position].meta).value_ty; + let [key] = arena + .index(scan.index_infos[position].meta) + .value_ty + .as_slice() + else { + return Ok(None); + }; + let key_type = &key.ty; let left_type = left_expr.return_type(arena); if left_type.as_ref() != key_type { let common = LogicalType::max_logical_type(&left_type, key_type)?; @@ -243,6 +250,7 @@ fn pick_parameterized_index_position( .filter(|(_, index_info)| { let index_meta = arena.index(index_info.meta); index_meta.table_id == table_id + && !index_meta.has_prefix() && index_meta.column_ids.len() == 1 && index_meta.column_ids.first().copied() == Some(column_id) }) @@ -339,7 +347,9 @@ pub(crate) fn probe_index( let mut probe = Vec::new(); 'indexes: for (position, info) in scan.index_infos.iter().enumerate() { let meta = arena.index(info.meta); - if !matches!(meta.ty, IndexType::PrimaryKey { .. } | IndexType::Unique) { + if meta.has_prefix() + || !matches!(meta.ty, IndexType::PrimaryKey { .. } | IndexType::Unique) + { continue; } probe.clear(); @@ -796,11 +806,7 @@ mod inner_join_tests { column_ids: keys.iter().map(|id| *id as _).collect(), table_id: table_id(name), pk_ty: LogicalType::Integer, - value_ty: if keys.len() == 1 { - types[keys[0]].clone() - } else { - LogicalType::Tuple(keys.iter().map(|id| types[*id].clone()).collect()) - }, + value_ty: keys.iter().map(|&id| types[id].clone().into()).collect(), name: format!("idx{id}"), ty: if keys.len() == 1 { IndexType::Normal diff --git a/src/optimizer/rule/normalization/pushdown_predicates.rs b/src/optimizer/rule/normalization/pushdown_predicates.rs index c932a270..c66ac44b 100644 --- a/src/optimizer/rule/normalization/pushdown_predicates.rs +++ b/src/optimizer/rule/normalization/pushdown_predicates.rs @@ -344,15 +344,23 @@ impl NormalizationRule for PushPredicateIntoScan { if lookup.is_some() { continue; } - let SortOption::OrderBy { - ignore_prefix_len, .. - } = sort_option - else { - return Err(DatabaseError::InvalidIndex); + let index = arena.index(*meta); + let has_prefix = index.has_prefix(); + let sort_skip = match sort_option { + SortOption::OrderBy { + ignore_prefix_len, .. + } => Some(ignore_prefix_len), + SortOption::None if has_prefix => None, + _ => return Err(DatabaseError::InvalidIndex), }; // Uniqueness does not determine key width: UNIQUE indexes can be composite too. - let detached = if arena.index(*meta).column_ids.len() > 1 { - Self::composite_range(filter_op, *meta, ignore_prefix_len, arena)? + let detached = if index.column_ids.len() > 1 { + let (detached, leading_eq_columns) = + Self::composite_range(filter_op, *meta, arena)?; + if let Some(sort_skip) = sort_skip { + *sort_skip = leading_eq_columns; + } + detached } else { RangeDetacher::for_index(*meta, 0, arena).detach(filter_op.predicate)? }; @@ -361,10 +369,19 @@ impl NormalizationRule for PushPredicateIntoScan { *residual_predicate = None; continue; }; + // Different full values can map to the same prefix. Only a single equality + // lookup can be used here without widening ranges or deduplicating candidates. + if has_prefix && !matches!(detached.range, Range::Eq(_)) { + continue; + } changed = true; *lookup = Some(IndexLookup::Static(detached.range)); - *residual_predicate = detached.residual; + *residual_predicate = if has_prefix { + Some(filter_op.predicate) + } else { + detached.residual + }; let columns = scan_op .deserializers .read_columns() @@ -395,6 +412,9 @@ pub(crate) fn index_covering( arena: &PlanArena, ) -> Option>> { let index_meta = arena.index(index); + if index_meta.has_prefix() { + return None; + } let mut mapping_slots = Vec::with_capacity(index_meta.column_ids.len()); let mut needs_mapping = false; @@ -414,7 +434,8 @@ pub(crate) fn is_index_covers( arena: &PlanArena, ) -> bool { let index_meta = arena.index(index); - columns.all(|column| covering_idx(column, index_meta, arena).is_some()) + !index_meta.has_prefix() + && columns.all(|column| covering_idx(column, index_meta, arena).is_some()) } fn covering_idx(column: ColumnRef, index_meta: &IndexMeta, arena: &PlanArena) -> Option { @@ -437,9 +458,8 @@ impl PushPredicateIntoScan { fn composite_range( op: &FilterOperator, meta: IndexMetaRef, - ignore_prefix_len: &mut usize, - arena: &mut crate::planner::PlanArena, - ) -> Result, DatabaseError> { + arena: &mut PlanArena<'_>, + ) -> Result<(Option, usize), DatabaseError> { let column_count = arena.index(meta).column_ids.len(); let mut res = None; let mut eq_ranges = Vec::with_capacity(column_count); @@ -468,7 +488,7 @@ impl PushPredicateIntoScan { res = range.combining_eqs(&eq_ranges); break; } - *ignore_prefix_len = eq_ranges.len(); + let leading_eq_columns = eq_ranges.len(); if res.is_none() { if let Some(range) = eq_ranges.pop() { @@ -497,7 +517,10 @@ impl PushPredicateIntoScan { } range }); - Ok(range.map(|range| DetachedPredicate { range, residual })) + Ok(( + range.map(|range| DetachedPredicate { range, residual }), + leading_eq_columns, + )) } } @@ -799,7 +822,7 @@ mod tests { column_ids: vec![1, 2], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Tuple(vec![LogicalType::Integer, LogicalType::Integer]), + value_ty: vec![LogicalType::Integer.into(); 2], name: "unique_c1_c2".to_string(), ty: IndexType::Unique, }); @@ -890,11 +913,7 @@ mod tests { column_ids: vec![1, 2, 3], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Tuple(vec![ - LogicalType::Integer, - LogicalType::Integer, - LogicalType::Integer, - ]), + value_ty: vec![LogicalType::Integer.into(); 3], name: "idx_c1_c2_c3".to_string(), ty: IndexType::Composite, }); @@ -910,17 +929,11 @@ mod tests { is_optimized: false, having: false, }; - let mut ignore_prefix_len = 0; - - let detached = super::PushPredicateIntoScan::composite_range( - &filter, - index_meta, - &mut ignore_prefix_len, - &mut arena, - )? - .expect("composite prefix should be consumed"); + let (detached, leading_eq_columns) = + super::PushPredicateIntoScan::composite_range(&filter, index_meta, &mut arena)?; + let detached = detached.expect("composite prefix should be consumed"); - assert_eq!(ignore_prefix_len, 3); + assert_eq!(leading_eq_columns, 3); assert_eq!( detached.range, Range::Eq( @@ -958,11 +971,7 @@ mod tests { column_ids: vec![1, 2, 3], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Tuple(vec![ - LogicalType::Integer, - LogicalType::Integer, - LogicalType::Integer, - ]), + value_ty: vec![LogicalType::Integer.into(); 3], name: "idx_c1_c2_c3".to_string(), ty: IndexType::Composite, }); @@ -976,17 +985,11 @@ mod tests { is_optimized: false, having: false, }; - let mut ignore_prefix_len = 0; - - let detached = super::PushPredicateIntoScan::composite_range( - &filter, - index_meta, - &mut ignore_prefix_len, - &mut arena, - )? - .expect("composite prefix should be consumed"); + let (detached, leading_eq_columns) = + super::PushPredicateIntoScan::composite_range(&filter, index_meta, &mut arena)?; + let detached = detached.expect("composite prefix should be consumed"); - assert_eq!(ignore_prefix_len, 1); + assert_eq!(leading_eq_columns, 1); assert_eq!( detached.range, Range::Scope { @@ -1047,11 +1050,7 @@ mod tests { column_ids: vec![c2_id, c3_id, c1_id], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Tuple(vec![ - LogicalType::Integer, - LogicalType::Integer, - LogicalType::Integer, - ]), + value_ty: vec![LogicalType::Integer.into(); 3], name: "idx_c2_c3_c1".to_string(), ty: IndexType::Composite, }); @@ -1060,7 +1059,7 @@ mod tests { column_ids: vec![c1_id, c2_id], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Tuple(vec![LogicalType::Integer, LogicalType::Integer]), + value_ty: vec![LogicalType::Integer.into(); 2], name: "idx_c1_c2".to_string(), ty: IndexType::Composite, }); diff --git a/src/orm/ddl.rs b/src/orm/ddl.rs index 63a1d7a6..f0e30e19 100644 --- a/src/orm/ddl.rs +++ b/src/orm/ddl.rs @@ -1,4 +1,5 @@ use super::*; +use crate::planner::operator::create_index::CreateIndexOperator; enum OrmDefaultChange { NoChange, @@ -458,24 +459,23 @@ async fn execute_create_index( ) -> Result<(), DatabaseError> { let (index_name, index_columns, unique) = *index; let index_name = index_name.to_string(); - let column_names = index_columns.to_vec(); database .execute_mut("ORM CREATE INDEX", &[], move |binder, arena| { let mut input = binder.bind_create_index_source(table_name, arena)?; + let table_id = binder.context.table_id(table_name)?; let schema = input.output_schema(arena).clone(); - let mut columns = Vec::with_capacity(column_names.len()); - for column_name in column_names { + let key_parts = index_columns.iter().copied().map(|column_name| { let column = schema .iter() .copied() .find(|column| arena.column(*column).name() == column_name) .ok_or_else(|| DatabaseError::column_not_found(column_name.to_string()))?; - columns.push(column); - } - binder.bind_create_index( - table_name, + Ok((column, arena.column(column).datatype().clone().into())) + }); + CreateIndexOperator::build( + table_id, index_name, - columns, + key_parts, if_not_exists, unique, input, diff --git a/src/planner/arena.rs b/src/planner/arena.rs index de1612ab..a7cd15ce 100644 --- a/src/planner/arena.rs +++ b/src/planner/arena.rs @@ -1576,7 +1576,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: name.to_string(), ty: IndexType::Normal, } diff --git a/src/planner/operator/create_index.rs b/src/planner/operator/create_index.rs index de4fe9e4..e9f74253 100644 --- a/src/planner/operator/create_index.rs +++ b/src/planner/operator/create_index.rs @@ -12,22 +12,61 @@ // See the License for the specific language governing permissions and // limitations under the License. +use super::Operator; use crate::catalog::{ColumnRef, TableId}; -use crate::planner::MetaArena; -use crate::planner::{fmt_explain_list, fmt_table, Explain}; -use crate::types::index::IndexType; +use crate::errors::DatabaseError; +use crate::planner::{fmt_table, Childrens, Explain, LogicalPlan, MetaArena}; +use crate::types::index::{IndexType, IndexValType}; use kite_sql_serde_macros::ReferenceSerialization; #[derive(Debug, PartialEq, Eq, Clone, Hash, ReferenceSerialization)] pub struct CreateIndexOperator { pub table_id: TableId, - /// List of columns of the index pub columns: Vec, + pub index_val_ty: Vec, pub index_name: String, pub if_not_exists: bool, pub ty: IndexType, } +impl CreateIndexOperator { + pub fn build( + table_id: TableId, + index_name: String, + key_parts: impl ExactSizeIterator>, + if_not_exists: bool, + is_unique: bool, + input: LogicalPlan, + ) -> Result { + let mut columns = Vec::with_capacity(key_parts.len()); + let mut index_val_ty = Vec::with_capacity(key_parts.len()); + for part in key_parts { + let (column, key_ty) = part?; + columns.push(column); + index_val_ty.push(key_ty); + } + let ty = if is_unique { + IndexType::Unique + } else if columns.len() == 1 { + IndexType::Normal + } else { + IndexType::Composite + }; + + Ok(LogicalPlan::new( + Operator::CreateIndex(Self { + table_id, + columns, + index_val_ty, + index_name, + if_not_exists, + ty, + }), + Childrens::Only(Box::new(input)), + )) + } +} + impl Explain for CreateIndexOperator { fn fmt( &self, @@ -37,7 +76,15 @@ impl Explain for CreateIndexOperator { f.write_str("Create Index On ")?; fmt_table(self.table_id, arena, f)?; f.write_str(" -> [")?; - fmt_explain_list(&self.columns, ", ", arena, f)?; + for (i, (column, key_ty)) in self.columns.iter().zip(&self.index_val_ty).enumerate() { + if i > 0 { + f.write_str(", ")?; + } + write!(f, "{}", column.explain(arena))?; + if let Some(len) = key_ty.prefix_len { + write!(f, "({len})")?; + } + } write!(f, "], If Not Exists: {}", self.if_not_exists) } } diff --git a/src/planner/operator/create_table.rs b/src/planner/operator/create_table.rs index eaef9476..6cafa1ba 100644 --- a/src/planner/operator/create_table.rs +++ b/src/planner/operator/create_table.rs @@ -14,18 +14,25 @@ use crate::catalog::{ColumnCatalog, TableName}; use crate::iter_ext::Itertools; +use crate::types::index::IndexValType; use kite_sql_serde_macros::ReferenceSerialization; use std::fmt; use std::fmt::Formatter; +#[derive(Debug, PartialEq, Eq, Clone, Hash, ReferenceSerialization)] +pub struct UniqueKey { + pub column_positions: Vec, + pub index_val_ty: Vec, +} + #[derive(Debug, PartialEq, Eq, Clone, Hash, ReferenceSerialization)] pub struct CreateTableOperator { /// Table name to insert to pub table_name: TableName, /// List of columns of the table pub columns: Vec, - /// Each key lists positions in `columns` in constraint order. - pub composite_unique_keys: Vec>, + /// Bound composite or prefixed unique keys. + pub composite_unique_keys: Vec, pub if_not_exists: bool, } diff --git a/src/planner/operator/mod.rs b/src/planner/operator/mod.rs index df5487e2..d89fca78 100644 --- a/src/planner/operator/mod.rs +++ b/src/planner/operator/mod.rs @@ -1159,7 +1159,7 @@ mod tests { use crate::planner::test::PlanArenaTestExt; use crate::planner::ExprRef; use crate::planner::{Childrens, LogicalPlan, TableArenaCell}; - use crate::types::index::{IndexInfo, IndexMeta, IndexMetaRef, IndexType}; + use crate::types::index::{IndexInfo, IndexMeta, IndexMetaRef, IndexType, IndexValType}; use crate::types::value::DataValue; use crate::types::LogicalType; @@ -1348,7 +1348,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx_users_id".to_string(), ty: IndexType::Normal, }); @@ -1681,11 +1681,18 @@ mod tests { Operator::CreateIndex(CreateIndexOperator { table_id: 0, columns: vec![id, name], + index_val_ty: vec![ + LogicalType::Integer.into(), + IndexValType { + ty: LogicalType::Varbinary(None), + prefix_len: Some(2), + }, + ], index_name: "idx_users_name".to_string(), if_not_exists: false, - ty: IndexType::Normal, + ty: IndexType::Composite, }), - "Create Index On users -> [id, name], If Not Exists: false", + "Create Index On users -> [id, name(2)], If Not Exists: false", ), ( Operator::CreateView(CreateViewOperator { @@ -1756,7 +1763,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx_users_id".to_string(), ty: IndexType::Normal, }); diff --git a/src/planner/operator/table_scan.rs b/src/planner/operator/table_scan.rs index 7a3cbd41..eaf1ea8e 100644 --- a/src/planner/operator/table_scan.rs +++ b/src/planner/operator/table_scan.rs @@ -54,7 +54,9 @@ impl TableScanOperator { let mut index_infos = Vec::with_capacity(table_catalog.indexes.len()); for index_ref in table_catalog.indexes.iter().copied() { - let column_ids = arena.index(index_ref).column_ids.clone(); + let index = arena.index(index_ref); + let has_prefix = index.has_prefix(); + let column_ids = index.column_ids.clone(); let mut sort_fields = Vec::with_capacity(column_ids.len()); for (position, col_id) in column_ids.iter().enumerate() { let (_, column_ref) = table_catalog.get_column_by_id(col_id).ok_or_else(|| { @@ -70,9 +72,13 @@ impl TableScanOperator { index_infos.push(IndexInfo { meta: index_ref, - sort_option: SortOption::OrderBy { - fields: sort_fields, - ignore_prefix_len: 0, + sort_option: if has_prefix { + SortOption::None + } else { + SortOption::OrderBy { + fields: sort_fields, + ignore_prefix_len: 0, + } }, lookup: None, residual_predicate: None, diff --git a/src/planner/operator/visitor.rs b/src/planner/operator/visitor.rs index b07f9eea..2497e90c 100644 --- a/src/planner/operator/visitor.rs +++ b/src/planner/operator/visitor.rs @@ -791,6 +791,7 @@ pub(crate) mod tests { Operator::CreateIndex(CreateIndexOperator { table_id: 0, columns: vec![column_ref], + index_val_ty: vec![LogicalType::Integer.into()], index_name: "idx".to_string(), if_not_exists: false, ty: IndexType::Normal, diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 522ef397..a1b9e292 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -36,10 +36,11 @@ use crate::optimizer::core::cm_sketch::{ use crate::optimizer::core::histogram::HistogramMeta; use crate::optimizer::core::statistics_meta::IndexStatistics; use crate::planner::operator::alter_table::change_column::{DefaultChange, NotNullChange}; +use crate::planner::operator::create_table::UniqueKey; use crate::planner::{MetaArena, TableArenaCell}; use crate::serdes::ReferenceDecodeContext; use crate::storage::table_codec::{Bytes, IndexStatisticsCodecType, TableCodec, BOUND_MAX_TAG}; -use crate::types::index::{Index, IndexId, IndexMeta, IndexMetaRef, IndexType}; +use crate::types::index::{Index, IndexId, IndexMeta, IndexMetaRef, IndexType, IndexValType}; use crate::types::mapped::MappedScope; use crate::types::serialize::{BytesPool, TupleValueSerializableImpl}; use crate::types::tuple::{Tuple, TupleId, TupleImpl, TupleLike}; @@ -130,29 +131,6 @@ impl Display for TransactionIsolationLevel { } } -pub(crate) fn index_value_type( - table: &TableCatalog, - arena: &(impl MetaArena + ?Sized), - column_ids: &[ColumnId], -) -> Result { - let mut value_types = Vec::with_capacity(column_ids.len()); - for column_id in column_ids { - let value_type = table - .get_column_by_id(column_id) - .map(|(_, column)| arena.column(column)) - .ok_or_else(|| DatabaseError::column_not_found(column_id.to_string()))? - .datatype() - .clone(); - value_types.push(value_type); - } - - Ok(if value_types.len() == 1 { - value_types.pop().unwrap() - } else { - LogicalType::Tuple(value_types) - }) -} - #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct EmptyStorageMetrics; @@ -305,15 +283,16 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { table_name: &str, index_name: String, column_ids: Vec, + value_ty: Vec, ty: IndexType, context: &mut ReferenceDecodeContext<'_, Self>, - ) -> Result<(TableCatalog, IndexId), DatabaseError> { + ) -> Result<(TableCatalog, IndexMetaRef), DatabaseError> { let mut table = self .load_table(table_codec, plan_arena, table_name, context) .await? .ok_or(DatabaseError::TableNotFound)?; - let index_meta = table.add_index_meta(index_name, column_ids, ty, plan_arena)?; - let index_meta = plan_arena.index(index_meta); + let index_ref = table.add_index_meta(index_name, column_ids, value_ty, ty, plan_arena)?; + let index_meta = plan_arena.index(index_ref); let index_id = index_meta.id; table_codec.with_index_meta( table.id(), @@ -323,7 +302,7 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { |key, value| self.set(key, value), )?; - Ok((table, index_id)) + Ok((table, index_ref)) } async fn add_index( @@ -532,7 +511,8 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { column_ids: index_meta.column_ids.clone(), table_id: index_meta.table_id, pk_ty: temp_table.primary_keys_type().clone(), - value_ty: index_value_type(&temp_table, plan_arena, &index_meta.column_ids)?, + // Indexed column types cannot change during this metadata rewrite. + value_ty: index_meta.value_ty.clone(), name: index_meta.name.clone(), ty: index_meta.ty, }) @@ -589,6 +569,7 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { let meta_ref = table.add_index_meta( format!("uk_{}", column.name()), vec![col_id], + vec![column.datatype().clone().into()], IndexType::Unique, plan_arena, )?; @@ -685,7 +666,7 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { plan_arena: &mut (dyn MetaArena + '_), table_name: TableName, columns: Vec, - composite_unique_keys: &[Vec], + composite_unique_keys: &[UniqueKey], if_not_exists: bool, ) -> Result, DatabaseError> { match self @@ -1262,7 +1243,7 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { table_codec: &mut TableCodec, arena: &mut (impl MetaArena + ?Sized), table: &mut TableCatalog, - composite_unique_keys: &[Vec], + composite_unique_keys: &[UniqueKey], ) -> Result<(), DatabaseError> { let table_id = table.id(); @@ -1276,7 +1257,8 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { continue; } let index_name = format!("uk_{}_index", col.name()); - table.add_index_meta(index_name, vec![col_id], IndexType::Unique, arena)?; + let value_ty = vec![col.datatype().clone().into()]; + table.add_index_meta(index_name, vec![col_id], value_ty, IndexType::Unique, arena)?; } let primary_keys = table .primary_keys() @@ -1286,10 +1268,24 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { let pk_index_ty = IndexType::PrimaryKey { is_multiple: primary_keys.len() != 1, }; - table.add_index_meta("pk_index".to_string(), primary_keys, pk_index_ty, arena)?; + let pk_value_ty = table + .primary_keys_type() + .as_slice() + .iter() + .cloned() + .map(IndexValType::from) + .collect(); + table.add_index_meta( + "pk_index".to_string(), + primary_keys, + pk_value_ty, + pk_index_ty, + arena, + )?; for (i, key) in composite_unique_keys.iter().enumerate() { let column_ids = key + .column_positions .iter() .map(|&position| { table @@ -1297,9 +1293,10 @@ pub trait StorageTransaction: Sized + MaybeSend + MaybeSync + MaybeStatic { .and_then(|column| arena.column(column).id()) .ok_or(DatabaseError::InvalidIndex) }) - .collect::, _>>()?; + .collect::>()?; let name = format!("uk_composite_index_{}", i + 1); - table.add_index_meta(name, column_ids, IndexType::Unique, arena)?; + let value_ty = key.index_val_ty.clone(); + table.add_index_meta(name, column_ids, value_ty, IndexType::Unique, arena)?; } for &meta_ref in table.indexes() { @@ -1547,10 +1544,7 @@ impl TupleMapping { if matches!(meta.ty, IndexType::PrimaryKey { .. }) { return None; } - let tuple_len = match &meta.value_ty { - LogicalType::Tuple(tys) => tys.len(), - _ => 1, - }; + let tuple_len = meta.value_ty.len(); let columns_len = deserializers.read_columns().count(); match indices { Some(slots) => Some(TupleMapping::new(slots.iter().copied(), tuple_len)), @@ -1604,11 +1598,6 @@ impl IndexImplParams<'_, T> { self.meta_arena.index(self.index_meta) } - #[inline] - pub(crate) fn value_ty(&self) -> &LogicalType { - &self.index_meta().value_ty - } - #[inline] async fn get_tuple_by_id_into( &self, @@ -1929,7 +1918,7 @@ impl IndexImpl for UniqueIndexImpl { encode_max: &mut Bytes, ) -> Result, DatabaseError> { let meta = params.index_meta(); - let index = Index::new(meta.id, value.as_slice(), IndexType::Unique); + let index = Index::from_meta(meta, value.as_slice()); if index.values.len() < meta.column_ids.len() || index.is_unique_with_null() { return eq_to_res_scope( table_codec, @@ -1969,7 +1958,7 @@ impl IndexImpl for UniqueIndexImpl { is_upper: bool, out: &mut Bytes, ) -> Result<(), DatabaseError> { - let index = Index::new(params.index_meta().id, value.as_slice(), IndexType::Unique); + let index = Index::from_meta(params.index_meta(), value.as_slice()); table_codec .with_index(params.table_id, &index, None, async |key, _| { @@ -2031,7 +2020,7 @@ impl IndexImpl for NormalIndexImpl { is_upper: bool, out: &mut Bytes, ) -> Result<(), DatabaseError> { - let index = Index::new(params.index_meta().id, value.as_slice(), IndexType::Normal); + let index = Index::from_meta(params.index_meta(), value.as_slice()); table_codec .with_index(params.table_id, &index, None, async |key, _| { encode_bound_key(out, key, is_upper); @@ -2084,11 +2073,7 @@ impl IndexImpl for CompositeIndexImpl { is_upper: bool, out: &mut Bytes, ) -> Result<(), DatabaseError> { - let index = Index::new( - params.index_meta().id, - value.as_slice(), - IndexType::Composite, - ); + let index = Index::from_meta(params.index_meta(), value.as_slice()); table_codec .with_index(params.table_id, &index, None, async |key, _| { encode_bound_key(out, key, is_upper); @@ -2109,13 +2094,13 @@ impl IndexImpl for CoveredIndexImpl { params: &IndexImplParams<'_, T>, cover_mapping: Option<&TupleMapping>, ) -> Result<(), DatabaseError> { - let ty = params.value_ty(); + let types = ¶ms.index_meta().value_ty; match cover_mapping { Some(mapping) => TableCodec::decode_index_into( tuple, key, value, - ty, + types, &mapping.as_ref(), params.with_pk, ), @@ -2123,7 +2108,7 @@ impl IndexImpl for CoveredIndexImpl { tuple, key, value, - ty, + types, &OrderedMapping, params.with_pk, ), @@ -2159,11 +2144,7 @@ impl IndexImpl for CoveredIndexImpl { is_upper: bool, out: &mut Bytes, ) -> Result<(), DatabaseError> { - let index = Index::new( - params.index_meta().id, - value.as_slice(), - params.index_meta().ty, - ); + let index = Index::from_meta(params.index_meta(), value.as_slice()); table_codec .with_index(params.table_id, &index, None, async |key, _| { encode_bound_key(out, key, is_upper); @@ -3273,6 +3254,7 @@ mod test { "t1", "i1".to_string(), vec![c3_column_id], + vec![LogicalType::Integer.into()], IndexType::Normal, &mut Default::default(), ) @@ -3287,6 +3269,7 @@ mod test { "t1", "i2".to_string(), vec![c3_column_id, c2_column_id], + vec![LogicalType::Integer.into(), LogicalType::Boolean.into()], IndexType::Composite, &mut Default::default(), ) @@ -3306,6 +3289,7 @@ mod test { assert_eq!(i1_meta.column_ids, vec![c3_column_id]); assert_eq!(i1_meta.table_id, 0); assert_eq!(i1_meta.pk_ty, LogicalType::Integer); + assert_eq!(i1_meta.value_ty, vec![LogicalType::Integer.into()]); assert_eq!(i1_meta.name, "i1".to_string()); assert_eq!(i1_meta.ty, IndexType::Normal); @@ -3314,6 +3298,10 @@ mod test { assert_eq!(i2_meta.column_ids, vec![c3_column_id, c2_column_id]); assert_eq!(i2_meta.table_id, 0); assert_eq!(i2_meta.pk_ty, LogicalType::Integer); + assert_eq!( + i2_meta.value_ty, + vec![LogicalType::Integer.into(), LogicalType::Boolean.into()] + ); assert_eq!(i2_meta.name, "i2".to_string()); assert_eq!(i2_meta.ty, IndexType::Composite); @@ -3469,6 +3457,7 @@ mod test { "t1", "i1".to_string(), vec![c3_column_id], + vec![LogicalType::Integer.into()], IndexType::Normal, &mut Default::default(), ) diff --git a/src/storage/table_codec.rs b/src/storage/table_codec.rs index 0ed94362..ddb7356c 100644 --- a/src/storage/table_codec.rs +++ b/src/storage/table_codec.rs @@ -24,7 +24,7 @@ use crate::optimizer::core::top_n::ColumnTopN; use crate::planner::MetaArena; use crate::serdes::{ReferenceDecodeContext, ReferenceSerialization}; use crate::storage::StorageTransaction; -use crate::types::index::{Index, IndexId, IndexMeta, IndexType, INDEX_ID_LEN}; +use crate::types::index::{Index, IndexId, IndexMeta, IndexType, IndexValType, INDEX_ID_LEN}; use crate::types::mapped::MappedScope; use crate::types::serialize::{BytesPool, TupleValueSerializableImpl}; use crate::types::tuple::{Tuple, TupleId, TupleLike}; @@ -442,8 +442,9 @@ impl TableCodec { { let prefix = table_id.to_be_bytes(); let (lower, value) = self.slots_mut(); + let prefix_len = |i: usize| index.key_types.get(i).and_then(|ty| ty.prefix_len); let values_len = (0..index.values.len()) - .map(|i| index.values.value_at(i).memcomparable_len_hint()) + .map(|i| index.values.value_at(i).index_key_len_hint(prefix_len(i))) .sum::(); let tuple_id_len = tuple_id.map_or(0, DataValue::memcomparable_len_hint); lower.reserve( @@ -458,7 +459,12 @@ impl TableCodec { lower.extend_from_slice(&index.id.to_le_bytes()); lower.push(BOUND_MIN_TAG); for i in 0..index.values.len() { - index.values.value_at(i).memcomparable_encode(lower)?; + let value = index.values.value_at(i); + let truncated = value.truncate_index_key(prefix_len(i))?; + truncated + .as_ref() + .unwrap_or(value) + .memcomparable_encode(lower)?; } if let Some(tuple_id) = tuple_id { @@ -907,7 +913,7 @@ impl TableCodec { tuple: &mut Tuple, key: &[u8], value: &[u8], - ty: &LogicalType, + types: &[IndexValType], mapping: &M, with_pk: bool, ) -> Result<(), DatabaseError> { @@ -925,15 +931,11 @@ impl TableCodec { let start = TUPLE_KEY_PREFIX_LEN + INDEX_ID_LEN + KEY_BOUND_LEN; let bytes = key.get(start..).ok_or(DatabaseError::InvalidIndex)?; let mut reader = Cursor::new(bytes); - let types = match ty { - LogicalType::Tuple(types) => types.as_slice(), - ty => std::slice::from_ref(ty), - }; tuple.values.clear(); tuple .values .resize(mapping.target_len(types.len()), DataValue::Null); - for (index_pos, ty) in types.iter().enumerate() { + for (index_pos, IndexValType { ty, .. }) in types.iter().enumerate() { match mapping_value(&mut tuple.values, mapping, index_pos)? { Some(target) => *target = DataValue::memcomparable_decode(&mut reader, ty)?, None => DataValue::memcomparable_skip(&mut reader, ty)?, @@ -1140,7 +1142,7 @@ mod tests { use crate::planner::{PlanArena, TableArenaCell}; use crate::storage::table_codec::{Bytes, TableCodec}; use crate::storage::TestTransaction; - use crate::types::index::{Index, IndexMeta, IndexType}; + use crate::types::index::{Index, IndexMeta, IndexType, IndexValType}; use crate::types::tuple::Tuple; use crate::types::value::{DataValue, OrderedMapping, TupleMappingRef, Utf8Type}; use crate::types::LogicalType; @@ -1194,13 +1196,13 @@ mod tests { Ok((key.to_vec(), value.to_vec())) }) .await?; - let index_ty = LogicalType::Tuple(vec![ - LogicalType::Integer, - varchar.clone(), - varchar, - char_type, - LogicalType::Integer, - ]); + let index_ty: Vec = vec![ + LogicalType::Integer.into(), + varchar.clone().into(), + varchar.into(), + char_type.into(), + LogicalType::Integer.into(), + ]; let mapping = TupleMappingRef::new(&[1, usize::MAX, usize::MAX, usize::MAX, 0], 2); let mut tuple = Tuple::new(None, Vec::with_capacity(8)); let allocation = (tuple.values.as_ptr(), tuple.values.capacity()); @@ -1328,7 +1330,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "pk_c1".to_string(), ty: IndexType::PrimaryKey { is_multiple: false }, }; @@ -1502,7 +1504,7 @@ mod tests { column_ids: vec![1], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "index_1".to_string(), ty: IndexType::PrimaryKey { is_multiple: false }, }; @@ -1756,7 +1758,7 @@ mod tests { column_ids: vec![], table_id, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: format!("{index_id}_index"), ty: IndexType::PrimaryKey { is_multiple: false }, }; diff --git a/src/types/index.rs b/src/types/index.rs index ec9ecf60..b6de826f 100644 --- a/src/types/index.rs +++ b/src/types/index.rs @@ -24,6 +24,7 @@ use crate::types::tuple::TupleLike; use crate::types::value::DataValue; use crate::types::{ColumnId, LogicalType}; use kite_sql_serde_macros::ReferenceSerialization; +use std::borrow::Cow; use std::collections::Bound; use std::fmt; use std::fmt::Formatter; @@ -120,12 +121,63 @@ pub struct IndexMeta { pub column_ids: Vec, pub table_id: TableId, pub pk_ty: LogicalType, - pub value_ty: LogicalType, + /// One entry per indexed column, in key order. + pub value_ty: Vec, pub name: String, pub ty: IndexType, } +/// An index key part: the column's own type and an optional prefix length. +/// A string prefix counts characters, a binary prefix counts bytes. +#[derive(Debug, Clone, Eq, PartialEq, Hash, ReferenceSerialization)] +pub struct IndexValType { + pub ty: LogicalType, + pub prefix_len: Option, +} + +impl IndexValType { + pub(crate) fn new(ty: LogicalType, prefix_len: Option) -> Result { + if prefix_len.is_some() + && !matches!( + ty, + LogicalType::Char(..) | LogicalType::Varchar(..) | LogicalType::Varbinary(_) + ) + { + return Err(DatabaseError::UnsupportedStmt(format!( + "index prefix length requires a string or binary column, got {ty}" + ))); + } + Ok(Self { ty, prefix_len }) + } +} + +impl From for IndexValType { + fn from(ty: LogicalType) -> Self { + Self { + ty, + prefix_len: None, + } + } +} + impl IndexMeta { + pub(crate) fn has_prefix(&self) -> bool { + self.value_ty.iter().any(|ty| ty.prefix_len.is_some()) + } + + pub(crate) fn truncate_key( + &self, + value: Cow<'_, DataValue>, + ) -> Result { + let mut value = value.into_owned(); + for (part, ty) in value.as_mut_slice().iter_mut().zip(&self.value_ty) { + if let Some(truncated) = part.truncate_index_key(ty.prefix_len)? { + *part = truncated; + } + } + Ok(value) + } + pub(crate) fn column_exprs<'a>( &'a self, table: &'a TableCatalog, @@ -144,6 +196,7 @@ pub struct Index<'a, V: TupleLike + ?Sized = [DataValue]> { pub id: IndexId, pub values: &'a V, pub ty: IndexType, + pub(crate) key_types: &'a [IndexValType], } impl Clone for Index<'_, V> { @@ -156,7 +209,21 @@ impl Copy for Index<'_, V> {} impl<'a, V: TupleLike + ?Sized> Index<'a, V> { pub fn new(id: IndexId, values: &'a V, ty: IndexType) -> Self { - Index { id, values, ty } + Index { + id, + values, + ty, + key_types: &[], + } + } + + pub(crate) fn from_meta(meta: &'a IndexMeta, values: &'a V) -> Self { + Self { + id: meta.id, + values, + ty: meta.ty, + key_types: &meta.value_ty, + } } pub(crate) fn is_unique_with_null(&self) -> bool { @@ -244,7 +311,7 @@ mod tests { column_ids: vec![10], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx_t".to_string(), ty: IndexType::Normal, } @@ -443,7 +510,7 @@ mod tests { column_ids: vec![id_column], table_id: 0, pk_ty: LogicalType::Integer, - value_ty: LogicalType::Integer, + value_ty: vec![LogicalType::Integer.into()], name: "idx_id".to_string(), ty: IndexType::Normal, }; diff --git a/src/types/mod.rs b/src/types/mod.rs index 77fafe59..a5e9bba8 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -76,6 +76,23 @@ pub enum LogicalType { } impl LogicalType { + pub(crate) fn from_key_types( + mut key_types: impl ExactSizeIterator>, + ) -> Result { + if key_types.len() == 1 { + key_types.next().ok_or(DatabaseError::InvalidIndex)? + } else { + key_types.collect::>().map(Self::Tuple) + } + } + + pub(crate) fn as_slice(&self) -> &[Self] { + match self { + Self::Tuple(types) => types, + ty => std::slice::from_ref(ty), + } + } + pub fn type_trans() -> Option { let type_id = TypeId::of::(); diff --git a/src/types/value.rs b/src/types/value.rs index 85d0e03b..b4d93845 100644 --- a/src/types/value.rs +++ b/src/types/value.rs @@ -1383,6 +1383,46 @@ impl DataValue { self.memcomparable_encode_with_null_order(b, false) } + pub(crate) fn truncate_index_key( + &self, + prefix_len: Option, + ) -> Result, DatabaseError> { + let Some(len) = prefix_len else { + return Ok(None); + }; + Ok(match self { + Self::Utf8 { value, .. } => { + let end = value + .char_indices() + .nth(len as usize) + .map_or(value.len(), |(i, _)| i); + Some(Self::Utf8 { + value: (&value[..end]).into(), + ty: Utf8Type::Variable(Some(len)), + unit: CharLengthUnits::Characters, + }) + } + Self::Binary { value, .. } => Some(Self::Binary { + value: (&value[..value.len().min(len as usize)]).into(), + len: Some(len), + }), + Self::Null => None, + _ => return Err(DatabaseError::InvalidIndex), + }) + } + + pub(crate) fn index_key_len_hint(&self, prefix_len: Option) -> usize { + let len = match (self, prefix_len) { + // A UTF-8 character takes at most four bytes. No need to scan the string here. + (Self::Utf8 { value, .. }, Some(len)) => { + value.len().min((len as usize).saturating_mul(4)) + } + (Self::Binary { value, .. }, Some(len)) => value.len().min(len as usize), + _ => return self.memcomparable_len_hint(), + }; + 1 + Self::encoded_string_len(len) + } + pub(crate) fn memcomparable_len_hint(&self) -> usize { 1 + match self { // Unbound values fail to encode, so they write nothing past the tag. @@ -2265,6 +2305,22 @@ mod test { Ok(()) } + #[test] + fn index_key_len_hint_bounds_prefix_encoding() -> Result<(), DatabaseError> { + for (value, prefix_len) in [ + (DataValue::new_utf8("😀😀a long suffix".into()), 2), + (DataValue::from(vec![1; 32]), 8), + ] { + let hint = value.index_key_len_hint(Some(prefix_len)); + let key = value.truncate_index_key(Some(prefix_len))?.unwrap(); + let mut bytes = Vec::new(); + key.memcomparable_encode(&mut bytes)?; + assert!(bytes.len() <= hint); + assert!(hint < value.memcomparable_len_hint()); + } + Ok(()) + } + #[test] fn borrowed_tuple_matches_owned_tuple_without_materialization() { let values = [DataValue::Int32(1), DataValue::Null]; diff --git a/tests/slt/create_index.slt b/tests/slt/create_index.slt index 6a629c44..f616b65f 100644 --- a/tests/slt/create_index.slt +++ b/tests/slt/create_index.slt @@ -240,3 +240,84 @@ true statement ok drop table t_func_default; + +# String prefixes count characters, not bytes. +statement ok +create table prefix_text (id int primary key, b varchar(20), unique (b(2))); + +statement error index prefix length requires a string or binary column +create index bad on prefix_text (id(2)); + +statement error index prefix length requires a string or binary column +create table bad_prefix (id int primary key, unique (id(2))); + +statement error PRIMARY KEY index prefixes +create table bad_prefix (b varchar(20), primary key (b(2))); + +statement error +create index bad on prefix_text (b(0)); + +statement ok +insert into prefix_text values (1, '你好A'), (2, '你们B'); + +statement error the column has been declared unique +insert into prefix_text values (3, '你好B'); + +statement ok +drop table prefix_text; + +# The prefix scan rechecks full values before applying LIMIT/OFFSET. +statement ok +create table prefix_scan (id int primary key, b char(8)); + +statement ok +create index b_prefix on prefix_scan (b(2)); + +statement ok +insert into prefix_scan values (1, 'abA'), (2, 'abB'), (3, 'abB'), (4, 'ac'), (5, 'ad'), (6, 'ae'), (7, 'af'), (8, 'ag'); + +statement ok +analyze table prefix_scan; + +query T +explain select id, b from prefix_scan where b = 'abB' limit 1 offset 1; +---- +Projection [prefix_scan.id, prefix_scan.b] [Project => (Sort Option: Follow)] Limit 1, Offset 1 [Limit => (Sort Option: Follow)] TableScan prefix_scan -> [prefix_scan.id, prefix_scan.b], Filter: (cast (prefix_scan.b as Varchar(None, CHARACTERS)) = abB) [IndexScan By b_prefix => abB => (Sort Option: None)] + +query IT +select id, b from prefix_scan where b = 'abB' limit 1 offset 1; +---- +3 abB + +statement ok +drop table prefix_scan; + +# Binary prefixes enforce byte-based uniqueness during backfill and writes. +statement ok +create table prefix_binary (id int primary key, b varbinary(10), g int); + +statement ok +insert into prefix_binary values (1, x'00ff01', 10), (2, x'00ff02', 20), (4, x'008001', 10); + +statement error the column has been declared unique +create unique index bad on prefix_binary (b(2)); + +statement ok +create unique index b_group on prefix_binary (b(2), g); + +statement error the column has been declared unique +insert into prefix_binary values (3, x'00ff03', 10); + +statement ok +update prefix_binary set b = x'00aa01' where id = 1; + +statement ok +insert into prefix_binary values (3, x'00ff03', 10); + +query T +select b from prefix_binary where b = x'00ff03' and g = 10; +---- +X'00FF03' + +statement ok +drop table prefix_binary;