I've got to build some somewhat complicated WHERE clauses in SQL for a project I'm working on, and the clauses feel very hierarchical with their combination of ANDs and ORs. Instead of:
WHERE ([userId] NOT IN @excludeUsers) AND ((([firstname] LIKE @nameFilter) OR ([surname] LIKE @nameFilter)) AND (([jobTitle] LIKE @infoFilter) OR ([mobileNo] LIKE @infoFilter)))
... I want to be able to write something like the following:
// Wcb is a WhereClauseBuilder
OrClause innerOr;
var whereClause =
Wcb.And(
"[userId] NOT IN @excludeUsers",
Wcb.And(
Wcb.Or(
"[firstname] LIKE @nameFilter",
"[surname] LIKE @nameFilter"
),
innerOr = Wcb.Or(
"[jobTitle] LIKE @infoFilter",
"[mobileNo] LIKE @infoFilter"
)
)
);
The idea is to eliminate mistakes like missing whitespace, brackets, and AND/OR keywords, from the query. The And
and Or
static methods would create instances of AndClause
and OrClause
classes, and they'd overload ToString
allowing the whole object graph to resolve to a string upon $"{whereClause}"
. I'd also like to be able to add to the query later on, like:
if (extraInfoFilter != null) {
innerOr.Or(
"[extraInfo] LIKE @extraInfoFilter"
);
}
However, the code I'm writing for this has gotten complex enough to prompt me to ask: is this solution over-engineered? Should I just build the strings manually instead of generating them from a hierarchical object model like this? Are there any practical reasons why that would be a better approach?