-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathselect.py
2724 lines (2345 loc) · 89 KB
/
select.py
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Functions to select data from the database."""
import asyncio
import json
from fastapi import HTTPException, status
from psycopg import sql
from zeno_backend.classes.base import MetadataType, ZenoColumn, ZenoColumnType
from zeno_backend.classes.chart import Chart, ChartConfig
from zeno_backend.classes.filter import FilterPredicateGroup, Join, Operation
from zeno_backend.classes.folder import Folder
from zeno_backend.classes.homepage import EntrySort, HomeRequest
from zeno_backend.classes.metadata import HistogramBucket, StringFilterRequest
from zeno_backend.classes.metric import Metric
from zeno_backend.classes.project import (
Project,
ProjectState,
ProjectStats,
)
from zeno_backend.classes.report import (
Report,
ReportElement,
ReportResponse,
ReportStats,
SliceElementOptions,
TagElementOptions,
)
from zeno_backend.classes.slice import Slice
from zeno_backend.classes.slice_finder import SQLTable
from zeno_backend.classes.table import (
SliceTableRequest,
TableRequest,
TagTableRequest,
)
from zeno_backend.classes.tag import Tag
from zeno_backend.classes.user import Author, Organization, User
from zeno_backend.database.database import db_pool
from zeno_backend.database.util import hash_api_key, match_instance_view
from zeno_backend.processing.filtering import table_filter
from zeno_backend.processing.histogram_processing import calculate_histogram_bucket
PROJECTS_BASE_QUERY = sql.SQL(
"""
(SELECT main.*, u.name AS owner_name FROM (
SELECT p.uuid, p.name, p.owner_id, p.view, p.samples_per_page,
p.public, p.description, TRUE AS editor, p.created_at, p.updated_at
FROM projects AS p
WHERE p.owner_id = %s
UNION
SELECT p.uuid, p.name, p.owner_id, p.view, p.samples_per_page,
p.public, p.description, up.editor, p.created_at, p.updated_at
FROM projects AS p
LEFT JOIN user_project AS up ON p.uuid = up.project_uuid
WHERE up.user_id = %s AND p.owner_id != %s
UNION
SELECT p.uuid, p.name, p.owner_id, p.view, p.samples_per_page,
p.public, p.description, op.editor, p.created_at, p.updated_at
FROM projects AS p
JOIN (SELECT op.project_uuid, uo.organization_id, editor
FROM user_organization AS uo
JOIN organization_project AS op
ON uo.organization_id = op.organization_id
WHERE uo.user_id = %s) AS op ON p.uuid = op.project_uuid
WHERE p.owner_id != %s) AS main
LEFT JOIN users AS u ON main.owner_id = u.id)
"""
)
REPORTS_BASE_QUERY = sql.SQL(
"""
(SELECT main.*, u.name AS owner_name FROM (
SELECT r.id, r.name, r.owner_id, r.public, r.description, TRUE AS editor,
r.created_at, r.updated_at FROM reports AS r
WHERE r.owner_id = %s
UNION
SELECT r.id, r.name, r.owner_id, r.public, r.description, ur.editor,
r.created_at, r.updated_at FROM reports AS r
LEFT JOIN user_report AS ur ON r.id = ur.report_id
WHERE ur.user_id = %s AND r.owner_id != %s
UNION
SELECT r.id, r.name, r.owner_id, r.public, r.description, orr.editor,
r.created_at, r.updated_at FROM reports AS r
JOIN (SELECT orr.report_id, uo.organization_id, editor
FROM user_organization AS uo
JOIN organization_report AS orr
ON uo.organization_id = orr.organization_id
WHERE uo.user_id = %s) AS orr ON r.id = orr.report_id
WHERE r.owner_id != %s) AS main
LEFT JOIN users AS u ON main.owner_id = u.id)
"""
)
async def models(project: str) -> list[str]:
"""Get all models for a specified project.
Args:
project (str): the project the user is currently working with.
Returns:
list[str]: a list of model names included in the project.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
sql.SQL(
"SELECT DISTINCT model FROM {} WHERE model IS NOT NULL "
"ORDER BY model;"
).format(sql.Identifier(f"{project}_column_map"))
)
model_results = await cur.fetchall()
return [m[0] for m in model_results]
async def projects(
user: User, home_request: HomeRequest = HomeRequest()
) -> list[Project]:
"""Get all projects available to the user.
Args:
user (User): the user for which to fetch the available projects.
home_request (ProjectsRequest): the request object.
Returns:
list[Project]: the projects that the user can interact with.
"""
params = [user.id, user.id, user.id, user.id, user.id]
likes_query = sql.SQL(
"SELECT project_uuid, COUNT(*) as total_likes"
" FROM project_like GROUP BY project_uuid "
)
projects_query = (
sql.SQL("WITH LikesSummary AS (")
+ likes_query
+ sql.SQL("),")
+ sql.SQL(" CombinedProjects AS (")
+ PROJECTS_BASE_QUERY
+ sql.SQL(") ")
+ sql.SQL(
"SELECT cp.*, COALESCE(ls.total_likes, 0) AS total_likes FROM"
" CombinedProjects cp LEFT JOIN LikesSummary ls "
" ON cp.uuid = ls.project_uuid "
)
)
if home_request.search_string:
projects_query += sql.SQL(
"WHERE (LOWER(cp.name) LIKE LOWER(%s) OR "
"LOWER(cp.description) LIKE LOWER(%s)) "
)
params += [
"%" + home_request.search_string + "%",
"%" + home_request.search_string + "%",
]
if home_request.sort == EntrySort.POPULAR:
projects_query += sql.SQL(" ORDER BY total_likes DESC, updated_at DESC ")
elif home_request.sort == EntrySort.RECENT:
projects_query += sql.SQL(" ORDER BY updated_at DESC, total_likes DESC ")
if home_request.limit:
projects_query += sql.SQL(" LIMIT %s ")
params += [home_request.limit]
projects_query += sql.SQL(" OFFSET %s; ")
params += [home_request.project_offset]
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(projects_query, params)
projects_result = await cur.fetchall()
projects = []
for res in projects_result:
projects.append(
Project(
uuid=res[0],
name=res[1],
view="",
samples_per_page=res[4],
public=res[5],
description=res[6],
editor=res[7],
created_at=res[8].isoformat(),
updated_at=res[9].isoformat(),
owner_name=res[10],
)
)
return projects
async def public_projects(home_request: HomeRequest) -> list[Project]:
"""Fetch all publicly accessible projects.
Args:
home_request (ProjectsRequest): the request object.
Returns:
list[Project]: all publicly accessible projects.
"""
params = []
projects_query = sql.SQL(
"SELECT p.uuid, p.name, p.owner_id, p.view, p.samples_per_page, "
"p.description, p.public, p.created_at, p.updated_at, "
"COALESCE(ls.total_likes, 0) AS total_likes "
"FROM projects AS p "
"LEFT JOIN (SELECT project_uuid, COUNT(*) as total_likes "
"FROM project_like GROUP BY project_uuid) AS ls "
"ON p.uuid = ls.project_uuid "
"WHERE p.public IS TRUE "
)
if home_request.search_string:
projects_query += sql.SQL(
"AND (LOWER(p.name) LIKE LOWER(%s) OR "
"LOWER(p.description) LIKE LOWER(%s)) "
)
params += [
"%" + home_request.search_string + "%",
"%" + home_request.search_string + "%",
]
if home_request.sort == EntrySort.POPULAR:
projects_query += sql.SQL(" ORDER BY total_likes DESC, updated_at DESC ")
elif home_request.sort == EntrySort.RECENT:
projects_query += sql.SQL(" ORDER BY updated_at DESC, total_likes DESC ")
if home_request.limit:
projects_query += sql.SQL(" LIMIT %s ")
params += [home_request.limit]
projects_query += sql.SQL(" OFFSET %s")
params += [home_request.project_offset]
projects_query = (
sql.SQL("(SELECT main.*, u.name AS owner_name FROM (")
+ projects_query
+ sql.SQL(") AS main LEFT JOIN users AS u ON main.owner_id = u.id)")
)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(projects_query, params)
projects_result = await cur.fetchall()
projects = []
for res in projects_result:
projects.append(
Project(
uuid=res[0],
name=res[1],
view="",
samples_per_page=res[4],
editor=False,
public=True,
description=res[5],
created_at=res[7].isoformat(),
updated_at=res[8].isoformat(),
owner_name=res[10],
)
)
return projects
async def reports(
user: User, home_request: HomeRequest = HomeRequest()
) -> list[Report]:
"""Get all reports available to the user.
Args:
user (User): the user for which to fetch the available reports.
home_request (HomeRequest): the request object.
Returns:
list[Report]: the reports that the user can interact with.
"""
params = [user.id, user.id, user.id, user.id, user.id]
likes_query = sql.SQL(
"SELECT report_id, COUNT(*) as total_likes"
" FROM report_like GROUP BY report_id "
)
reports_query = (
sql.SQL("WITH LikesSummary AS (")
+ likes_query
+ sql.SQL("),")
+ sql.SQL(" CombinedReports AS (")
+ REPORTS_BASE_QUERY
+ sql.SQL(") ")
+ sql.SQL(
"SELECT cp.*, COALESCE(ls.total_likes, 0) AS total_likes FROM"
" CombinedReports cp LEFT JOIN LikesSummary ls "
" ON cp.id = ls.report_id "
)
)
if home_request.search_string:
reports_query += sql.SQL(
"WHERE (LOWER(cp.name) LIKE LOWER(%s) OR "
"LOWER(cp.description) LIKE LOWER(%s)) "
)
params += [
"%" + home_request.search_string + "%",
"%" + home_request.search_string + "%",
]
if home_request.sort == EntrySort.POPULAR:
reports_query += sql.SQL(" ORDER BY total_likes DESC, updated_at DESC ")
elif home_request.sort == EntrySort.RECENT:
reports_query += sql.SQL(" ORDER BY updated_at DESC, total_likes DESC ")
if home_request.limit:
reports_query += sql.SQL(" LIMIT %s ")
params += [home_request.limit]
reports_query += sql.SQL(" OFFSET %s; ")
params += [home_request.report_offset]
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(reports_query, params)
reports_result = await cur.fetchall()
reports = []
for report in reports_result:
await cur.execute(
"SELECT project_uuid FROM report_project WHERE report_id = %s;",
[report[0]],
)
linked_projects = await cur.fetchall()
reports.append(
Report(
id=report[0],
name=report[1],
linked_projects=[]
if len(linked_projects) == 0
else list(map(lambda linked: str(linked[0]), linked_projects)),
public=report[3],
description=report[4],
editor=report[5],
created_at=report[6].isoformat(),
updated_at=report[7].isoformat(),
owner_name=report[8],
)
)
return reports
async def public_reports(home_request: HomeRequest) -> list[Report]:
"""Fetch all publicly accessible reports.
Args:
home_request (HomeRequest): the request object.
Returns:
list[Report]: all publicly accessible reports.
"""
params = []
reports_query = sql.SQL(
"SELECT r.id, r.name, r.owner_id, r.description, r.public,"
" r.created_at, r.updated_at, COALESCE(ls.total_likes, 0) AS total_likes "
"FROM reports AS r "
"LEFT JOIN (SELECT report_id, COUNT(*) as total_likes "
"FROM report_like GROUP BY report_id) AS ls "
"ON r.id = ls.report_id "
"WHERE r.public IS TRUE "
)
if home_request.search_string:
reports_query += sql.SQL(
"AND (LOWER(r.name) LIKE LOWER(%s) OR "
"LOWER(r.description) LIKE LOWER(%s)) "
)
params += [
"%" + home_request.search_string + "%",
"%" + home_request.search_string + "%",
]
if home_request.sort == EntrySort.POPULAR:
reports_query += sql.SQL(" ORDER BY total_likes DESC, updated_at DESC ")
elif home_request.sort == EntrySort.RECENT:
reports_query += sql.SQL(" ORDER BY r.updated_at DESC, total_likes DESC ")
if home_request.limit:
reports_query += sql.SQL(" LIMIT %s ")
params += [home_request.limit]
reports_query += sql.SQL(" OFFSET %s")
params += [home_request.report_offset]
reports_query = (
sql.SQL("SELECT main.*, u.name AS owner_name FROM (")
+ reports_query
+ sql.SQL(") AS main LEFT JOIN users AS u ON main.owner_id = u.id")
)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(reports_query, params)
reports_result = await cur.fetchall()
reports = []
if reports_result is not None:
for res in reports_result:
await cur.execute(
"SELECT project_uuid FROM report_project WHERE report_id = %s;",
[res[0]],
)
linked_projects = await cur.fetchall()
reports.append(
Report(
id=res[0],
name=res[1],
linked_projects=[]
if len(linked_projects) == 0
else list(
map(lambda linked: str(linked[0]), linked_projects)
),
editor=False,
public=True,
description=res[3],
created_at=res[5].isoformat(),
updated_at=res[6].isoformat(),
owner_name=res[8],
)
)
return reports
async def project_count(user: User | None = None) -> int:
"""Get the number of projects.
Args:
user (User | None): the user making the request.
Returns:
int: the number of projects.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
if user is None:
await cur.execute("SELECT COUNT(*) FROM projects WHERE public = TRUE;")
else:
await cur.execute(
sql.SQL("SELECT COUNT(*) FROM")
+ PROJECTS_BASE_QUERY
+ sql.SQL(";"),
[user.id, user.id, user.id, user.id, user.id],
)
res = await cur.fetchall()
if len(res) > 0:
return res[0][0]
return 0
async def report_count(user: User | None = None) -> int:
"""Get the number of reports.
Args:
user (User | None): the user making the request.
Returns:
int: the number of reports.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
if user is None:
await cur.execute("SELECT COUNT(*) FROM reports WHERE public = TRUE;")
else:
await cur.execute(
sql.SQL("SELECT COUNT(*) FROM") + REPORTS_BASE_QUERY + sql.SQL(";"),
[user.id, user.id, user.id, user.id, user.id],
)
res = await cur.fetchall()
if len(res) > 0:
return res[0][0]
return 0
async def project_uuid(owner_name: str, project_name: str) -> str:
"""Get the project uuid given an owner and project name.
Args:
owner_name (str): name of the owner of the project.
project_name (str): name of the project.
Returns:
str | None: uuid of the requested project.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT id FROM users WHERE name = %s;", [owner_name])
owner_id = await cur.fetchall()
await cur.execute(
"SELECT uuid FROM projects WHERE name = %s AND owner_id = %s;",
[project_name, owner_id[0][0]],
)
project_uuid = await cur.fetchall()
if len(project_uuid) == 0:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="ERROR: Project not found.",
)
return str(project_uuid[0][0])
async def project_public(project_uuid: str) -> bool:
"""Check whether a project is public.
Args:
project_uuid (str): UUID of the project to be checked.
Returns:
bool: whether the project is public.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT public FROM projects WHERE uuid = %s;", [project_uuid]
)
public = await cur.fetchall()
return bool(public[0][0]) if len(public) > 0 else False
async def report_public(report: int) -> bool:
"""Check whether a report is public.
Args:
report (int): ID of the report to be checked.
Returns:
bool: whether the report is public.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT public FROM reports WHERE id = %s;", [report])
public = await cur.fetchall()
return bool(public[0][0]) if len(public) > 0 else False
async def api_key_exists(api_key: str) -> bool:
"""Check whether an API key exists.
Args:
api_key (str): the API key to check for.
Returns:
bool: whether the API key exists.
"""
api_key_hash = hash_api_key(api_key)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT EXISTS(SELECT 1 FROM users WHERE api_key_hash = %s);",
[api_key_hash],
)
exists = await cur.fetchall()
if len(exists) > 0:
return bool(exists[0][0])
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not check whether API key exists.",
)
async def user_by_api_key(api_key: str) -> User:
"""Get the user ID given an API key.
Args:
api_key (str): the API key to get the user ID for.
Returns:
int | None: the user ID of the user with the given API key.
"""
api_key_hash = hash_api_key(api_key)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id, name, display_name, cognito_id FROM users "
"WHERE api_key_hash = %s;",
[api_key_hash],
)
user_res = await cur.fetchall()
if len(user_res) == 1:
return User(
id=user_res[0][0],
name=user_res[0][1],
display_name=user_res[0][2],
cognito_id=user_res[0][3],
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="ERROR: Invalid API key. Double check your API key or generate"
+ " a new one at https://hub.zenoml.com/account.",
)
async def user_name_by_api_key(api_key: str) -> str | None:
"""Get the user name given an API key.
Args:
api_key (str): the API key to get the user name for.
Returns:
str | None: the user name of the user with the given API key.
"""
api_key_hash = hash_api_key(api_key)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT name FROM users WHERE api_key_hash = %s;", [api_key_hash]
)
user_id = await cur.fetchall()
return user_id[0][0] if len(user_id) > 0 else None
async def project_uuid_exists(project_uuid: str) -> bool:
"""Check whether a project exists.
Args:
project_uuid (str): the UUID of the project.
Returns:
bool: whether the project exists.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT EXISTS(SELECT 1 FROM projects WHERE uuid = %s);", [project_uuid]
)
exists = await cur.fetchall()
if len(exists) > 0:
return True
return False
async def project_exists(owner_id: int, project_name: str) -> bool:
"""Check whether a project exists.
Args:
owner_id (int): the ID of the owner of the project.
project_name (str): name of the project.
Returns:
bool: whether the project exists.
Raises:
Exception: something went wrong while checking whether the project exists.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT EXISTS(SELECT 1 FROM projects WHERE name = %s"
" AND owner_id = %s);",
[project_name, owner_id],
)
exists = await cur.fetchall()
if len(exists) > 0:
return bool(exists[0][0])
else:
raise HTTPException(
status_code=500, detail="Could not check if project exists."
)
async def report_id(owner: str, name: str) -> int | None:
"""Get report ID given owner and name.
Args:
owner (str): the owner of the report.
name (str): the name of the report.
Returns:
int | None: the ID of the report.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT id FROM users WHERE name = %s;", [owner])
owner_id = await cur.fetchall()
await cur.execute(
"SELECT id FROM reports WHERE name = %s AND owner_id = %s;",
[name, owner_id[0][0]],
)
id = await cur.fetchall()
if len(id) > 0:
return id[0][0]
async def report_response(id: int, user: User | None) -> ReportResponse:
"""Get the report data given a report ID.
Args:
id (int): the id of the report to be fetched.
user (User | None): user making the request.
Returns:
ReportResponse | None: the data for the requested report.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id, name, owner_id, public, description, created_at, "
"updated_at FROM reports WHERE id = %s;",
[id],
)
report_result = await cur.fetchall()
if len(report_result) == 0:
raise HTTPException(
status.HTTP_500_INTERNAL_SERVER_ERROR,
"ERROR: Report could not be found.",
)
else:
report_result = report_result[0]
await cur.execute(
"SELECT display_name FROM users WHERE id = %s;", [report_result[2]]
)
owner_name = await cur.fetchall()
if len(owner_name) == 0:
raise HTTPException(
status.HTTP_500_INTERNAL_SERVER_ERROR,
"ERROR: Could not fetch owner of project.",
)
else:
owner_name = owner_name[0][0]
if user is None:
editor = False
elif int(report_result[2]) == user.id:
# Owners can always edit projects
editor = True
else:
# Check whether the user or an org of the user have project edit rights
await cur.execute(
"SELECT editor FROM user_report WHERE user_id = %s "
"AND report_id = %s",
[user.id, id],
)
user_editor = await cur.fetchall()
await cur.execute(
"SELECT * FROM organization_report AS r JOIN user_organization "
"AS o ON r.organization_id = o.organization_id "
"WHERE r.report_id = %s AND o.user_id = %s AND r.editor = TRUE;",
[id, user.id],
)
org_editor = await cur.fetchall()
editor = len(org_editor) > 0 or (
bool(user_editor[0][0]) if len(user_editor) > 0 else False
)
await cur.execute(
"SELECT project_uuid FROM report_project WHERE report_id = %s;",
[id],
)
linked_projects = await cur.fetchall()
await cur.execute(
"SELECT id, type, data, position FROM report_elements "
"WHERE report_id = %s ORDER BY position;",
[id],
)
element_result = await cur.fetchall()
await cur.execute(
"SELECT COUNT(*) FROM report_like WHERE report_id = %s;", [id]
)
num_likes = await cur.fetchall()
user_liked = False
if user is not None:
await cur.execute(
"SELECT EXISTS(SELECT 1 FROM report_like WHERE report_id = %s AND "
"user_id = %s);",
[id, user.id],
)
user_liked = await cur.fetchall()
if len(user_liked) > 0:
user_liked = bool(user_liked[0][0])
else:
user_liked = False
return ReportResponse(
report=Report(
id=report_result[0],
name=report_result[1],
owner_name=owner_name,
linked_projects=[]
if len(linked_projects) == 0
else list(map(lambda linked: str(linked[0]), linked_projects)),
editor=editor,
public=report_result[3],
description=report_result[4],
created_at=report_result[5].isoformat(),
updated_at=report_result[6].isoformat(),
),
report_elements=list(
map(
lambda element: ReportElement(
id=element[0],
type=element[1],
data=element[2],
position=element[3],
),
element_result,
)
),
num_likes=num_likes[0][0] if isinstance(num_likes[0][0], int) else 0,
user_liked=user_liked,
)
async def charts_for_projects(project_uuids: list[str]) -> list[Chart]:
"""Get all charts for a list of projects.
Args:
project_uuids (list[str]): the list of project uuids.
Returns:
list[Chart]: the list of charts.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
sql.SQL(
"SELECT id, name, type, parameters, data, project_uuid"
" FROM charts WHERE project_uuid IN ({})"
).format(sql.SQL(",").join(map(sql.Literal, project_uuids)))
)
chart_results = await cur.fetchall()
if len(chart_results) == 0:
return []
return list(
map(
lambda r: Chart(
id=r[0],
name=r[1],
type=r[2],
parameters=json.loads(r[3]),
project_uuid=r[5],
),
chart_results,
)
)
async def tags_for_projects(project_uuids: list[str]) -> list[Tag]:
"""Get all tags for a list of projects.
Args:
project_uuids (list[str]): the list of project uuids.
Returns:
list[Tag]: the list of tags.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
sql.SQL(
"SELECT id, name, folder_id, project_uuid"
" FROM tags WHERE project_uuid IN ({})"
).format(sql.SQL(",").join(map(sql.Literal, project_uuids)))
)
tag_results = await cur.fetchall()
if len(tag_results) == 0:
return []
return list(
map(
lambda r: Tag(
id=r[0],
tag_name=r[1],
data_ids=[],
folder_id=r[2],
project_uuid=r[3],
),
tag_results,
)
)
async def slices_for_projects(project_uuids: list[str]) -> list[Slice]:
"""Get all slices for a list of projects.
Args:
project_uuids (list[str]): the list of project uuids.
Returns:
list[Slice]: the list of slices.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
sql.SQL(
"SELECT id, name, folder_id, filter, project_uuid"
" FROM slices WHERE project_uuid IN ({})"
).format(sql.SQL(",").join(map(sql.Literal, project_uuids)))
)
slice_results = await cur.fetchall()
if len(slice_results) == 0:
return []
return list(
map(
lambda r: Slice(
id=r[0],
slice_name=r[1],
folder_id=r[2],
filter_predicates=FilterPredicateGroup(
predicates=json.loads(r[3])["predicates"],
join=Join.OMITTED,
),
project_uuid=r[4],
),
slice_results,
)
)
async def project_from_uuid(project_uuid: str) -> Project:
"""Get the project data given a UUID.
Args:
project_uuid (str): the uuid of the project to be fetched.
Returns:
Project | None: data for the requested project.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT uuid, name, owner_id, view, "
"samples_per_page, public, description, created_at, updated_at "
"FROM projects WHERE uuid = %s;",
[project_uuid],
)
project_result = await cur.fetchall()
if len(project_result) == 0:
raise HTTPException(
status.HTTP_500_INTERNAL_SERVER_ERROR,
"ERROR: Project could not be found.",
)
project_result = project_result[0]
await cur.execute(
"SELECT name from users WHERE id = %s;", [project_result[2]]
)
owner_result = await cur.fetchall()
if len(owner_result) > 0:
return Project(
uuid=str(project_result[0]),
name=str(project_result[1]),
owner_name=str(owner_result[0][0]),
view=match_instance_view(str(project_result[3])),
editor=False,
samples_per_page=project_result[4]
if isinstance(project_result[4], int)
else 10,
public=bool(project_result[5]),
description=str(project_result[6]),
created_at=project_result[7].isoformat(),
updated_at=project_result[8].isoformat(),
)
else:
raise HTTPException(
status.HTTP_500_INTERNAL_SERVER_ERROR,
"ERROR: Could not load project owner.",
)
async def report_from_id(report_id: int) -> Report:
"""Get the report data given a ID.
Args:
report_id (int): the id of the report to be fetched.
Returns:
Report | None: data for the requested report.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur: