diff --git a/ckanext/datastore/db.py b/ckanext/datastore/db.py index efb67a3c97b..568ac7be7a1 100644 --- a/ckanext/datastore/db.py +++ b/ckanext/datastore/db.py @@ -71,11 +71,13 @@ def _pluck(field, arr): def _is_valid_field_name(name): ''' Check that field name is valid: + * can't start or end with whitespace characters * can't start with underscore * can't contain double quote (") * can't be empty ''' - return name.strip() and not name.startswith('_') and not '"' in name + return (name and name == name.strip() and not name.startswith('_') + and not '"' in name) def _is_valid_table_name(name): diff --git a/ckanext/datastore/tests/test_create.py b/ckanext/datastore/tests/test_create.py index 39dd2e91273..4a9d585cce6 100644 --- a/ckanext/datastore/tests/test_create.py +++ b/ckanext/datastore/tests/test_create.py @@ -305,39 +305,21 @@ def test_create_invalid_field_type(self): def test_create_invalid_field_name(self): resource = model.Package.get('annakarenina').resources[0] - data = { - 'resource_id': resource.id, - 'fields': [{'id': 'book', 'type': 'text'}, - {'id': '_author', 'type': 'text'}] - } - postparams = '%s=1' % json.dumps(data) auth = {'Authorization': str(self.sysadmin_user.apikey)} - res = self.app.post('/api/action/datastore_create', params=postparams, - extra_environ=auth, status=409) - res_dict = json.loads(res.body) - assert res_dict['success'] is False - - data = { - 'resource_id': resource.id, - 'fields': [{'id': 'book', 'type': 'text'}, - {'id': '"author', 'type': 'text'}] - } - postparams = '%s=1' % json.dumps(data) - res = self.app.post('/api/action/datastore_create', params=postparams, - extra_environ=auth, status=409) - res_dict = json.loads(res.body) - assert res_dict['success'] is False - - data = { - 'resource_id': resource.id, - 'fields': [{'id': 'book', 'type': 'text'}, - {'id': '', 'type': 'text'}] - } - postparams = '%s=1' % json.dumps(data) - res = self.app.post('/api/action/datastore_create', params=postparams, - extra_environ=auth, status=409) - res_dict = json.loads(res.body) - assert res_dict['success'] is False + invalid_names = ['_author', '"author', '', ' author', 'author ', + '\tauthor', 'author\n'] + + for field_name in invalid_names: + data = { + 'resource_id': resource.id, + 'fields': [{'id': 'book', 'type': 'text'}, + {'id': field_name, 'type': 'text'}] + } + postparams = '%s=1' % json.dumps(data) + res = self.app.post('/api/action/datastore_create', params=postparams, + extra_environ=auth, status=409) + res_dict = json.loads(res.body) + assert res_dict['success'] is False def test_create_invalid_record_field(self): resource = model.Package.get('annakarenina').resources[0]