sql-builder icon indicating copy to clipboard operation
sql-builder copied to clipboard

Construct query with where clause that can append `and_where` to an existing `or_where`

Open elertan opened this issue 4 years ago • 2 comments

I want to construct a query that looks as following:

SELECT * FROM table WHERE field1 = '' OR (field2 = '' AND field3 = '');

The code below does not work for obvious reasons:

use sql_builder::{SqlBuilder, quote};

let sql = SqlBuilder::select_from("table")
    .field("*")
    .and_where_eq("field1", quote(""))
    .or_where_eq("field2", quote(""))
    .and_where_eq("field3", quote(""))
    .sql()?;

But I can't find a construct in the docs which would allow me to express this query. It would be ideal if I would just be able to encapsulate the last two where clause statements within ()? Note: The data for this query is being dynamically build by some dynamic filter data from user input, similar to as shown below.

enum Filter {
    Field1(StringFilter),
    Field2(StringFilter),
    Field2(StringFilter),
    And(Vec<Filter>),
    Or(Vec<Filter>),
}

elertan avatar Sep 08 '21 13:09 elertan

@elertan This is also something I need and came to check what would need to be added. It seems it's possible in the 4.0.0 version in the repo: See my example in #13

@perdumonocle Can you please publish version 4.0.0 to crates.io so we can use the new where_builder::Where struct?

thepacketgeek avatar Apr 27 '22 21:04 thepacketgeek

I am also looking to use this to build queries with nested conditions!

bwo avatar Aug 25 '23 02:08 bwo