Skip to content

Commit

Permalink
Escape quotes in identifiers
Browse files Browse the repository at this point in the history
  • Loading branch information
Oleksandr Malyga committed Nov 24, 2023
1 parent 627b60a commit 8f6febf
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
1 change: 0 additions & 1 deletion pypika/terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,6 @@ def get_formatted_value(cls, value: Any, **kwargs):
if isinstance(value, date):
return cls.get_formatted_value(value.isoformat(), **kwargs)
if isinstance(value, str):
value = value.replace(quote_char, quote_char * 2)
return format_quotes(value, quote_char)
if isinstance(value, bool):
return str.lower(str(value))
Expand Down
22 changes: 22 additions & 0 deletions pypika/tests/test_terms.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,25 @@ def test_passes_kwargs_to_field_get_sql(self):
'FROM "customers" JOIN "accounts" ON "customers"."account_id"="accounts"."account_id"',
query.get_sql(with_namespace=True),
)


class IdentifierEscapingTests(TestCase):
def test_escape_identifier_quotes(self):
customers = Table('customers"')
customer_id = getattr(customers, '"id')
email = getattr(customers, 'email"').as_('customer_email"')

query = (
Query.from_(customers)
.select(customer_id, email)
.where(customer_id == "abc")
.where(email == "abc@abc.com")
.orderby(email, customer_id)
)

self.assertEqual(
'SELECT """id","email""" "customer_email""" '
'FROM "customers""" WHERE """id"=\'abc\' AND "email"""=\'abc@abc.com\' '
'ORDER BY "customer_email""","""id"',
query.get_sql(),
)
3 changes: 3 additions & 0 deletions pypika/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ def resolve_is_aggregate(values: List[Optional[bool]]) -> Optional[bool]:


def format_quotes(value: Any, quote_char: Optional[str]) -> str:
if quote_char:
value = value.replace(quote_char, quote_char * 2)

return "{quote}{value}{quote}".format(value=value, quote=quote_char or "")


Expand Down

0 comments on commit 8f6febf

Please sign in to comment.