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 apostrophes in SQL queries #1542

Merged
merged 1 commit into from
Jan 23, 2019
Merged
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
Binary file modified onadata/apps/main/tests/fixtures/sample_accent.xlsx
Binary file not shown.
9 changes: 8 additions & 1 deletion onadata/libs/data/query.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import logging
from django.conf import settings
from django.db import connection

from onadata.libs.utils.common_tags import SUBMISSION_TIME
from onadata.apps.logger.models.data_view import DataView


logger = logging.getLogger(__name__)


def _dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
Expand Down Expand Up @@ -48,7 +52,10 @@ def _additional_data_view_filters(data_view):


def _json_query(field):
return "json->>'%s'" % field
if not field:
logger.info("Field is empty")
return "json->>'%s'" % field
return "json->>'%s'" % field.replace("'", "''")


def _postgres_count_group_field_n_group_by(field, name, xform, group_by,
Expand Down
20 changes: 20 additions & 0 deletions onadata/libs/tests/utils/test_chart_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,26 @@ def test_build_chart_data_for_fields_with_accents(self):
data = build_chart_data_for_field(self.xform, field)
self.assertEqual(data['field_name'], 'père')

def test_build_chart_data_for_fields_with_apostrophies(self):
"""
Test that apostrophes are escaped before they are sent to the database.

If the not escaped a django.db.utils.ProgrammingError would be raised.
"""
xls_path = os.path.join(self.this_directory, "fixtures",
"sample_accent.xlsx")
count = XForm.objects.count()
self._publish_xls_file(xls_path)

self.assertEquals(XForm.objects.count(), count + 1)

xform = XForm.objects.get(id_string='sample_accent')
self.assertEqual(xform.title, "sample_accent")

field = find_field_by_name(xform, "ChưR'căm")
data = build_chart_data_for_field(xform, field)
self.assertEqual(data['field_name'], "ChưR'căm")

def test_build_chart_data_for_field_on_select_one(self):
field_name = 'gender'
field = find_field_by_name(self.xform, field_name)
Expand Down