Skip to content

Commit aa2c61a

Browse files
committed
syntax
1 parent 3dfd578 commit aa2c61a

File tree

4 files changed

+70
-39
lines changed

4 files changed

+70
-39
lines changed

ckanext/datastore_search/backend/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from ckan.types import DataDict
2-
from typing import Any
2+
from typing import Any, Dict, Optional
33

44
import ckan.plugins as plugins
55
from ckan.common import CKANConfig
@@ -61,7 +61,7 @@ def get_active_backend(cls):
6161
return cls._active_backend
6262

6363
@property
64-
def field_type_map(self):
64+
def field_type_map(self) -> Dict[str, str]:
6565
"""
6666
Map of DataStore field types to their corresponding
6767
search index field types.
@@ -80,8 +80,8 @@ def configure(self, config: CKANConfig):
8080
return config
8181

8282
def reindex(self,
83-
resource_id: str,
84-
connection: Any,
83+
resource_id: Optional[str] = None,
84+
connection: Optional[Any] = None,
8585
only_missing: bool = False) -> Any:
8686
"""Reindex/sync records between the database and the search engine.
8787
"""

ckanext/datastore_search/backend/solr.py

Lines changed: 52 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,13 @@ def field_type_map(self):
7979
# TODO: map object/array types
8080
}
8181

82-
def _make_connection(self, resource_id: str) -> Optional[pysolr.Solr]:
82+
def _make_connection(self,
83+
resource_id: Optional[str] = None) -> Optional[pysolr.Solr]:
8384
"""
8485
Tries to make a SOLR connection to a core.
8586
"""
87+
if not resource_id:
88+
return
8689
core_name = f'{self.prefix}{resource_id}'
8790
conn_string = f'{self.url}/solr/{core_name}'
8891
try:
@@ -122,20 +125,23 @@ def _get_site_context(self) -> Context:
122125
return cast(Context, {'user': site_user['name']})
123126

124127
def reindex(self,
125-
resource_id: str,
128+
resource_id: Optional[str] = None,
126129
connection: Optional[pysolr.Solr] = None,
127130
only_missing: bool = False) -> Any:
128131
"""
129132
Reindexes the SOLR core.
130133
"""
131-
#FIXME: put this in a background task as a larger
132-
# DS Resource could take a long time??
134+
if not resource_id:
135+
return
136+
# FIXME: put this in a background task as a larger
137+
# DS Resource could take a long time??
133138
context = self._get_site_context()
134139
core_name = f'{self.prefix}{resource_id}'
135140
conn = self._make_connection(resource_id) if not connection else connection
136141

137142
if not conn:
138-
return
143+
raise DatastoreSearchException(
144+
_('SOLR core does not exist for DataStore Resource %s') % resource_id)
139145

140146
errmsg = _('Could not reload SOLR core %s') % core_name
141147
resp = self._send_api_request(method='POST',
@@ -172,7 +178,8 @@ def reindex(self,
172178
conn)
173179
if not solr_records:
174180
gathering_solr_records = False
175-
indexed_ids += [r['_id'] for r in solr_records]
181+
# type_ignore_reason: checking solr_records
182+
indexed_ids += [r['_id'] for r in solr_records] # type: ignore
176183
offset += 1000
177184
gathering_ds_records = True
178185
offset = 0
@@ -222,25 +229,34 @@ def reindex(self,
222229
log.debug('Reindexed SOLR Core for DataStore Resource %s' % resource_id)
223230

224231
def _check_counts(self,
225-
resource_id: str,
226-
connection: pysolr.Solr) -> Any:
232+
resource_id: Optional[str] = None,
233+
connection: Optional[pysolr.Solr] = None) -> Any:
227234
"""
228235
Checks if the record counts match between the DataStore and SOLR.
229236
"""
237+
if not resource_id:
238+
return
239+
240+
conn = self._make_connection(resource_id) if not connection else connection
241+
242+
if not conn:
243+
raise DatastoreSearchException(
244+
_('SOLR core does not exist for DataStore Resource %s') % resource_id)
245+
230246
ds_result = get_action('datastore_search')(
231247
self._get_site_context(), {'resource_id': resource_id,
232248
'limit': 0,
233249
'include_total': True,
234250
'skip_search_engine': True})
235251
ds_total = ds_result['total']
236-
solr_result = connection.search(q='*:*', rows=0)
252+
solr_result = conn.search(q='*:*', rows=0)
237253
solr_total = solr_result.hits
238254

239255
if int(ds_total) != int(solr_total):
240256
log.debug('SOLR (count: %s) and Postgres (count: %s) out of sync, '
241257
'reindexing SOLR for DataStore Resource %s' %
242258
(solr_total, ds_total, resource_id))
243-
self.reindex(resource_id, connection, only_missing=True)
259+
self.reindex(resource_id, connection=conn, only_missing=True)
244260

245261
def create(self,
246262
data_dict: DataDict,
@@ -254,17 +270,19 @@ def create(self,
254270
if not conn:
255271
errmsg = _('Could not create SOLR core %s') % core_name
256272
callback_queue = add_queue_name_prefix(self.redis_callback_queue_name)
257-
enqueue_job(fn='solr_utils.create_solr_core.proc.create_solr_core',
258-
kwargs={
259-
'core_name': core_name,
260-
'config_set': self.configset_name,
261-
'callback_fn': 'ckanext.datastore_search.logic.'
262-
'action.datastore_search_create_callback',
263-
'callback_queue': callback_queue,
264-
'callback_timeout': config.get('ckan.jobs.timeout', 300)},
265-
title='SOLR Core creation %s' % core_name,
266-
queue=self.redis_queue_name,
267-
rq_kwargs={'timeout': 60})
273+
enqueue_job(
274+
# type_ignore_reason: incomplete typing
275+
fn='solr_utils.create_solr_core.proc.create_solr_core', # type: ignore
276+
kwargs={
277+
'core_name': core_name,
278+
'config_set': self.configset_name,
279+
'callback_fn': 'ckanext.datastore_search.logic.'
280+
'action.datastore_search_create_callback',
281+
'callback_queue': callback_queue,
282+
'callback_timeout': config.get('ckan.jobs.timeout', 300)},
283+
title='SOLR Core creation %s' % core_name,
284+
queue=self.redis_queue_name,
285+
rq_kwargs={'timeout': 60})
268286
log.debug('Enqueued SOLR Core creation for DataStore Resource %s ' %
269287
resource_id)
270288
return
@@ -276,6 +294,7 @@ def create(self,
276294
solr_fields = json.loads(conn._send_request(
277295
method='GET', path='schema/fields'))['fields']
278296
except pysolr.SolrError as e:
297+
errmsg = _('Could not get SOLR fields from core %s') % core_name
279298
raise DatastoreSearchException(
280299
errmsg if not DEBUG else e.args[0][:MAX_ERR_LEN])
281300
keyed_solr_fields = {}
@@ -297,11 +316,13 @@ def create(self,
297316
'stored': True,
298317
'indexed': True})
299318
continue
300-
if self.field_type_map[ds_field['type']] == keyed_solr_fields[ds_field['id']]['type']:
319+
if self.field_type_map[ds_field['type']] == \
320+
keyed_solr_fields[ds_field['id']]['type']:
301321
continue
302322
updated_fields.append(dict(keyed_solr_fields[ds_field['id']],
303323
type=self.field_type_map[ds_field['type']]))
304-
for field_name in [i for i in keyed_solr_fields.keys() if i not in ds_field_ids]:
324+
for field_name in [i for i in keyed_solr_fields.keys()
325+
if i not in ds_field_ids]:
305326
remove_fields.append({'name': field_name})
306327

307328
for f in new_fields:
@@ -401,7 +422,8 @@ def upsert(self,
401422
conn = self._make_connection(resource_id) if not connection else connection
402423

403424
if not conn:
404-
return
425+
raise DatastoreSearchException(
426+
_('SOLR core does not exist for DataStore Resource %s') % resource_id)
405427

406428
if data_dict['records']:
407429
for r in data_dict['records']:
@@ -420,7 +442,8 @@ def upsert(self,
420442

421443
def search(self,
422444
data_dict: DataDict,
423-
connection: Optional[pysolr.Solr] = None) -> Optional[List[Dict[str, Any]]]:
445+
connection: Optional[pysolr.Solr] = None) \
446+
-> Optional[List[Dict[str, Any]]]:
424447
"""
425448
Searches the SOLR records.
426449
"""
@@ -487,13 +510,15 @@ def delete(self,
487510
conn = self._make_connection(resource_id) if not connection else connection
488511

489512
if not conn:
490-
return
513+
raise DatastoreSearchException(
514+
_('SOLR core does not exist for DataStore Resource %s') % resource_id)
491515

492516
if not data_dict.get('filters'):
493517
errmsg = _('Could not delete SOLR core %s') % core_name
494518
try:
495519
conn.delete(q='*:*', commit=False)
496-
log.debug('Unindexed all DataStore records for Resource %s' % resource_id)
520+
log.debug('Unindexed all DataStore records for Resource %s' %
521+
resource_id)
497522
except pysolr.SolrError as e:
498523
raise DatastoreSearchException(
499524
errmsg if not DEBUG else e.args[0][:MAX_ERR_LEN])

ckanext/datastore_search/logic/action.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from typing import Dict, Any, Union
12
from ckan.types import Context, DataDict, Action, ChainedAction
23

34
from ckan.plugins import toolkit
@@ -64,7 +65,8 @@ def datastore_delete(up_func: Action,
6465
@toolkit.chained_action
6566
def datastore_search(up_func: Action,
6667
context: Context,
67-
data_dict: DataDict) -> ChainedAction:
68+
data_dict: DataDict) -> Union[ChainedAction,
69+
Dict[str, Any]]:
6870
schema = context.get('schema', datastore_search_schema())
6971
schema['skip_search_engine'] = [ignore_missing, ignore_not_sysadmin]
7072
data_dict, errors = validate(data_dict, schema, context)

ckanext/datastore_search/plugin.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import ckan.plugins as plugins
22
from ckan.common import CKANConfig
33

4-
from typing import Dict, Union
4+
from typing import Dict, Union, Type
55
from ckan.types import (
66
Context,
77
DataDict,
@@ -16,10 +16,13 @@
1616

1717
from ckanext.datapusher.interfaces import IDataPusher
1818
try:
19-
from ckanext.xloader.interfaces import IXloader
20-
HAS_XLOADER = True
19+
# type_ignore_reason: catch ImportError
20+
from ckanext.xloader.interfaces import IXloader # type: ignore
21+
# type_ignore_reason: not redifined if ImportError
22+
HAS_XLOADER = True # type: ignore
2123
except ImportError:
22-
HAS_XLOADER = False
24+
# type_ignore_reason: not redifined if ImportError
25+
HAS_XLOADER = False # type: ignore
2326

2427

2528
@plugins.toolkit.blanket.config_declarations
@@ -30,10 +33,11 @@ class DataStoreSearchPlugin(plugins.SingletonPlugin):
3033
plugins.implements(IDatastoreSearchBackend, inherit=True)
3134
plugins.implements(IDataPusher, inherit=True)
3235
if HAS_XLOADER:
33-
plugins.implements(IXloader, inherit=True)
36+
# type_ignore_reason: never unbound due to HAS_XLOADER
37+
plugins.implements(IXloader, inherit=True) # type: ignore
3438

3539
# IDatastoreSearchBackend
36-
def register_backends(self) -> Dict[str, DatastoreSearchBackend]:
40+
def register_backends(self) -> Dict[str, Type[DatastoreSearchBackend]]:
3741
return {'solr': DatastoreSolrBackend}
3842

3943
# IConfigurer
@@ -76,4 +80,4 @@ def after_upload(self,
7680
'resource_id': resource_dict.get('id'),
7781
'fields': [f for f in ds_result['fields'] if
7882
f['id'] not in backend.default_search_fields]}
79-
backend.create(context, create_dict)
83+
backend.create(create_dict)

0 commit comments

Comments
 (0)