-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathtable_components.py
More file actions
4690 lines (4048 loc) · 193 KB
/
table_components.py
File metadata and controls
4690 lines (4048 loc) · 193 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
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
import asyncio
import hashlib
import json
import logging
import os
import re
import tempfile
import time
import uuid
from collections import OrderedDict
from dataclasses import dataclass, field
from datetime import datetime
from io import BytesIO
from typing import Any, Dict, List, Optional, Protocol, Tuple, Union
import pandas as pd
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from typing_extensions import Self
from synapseclient import Synapse
from synapseclient.api import (
ViewEntityType,
ViewTypeMask,
delete_entity,
get_columns,
get_default_columns,
get_from_entity_factory,
post_columns,
post_entity_bundle2_create,
put_entity_id_bundle2,
)
from synapseclient.core.async_utils import async_to_sync, otel_trace_method
from synapseclient.core.download.download_functions import (
download_by_file_handle,
ensure_download_location_is_directory,
)
from synapseclient.core.exceptions import SynapseTimeoutError
from synapseclient.core.typing_utils import DataFrame as DATA_FRAME_TYPE
from synapseclient.core.typing_utils import Series as SERIES_TYPE
from synapseclient.core.upload.multipart_upload_async import (
multipart_upload_dataframe_async,
multipart_upload_file_async,
multipart_upload_partial_file_async,
)
from synapseclient.core.utils import (
MB,
extract_synapse_id_from_query,
log_dataclass_diff,
merge_dataclass_entities,
test_import_pandas,
)
from synapseclient.models import Activity
from synapseclient.models.services.search import get_id
from synapseclient.models.services.storable_entity_components import (
FailureStrategy,
store_entity_components,
)
from synapseclient.models.table_components import (
AppendableRowSetRequest,
Column,
ColumnChange,
ColumnExpansionStrategy,
ColumnType,
CsvTableDescriptor,
PartialRow,
PartialRowSet,
Query,
QueryBundleRequest,
QueryJob,
QueryNextPageToken,
QueryResultBundle,
QueryResultOutput,
Row,
SchemaStorageStrategy,
SnapshotRequest,
TableSchemaChangeRequest,
TableUpdateTransaction,
UploadToTableRequest,
)
CLASSES_THAT_CONTAIN_ROW_ETAG = [
"Dataset",
"EntityView",
"DatasetCollection",
"SubmissionView",
]
CLASSES_WITH_READ_ONLY_SCHEMA = ["MaterializedView", "VirtualTable"]
PANDAS_TABLE_TYPE = {
"floating": "DOUBLE",
"decimal": "DOUBLE",
"integer": "INTEGER",
"mixed-integer-float": "DOUBLE",
"boolean": "BOOLEAN",
"datetime64": "DATE",
"datetime": "DATE",
"date": "DATE",
}
DEFAULT_QUOTE_CHARACTER = '"'
DEFAULT_SEPARATOR = ","
DEFAULT_ESCAPSE_CHAR = "\\"
# Taken from <https://github.com/Sage-Bionetworks/Synapse-Repository-Services/blob/cce01ec2c9f8ae44dabe957ca70e87942431aff5/lib/models/src/main/java/org/sagebionetworks/repo/model/table/TableConstants.java#L77>
RESERVED_COLUMN_NAMES = [
"ROW_ID",
"ROW_VERSION",
"ROW_ETAG",
"ROW_BENEFACTOR",
"ROW_SEARCH_CONTENT",
"ROW_HASH_CODE",
]
LIST_COLUMN_TYPES = {
"STRING_LIST",
"INTEGER_LIST",
"BOOLEAN_LIST",
"DATE_LIST",
"ENTITYID_LIST",
"USERID_LIST",
}
def row_labels_from_id_and_version(rows):
return ["_".join(map(str, row)) for row in rows]
def row_labels_from_rows(rows: List[Row]) -> List[Row]:
return row_labels_from_id_and_version(
[
(
(row.row_id, row.version_number, row.etag)
if row.etag
else (row.row_id, row.version_number)
)
for row in rows
]
)
def convert_dtypes_to_json_serializable(df) -> pd.DataFrame:
"""
Convert the dtypes of the int64 and float64 columns to object columns which are JSON serializable types.
Replace both Ellipsis and pandas NA within nested structures which are not JSON serializable types.
Also, convert the ROW_ID, ROW_VERSION, and ROW_ID.1 columns to int columns which are JSON serializable types.
Arguments:
df: The dataframe to convert the dtypes of.
Returns:
The dataframe with the dtypes converted to JSON serializable types.
Example:
df = pd.DataFrame({
"ROW_ID": [1, 2, 3, 4],
"ROW_VERSION": [1, 2, 3, 4],
"ROW_ETAG": ['test-etag-1', 'test-etag-2', 'test-etag-3', 'test-etag-4'],
"int64_col": [1, 2, 3, None],
"float64_col": [1.1, 2.2, 3.3, 4.4],
"string_col": ["a", "b", "c", "d"],
"string_col_with_na": ["a", "b", "c", None],
"boolean_col": [True, False, None, False],
"datetime_col": [datetime(2021, 1, 1), datetime(2021, 1, 2), None, datetime(2021, 1, 4)],
"int_list_col": [[1, 2, 3], [4, 5, 6], None, [7, 8, 9]],
"string_list_col": [["a", "b", "c"], ["d", "e", "f"], None, ["g", "h", "i"]],
"boolean_list_col": [[True, None, True], [False, True, False], None, [True, False, True]],
"datetime_list_col": [[datetime(2021, 1, 1), datetime(2021, 1, 2), datetime(2021, 1, 3)], [datetime(2021, 1, 4), datetime(2021, 1, 5), datetime(2021, 1, 6)], None, [datetime(2021, 1, 7), datetime(2021, 1, 8), datetime(2021, 1, 9)]],
"entityid_list_col": [["syn123", "syn456", None], ["syn101", "syn102", "syn103"], None, ["syn104", "syn105", "syn106"]],
"userid_list_col": [["user1", "user2", "user3"], ["user4", "user5", None], None, ["user7", "user8", "user9"]],
"json_col_with_quotes": [
{
"id": 1,
"description": 'Text with "quotes" in the description field',
"references": []
},
{
"id": 2,
"description": 'Another description with "quoted text" here',
"references": ["ref1", "ref2"]
},
{
"id": 3,
"description": 'Description containing "multiple" quoted "words"',
"references": [...]
},
{
"id": 4,
"description": 'Description containing apostrophes sage\'s',
"references": [...]
}
],
}).convert_dtypes()
df = convert_dtypes_to_json_serializable(df)
print(df)
"""
def _serialize_json_value(x):
if isinstance(x, (list, dict)):
def _reformat_special_values(obj):
if obj is ...:
return "..."
if obj is pd.NA:
return None
if isinstance(obj, dict):
return {k: _reformat_special_values(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_reformat_special_values(item) for item in obj]
return obj
cleaned_x = _reformat_special_values(x)
return cleaned_x
# Handle standalone ellipsis
if x is ...:
return "..."
return x
for col in df.columns:
sample_values = df[col].dropna()
if len(sample_values):
df[col] = df[col].apply(_serialize_json_value)
# restore the original values of the column especially for the int64 and float64 columns since apply function changes the dtype
df[col] = df[col].convert_dtypes()
df[col] = df[col].replace({pd.NA: None}).astype(object)
# Convert ROW_ prefixed columns back to int (like ROW_ID, ROW_VERSION)
if col in [
"ROW_ID",
"ROW_VERSION",
"ROW_ID.1",
]: # ROW_ID.1 is the temporary row id to constrct row to upsert
df[col] = df[col].astype(int)
return df
async def _query_table_csv(
query: str,
synapse_client: Synapse,
header: bool = True,
include_row_id_and_row_version: bool = True,
# for csvTableDescriptor
quote_character: str = '"',
escape_character: str = "\\",
line_end: str = os.linesep,
separator: str = ",",
# END for csvTableDescriptor
file_name: str = None,
additional_filters: Dict[str, Any] = None,
selected_facets: Dict[str, Any] = None,
include_entity_etag: bool = False,
select_file_column: int = None,
select_file_version_column: int = None,
offset: int = None,
sort: List[Dict[str, Any]] = None,
download_location: str = None,
timeout: int = 250,
) -> Tuple[QueryJob, str]:
"""
Query a Synapse Table and download a CSV file containing the results.
Sends a [DownloadFromTableRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/DownloadFromTableRequest.html) to Synapse.
Arguments:
query: The SQL query string to execute against the table.
synapse_client: An authenticated Synapse client instance used for making the API call.
header: Should the first line contain the column names as a header in the
resulting file? Set to True to include the headers, False otherwise.
The default value is True.
include_row_id_and_row_version: Should the first two columns contain the row ID
and row version? The default value is True.
quote_character: The character used for quoting fields in the CSV.
The default is a double quote (").
escape_character: The character used for escaping special characters in the CSV.
The default character '\\' will be used if this is not provided by the caller.
line_end: The string used to separate lines in the CSV.
The default is the system's line separator.
separator: The character used to separate fields in the CSV.
The default is a comma (,).
file_name: The optional name for the downloaded table file.
additional_filters: Appends additional filters to the SQL query. These are
applied before facets. Filters within the list have an AND relationship.
If a WHERE clause already exists on the SQL query or facets are selected,
it will also be ANDed with the query generated by these additional filters.
selected_facets: The selected facet filters to apply to the query.
include_entity_etag: Optional, default False. When True, query results against
views will include the Etag of each entity in the results. Note: The etag
is necessary to update Entities in the view.
select_file_column: The id of the column used to select file entities
(e.g. to fetch the action required for download). The column needs to be
an ENTITYID type column and be part of the schema of the underlying table/view.
select_file_version_column: The id of the column used as the version for
selecting file entities when required (e.g. to add a materialized view
query to the download cart with version enabled). The column needs to be
an INTEGER type column and be part of the schema of the underlying table/view.
offset: The optional offset into the results for pagination.
sort: Optional list of sort items to specify the ordering of results.
download_location: The download location
Returns:
A tuple containing the download result (QueryJob object) and the path to the downloaded CSV file.
The download result is a dictionary containing information about the download.
"""
client = Synapse.get_client(synapse_client=synapse_client)
csv_descriptor = CsvTableDescriptor(
separator=separator,
escape_character=escape_character,
quote_character=quote_character,
line_end=line_end,
is_first_line_header=header,
)
entity_id = extract_synapse_id_from_query(query)
query_job_request = QueryJob(
entity_id=entity_id,
sql=query,
write_header=header,
csv_table_descriptor=csv_descriptor,
include_row_id_and_row_version=include_row_id_and_row_version,
file_name=file_name,
additional_filters=additional_filters,
selected_facets=selected_facets,
include_entity_etag=include_entity_etag,
select_file_column=select_file_column,
select_file_version_column=select_file_version_column,
offset=offset,
sort=sort,
)
download_from_table_result = await query_job_request.send_job_and_wait_async(
synapse_client=client, timeout=timeout
)
file_handle_id = download_from_table_result.results_file_handle_id
cached_file_path = client.cache.get(
file_handle_id=file_handle_id, path=download_location
)
if cached_file_path is not None:
return download_from_table_result, cached_file_path
if download_location:
download_dir = ensure_download_location_is_directory(
download_location=download_location
)
else:
download_dir = client.cache.get_cache_dir(file_handle_id=file_handle_id)
os.makedirs(download_dir, exist_ok=True)
filename = f"SYNAPSE_TABLE_QUERY_{file_handle_id}.csv"
path = await download_by_file_handle(
file_handle_id=file_handle_id,
synapse_id=extract_synapse_id_from_query(query),
entity_type="TableEntity",
destination=os.path.join(download_dir, filename),
synapse_client=client,
)
return download_from_table_result, path
def _query_table_next_page(
next_page_token: "QueryNextPageToken", table_id: str, synapse_client: Synapse
) -> "QueryResultBundle":
"""
Retrieve following pages if the result contains a *nextPageToken*
Arguments:
next_page_token: Forward this token to get the next page of results.
table_id: The Synapse ID of the table
synapse_client: An authenticated Synapse client instance used for making the API call.
Returns:
The following page of results as a QueryResultBundle
<https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryResultBundle.html>
"""
synapse = Synapse.get_client(synapse_client=synapse_client)
uri = "/entity/{id}/table/query/nextPage/async".format(id=table_id)
result = synapse._waitForAsync(uri=uri, request=next_page_token.token)
return QueryResultBundle.fill_from_dict(data=result)
async def _query_table_row_set(
query: str,
synapse_client: Synapse,
limit: int = None,
offset: int = None,
part_mask=None,
timeout: int = 250,
) -> "QueryResultBundle":
"""
Executes a SQL query against a Synapse table and returns the resulting row set.
Args:
query (str): The SQL query string to execute.
synapse (Synapse): An authenticated Synapse client instance.
limit (int, optional): Maximum number of rows to return. Defaults to None.
offset (int, optional): Number of rows to skip before starting to return rows. Defaults to None.
part_mask (optional): Bit mask to specify which parts of the query result bundle to return. See Synapse REST docs for details.
Returns: a QueryResultBundle object <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryResultBundle.html>
"""
entity_id = extract_synapse_id_from_query(query)
query_cls = Query(
sql=query,
include_entity_etag=True,
limit=limit,
offset=offset,
)
query_request = query_cls.to_synapse_request()
query_bundle_request = QueryBundleRequest(
entity_id=entity_id, query=query_request, part_mask=part_mask
)
completed_request = await query_bundle_request.send_job_and_wait_async(
synapse_client=synapse_client, timeout=timeout
)
return QueryResultBundle(
query_result=completed_request.query_result,
query_count=completed_request.query_count,
select_columns=completed_request.select_columns,
max_rows_per_page=completed_request.max_rows_per_page,
column_models=completed_request.column_models,
facets=completed_request.facets,
sum_file_sizes=completed_request.sum_file_sizes,
last_updated_on=completed_request.last_updated_on,
combined_sql=completed_request.combined_sql,
actions_required=completed_request.actions_required,
)
async def _table_query(
query: str,
synapse_client: Optional[Synapse] = None,
results_as: str = "csv",
timeout: int = 250,
**kwargs,
) -> Union["QueryResultBundle", Tuple["QueryJob", str]]:
"""
Query a Synapse Table.
Optional keyword arguments differ for the two return types of `rowset` or `csv`:
- For `rowset`, you can specify:
- `limit`: Maximum number of rows to return.
- `offset`: Number of rows to skip before starting to return rows.
- `part_mask`: Bit mask to specify which parts of the query result bundle to return.
- For `csv`, you can specify:
- `quote_character`: Character used for quoting fields. Default is double quote (").
- `escape_character`: Character used for escaping special characters. Default is backslash.
- `line_end`: Character(s) used to terminate lines. Default is system line separator.
- `separator`: Character used to separate fields. Default is comma (,).
- `header`: Whether to include a header row. Default is True.
- `include_row_id_and_row_version`: Whether to include row ID and version in the output. Default is True.
- `file_name`: Optional name for the downloaded table file.
- `additional_filters`: Additional filters to append to the SQL query.
- `selected_facets`: Selected facet filters to apply to the query.
- `include_entity_etag`: Whether to include entity etag in view results. Default is False.
- `select_file_column`: Column ID for selecting file entities.
- `select_file_version_column`: Column ID for file version selection.
- `offset`: Optional offset into the results for pagination.
- `sort`: Optional list of sort items for result ordering.
- `download_location`: Location to download the CSV file.
Returns:
If `results_as` is "rowset", returns a QueryResultBundle object.
If `results_as` is "csv", returns a tuple of (QueryJob, csv_path).
"""
if results_as.lower() == "rowset":
return await _query_table_row_set(
query=query, synapse_client=synapse_client, timeout=timeout, **kwargs
)
elif results_as.lower() == "csv":
result, csv_path = await _query_table_csv(
query=query,
synapse_client=synapse_client,
quote_character=kwargs.get("quote_character", DEFAULT_QUOTE_CHARACTER),
escape_character=kwargs.get("escape_character", DEFAULT_ESCAPSE_CHAR),
line_end=kwargs.get("line_end", str(os.linesep)),
separator=kwargs.get("separator", DEFAULT_SEPARATOR),
header=kwargs.get("header", True),
include_row_id_and_row_version=kwargs.get(
"include_row_id_and_row_version", True
),
file_name=kwargs.get("file_name", None),
additional_filters=kwargs.get("additional_filters", None),
selected_facets=kwargs.get("selected_facets", None),
include_entity_etag=kwargs.get("include_entity_etag", False),
select_file_column=kwargs.get("select_file_column", None),
select_file_version_column=kwargs.get("select_file_version_column", None),
offset=kwargs.get("offset", None),
sort=kwargs.get("sort", None),
download_location=kwargs.get("download_location", None),
timeout=timeout,
)
return result, csv_path
def _rowset_to_pandas_df(
query_result_bundle: QueryResultBundle,
synapse_client: Synapse,
row_id_and_version_in_index: bool = True,
**kwargs,
) -> "DATA_FRAME_TYPE":
"""
Converts a Synapse table query rowset result to a pandas DataFrame.
Arguments:
query_result_bundle: The query result bundle containing rows and headers from a Synapse
table query. This is typically the response from a table query operation
that includes query results, headers, and pagination information.
see here: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryResultBundle.html
synapse_client: An authenticated Synapse client instance used for making additional
API calls when pagination is required to fetch subsequent pages of results.
row_id_and_version_in_index: If True, uses ROW_ID, ROW_VERSION (and ROW_ETAG
if present) as the DataFrame index.
**kwargs: Additional keyword arguments (currently unused but maintained for
API compatibility).
Returns:
A pandas DataFrame containing all the query results.
"""
test_import_pandas()
import collections
import pandas as pd
def construct_rownames(query_result_bundle, offset=0):
try:
return (
row_labels_from_rows(
query_result_bundle.query_result.query_results.rows
)
if row_id_and_version_in_index
else None
)
except KeyError:
# if we don't have row id and version, just number the rows
# python3 cast range to list for safety
return list(range(offset, offset + len(rowset["rows"])))
# first page of rows
offset = 0
rownames = construct_rownames(query_result_bundle, offset)
query_result = query_result_bundle.query_result
rowset = query_result.query_results
if not rowset:
raise ValueError("The provided query_result_bundle has no 'rowset' data.")
rows = rowset.rows or []
headers = rowset.headers
offset += len(rows)
series = collections.OrderedDict()
if not row_id_and_version_in_index:
# Since we use an OrderedDict this must happen before we construct the other columns
# add row id, verison, and etag as rows
append_etag = False # only useful when (not row_id_and_version_in_index), hooray for lazy variables!
series["ROW_ID"] = pd.Series(name="ROW_ID", data=[row.row_id for row in rows])
series["ROW_VERSION"] = pd.Series(
name="ROW_VERSION",
data=[row.version_number for row in rows],
)
row_etag = [row.etag for row in rows]
if any(row_etag):
append_etag = True
series["ROW_ETAG"] = pd.Series(name="ROW_ETAG", data=row_etag)
for i, header in enumerate(headers):
column_name = header.name
series[column_name] = pd.Series(
name=column_name,
data=[row.values[i] for row in rows],
index=rownames,
)
next_page_token = query_result.next_page_token
while next_page_token:
# see QueryResult: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryResult.html
# see RowSet: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/RowSet.html
result = _query_table_next_page(
next_page_token=next_page_token,
table_id=rowset.table_id,
synapse_client=synapse_client,
)
rowset = result.query_result.query_results
next_page_token = result.query_result.next_page_token
rownames = construct_rownames(rowset, offset)
offset += len(rowset.rows)
if not row_id_and_version_in_index:
# TODO: Look into why this isn't being assigned
series["ROW_ID"].append(
pd.Series(name="ROW_ID", data=[row.id for row in rowset.rows])
)
series["ROW_VERSION"].append(
pd.Series(
name="ROW_VERSION",
data=[row.version_number for row in rowset.rows],
)
)
if append_etag:
series["ROW_ETAG"] = pd.Series(
name="ROW_ETAG",
data=[row.etag for row in rowset.rows],
)
for i, header in enumerate(rowset.headers):
column_name = header.name
series[column_name] = pd.concat(
[
series[column_name],
pd.Series(
name=column_name,
data=[row.values[i] for row in rowset.rows],
index=rownames,
),
],
# can't verify integrity when indices are just numbers instead of 'rowid_rowversion'
verify_integrity=row_id_and_version_in_index,
)
return pd.DataFrame(data=series)
@dataclass
class TableBase:
"""Base class for any `Table`-like entities in Synapse.
Provides the minimum required attributes for any such entity.
<https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/TableEntity.html>
"""
id: None = None
name: None = None
parent_id: None = None
activity: None = None
version_number: None = None
_last_persistent_instance: None = None
_columns_to_delete: Optional[Dict] = None
@dataclass
class ViewBase(TableBase):
"""A class that extends TableBase for additional attributes specific to `View`-like objects.
In the Synapse API, a `View` is a sub-category of the `Table` model interface which includes other `Table`-like
entities including: `SubmissionView`, `EntityView`, and `Dataset`.
<https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/View.html>
"""
view_entity_type: Optional[ViewEntityType] = field(default=None, compare=False)
"""
The type of view. This is used to determine the default columns that are
added to the table. Must be defined as a `ViewEntityType` enum.
<https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/ViewEntityType.html>
"""
view_type_mask: Optional[ViewTypeMask] = field(default=None, compare=False)
"""
Bit mask representing the types to include in the view. This is used to determine
the default columns that are added to the table. Must be defined as a `ViewTypeMask` enum.
<https://rest-docs.synapse.org/rest/GET/column/tableview/defaults.html>
"""
include_default_columns: Optional[bool] = field(default=True, compare=False)
"""
When creating a entityview or view, specifies if default columns should be included.
Default columns are columns that are automatically added to the entityview or view. These
columns are managed by Synapse and cannot be modified. If you attempt to create a
column with the same name as a default column, you will receive a warning when you
store the entityview.
**`include_default_columns` is only used if this is the first time that the view is
being stored.** If you are updating an existing view this attribute will be ignored.
If you want to add all default columns back to your view then you may use this code
snippet to accomplish this:
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import EntityView # May also use: Dataset
syn = Synapse()
syn.login()
async def main():
view = await EntityView(id="syn1234").get_async()
await view._append_default_columns()
await view.store_async()
asyncio.run(main())
```
The column you are overriding will not behave the same as a default column. For
example, suppose you create a column called `id` on a EntityView. When using a
default column, the `id` stores the Synapse ID of each of the entities included in
the scope of the view. If you override the `id` column with a new column, the `id`
column will no longer store the Synapse ID of the entities in the view. Instead, it
will store the values you provide when you store the entityview. It will be stored as an
annotation on the entity for the row you are modifying.
"""
@async_to_sync
class TableStoreMixin:
"""Mixin class providing methods for storing a `Table`-like entity."""
async def _generate_schema_change_request(
self, dry_run: bool = False, *, synapse_client: Optional[Synapse] = None
) -> Union["TableSchemaChangeRequest", None]:
"""
Create a `TableSchemaChangeRequest` object that will be used to update the
schema of the table. This method will only create a `TableSchemaChangeRequest`
if the columns have changed. If the columns have not changed this method will
return `None`. Since columns are idompotent, the columns will always be stored
to Synapse if there is a change, but the table will not be updated if `dry_run`
is set to `True`.
Arguments:
dry_run: If True, will not actually store the table but will log to
the console what would have been stored.
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor
Returns:
A `TableSchemaChangeRequest` object that will be used to update the schema
of the table. If there are no changes to the columns this method will
return `None`.
"""
if (
self.__class__.__name__ in CLASSES_WITH_READ_ONLY_SCHEMA
or not self.has_columns_changed
or not self.columns
):
return None
column_name_to_id = {}
column_changes = []
client = Synapse.get_client(synapse_client=synapse_client)
# This portion of the code is checking if the content of the Column has
# changed, and if it has, the column will be stored in Synapse and a
# `ColumnChange` will be created to track the changes and submit it as
# part of the `TableSchemaChangeRequest`
columns_to_persist = []
for column in self.columns.values():
if column.has_changed:
if (
column._last_persistent_instance
and column._last_persistent_instance.id
):
column_name_to_id[column.name] = column._last_persistent_instance.id
if (
column._last_persistent_instance
and column._last_persistent_instance.id
):
log_dataclass_diff(
logger=client.logger,
prefix=f"[{self.id}:{self.name}:Column_{column.name}]: ",
obj1=column._last_persistent_instance,
obj2=column,
fields_to_ignore=["_last_persistent_instance", "id"],
)
else:
client.logger.info(
f"[{self.id}:{self.name}:Column_{column.name} (Add)]: {column}"
)
if not dry_run:
columns_to_persist.append(column)
# This conditional is to handle for cases where a Column object has not
# been modified (ie: It's a default Column in Synapse), but it hasn't been
# associated with this Table yet.
elif (
not self._last_persistent_instance
or not self._last_persistent_instance.columns
or column.name not in self._last_persistent_instance.columns
):
client.logger.info(
f"[{self.id}:{self.name}:Column_{column.name} (Add)]: {column}"
)
if not dry_run:
columns_to_persist.append(column)
column_changes.append(ColumnChange(new_column_id=column.id))
if columns_to_persist:
await post_columns(
columns=columns_to_persist, synapse_client=synapse_client
)
for column in columns_to_persist:
old_id = column_name_to_id.get(column.name, None)
if not old_id:
column_changes.append(ColumnChange(new_column_id=column.id))
elif old_id != column.id:
column_changes.append(
ColumnChange(old_column_id=old_id, new_column_id=column.id)
)
if self._columns_to_delete:
for column in self._columns_to_delete.values():
column_changes.append(ColumnChange(old_column_id=column.id))
order_of_existing_columns = (
[column.id for column in self._last_persistent_instance.columns.values()]
if self._last_persistent_instance and self._last_persistent_instance.columns
else []
)
order_of_new_columns = []
for column in self.columns.values():
if (
not self._columns_to_delete
or column.id not in self._columns_to_delete.keys()
):
order_of_new_columns.append(column.id)
if (order_of_existing_columns != order_of_new_columns) or column_changes:
# To be human readable we're using the names of the columns,
# however, it's slightly incorrect as a replacement of a column
# might have occurred if a field of the column was modified
# since columns are immutable after creation each column
# modification recieves a new ID.
order_of_existing_column_names = (
[
column.name
for column in self._last_persistent_instance.columns.values()
]
if self._last_persistent_instance
and self._last_persistent_instance.columns
else []
)
order_of_new_column_names = [
column.name for column in self.columns.values()
]
columns_being_deleted = (
[column.name for column in self._columns_to_delete.values()]
if self._columns_to_delete
else []
)
if columns_being_deleted:
client.logger.info(
f"[{self.id}:{self.name}]: (Columns Being Deleted): {columns_being_deleted}"
)
if order_of_existing_column_names != order_of_new_column_names:
client.logger.info(
f"[{self.id}:{self.name}]: (Column Order): "
f"{[column.name for column in self.columns.values()]}"
)
return TableSchemaChangeRequest(
entity_id=self.id,
changes=column_changes,
ordered_column_ids=order_of_new_columns,
)
return None
@otel_trace_method(
method_to_trace_name=lambda self, **kwargs: f"{self.__class__}_Store: {self.name}"
)
async def store_async(
self,
dry_run: bool = False,
*,
job_timeout: int = 600,
synapse_client: Optional[Synapse] = None,
) -> "Self":
"""Store non-row information about a table including the columns and annotations.
Note the following behavior for the order of columns:
- If a column is added via the `add_column` method it will be added at the
index you specify, or at the end of the columns list.
- If column(s) are added during the contruction of your `Table` instance, ie.
`Table(columns=[Column(name="foo")])`, they will be added at the begining
of the columns list.
- If you use the `store_rows` method and the `schema_storage_strategy` is set to
`INFER_FROM_DATA` the columns will be added at the end of the columns list.
Arguments:
dry_run: If True, will not actually store the table but will log to
the console what would have been stored.
job_timeout: The maximum amount of time to wait for a job to complete.
This is used when updating the table schema. If the timeout
is reached a `SynapseTimeoutError` will be raised.
The default is 600 seconds
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Returns:
The Table instance stored in synapse.
"""
client = Synapse.get_client(synapse_client=synapse_client)
if (
(not self._last_persistent_instance)
and (
existing_id := await get_id(
entity=self, synapse_client=synapse_client, failure_strategy=None
)
)
and (
existing_entity := await self.__class__(id=existing_id).get_async(
include_columns=True, synapse_client=synapse_client
)
)
):
merge_dataclass_entities(
source=existing_entity,
destination=self,
)
if (not self._last_persistent_instance) and (
hasattr(self, "_append_default_columns")
and hasattr(self, "include_default_columns")
and self.include_default_columns
):
await self._append_default_columns(synapse_client=synapse_client)
if (
self.__class__.__name__ not in CLASSES_WITH_READ_ONLY_SCHEMA
and self.columns
):
# check that column names match this regex "^[a-zA-Z0-9 _\-\.\+\(\)']+$"
for _, column in self.columns.items():
if not re.match(r"^[a-zA-Z0-9 _\-\.\+\(\)']+$", column.name):
raise ValueError(
f"Column name '{column.name}' contains invalid characters. "
"Names may only contain: letters, numbers, spaces, underscores, "
"hyphens, periods, plus signs, apostrophes, and parentheses."
)
if dry_run:
client.logger.info(
f"[{self.id}:{self.name}]: Dry run enabled. No changes will be made."
)
if self.has_changed:
if self.id:
if dry_run:
client.logger.info(
f"[{self.id}:{self.name}]: Dry run {self.__class__} update, expected changes:"
)
log_dataclass_diff(
logger=client.logger,
prefix=f"[{self.id}:{self.name}]: ",
obj1=self._last_persistent_instance,
obj2=self,
fields_to_ignore=["columns", "_last_persistent_instance"],
)
else:
entity = await put_entity_id_bundle2(
entity_id=self.id,
request=self.to_synapse_request(),
synapse_client=synapse_client,
)
self.fill_from_dict(entity=entity["entity"], set_annotations=False)
else:
if dry_run:
client.logger.info(
f"[{self.id}:{self.name}]: Dry run {self.__class__} update, expected changes:"
)
log_dataclass_diff(
logger=client.logger,
prefix=f"[{self.name}]: ",
obj1=self.__class__(),
obj2=self,
fields_to_ignore=["columns", "_last_persistent_instance"],
)
else:
entity = await post_entity_bundle2_create(
request=self.to_synapse_request(), synapse_client=synapse_client
)
self.fill_from_dict(entity=entity["entity"], set_annotations=False)
schema_change_request = await self._generate_schema_change_request(
dry_run=dry_run, synapse_client=synapse_client
)
if dry_run:
return self
if schema_change_request:
await TableUpdateTransaction(
entity_id=self.id, changes=[schema_change_request]
).send_job_and_wait_async(synapse_client=client, timeout=job_timeout)
# Replace the columns after a schema change in case any column names were updated
updated_columns = OrderedDict()
for column in self.columns.values():
updated_columns[column.name] = column
self.columns = updated_columns
await self.get_async(
include_columns=False,