Skip to content

Commit 824257a

Browse files
author
Josh Schwartzberg
committed
Adds ability to escape identifiers w/ tests
1 parent 74e6265 commit 824257a

3 files changed

Lines changed: 24 additions & 5 deletions

File tree

QueryBuilder.Tests/HelperTests.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,5 +224,14 @@ public void ExpandParameters()
224224

225225
Assert.Equal("where id = ? or id in (?,?) or id in ()", expanded);
226226
}
227+
228+
[Theory]
229+
[InlineData(@"ANY('\{1,2,3,4,5\}')", @"\", "{", "[", @"ANY('\{1,2,3,4,5\}')")]
230+
[InlineData(@"ANY('{1,2,3,4,5}')", @"\", "{", "[", @"ANY('[1,2,3,4,5}')")]
231+
public void ReplaceIdentifierUnlessEscaped(string input, string escapeCharacter, string identifier, string newIdentifier, string expected)
232+
{
233+
var result = input.ReplaceIdentifierUnlessEscaped(escapeCharacter, identifier, newIdentifier);
234+
Assert.Equal(expected, result);
235+
}
227236
}
228237
}

QueryBuilder/Compilers/Compiler.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ public partial class Compiler
1515
protected virtual string ColumnAsKeyword { get; set; } = "AS ";
1616
protected virtual string TableAsKeyword { get; set; } = "AS ";
1717
protected virtual string LastId { get; set; } = "";
18+
protected virtual string EscapeCharacter { get; set; } = "\\";
1819

1920
protected Compiler()
2021
{
@@ -809,12 +810,11 @@ public virtual string WrapIdentifiers(string input)
809810
return input
810811

811812
// deprecated
812-
.Replace("{", this.OpeningIdentifier)
813-
.Replace("}", this.ClosingIdentifier)
813+
.ReplaceIdentifierUnlessEscaped(this.EscapeCharacter,"{", this.OpeningIdentifier)
814+
.ReplaceIdentifierUnlessEscaped(this.EscapeCharacter,"}", this.ClosingIdentifier)
814815

815-
.Replace("[", this.OpeningIdentifier)
816-
.Replace("]", this.ClosingIdentifier);
816+
.ReplaceIdentifierUnlessEscaped(this.EscapeCharacter,"[", this.OpeningIdentifier)
817+
.ReplaceIdentifierUnlessEscaped(this.EscapeCharacter,"]", this.ClosingIdentifier);
817818
}
818-
819819
}
820820
}

QueryBuilder/Helper.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,5 +158,15 @@ public static IEnumerable<string> Repeat(this string str, int count)
158158
{
159159
return Enumerable.Repeat(str, count);
160160
}
161+
162+
public static string ReplaceIdentifierUnlessEscaped(this string input, string escapeCharacter, string identifier, string newIdentifier)
163+
{
164+
var nonEscapedRegex = new Regex($@"(?<!\{escapeCharacter}){identifier}");
165+
if (nonEscapedRegex.IsMatch(identifier))
166+
{
167+
return nonEscapedRegex.Replace(input, newIdentifier);
168+
}
169+
return input.Replace(escapeCharacter + identifier, newIdentifier);
170+
}
161171
}
162172
}

0 commit comments

Comments
 (0)