diff --git a/ckanext/datastore/helpers.py b/ckanext/datastore/helpers.py index d2441cdc439..08007a9d93d 100644 --- a/ckanext/datastore/helpers.py +++ b/ckanext/datastore/helpers.py @@ -99,4 +99,11 @@ def literal_string(s): """ Return s as a postgres literal string """ - return u"'" + s.replace(u"'", u"''") + u"'" + return u"'" + s.replace(u"'", u"''").replace(u'\0', '') + u"'" + + +def identifier(s): + """ + Return s as a quoted postgres identifier + """ + return u'"' + s.replace(u'"', u'""').replace(u'\0', '') + u'"' diff --git a/ckanext/datastore/plugin.py b/ckanext/datastore/plugin.py index 2a924f21759..9b3bc40110c 100644 --- a/ckanext/datastore/plugin.py +++ b/ckanext/datastore/plugin.py @@ -357,6 +357,8 @@ def _parse_sort_clause(self, clause, fields_types): return False field = clause_match.group(1) + if field[0] == field[-1] == u'"': + field = field[1:-1] sort = (clause_match.group(3) or u'asc').lower() if field not in fields_types: @@ -460,7 +462,8 @@ def _sort(self, data_dict, fields_types): for clause in clauses: field, sort = self._parse_sort_clause(clause, fields_types) - clause_parsed.append(u'"{0}" {1}'.format(field, sort)) + clause_parsed.append( + u'{0} {1}'.format(datastore_helpers.identifier(field), sort)) return clause_parsed