Skip to content
This repository has been archived by the owner on Feb 15, 2022. It is now read-only.

Add absolute form query, label and delete queries #21

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
38 changes: 29 additions & 9 deletions cqapi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,25 @@ class ConqueryClientConnectionError(CqApiError):
def __init__(self, msg):
self.message = msg


async def get(session, url):
async with session.get(url) as response:
return await response.json()


async def get_text(session, url):
async with session.get(url) as response:
return await response.text()


async def post(session, url, data):
async with session.post(url, json=data) as response:
return await response.json()

async def patch(session, url, data):
async with session.patch(url, json = data) as response:
return await response.json()

async def delete(session, url, ):
async with session.delete(url) as response:
return await response.text()

class ConqueryConnection(object):
async def __aenter__(self):
Expand Down Expand Up @@ -68,28 +72,44 @@ async def get_stored_query(self, dataset, query_id):
result = await get(self._session, f"{self._url}/api/datasets/{dataset}/stored-queries/{query_id}")
return result.get('query')

async def get_query(self, dataset, query_id):
result = await get(self._session, f"{self._url}/api/datasets/{dataset}/queries/{query_id}")
async def delete_stored_query(self, dataset, query_id):
result = await delete(self._session, f"{self._url}/api/datasets/{dataset}/stored-queries/{query_id}")
return result

async def execute_query(self, dataset, query):
async def get_query(self, dataset, query_id, is_form_query):
if is_form_query:
result = await get(self._session, f"{self._url}/api/datasets/{dataset}/form-queries/{query_id}")
else:
result = await get(self._session, f"{self._url}/api/datasets/{dataset}/queries/{query_id}")
return result

async def execute_query(self, dataset, query, label = None):
result = await post(self._session, f"{self._url}/api/datasets/{dataset}/queries", query)
try:
if label is not None:
await patch(self._session, f"{self._url}/api/datasets/{dataset}/stored-queries/{result['id']}",data={"label":label})
return result['id']
except KeyError:
raise ValueError("Error encountered when executing query", result.get('message'), result.get('details'))

async def execute_form_query(self, dataset, form_query):
result = await post(self._session, f"{self._url}/api/datasets/{dataset}/form-queries", form_query)
try:
return result['id']
except KeyError:
raise ValueError("Error encountered when executing query", result.get('message'), result.get('details'))

async def get_query_result(self, dataset, query_id):
async def get_query_result(self, dataset, query_id, is_form_query = False):
""" Returns results for given query.
Blocks until the query is DONE.

:param dataset:
:param query_id:
:return: str containing the returned csv's
"""
response = await self.get_query(dataset, query_id)
response = await self.get_query(dataset, query_id, is_form_query)
while not response['status'] == 'DONE':
response = await self.get_query(dataset, query_id)
response = await self.get_query(dataset, query_id, is_form_query)

result_string = await self._download_query_results(response["resultUrl"])
return list(csv.reader(result_string.splitlines(), delimiter=';'))
Expand Down
31 changes: 30 additions & 1 deletion cqapi/util.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import date
from datetime import datetime
from copy import deepcopy


Expand Down Expand Up @@ -233,6 +234,35 @@ def add_subquery_to_concept_query(query, subquery):
}
return query

def create_absolute_form_query(query_id, feature_queries: list, dateRange: list):

""" Create an ABSOLUTE_FORM_QUERY
:param query_id: ID of the query that will be used to get the patient group
:param feature_queries: list of concept queries to add columns
:param dateRange: date range with list containing first and last date, dates have to be in format %Y-%m-%d
:return:
"""

if datetime.strptime(dateRange[0],'%Y-%m-%d') > datetime.strptime(dateRange[1],'%Y-%m-%d'):
raise ValueError(f"Invalid dateRange. {dateRange[0]} is after {dateRange[1]}")
for feature_query in feature_queries:
if 'root' not in feature_query.keys():
raise ValueError(f"Invalid feature query. Query {feature_query} has no key root")

features = [ {'type' : 'OR', 'children' : [ feature_query['root'] ] } for feature_query in feature_queries ]

return {
'type' : 'EXPORT_FORM',
'queryGroup' : query_id,
'timeMode' : {
"value" : 'ABSOLUTE',
'dateRange' : {
'min' : dateRange[0],
'max' : dateRange[1]
},
'features' : features
}
}

def create_relative_query(index_query, before_query, after_query, time_before, time_after,
index_selector='FIRST', index_placement='NEUTRAL', time_unit='QUARTERS'):
Expand Down Expand Up @@ -280,7 +310,6 @@ def create_relative_query(index_query, before_query, after_query, time_before, t
'timeUnit': time_unit
}


def _parse_iso_date(datestring: str):
y, m, d = map(lambda x: int(x), datestring.split('-'))
return date(y, m, d)