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

(mysql) LIKE for non-text columns #1802

Closed
RazrFalcon opened this Issue Jul 30, 2018 · 4 comments

Comments

Projects
None yet
2 participants
@RazrFalcon

RazrFalcon commented Jul 30, 2018

I there a way to use LIKE statement for any column? Currently, it tied to TextExpressionMethods. But MySQL works fine with any column type.

PS: I need this to fuzzy search in DECIMAL column.

@sgrif

This comment has been minimized.

Member

sgrif commented Jul 30, 2018

See http://diesel.rs/guides/extending-diesel/#custom-operators for examples of how to add new operators to Diesel

@sgrif sgrif closed this Jul 30, 2018

@RazrFalcon

This comment has been minimized.

RazrFalcon commented Jul 30, 2018

Thanks.

I've tried this:

diesel_infix_operator!(MyLike, " LIKE ");

pub trait MyLikeMethods: Expression + Sized {
    fn my_like<T: AsExpression<Self::SqlType>>(self, rhs: T) -> MyLike<Self, T::Expression> {
        MyLike::new(self, rhs.as_expression())
    }
}

impl<T: Expression> MyLikeMethods for T {}

{
    let some_text = "some text".to_string();
    let list: Vec<MyStruct> = table::my_table
        .filter(columns::my_table::price.my_like(format!("%{}%", some_text)))
        .load(conn)?;
}

But I'm getting:

error[E0277]: the trait bound `std::string::String: diesel::Expression` is not satisfied
   --> src/db/invoices.rs:253:48
    |
253 |         .filter(columns::invoices::total_price.my_like(format!("%{}%", some_text)))
    |                                                ^^^^^^^ the trait `diesel::Expression` is not implemented for `std::string::String`
    |
    = note: required because of the requirements on the impl of `diesel::expression::AsExpression<diesel::sql_types::Numeric>` for `std::string::String`

The price column is Decimal.

@sgrif

This comment has been minimized.

Member

sgrif commented Jul 30, 2018

You defined my_like to exist on all types, and take any argument of the same type. It sounds like you want it to be only on decimal columns, and only take text arguments. You should write fn my_like<T: AsExpression<Text>> and impl<T: Expression<SqlType = Decimal>>

@RazrFalcon

This comment has been minimized.

RazrFalcon commented Jul 31, 2018

Thanks! It worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment