DapperLib / DapperLib/Dapper

Multiple SqlBuilder.Where() calls produce wrong SQL

Open
#1,599 2 comments 1 reaction 0 assignees View on GitHub

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

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.