Multiple SqlBuilder.Where() calls produce wrong SQL
Nobody has claimed this yet.
- Dominant language
- C#
- Stars
- 18.4k
- Forks
- 3.7k
- Avg merge
- 5h 8m
- Merged PRs (30d)
- 1
Description
When SqlBuilder.Where() is called more than once int the resulting SQL all passed SQL parts are concatenated with " AND " in between. That produces some unexpected results.
For example, get someone's salaries:
var sqlBuilder = new SqlBuilder();
var template = sqlBuilder.AddTemplate(@"
SELECT * FROM salaries
/**where**/
");
// current user only
sqlBuilder.Where("person_id = @currentAccountId", new { currentAccountId });
// only January and February
sqlBuilder.Where("month = @month1 OR month = @month2", new { month1 = 1, month2 = 2 });
That will produce the following code:
SELECT * FROM salaries
WHERE person_id = @currentAccountId AND month = @month1 OR month = @month2 -- no parentheses!
See the condition is wrong because no parentheses used. So the query will also return February salaries of all users.
To me, it is a huge problem because the behaviour is far from obvious. I can easily be fixed by enclosing all SQL parts passed to Where() in parentheses before resolving.
The same fix should be applied to Having().
In other aspects, SqlBuilder is a nice simple thing.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the SqlBuilder.Where() and Having() entry points and read how their SQL fragments are combined when the template is resolved. Add regression coverage for repeated conditions containing OR, and verify that the generated SQL groups each fragment so the documented salary query applies both filters correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp, sql
- Domain
- database
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100