Skip to content

Commit 2fcb182

Browse files
Escape quotes in identifiers
1 parent 627b60a commit 2fcb182

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

pypika/terms.py

-1
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,6 @@ def get_formatted_value(cls, value: Any, **kwargs):
375375
if isinstance(value, date):
376376
return cls.get_formatted_value(value.isoformat(), **kwargs)
377377
if isinstance(value, str):
378-
value = value.replace(quote_char, quote_char * 2)
379378
return format_quotes(value, quote_char)
380379
if isinstance(value, bool):
381380
return str.lower(str(value))

pypika/tests/test_terms.py

+22
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,25 @@ def test_passes_kwargs_to_field_get_sql(self):
7373
'FROM "customers" JOIN "accounts" ON "customers"."account_id"="accounts"."account_id"',
7474
query.get_sql(with_namespace=True),
7575
)
76+
77+
78+
class IdentifierEscapingTests(TestCase):
79+
def test_escape_identifier_quotes(self):
80+
customers = Table('customers"')
81+
customer_id = getattr(customers, '"id')
82+
email = getattr(customers, 'email"').as_('customer_email"')
83+
84+
query = (
85+
Query.from_(customers)
86+
.select(customer_id, email)
87+
.where(customer_id == "abc")
88+
.where(email == "abc@abc.com")
89+
.orderby(email, customer_id)
90+
)
91+
92+
self.assertEqual(
93+
'SELECT """id","email""" "customer_email""" '
94+
'FROM "customers""" WHERE """id"=\'abc\' AND "email"""=\'abc@abc.com\' '
95+
'ORDER BY "customer_email""","""id"',
96+
query.get_sql(),
97+
)

pypika/utils.py

+3
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ def resolve_is_aggregate(values: List[Optional[bool]]) -> Optional[bool]:
103103

104104

105105
def format_quotes(value: Any, quote_char: Optional[str]) -> str:
106+
if quote_char:
107+
value = value.replace(quote_char, quote_char * 2)
108+
106109
return "{quote}{value}{quote}".format(value=value, quote=quote_char or "")
107110

108111

0 commit comments

Comments
 (0)