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

starts_with #375

Closed
porglezomp opened this Issue Jul 6, 2016 · 2 comments

Comments

Projects
None yet
2 participants
@porglezomp

porglezomp commented Jul 6, 2016

It would be nice to have a starts_with method that could be used in place of like. I find myself wanting to do path.starts_with(dynamic_data), and if every application has to generate the like("something%") themselves then that's duplicated %-sanitation in everyone's code.
I'm not even quite sure the proper way to do it, in some of my test applications I'm just doing path.like(format!("{}%", prefix.replace("%", "_"))) since I don't have to be very permissive in my input format.

@sgrif

This comment has been minimized.

Member

sgrif commented Jul 11, 2016

I don't think that is something which makes a ton of sense for Diesel to do, as there's no direct equivalent in SQL. I wouldn't do this with LIKE either, since as you've pointed out, escaping special characters can be a pain. I'd probably do something like this (I'm assuming you're using PG, not sure if there's a direct equivalent on SQLite):

sql_function!(left, left_t, (Text, Integer) -> Text);

.filter(left(some_expr, str.len()).eq(str))

And if you really want to do some_expr.starts_with(str), you could do something like:

use diesel::expression::helper_types::*;

trait MyExpressionMethods: Expression<SqlType=Text> + Sized {
    fn starts_with(self, needle: String) -> Eq<left_t<Self, AsExprOf<i32, Integer>>, AsExprOf<Text, String>> {
        left(self, needle.len()).eq(needle)
    }
}

impl<T> MyExpressionMethods for T where
    T: Expression<SqlType=Text> + Sized,
{}

(Yeah the type signature is a bit gnarly there, but it's a pain to hide that return type right now)

Anyway I think this makes a ton of sense to do as a small third party crate, but it's above the level where I want Diesel to live right now, as it's meant to stay pretty close to SQL. I may re-evaluate that in the future as more common patterns come about, but until we get a lot of other things figured out with regards to documentation and discoverability I'd like to keep the surface area of the API small.

@sgrif sgrif closed this Jul 11, 2016

@porglezomp

This comment has been minimized.

porglezomp commented Jul 11, 2016

Thanks, that's really the solution I needed here.

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