-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathinsert.py
888 lines (771 loc) · 31 KB
/
insert.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
"""Functions to insert new data into Zeno's database."""
import json
import secrets
import uuid
from fastapi import HTTPException, status
from pgpq import ArrowToPostgresBinaryEncoder
from psycopg import sql
from pyarrow import RecordBatch, Schema
import zeno_backend.database.delete as delete
from zeno_backend.classes.base import MetadataType, ZenoColumn, ZenoColumnType
from zeno_backend.classes.chart import (
Chart,
ChartConfig,
ConfigEncoder,
ParametersEncoder,
)
from zeno_backend.classes.filter import (
FilterPredicate,
FilterPredicateGroup,
Join,
Operation,
PredicatesEncoder,
)
from zeno_backend.classes.project import Project
from zeno_backend.classes.report import ReportElement
from zeno_backend.classes.slice import Slice
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, resolve_metadata_type
async def api_key(user: User) -> str | None:
"""Generate an API key for the user and save the hash.
Args:
user (User): the user for which to fetch the API key.
Returns:
str | None: the API key of the user.
"""
# Generate a new API key for the user.
api_key = "zen_" + secrets.token_urlsafe(32)
hashed_api_key = hash_api_key(api_key)
# Set the API key hash in the database.
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"UPDATE users SET api_key_hash = %s WHERE id = %s;",
[hashed_api_key, user.id],
)
await conn.commit()
return api_key
async def project(project_config: Project, owner_id: int):
"""Setting up a new project in Zeno.
Creates a new entry in the projects table, creates a new table for the project's
data, creates a table to map data columns to ids and types, and creates a table for
all tags of the project.
Args:
project_config (Project): the configuration with which to
initialize the new project.
owner_id (int): the id of the user who owns the project.
Raises:
Exception: something went wrong in the process of creating the new project in
the database.
"""
default_project = Project(uuid="", name="", owner_name="", view="")
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO projects (uuid, name, owner_id, view, "
+ "samples_per_page, public, description) "
+ "VALUES (%s,%s,%s,%s,%s,%s,%s);",
[
project_config.uuid,
project_config.name,
owner_id,
project_config.view,
default_project.samples_per_page
if project_config.samples_per_page is None
else project_config.samples_per_page,
default_project.public
if project_config.public is None
else project_config.public,
default_project.description
if project_config.description is None
else project_config.description,
],
)
await cur.execute(
"INSERT INTO user_project (user_id, project_uuid, editor) "
"VALUES (%s,%s,%s)",
[owner_id, project_config.uuid, True],
)
# Create table to hold information about the columns in the project data.
await cur.execute(
sql.SQL(
"CREATE TABLE {}(column_id TEXT NOT NULL PRIMARY KEY, "
"name TEXT NOT NULL, type TEXT NOT NULL, model TEXT, "
"data_type TEXT NOT NULL, histogram JSONB);"
).format(sql.Identifier(f"{project_config.uuid}_column_map"))
)
# Add metrics to the metrics table.
for metric in project_config.metrics:
await cur.execute(
"INSERT INTO metrics (project_uuid, name, type, columns) VALUES "
"(%s, %s, %s, %s);",
[project_config.uuid, metric.name, metric.type, metric.columns],
)
await conn.commit()
async def dataset_schema(
project_uuid: str,
id_column: str,
data_column: str | None,
label_column: str | None,
pa_schema: Schema,
) -> list[str]:
"""Adding a dataset schema column_map to an existing project.
Args:
project_uuid (str): the project the user is currently working with.
id_column (str): the column of the dataset that contains the ids.
data_column (str | None): the column of the dataset that contains the data.
label_column (str | None): the column of the dataset that contains the labels.
pa_schema (Schema): the PyArrow schema of the dataset to be added.
Returns:
list[str]: the ids of the columns in the dataset schema.
"""
await delete.dataset(project_uuid)
columns: list[ZenoColumn] = []
for col in pa_schema:
id_uuid = str(uuid.uuid4())
column_type = ZenoColumnType.FEATURE
if col.name == id_column:
column_type = ZenoColumnType.ID
id_column = id_uuid
elif col.name == label_column:
column_type = ZenoColumnType.LABEL
elif col.name == data_column:
column_type = ZenoColumnType.DATA
columns.append(
ZenoColumn(
id=id_uuid,
name=col.name,
column_type=column_type,
data_type=resolve_metadata_type(col.type),
)
)
encoder = ArrowToPostgresBinaryEncoder(pa_schema)
pg_schema = encoder.schema()
cols = sql.SQL(",").join(
[
sql.Identifier(columns[i].id)
+ sql.SQL(" ")
+ sql.SQL(col[1].data_type.ddl())
for i, col in enumerate(pg_schema.columns)
]
)
# Create and populate column_map table.
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
for column in columns:
await cur.execute(
sql.SQL(
"INSERT INTO {} (column_id, name, type, data_type) "
"VALUES (%s,%s,%s,%s);"
).format(sql.Identifier(f"{project_uuid}_column_map")),
[column.id, column.name, column.column_type, column.data_type],
)
await cur.execute(
sql.SQL("CREATE TABLE IF NOT EXISTS {} (").format(
sql.Identifier(project_uuid)
)
+ cols
+ sql.SQL(")")
)
# Make ID column primary key.
await cur.execute(
sql.SQL("ALTER TABLE {} ADD PRIMARY KEY ({});").format(
sql.Identifier(project_uuid),
sql.Identifier(id_column),
)
)
# Create table to hold information about tags and associated datapoints.
await cur.execute(
sql.SQL(
"CREATE TABLE {}(id integer GENERATED ALWAYS AS IDENTITY PRIMARY "
"KEY, tag_id integer NOT "
"NULL REFERENCES tags(id) ON DELETE CASCADE "
"ON UPDATE CASCADE, data_id text NOT NULL REFERENCES {}({}) "
"ON DELETE CASCADE ON UPDATE CASCADE);"
).format(
sql.Identifier(f"{project_uuid}_tags_datapoints"),
sql.Identifier(project_uuid),
sql.Identifier(id_column),
)
)
return [c.id for c in columns]
async def dataset(project_uuid: str, batch: RecordBatch):
"""Adds a dataset to an existing project.
Args:
project_uuid (str): project the user is currently working with.
batch (RecordBatch): dataset to be added.
"""
encoder = ArrowToPostgresBinaryEncoder(batch.schema)
pg_schema = encoder.schema()
cols = sql.SQL(",").join(
[
sql.Identifier(col_name) + sql.SQL(" ") + sql.SQL(col.data_type.ddl())
for col_name, col in pg_schema.columns
]
)
async with db_pool.connection() as conn:
async with conn.cursor() as cursor:
await cursor.execute("DROP TABLE IF EXISTS temp_data")
await cursor.execute(
sql.SQL("CREATE TABLE temp_data (") + cols + sql.SQL(")")
)
async with cursor.copy(
"COPY temp_data FROM STDIN WITH (FORMAT BINARY)"
) as copy:
await copy.write(encoder.write_header())
await copy.write(encoder.write_batch(batch))
await copy.write(encoder.finish())
await cursor.execute(
sql.SQL("INSERT INTO {} SELECT * FROM temp_data").format(
sql.Identifier(project_uuid)
)
)
await conn.commit()
async def system_schema(
project_uuid: str,
system_name: str,
id_column: str,
output_column: str,
pa_schema: Schema,
) -> list[str]:
"""Adding a system schema column_map to an existing project.
Args:
project_uuid (str): the project the user is currently working with.
system_name (str): the name of the system.
id_column (str): the column of the system output that contains the ids.
output_column (str): the column of the system output that contains the output.
pa_schema (Schema): the PyArrow schema of the system output to be added.
"""
await delete.system(project_uuid, system_name)
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
# add columns to column_map
columns: list[ZenoColumn] = []
for col in pa_schema:
if col.name == id_column:
# get id column id
await cur.execute(
sql.SQL("SELECT column_id FROM {} WHERE type = 'ID';").format(
sql.Identifier(f"{project_uuid}_column_map")
)
)
id_col = await cur.fetchall()
if id_col is None or len(id_col) == 0:
raise HTTPException(
status_code=400,
detail="No ID column found. Have you uploaded a dataset?",
)
columns.append(
ZenoColumn(
id=id_col[0][0],
name="",
column_type=ZenoColumnType.ID,
data_type=MetadataType.OTHER,
model=system_name,
)
)
continue
elif col.name == output_column:
column_type = ZenoColumnType.OUTPUT
else:
column_type = ZenoColumnType.FEATURE
columns.append(
ZenoColumn(
id=str(uuid.uuid4()),
name=col.name,
column_type=column_type,
data_type=resolve_metadata_type(col.type),
model=system_name,
)
)
encoder = ArrowToPostgresBinaryEncoder(pa_schema)
pg_schema = encoder.schema()
for i, column in enumerate(columns):
if column.column_type == ZenoColumnType.ID:
continue
await cur.execute(
sql.SQL(
"INSERT INTO {} (column_id, name, type, data_type, model) "
"VALUES (%s,%s,%s,%s,%s);"
).format(sql.Identifier(f"{project_uuid}_column_map")),
[
column.id,
column.name,
column.column_type,
column.data_type,
column.model,
],
)
await cur.execute(
sql.SQL("ALTER TABLE {} ADD COLUMN IF NOT EXISTS {} ").format(
sql.Identifier(project_uuid),
sql.Identifier(column.id),
)
+ sql.SQL(pg_schema.columns[i][1].data_type.ddl())
)
await conn.commit()
return [c.id for c in columns]
async def system(
project_uuid: str,
batch: RecordBatch,
):
"""Adds a system to an existing project.
Args:
project_uuid (str): project the user is currently working with.
system_name (str): name of the system that produced the output.
batch (RecordBatch): system output to be added.
Raises:
HTTPException: no ID column found.
"""
encoder = ArrowToPostgresBinaryEncoder(batch.schema)
pg_schema = encoder.schema()
cols = sql.SQL(",").join(
[
sql.Identifier(col_name) + sql.SQL(" ") + sql.SQL(col.data_type.ddl())
for col_name, col in pg_schema.columns
]
)
async with db_pool.connection() as conn:
async with conn.cursor() as cursor:
await cursor.execute("DROP TABLE IF EXISTS temp_data")
await cursor.execute(
sql.SQL("CREATE TABLE temp_data (") + cols + sql.SQL(")")
)
async with cursor.copy(
"COPY temp_data FROM STDIN WITH (FORMAT BINARY)"
) as copy:
await copy.write(encoder.write_header())
await copy.write(encoder.write_batch(batch))
await copy.write(encoder.finish())
await cursor.execute(
sql.SQL("SELECT column_id FROM {} WHERE type = 'ID';").format(
sql.Identifier(f"{project_uuid}_column_map")
)
)
col_id = await cursor.fetchone()
if col_id is None:
raise HTTPException(
status_code=400,
detail="No ID column found.",
)
col_id = col_id[0]
await cursor.execute(
sql.SQL("UPDATE {} AS e SET ").format(sql.Identifier(project_uuid))
+ sql.SQL(",").join(
[
sql.SQL("{} = COALESCE({}, {})").format(
sql.Identifier(col_name),
sql.Identifier("t", col_name),
sql.Identifier("e", col_name),
)
for col_name, _ in pg_schema.columns
]
)
+ sql.SQL(" FROM temp_data AS t WHERE {} = {}").format(
sql.Identifier("t", col_id),
sql.Identifier("e", col_id),
)
)
await conn.commit()
async def report(name: str, user: User) -> int:
"""Adding a report to Zeno.
Args:
name (str): how the report is called.
user (User): user who created the report.
Returns:
int: the id of the newly created report.
Raises:
HTTPException: a report with the same name already exists.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id FROM reports WHERE name = %s AND owner_id = %s;",
[name, user.id],
)
res = await cur.fetchall()
if len(res) > 0:
raise HTTPException(
status_code=400,
detail="Report with this name already exists.",
)
await cur.execute(
"INSERT INTO reports (name, owner_id, public) VALUES (%s,%s,%s)"
" RETURNING id;",
[name, user.id, False],
)
id = await cur.fetchall()
# Per default, add the report creator as its first author
await cur.execute(
"INSERT INTO report_author (user_id, report_id, position) "
"VALUES (%s,%s,%s);",
[user.id, id[0][0], 0],
)
await conn.commit()
if len(id) == 0:
raise HTTPException(status_code=500, detail="Could not create report.")
return id[0][0]
async def report_element(report_id: int, element: ReportElement) -> int | None:
"""Adding a report element to a Zeno Report.
Args:
report_id (int): the id of the report the element is added to.
element (ReportElement): the element to be added to the report.
Returns:
int | None: the id of the newly created report element.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
# make room for new element position-wise
await cur.execute(
"UPDATE report_elements SET position = position + 1 "
"WHERE report_id = %s AND position >= %s;",
[report_id, element.position],
)
await cur.execute(
"INSERT INTO report_elements (report_id, type, data, position)"
" VALUES (%s,%s,%s,%s) RETURNING id;",
[report_id, element.type, element.data, element.position],
)
id = await cur.fetchall()
if len(id) > 0:
return id[0][0]
async def report_author(report_id: int, author: Author):
"""Adds an author to a report.
Args:
report_id (int): the id of the report to be added as an author.
author (Author): the author to be added.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
# make room for new element position-wise
await cur.execute(
"UPDATE report_author SET position = position + 1 "
"WHERE report_id = %s AND position >= %s;",
[report_id, author.position],
)
await cur.execute(
"INSERT INTO report_author (user_id, report_id, position) "
"VALUES (%s,%s,%s);",
[author.user.id, report_id, author.position],
)
await conn.commit()
async def like_report(user_id: int, report_id: int):
"""Like a report.
Args:
user_id: the id of the user liking the report.
report_id: the id of the report to be liked.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id FROM report_like WHERE user_id = %s AND report_id = %s;",
[user_id, report_id],
)
user_liked = await cur.fetchall()
if len(user_liked) > 0:
await cur.execute(
"DELETE FROM report_like WHERE user_id = %s AND report_id = %s;",
[user_id, report_id],
)
else:
await cur.execute(
"INSERT INTO report_like (user_id, report_id) VALUES (%s,%s);",
[user_id, report_id],
)
await conn.commit()
async def like_project(user_id: int, project_uuid: str):
"""Like a project.
Args:
user_id: the id of the user liking the report.
project_uuid: the uuid of the project to be liked.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT id FROM project_like WHERE user_id = %s AND project_uuid = %s;",
[user_id, project_uuid],
)
user_liked = await cur.fetchall()
if len(user_liked) > 0:
await cur.execute(
"DELETE FROM project_like WHERE user_id = %s AND project_uuid = %s",
[user_id, project_uuid],
)
else:
await cur.execute(
"INSERT INTO project_like (user_id, project_uuid) VALUES (%s,%s);",
[user_id, project_uuid],
)
await conn.commit()
async def folder(project: str, name: str) -> int | None:
"""Adding a folder to an existing project.
Args:
project (str): the project the user is currently working with.
name (str): name of the folder to be added.
Returns:
int | None: the id of the newly created folder.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO folders (name, project_uuid) VALUES (%s,%s) "
"RETURNING id;",
[name, project],
)
id = await cur.fetchall()
if len(id) > 0:
return id[0][0]
if id is not None and len(id) > 0:
return id[0][0]
async def slice(project: str, req: Slice) -> int:
"""Add a slice to an existing project.
Args:
project (str): the project the user is currently working with.
req (Slice): the slice to be added to the project.
Returns:
int | None: the id of the newly created slice.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO slices (name, folder_id, filter, project_uuid) "
"VALUES (%s,%s,%s,%s) RETURNING id;",
[
req.slice_name,
req.folder_id,
json.dumps(req.filter_predicates, cls=PredicatesEncoder),
project,
],
)
ids = await cur.fetchall()
if ids is not None:
return ids[0][0]
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="ERROR: Failed to insert slice.",
)
async def all_slices_for_column(
project: str, column: ZenoColumn, name: str | None = None
) -> list[int] | None:
"""Add slices for all values of a nominal data column.
Args:
project (str): project to add the slices to.
column (ZenoColumn): column for which to add slices.
name (str | None): name of the folder to add the slices to.
Returns:
list[int]|None: ids of all added slices.
"""
ids = []
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
sql.SQL("SELECT DISTINCT {} FROM {}").format(
sql.Identifier(column.id), sql.Identifier(project)
)
)
values = await cur.fetchall()
if len(values) > 100:
raise HTTPException(
status_code=400,
detail="Too many distinct values to create slices. Must be < 100",
)
folder_id = None
if len(values) > 0:
await cur.execute(
"INSERT INTO folders (name, project_uuid) VALUES (%s,%s) "
"RETURNING id;",
[name if name is not None else column.name, project],
)
folder_id = await cur.fetchone()
for value in values:
slice = Slice(
id=-1,
slice_name=str(value[0]),
filter_predicates=FilterPredicateGroup(
predicates=[
FilterPredicate(
column=column,
operation=Operation.EQUAL,
value=value[0],
join=Join.OMITTED,
)
],
join=Join.OMITTED,
),
folder_id=None if folder_id is None else folder_id[0],
)
await cur.execute(
sql.SQL(
"SELECT id FROM slices WHERE name={} AND project_uuid={};"
).format(slice.slice_name, project)
)
exists = await cur.fetchall()
if len(exists) == 0:
await cur.execute(
"INSERT INTO slices (name, filter, project_uuid, folder_id) "
"VALUES (%s,%s,%s,%s) RETURNING id;",
[
slice.slice_name,
json.dumps(slice.filter_predicates, cls=PredicatesEncoder),
project,
slice.folder_id,
],
)
id = await cur.fetchone()
if id is not None:
ids.append(id[0])
return ids
async def chart(project: str, chart: Chart) -> int | None:
"""Add a chart to an existing project.
Args:
project (str): the project the user is currently working with.
chart (Chart): the chart to be added to the project.
Returns:
int | None: the id of the newly created chart.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO charts (name, type, parameters, project_uuid) "
"VALUES (%s,%s,%s,%s) RETURNING id;",
[
chart.name,
chart.type,
json.dumps(chart.parameters, cls=ParametersEncoder),
project,
],
)
id = await cur.fetchall()
if id is not None and len(id) > 0:
return id[0][0]
async def tag(project: str, tag: Tag) -> int | None:
"""Add a tag to an existing project.
Args:
project (str): the project the user is currently working with.
tag (Tag): the tag to be added to the project.
Returns:
int | None: the id of the newly created tag.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO tags (name, folder_id, project_uuid) VALUES (%s,%s,%s) "
"RETURNING id;",
[tag.tag_name, tag.folder_id, project],
)
id = await cur.fetchall()
if id is None or len(id) == 0:
return
for datapoint in tag.data_ids:
await cur.execute(
sql.SQL("INSERT INTO {} (tag_id, data_id) VALUES (%s,%s);").format(
sql.Identifier(f"{project}_tags_datapoints")
),
[id[0][0], datapoint],
)
await conn.commit()
return id[0][0]
async def user(user: User) -> int | None:
"""Add a new user to the database.
Args:
user (User): the user to be added.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO users (name, display_name, cognito_id) values(%s, %s, %s) "
"RETURNING id;",
[user.name, user.display_name, user.cognito_id],
)
id = await cur.fetchall()
if id is not None:
return id[0][0]
async def organization(user: User, organization: Organization):
"""Add a new organization to the database.
Args:
user (User): the user who created the organization.
organization (Organization): the organization to be created.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO organizations (name) VALUES (%s) RETURNING id;",
[organization.name],
)
id = await cur.fetchall()
if id is None:
return
await cur.execute(
"INSERT INTO user_organization (user_id, organization_id, admin) "
"VALUES (%s,%s,%s);",
[user.id, id[0][0], True],
)
await conn.commit()
async def project_user(project: str, user: User):
"""Add a user to a project.
Args:
project (str): the project id to add the user to.
user (User): the user to add to the project.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO user_project (user_id, project_uuid, editor) "
"VALUES (%s,%s,%s)",
[user.id, project, user.admin],
)
async def project_org(project: str, organization: Organization):
"""Add a organization to a project.
Args:
project (str): the project id to add the organization to.
organization (Organization): the organization to add to the project.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO organization_project "
"(organization_id, project_uuid, editor) VALUES (%s,%s,%s)",
[organization.id, project, organization.admin],
)
async def report_user(report_id: int, user: User):
"""Add a user to a report.
Args:
report_id (int): the report id to add the user to.
user (User): the user to add to the report.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO user_report (user_id, report_id, editor)"
" VALUES (%s,%s,%s)",
[user.id, report_id, user.admin],
)
async def report_org(report_id: int, organization: Organization):
"""Add a organization to a report.
Args:
report_id (int): the report id to add the organization to.
organization (Organization): the organization to add to the report.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO organization_report (organization_id, report_id, editor) "
"VALUES (%s,%s,%s)",
[organization.id, report_id, organization.admin],
)
async def chart_config(config: ChartConfig, chart_id: int | None = None):
"""Add a chart config for a project or chart.
Args:
config (ChartConfig): the config to be added to the database.
chart_id (int | None): the id of the chart this is linked to. Defaults to None.
"""
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
await cur.execute(
"INSERT INTO chart_config (project_uuid, config, chart_id) "
"VALUES (%s,%s,%s);",
[config.project_uuid, json.dumps(config, cls=ConfigEncoder), chart_id],
)