Skip to content

Commit

Permalink
Bugfix: When working with SQL queries with string paramters, SQL esca…
Browse files Browse the repository at this point in the history
…pe (') characters as (''). (#93)

* Bugfix: When working with SQL queries with string paramters, SQL escape (') characters as ('').

* Forgot to remove debugging output.
  • Loading branch information
vnayar authored Jun 12, 2024
1 parent 6fc1767 commit 7f23495
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
11 changes: 9 additions & 2 deletions hdtest/source/embeddedtest.d
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ class EmbeddedTest : HibernateTest {
assert(c1Id > 0);

Customer c2 = new Customer();
c2.name = "Jumpy Bunny";
// Single quotes (') are quoted as ('') in SQL.
c2.name = "Erdrick O'Henry";
c2.shippingAddress = new Address();
c2.shippingAddress.street = "21 Grassy Knoll";
c2.shippingAddress.city = "Warrenton";
Expand All @@ -74,6 +75,13 @@ class EmbeddedTest : HibernateTest {
Customer c2 = r2.uniqueResult!Customer();
assert(c2 !is null);
assert(c2.billingAddress.street == "101001 Robotface");

// Make sure queries on strings with (') characters work.
auto r3 = sess.createQuery("FROM Customer WHERE name = :Name")
.setParameter("Name", "Erdrick O'Henry");
Customer c3 = r3.uniqueResult!Customer();
assert(c3.name == "Erdrick O'Henry");
assert(c3.shippingAddress.city == "Warrenton");
}

@Test("embedded.read.query-order-by")
Expand Down Expand Up @@ -139,5 +147,4 @@ class EmbeddedTest : HibernateTest {

sess.close();
}

}
8 changes: 7 additions & 1 deletion source/hibernated/query.d
Original file line number Diff line number Diff line change
Expand Up @@ -1521,7 +1521,13 @@ Token[] tokenize(string s) {
// string constant
i++;
for(int j=i; j<len; j++) {
if (s[j] != '\'') {
// In SQL, (') characters are quoted as ('').
if (s[j] == '\'' && j+1 < len && s[j+1] == '\'') {
text ~= s[j];
j++;
text ~= s[j];
}
else if (s[j] != '\'') {
text ~= s[j];
i = j;
} else {
Expand Down
4 changes: 3 additions & 1 deletion source/hibernated/session.d
Original file line number Diff line number Diff line change
Expand Up @@ -944,10 +944,12 @@ class PropertyLoadItem {
}

string createKeySQL(Variant id) {
import std.string : translate;
if (id.convertsTo!long || id.convertsTo!ulong) {
return id.toString();
} else {
return "'" ~ id.toString() ~ "'";
// Quote (') in strings as ('') according to the SQL standard.
return "'" ~ id.toString().translate(['\'': "''"]) ~ "'";
}
}

Expand Down

0 comments on commit 7f23495

Please sign in to comment.