Skip to content
Merged
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
2 changes: 1 addition & 1 deletion pqb/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,7 @@ fn write_binary_op<W: SqlWriter>(w: &mut W, op: &BinaryOp) {
})
}

fn write_tuple<W: SqlWriter>(w: &mut W, exprs: &[Expr]) {
pub(crate) fn write_tuple<W: SqlWriter>(w: &mut W, exprs: &[Expr]) {
w.push_char('(');
for (i, expr) in exprs.iter().enumerate() {
if i != 0 {
Expand Down
26 changes: 22 additions & 4 deletions pqb/src/index/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::borrow::Cow;
use crate::SqlWriterValues;
use crate::expr::Expr;
use crate::expr::write_expr;
use crate::expr::write_tuple;
use crate::types::Iden;
use crate::types::IntoIden;
use crate::types::TableRef;
Expand All @@ -33,7 +34,7 @@ pub struct CreateIndex {
primary: bool,
unique: bool,
name: Option<Iden>,
columns: Vec<Iden>,
columns: Vec<Expr>,
include_columns: Vec<Iden>,
method: Option<IndexMethod>,
options: Vec<IndexOption>,
Expand Down Expand Up @@ -83,7 +84,16 @@ impl CreateIndex {
where
T: IntoIden,
{
self.columns.push(column.into_iden());
self.columns.push(Expr::column(column.into_iden()));
self
}

/// Add an expression to the index.
pub fn expr<E>(mut self, expr: E) -> Self
where
E: Into<Expr>,
{
self.columns.push(expr.into());
self
}

Expand Down Expand Up @@ -305,13 +315,21 @@ pub(crate) fn write_table_index<W: SqlWriter>(w: &mut W, index: &CreateIndex) {
write_index_options(w, &index.options);
}

fn write_index_columns<W: SqlWriter>(w: &mut W, columns: &[Iden]) {
fn write_index_columns<W: SqlWriter>(w: &mut W, columns: &[Expr]) {
w.push_str("(");
for (i, col) in columns.iter().enumerate() {
if i > 0 {
w.push_str(", ");
}
write_iden(w, col);
match col {
// Wrap opclass expressions in parentheses for disambiguation
Expr::Binary(_, _, _) | Expr::Unary(_, _) => {
write_tuple(w, std::slice::from_ref(col));
}
_ => {
write_expr(w, col);
}
}
}
w.push_str(")");
}
Expand Down
23 changes: 23 additions & 0 deletions pqb/tests/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,29 @@ fn create_index_partial() {
);
}

#[test]
fn create_index_expression() {
assert_snapshot!(
CreateIndex::new()
.table("users")
.expr(Expr::function("lower", [Expr::column("email")]))
.to_sql(),
@r#"CREATE INDEX ON "users" (lower("email"))"#
);
}

#[test]
fn create_index_expression_with_column() {
assert_snapshot!(
CreateIndex::new()
.table("metrics")
.expr(Expr::column("value").add(Expr::value(1)))
.column("created_at")
.to_sql(),
@r#"CREATE INDEX ON "metrics" (("value" + 1), "created_at")"#
);
}

#[test]
fn create_index_concurrently() {
assert_snapshot!(
Expand Down