Repository: ckan/ckan

Issue:
API option doesn't show when the multiple resources are added to the new datasets. 
**CKAN version**
**2.9.5**

**Describe the bug**
Datastore won't get active when multiple resources are added to the newly created datasets. 

**Steps to reproduce**
1. Create Datasets 
2. Add New resource 
3.  Click `Save and add another` resource to add another resource. 
4.  Finally click `Save` to finish the dataset creation. You will see that only one dataset has an API option,  even all files pushed to the datastore. 

**Expected behavior**
datastore state should be active even when multiple resources are added. 

**Additional  details**
I think for some reason datastore state doesn't get updated for the draft dataset. 


Discussion:
Hey @smotornyuk, @sagargg,  I was doing a bit of research about this problem, seems everything's fine except this query from `solr` which returns an empty list after we submit the first resource:
https://github.com/ckan/ckan/blob/d61a533cc330b6050f4957573f58ec912695ed0a/ckanext/datastore/logic/action.py#L662-L668

So our first resource never reaches for the update in line 666 which contains the `{'datastore': True}`

Seems like `solr` cannot find the package with the given id when we are adding two resources in a row with `save & add another` `button`... (This is valid for the first resource only.)

Do you have any idea why this happens? 
Thanks

ps. One weird behavior I've noticed: accidentally forgot to remove breakpoints (which cause to stop the worker) and after submitting both resources in a row I noticed the worker stuck on the breakpoint after exiting it I can see now both resources are with Data API.
By default CKAN [filters out all draft datasets(non-active)](https://github.com/ckan/ckan/blob/master/ckan/lib/search/query.py#L339-L340). When created, the dataset remains in the draft state till the user clicks on the **Finish** button.

@smotornyuk instead of making a query on the `solr-side` and iterating over it, can we just do this? 

![image](https://user-images.githubusercontent.com/72216462/151158563-f9642ca4-46cb-4b4e-9d47-39585257c09c.png)

Thanks

Generally, yes. Just don't forget to take into account the fact that `package_show` can throw NotAuthorized/NotFound exceptions if the context is misformed. Not sure if it's possible to get such an exception  in this particular case(there person, who uploads a resource probably has full access to the given package), but it's better to check if any worth-case scenario can happen
@smotornyuk Thanks

Resolving patch:
diff --git a/ckanext/datastore/logic/action.py b/ckanext/datastore/logic/action.py
--- a/ckanext/datastore/logic/action.py
+++ b/ckanext/datastore/logic/action.py
@@ -170,7 +170,7 @@ def datastore_create(context, data_dict):
         log.debug(
             'Setting datastore_active=True on resource {0}'.format(resobj.id)
         )
-        set_datastore_active_flag(model, data_dict, True)
+        set_datastore_active_flag(context, data_dict, True)
 
     result.pop('id', None)
     result.pop('connection_url', None)
@@ -423,7 +423,7 @@ def datastore_delete(context, data_dict):
             'Setting datastore_active=False on resource {0}'.format(
                 resource.id)
         )
-        set_datastore_active_flag(model, data_dict, False)
+        set_datastore_active_flag(context, data_dict, False)
 
     result.pop('id', None)
     result.pop('connection_url', None)
@@ -622,7 +622,7 @@ def check_access(table_names):
     return result
 
 
-def set_datastore_active_flag(model, data_dict, flag):
+def set_datastore_active_flag(context, data_dict, flag):
     '''
     Set appropriate datastore_active flag on CKAN resource.
 
@@ -631,6 +631,7 @@ def set_datastore_active_flag(model, data_dict, flag):
     # We're modifying the resource extra directly here to avoid a
     # race condition, see issue #3245 for details and plan for a
     # better fix
+    model = context['model']
     update_dict = {'datastore_active': flag}
 
     # get extras(for entity update) and package_id(for search index update)
@@ -648,24 +649,20 @@ def set_datastore_active_flag(model, data_dict, flag):
 
     model.Session.commit()
 
-    # get package with  updated resource from solr
+    # get package with  updated resource from package_show
     # find changed resource, patch it and reindex package
     psi = search.PackageSearchIndex()
-    solr_query = search.PackageSearchQuery()
-    q = {
-        'q': 'id:"{0}"'.format(package_id),
-        'fl': 'data_dict',
-        'wt': 'json',
-        'fq': 'site_id:"%s"' % config.get_value('ckan.site_id'),
-        'rows': 1
-    }
-    for record in solr_query.run(q)['results']:
-        solr_data_dict = json.loads(record['data_dict'])
-        for resource in solr_data_dict['resources']:
+    try:
+        _data_dict = p.toolkit.get_action('package_show')(context, {
+            'id': package_id
+        })
+        for resource in _data_dict['resources']:
             if resource['id'] == data_dict['resource_id']:
                 resource.update(update_dict)
-                psi.index_package(solr_data_dict)
+                psi.index_package(_data_dict)
                 break
+    except (logic.NotAuthorized, logic.NotFound) as e:
+        log.error(e.message)
 
 
 def _check_read_only(context, resource_id):


Test patch: