-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataSource.py
More file actions
238 lines (213 loc) · 8.3 KB
/
DataSource.py
File metadata and controls
238 lines (213 loc) · 8.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
from rest_framework import status
from django.db.models import Q, Subquery, OuterRef
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django.contrib.postgres.search import TrigramWordSimilarity
from ...models import DataSource, Template, GenericEntity
from ...entity_utils import api_utils, gen_utils, constants
@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def get_datasources(request):
"""
Get all DataSources
Available parameters:
| Param | Type | Default | Desc |
|---------------|-----------------|---------|---------------------------------------------------------------|
| search | `str` | `NULL` | Full-text search across _name_ and _description_ fields |
| id | `int/list[int]` | `NULL` | Match by a single `int` _id_ field, or match by array overlap |
| name | `str` | `NULL` | Case insensitive direct match of _name_ field |
| uid | `str/uuid` | `NULL` | Case insensitive direct match of _uid_ field |
| datasource_id | `int` | `NULL` | Match by exact _datasource_id_ |
| url | `str` | `NULL` | Case insensitive direct match of _url_ field |
| source | `str` | `NULL` | Case insensitive direct match of _source_ field |
"""
params = gen_utils.parse_model_field_query(DataSource, request, ignored_fields=['description'])
if params is not None:
datasources = DataSource.objects.filter(**params)
else:
datasources = DataSource.objects.all()
search = request.query_params.get('search')
if not gen_utils.is_empty_string(search) and len(search.strip()) > 3:
datasources = datasources.annotate(
similarity=(
TrigramWordSimilarity(search, 'name') + \
TrigramWordSimilarity(search, 'description')
)
) \
.filter(Q(similarity__gte=0.7)) \
.order_by('-similarity')
else:
datasources = datasources.order_by('id')
return Response(
data=datasources.values('id', 'name', 'description', 'url', 'uid', 'datasource_id', 'source'),
status=status.HTTP_200_OK
)
@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def get_datasource_internal_detail(request, datasource_id):
"""
Get detail of specified datasource by by its internal Id
"""
query = None
if gen_utils.parse_int(datasource_id, default=None) is not None:
query = { 'id': int(datasource_id) }
if not query:
return Response(
data={
'message': 'Invalid id, expected int-like value'
},
content_type='json',
status=status.HTTP_400_BAD_REQUEST
)
datasource = DataSource.objects.filter(**query)
if not datasource.exists():
return Response(
data={
'message': 'Datasource with this internal Id does not exist'
},
content_type='json',
status=status.HTTP_404_NOT_FOUND
)
datasource = datasource.first()
# Get all templates and their versions where data_sources exist
templates = Template.history.filter(
definition__fields__has_key='data_sources'
) \
.annotate(
was_deleted=Subquery(
Template.history.filter(
id=OuterRef('id'),
history_date__gte=OuterRef('history_date'),
history_type='-'
)
.order_by('id', '-history_id')
.distinct('id')
.values('id')
)
) \
.exclude(was_deleted__isnull=False) \
.order_by('id', '-template_version', '-history_id') \
.distinct('id', 'template_version')
template_ids = list(templates.values_list('id', flat=True))
template_versions = list(templates.values_list('template_version', flat=True))
# Get all published entities with this datasource
entities = GenericEntity.history.filter(
template_id__in=template_ids,
template_version__in=template_versions,
publish_status=constants.APPROVAL_STATUS.APPROVED.value
) \
.extra(where=[f"""
exists(
select 1
from jsonb_array_elements(
case jsonb_typeof(template_data->'data_sources') when 'array'
then template_data->'data_sources'
else '[]'
end
) as val
where val in ('{datasource.id}')
)"""
]) \
.order_by('id', '-history_id') \
.distinct('id')
# Format results
entities = api_utils.annotate_linked_entities(entities)
result = {
'id': datasource.id,
'name': datasource.name,
'url': datasource.url,
'uid': datasource.uid,
'description': datasource.description,
'source': datasource.source,
'phenotypes': list(entities)
}
return Response(
data=result,
status=status.HTTP_200_OK
)
@api_view(['GET'])
@permission_classes([IsAuthenticatedOrReadOnly])
def get_datasource_detail(request, datasource_id):
"""
Get detail of specified datasource by `datasource_id`, _i.e._ the HDRUK DataSource `pid` or its `UUID` for linkage between applications, including associated published entities.
"""
query = None
if gen_utils.is_valid_uuid(datasource_id):
query = { 'uid': datasource_id }
elif gen_utils.parse_int(datasource_id, default=None) is not None:
query = { 'datasource_id': int(datasource_id) }
if not query:
return Response(
data={
'message': 'Invalid id, should be datasource id or datasource UUID'
},
content_type='json',
status=status.HTTP_400_BAD_REQUEST
)
datasource = DataSource.objects.filter(**query)
if not datasource.exists():
return Response(
data={
'message': 'Datasource with id/UUID does not exist'
},
content_type='json',
status=status.HTTP_404_NOT_FOUND
)
datasource = datasource.first()
# Get all templates and their versions where data_sources exist
templates = Template.history.filter(
definition__fields__has_key='data_sources'
) \
.annotate(
was_deleted=Subquery(
Template.history.filter(
id=OuterRef('id'),
history_date__gte=OuterRef('history_date'),
history_type='-'
)
.order_by('id', '-history_id')
.distinct('id')
.values('id')
)
) \
.exclude(was_deleted__isnull=False) \
.order_by('id', '-template_version', '-history_id') \
.distinct('id', 'template_version')
template_ids = list(templates.values_list('id', flat=True))
template_versions = list(templates.values_list('template_version', flat=True))
# Get all published entities with this datasource
entities = GenericEntity.history.filter(
template_id__in=template_ids,
template_version__in=template_versions,
publish_status=constants.APPROVAL_STATUS.APPROVED.value
) \
.extra(where=[f"""
exists(
select 1
from jsonb_array_elements(
case jsonb_typeof(template_data->'data_sources') when 'array'
then template_data->'data_sources'
else '[]'
end
) as val
where val in ('{datasource.id}')
)"""
]) \
.order_by('id', '-history_id') \
.distinct('id')
# Format results
entities = api_utils.annotate_linked_entities(entities)
result = {
'id': datasource.id,
'name': datasource.name,
'url': datasource.url,
'uid': datasource.uid,
'description': datasource.description,
'source': datasource.source,
'phenotypes': list(entities)
}
return Response(
data=result,
status=status.HTTP_200_OK
)