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

Support partial index #405

Closed
wants to merge 1 commit into from
Closed
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
6 changes: 6 additions & 0 deletions src/backend/index_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub trait IndexBuilder: QuotedBuilder {
self.prepare_index_type(&create.index_type, sql);

self.prepare_index_columns(&create.index.columns, sql);

self.prepare_filter(&create.r#where, sql);
}

/// Translate [`IndexDropStatement`] into SQL statement.
Expand Down Expand Up @@ -71,6 +73,10 @@ pub trait IndexBuilder: QuotedBuilder {
write!(sql, ")").unwrap();
}

#[doc(hidden)]
// Write WHERE clause for partial index. This function is not available in MySQL.
fn prepare_filter(&self, _condition: &ConditionHolder, _sql: &mut SqlWriter) {}

#[doc(hidden)]
/// Write index name.
fn prepare_index_name(&self, name: &Option<String>, sql: &mut SqlWriter) {
Expand Down
8 changes: 8 additions & 0 deletions src/backend/postgres/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ impl IndexBuilder for PostgresQueryBuilder {
self.prepare_index_type(&create.index_type, sql);

self.prepare_index_columns(&create.index.columns, sql);

self.prepare_filter(&create.r#where, sql);
}

fn prepare_index_drop_statement(&self, drop: &IndexDropStatement, sql: &mut SqlWriter) {
Expand All @@ -57,6 +59,12 @@ impl IndexBuilder for PostgresQueryBuilder {
}
}

fn prepare_filter(&self, condition: &ConditionHolder, sql: &mut SqlWriter) {
let mut _params: Vec<Value> = Vec::new();
let mut _collector = |v| _params.push(v);
self.prepare_condition(condition, "WHERE", sql, &mut _collector);
}

fn prepare_index_prefix(&self, create: &IndexCreateStatement, sql: &mut SqlWriter) {
if create.primary {
write!(sql, "PRIMARY KEY ").unwrap();
Expand Down
8 changes: 8 additions & 0 deletions src/backend/sqlite/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ impl IndexBuilder for SqliteQueryBuilder {
}

self.prepare_index_columns(&create.index.columns, sql);

self.prepare_filter(&create.r#where, sql);
}

fn prepare_index_drop_statement(&self, drop: &IndexDropStatement, sql: &mut SqlWriter) {
Expand All @@ -46,6 +48,12 @@ impl IndexBuilder for SqliteQueryBuilder {

fn write_column_index_prefix(&self, _col_prefix: &Option<u32>, _sql: &mut SqlWriter) {}

fn prepare_filter(&self, condition: &ConditionHolder, sql: &mut SqlWriter) {
let mut _params: Vec<Value> = Vec::new();
let mut _collector = |v| _params.push(v);
self.prepare_condition(condition, "WHERE", sql, &mut _collector);
}

fn prepare_index_prefix(&self, create: &IndexCreateStatement, sql: &mut SqlWriter) {
if create.primary {
write!(sql, "PRIMARY KEY ").unwrap();
Expand Down
42 changes: 42 additions & 0 deletions src/index/create.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::common::*;
use crate::query::IntoCondition;
use crate::{backend::SchemaBuilder, prepare::*, types::*, SchemaStatementBuilder};
use crate::{ConditionHolder, ConditionalStatement};

/// Create an index for an existing table
///
Expand Down Expand Up @@ -120,6 +122,28 @@ use crate::{backend::SchemaBuilder, prepare::*, types::*, SchemaStatementBuilder
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC)"#
/// );
/// ```
///
/// Partial Index with prefix and order
/// ```
/// use sea_query::{tests_cfg::*, *};
///
/// let index = Index::create()
/// .name("idx-glyph-aspect")
/// .table(Glyph::Table)
/// .col((Glyph::Aspect, 64, IndexOrder::Asc))
/// .and_where(Expr::tbl(Glyph::Table, Glyph::Aspect).is_in(vec![3, 4]))
/// .to_owned();
///
/// assert_eq!(
/// index.to_string(PostgresQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (64) ASC) WHERE "glyph"."aspect" IN ($1, $2)"#
/// );
/// assert_eq!(
/// index.to_string(SqliteQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC) WHERE "glyph"."aspect" IN (?, ?)"#
/// );
Comment on lines +137 to +144
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @kyoto7250, thanks again for contributing!!

For index statement, it doesn't support value binding. So, instead of writing a placeholder to the SQL - ? for MySQL and $N for PostgreSQL. It should just write the value in string. This QueryBuilder::value_to_string would come in handy.

Suggested change
/// assert_eq!(
/// index.to_string(PostgresQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (64) ASC) WHERE "glyph"."aspect" IN ($1, $2)"#
/// );
/// assert_eq!(
/// index.to_string(SqliteQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC) WHERE "glyph"."aspect" IN (?, ?)"#
/// );
/// assert_eq!(
/// index.to_string(PostgresQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" (64) ASC) WHERE "glyph"."aspect" IN (3, 4)"#
/// );
/// assert_eq!(
/// index.to_string(SqliteQueryBuilder),
/// r#"CREATE INDEX "idx-glyph-aspect" ON "glyph" ("aspect" ASC) WHERE "glyph"."aspect" IN (3, 4)"#
/// );

Copy link
Member

@billy1624 billy1624 Aug 29, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @kyoto7250, got any updates on this? :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kyoto7250 hello! Any updates?)

/// ```

#[derive(Debug, Clone)]
pub struct IndexCreateStatement {
pub(crate) table: Option<DynIden>,
Expand All @@ -128,6 +152,7 @@ pub struct IndexCreateStatement {
pub(crate) unique: bool,
pub(crate) index_type: Option<IndexType>,
pub(crate) if_not_exists: bool,
pub(crate) r#where: ConditionHolder,
}

/// Specification of a table index
Expand Down Expand Up @@ -155,6 +180,7 @@ impl IndexCreateStatement {
unique: false,
index_type: None,
if_not_exists: false,
r#where: ConditionHolder::new(),
}
}

Expand Down Expand Up @@ -233,6 +259,7 @@ impl IndexCreateStatement {
unique: self.unique,
index_type: self.index_type.take(),
if_not_exists: self.if_not_exists,
r#where: self.r#where.clone(),
}
}
}
Expand All @@ -250,3 +277,18 @@ impl SchemaStatementBuilder for IndexCreateStatement {
sql.result()
}
}

impl ConditionalStatement for IndexCreateStatement {
fn and_or_where(&mut self, condition: LogicalChainOper) -> &mut Self {
self.r#where.add_and_or(condition);
self
}

fn cond_where<C>(&mut self, condition: C) -> &mut Self
where
C: IntoCondition,
{
self.r#where.add_condition(condition.into_condition());
self
}
}
1 change: 1 addition & 0 deletions src/query/shim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ impl_ordered_statement!(delete_statement_ordered, DeleteStatement);
impl_conditional_statement!(select_statement_conditional, SelectStatement);
impl_conditional_statement!(update_statement_conditional, UpdateStatement);
impl_conditional_statement!(delete_statement_conditional, DeleteStatement);
impl_conditional_statement!(index_create_conditional, IndexCreateStatement);