Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape quotes in identifiers #771

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"')
Comment on lines +80 to +82
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens with single quotes inside double quotes?


query = (
Query.from_(customers)
.select(customer_id, email)
.where(customer_id == "abc")
.where(email == "[email protected]")
.orderby(email, customer_id)
)

self.assertEqual(
'SELECT """id","email""" "customer_email""" '
'FROM "customers""" WHERE """id"=\'abc\' AND "email"""=\'[email protected]\' '
'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