-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathentity.py
More file actions
988 lines (857 loc) · 32.6 KB
/
entity.py
File metadata and controls
988 lines (857 loc) · 32.6 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
import logging
from collections.abc import Collection, Iterable, Mapping, MutableMapping, Sequence
from copy import copy
from typing import Any, Literal, overload
import requests
from narwhals.stable.v2.dependencies import is_into_dataframe
from narwhals.stable.v2.typing import IntoDataFrame
from dataverse_api._api import Dataverse
from dataverse_api.errors import DataverseError, DataverseModeError
from dataverse_api.metadata.base import BASE_TYPE, MetadataDumper
from dataverse_api.metadata.complex_properties import Label
from dataverse_api.metadata.entity import get_altkey_metadata
from dataverse_api.schema import DataverseRelationships
from dataverse_api.utils.batching import (
APICommand,
RequestMethod,
check_altkey_support,
chunk_data,
transform_to_batch_for_create,
transform_to_batch_for_delete,
transform_to_batch_for_upsert,
transform_upsert_data,
)
from dataverse_api.utils.data import (
convert_dataframe_to_dict,
extract_collection_valued_relationships,
extract_single_valued_relationships,
)
class DataverseEntity(Dataverse):
def __init__(
self,
session: requests.Session,
environment_url: str,
logical_name: str,
):
super().__init__(session=session, environment_url=environment_url)
self.__logical_name = logical_name
self.__supports_create_multiple = False
self.__supports_update_multiple = False
# Populate entity properties
self.update_schema("all")
@property
def logical_name(self) -> str:
return self.__logical_name
@property
def entity_set_name(self) -> str:
return self.__entity_set_name
@property
def primary_id_attr(self) -> str:
return self.__primary_id_attr
@property
def primary_img_attr(self) -> str | None:
return self.__primary_img_attr
@property
def alternate_keys(self) -> dict[str, list[str]]:
return self.__alternate_keys
@property
def supports_create_multiple(self) -> bool:
return self.__supports_create_multiple
@property
def supports_update_multiple(self) -> bool:
return self.__supports_update_multiple
@property
def relationships(self) -> DataverseRelationships:
return self.__relationships
def __get_entity_set_properties(self) -> None:
"""
Fetch key attributes of the Entity.
- `EntitySetName`, used as the API endpoint
- `PrimaryIdAttribute`, the primary ID column
- `PrimaryImageAttribute`, the primary image column (if any)
Returns
-------
EntityData
A dataclass with the three relevant attributes.
"""
columns = ["EntitySetName", "PrimaryIdAttribute", "PrimaryImageAttribute"]
logging.debug("Retrieving EntityDefinitions for %s", self.logical_name)
resp = self._api_call(
method=RequestMethod.GET,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')",
params={"$select": ",".join(columns)},
).json()
self.__entity_set_name = resp["EntitySetName"]
self.__primary_id_attr = resp["PrimaryIdAttribute"]
self.__primary_img_attr = resp.get("PrimaryImageAttribute")
def __get_entity_alternate_keys(self) -> None:
"""
Fetch the alternate keys (if any) for the Entity.
"""
columns = ["SchemaName", "KeyAttributes"]
logging.debug("Retrieving alternate keys for %s", self.logical_name)
resp = self._api_call(
method=RequestMethod.GET,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Keys",
params={"$select": ",".join(columns)},
).json()["value"]
self.__alternate_keys = {r["SchemaName"]: r["KeyAttributes"] for r in resp}
def __get_entity_sdk_messages(self) -> None:
"""
Fetch sdk messages to determine whether Entity supports certain actions.
"""
create, update = "CreateMultiple", "UpdateMultiple"
actions = [create, update]
col = "primaryobjecttypecode"
msg_col = "sdkmessageid/name"
params: dict[str, str] = dict()
params["$select"] = "sdkmessagefilterid"
params["$expand"] = "sdkmessageid($select=name)"
params["$filter"] = (
f"""({" or ".join(f"{msg_col} eq '{x}'" for x in actions)}) and {col} eq '{self.logical_name}'"""
)
logging.debug("Retrieving SDK messages for %s", self.logical_name)
resp = self._api_call(
method=RequestMethod.GET,
url="sdkmessagefilters",
params=params,
).json()["value"]
returned_actions = {row["sdkmessageid"]["name"] for row in resp}
if create in returned_actions:
self.__supports_create_multiple = True
if update in returned_actions:
self.__supports_update_multiple = True
def __get_entity_relationships(self) -> None:
"""
Fetch the relationships for the Entity.
Collection-valued: 1:N relationships where this Entity is on the one-side.
Single-valued: N:1 relationships where this Entity is on the many-side.
"""
one_to_many = self._api_call(
method=RequestMethod.GET,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/OneToManyRelationships",
).json()["value"]
many_to_one = self._api_call(
method=RequestMethod.GET,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/ManyToOneRelationships",
).json()["value"]
collection_valued = extract_collection_valued_relationships(
data=one_to_many, entity_logical_name=self.logical_name
)
single_valued = extract_single_valued_relationships(data=many_to_one)
self.__relationships = DataverseRelationships(single_valued=single_valued, collection_valued=collection_valued)
def update_schema(
self, arg: Literal["all", "altkeys", "properties", "messages", "relationships"] | None = None
) -> None:
"""
Update schema.
"""
if arg == "altkeys":
self.__get_entity_alternate_keys()
return
if arg == "properties":
self.__get_entity_set_properties()
return
if arg == "messages":
self.__get_entity_sdk_messages()
return
if arg == "relationships":
self.__get_entity_relationships()
return
if arg == "all":
self.__get_entity_alternate_keys()
self.__get_entity_sdk_messages()
self.__get_entity_set_properties()
self.__get_entity_relationships()
@overload
def read(
self,
*,
select: Collection[str] | None = None,
top: int | None = None,
filter: str | None = None,
page_size: int | None = None,
expand: str | None = None,
order_by: str | None = None,
return_formatted_values: bool = False,
return_responses: Literal[False] = False,
) -> list[dict[str, Any]]: ...
@overload
def read(
self,
*,
select: Collection[str] | None = None,
top: int | None = None,
filter: str | None = None,
page_size: int | None = None,
expand: str | None = None,
order_by: str | None = None,
return_formatted_values: bool = False,
return_responses: Literal[True],
) -> list[requests.Response]: ...
def read(
self,
*,
select: Collection[str] | None = None,
top: int | None = None,
filter: str | None = None,
page_size: int | None = None,
expand: str | None = None,
order_by: str | None = None,
return_formatted_values: bool = False,
return_responses: bool = False,
) -> list[dict[str, Any]] | list[requests.Response]:
"""
Read data from Entity.
Parameters
----------
select : Collection[str]
Columns to return in the query.
top : int
Optional limit on returned records.
filter : str
A fully qualified filtering string.
expand : str
A fully qualified expand string.
orderby : str
A fully qualified order_by string.
apply : str
A fully qualified string describing aggregation and grouping of returned records.
page_size : int
Limits the total number of records retrieved per API call.
return_formatted_values : bool
Return formatted values (e.g. for lookup, choice columns) in response.
return_responses : bool
Returns complete responses instead of data records.
Returns
-------
list[dict[str, Any]]
The extended "value" element for all response-JSONs from server.
"""
additional_headers: dict[str, str] = dict()
formatted_arg = "odata.include-annotations=OData.Community.Display.V1.FormattedValue"
page_size_arg = f"odata.maxpagesize={page_size}"
if page_size is not None and return_formatted_values:
additional_headers["Prefer"] = f"{formatted_arg},{page_size_arg}"
elif page_size is not None:
additional_headers["Prefer"] = page_size_arg
elif return_formatted_values:
additional_headers["Prefer"] = formatted_arg
params: dict[str, Any] = dict()
if select:
params["$select"] = ",".join(select)
if filter:
params["$filter"] = filter
if top:
params["$top"] = top
if order_by:
params["$orderby"] = order_by
if expand:
params["$expand"] = expand
output: list[requests.Response] = list()
url = self.entity_set_name
# Looping through pages
logging.debug("Fetching data for read operation on %s.", self.logical_name)
response = self._api_call(
method=RequestMethod.GET,
url=url,
headers=additional_headers,
params=params,
)
output.append(response)
while response.json().get("@odata.nextLink"):
response = self._api_call(
method=RequestMethod.GET,
url=response.json()["@odata.nextLink"],
headers=additional_headers,
)
output.append(response)
if return_responses:
logging.debug("Fetched all data for read operation, %d responses.", len(output))
return output
else:
data_output: list[dict[str, Any]] = []
for resp in output:
data_output.extend(resp.json()["value"])
logging.debug("Fetched all data for read operation, %d elements.", len(data_output))
return data_output
@overload
def create(
self,
data: Sequence[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["individual"] = "individual",
detect_duplicates: bool = False,
return_created: bool = False,
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def create(
self,
data: Sequence[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["batch", "multiple"],
detect_duplicates: bool = False,
return_created: bool = False,
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]: ...
def create(
self,
data: Sequence[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["individual", "multiple", "batch"] = "individual",
detect_duplicates: bool = False,
return_created: bool = False,
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]:
"""
Create rows in Dataverse Entity. Failures will occur if trying to insert
a record where alternate key already exists, partial success is possible.
data : Sequence[MutableMapping[str, Any]] | IntoDataFrame
The data to create in Dataverse, JSON serializable.
mode : Literal["individual", "multiple", "batch"]
Whether to create rows using individual requests, `CreateMultiple` web API action
or as batch requests using the `$batch` endpoint.
detect_duplicates : bool
Whether Dataverse will run duplicate detection rules upon insertion.
return_created : bool
Whether the returned list of Responses will contain information on
created rows.
batch_size : int
Optional override if batch mode is specified, useful for tuning workload
per batch if e.g. timeouts or 429s occur.
"""
if is_into_dataframe(data):
data = convert_dataframe_to_dict(data)
assert isinstance(data, Sequence)
batch_size = batch_size or 500
headers: dict[str, str] = dict()
if detect_duplicates:
headers["MSCRM.SuppressDuplicateDetection"] = "false"
if return_created:
headers["Prefer"] = "return=representation"
length = len(data)
if mode == "individual":
logging.debug("%d rows to insert using individual inserts.", length)
return self.__create_singles(headers=headers, data=data, threading=threading)
if mode == "multiple":
if not self.supports_create_multiple:
raise DataverseError(f"CreateMultiple is not supported by {self.logical_name}. Use a different mode.")
logging.debug("%d rows to insert using CreateMultiple.", length)
return self.__create_multiple(
headers=headers,
data=data,
batch_size=batch_size,
threading=threading,
)
if mode == "batch":
logging.debug(
"%d rows to insert using batch insertion.",
length,
)
return self.__create_batch(data=data, batch_size=batch_size, threading=threading)
raise DataverseModeError(mode, "individual", "multiple", "batch")
def __create_singles(
self,
data: Collection[MutableMapping[str, Any]],
headers: Mapping[str, str],
threading: bool,
) -> list[requests.Response]:
"""
Insert rows one by one using threaded API call.
"""
calls = [
APICommand(
method=RequestMethod.POST,
url=self.entity_set_name,
headers=headers,
json=row,
)
for row in data
]
if threading:
return self._threaded_call(calls=calls)
return self._individual_call(calls=calls)
def __create_multiple(
self,
headers: Mapping[str, str],
data: Sequence[MutableMapping[str, Any]],
threading: bool,
batch_size: int,
) -> list[requests.Response]:
"""
Insert rows by using the `CreateMultiple` Web API Action.
"""
# Preserving input data
data = copy(data)
# Adding odata type to each record
for row in data:
row["@odata.type"] = BASE_TYPE + self.logical_name
# Chunking the payload to suggested size
calls = [
APICommand(
method=RequestMethod.POST,
url=f"{self.entity_set_name}/{BASE_TYPE}CreateMultiple",
headers=headers,
json={"Targets": rows},
)
for rows in chunk_data(data=data, size=batch_size)
]
if threading:
return self._threaded_call(calls=calls)
return self._individual_call(calls=calls)
def __create_batch(
self, data: Collection[MutableMapping[str, Any]], batch_size: int, threading: bool
) -> list[requests.Response]:
"""
Run a batch insert operation on the given data.
"""
batch_commands = transform_to_batch_for_create(url=self.entity_set_name, data=data)
return self._batch_api_call(batch_commands=batch_commands, batch_size=batch_size, threading=threading)
def __delete_singles(self, data: Iterable[str], threading: bool) -> list[requests.Response]:
calls = [
APICommand(
method=RequestMethod.DELETE,
url=f"{self.entity_set_name}({id})",
)
for id in data
]
if threading:
return self._threaded_call(calls=calls)
return self._individual_call(calls=calls)
@overload
def delete(
self,
*,
mode: Literal["individual"] = "individual",
ids: Collection[str],
) -> list[requests.Response]: ...
@overload
def delete(
self,
*,
mode: Literal["individual"] = "individual",
filter: str,
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def delete(
self,
*,
mode: Literal["batch"],
filter: str,
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def delete(
self,
*,
mode: Literal["batch"],
ids: Collection[str],
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]: ...
def delete(
self,
*,
mode: Literal["individual", "batch"] = "individual",
ids: Collection[str] | None = None,
filter: str | None = None,
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]:
"""
Delete rows in Entity.
Specify either a list of ID's for deletion or a filter
string for determining which records to delete.
Parameters
----------
mode : Literal["individual","batch"]
Whether to delete rows using individual requests or batch requests.
ids : Collection[str]
List of primary IDs to delete. Takes precedence if passed.
filter : str
Filter statement for targeting specific records in Entity
for deletion. Use `filter="all"` to delete all records.
batch_size : int
Optional override if batch mode is specified, useful for tuning workload
per batch if 429s occur.
"""
if ids is None and filter is None:
raise DataverseError("Function requires either ids to delete or a string passed as filter.")
if filter == "all":
filter = None
if ids is None:
records = self.read(select=[self.primary_id_attr], filter=filter)
ids = {row[self.primary_id_attr] for row in records}
length = len(ids)
logging.info("%d rows to delete.", length)
if mode == "individual":
logging.debug("%d rows to delete using individual deletes.", length)
return self.__delete_singles(data=ids, threading=threading)
if mode == "batch":
logging.debug("%d rows to delete using batch deletes.", length)
batch_commands = transform_to_batch_for_delete(url=self.entity_set_name, data=ids)
return self._batch_api_call(
batch_commands=batch_commands,
batch_size=batch_size or 100,
timeout=120,
threading=threading,
)
raise DataverseModeError(mode, "individual", "batch")
def __delete_column_singles(self, data: Iterable[str], column: str, threading: bool) -> list[requests.Response]:
"""
Delete row column value by individual requests.
"""
calls = [
APICommand(
method=RequestMethod.DELETE,
url=f"{self.entity_set_name}({id})/{column}",
)
for id in data
]
if threading:
return self._threaded_call(calls=calls)
return self._individual_call(calls=calls)
@overload
def delete_columns(
self,
columns: Collection[str],
*,
mode: Literal["individual"] = "individual",
ids: Collection[str],
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def delete_columns(
self,
columns: Collection[str],
*,
mode: Literal["individual"] = "individual",
filter: str,
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def delete_columns(
self,
columns: Collection[str],
*,
mode: Literal["batch"],
ids: Collection[str],
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]: ...
@overload
def delete_columns(
self,
columns: Collection[str],
*,
mode: Literal["batch"],
filter: str,
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]: ...
def delete_columns(
self,
columns: Collection[str],
*,
ids: Collection[str] | None = None,
filter: str | None = None,
mode: Literal["individual", "batch"] = "individual",
batch_size: int | None = None,
threading: bool = False,
) -> list[requests.Response]:
"""
Delete values in specific column for rows in Entity.
Specify either a list of ID's for deletion or a filter
string for determining which records to delete.
Parameters
----------
column : Collection[str]
The columns in Dataverse to target for deletion.
mode : Literal["individual", "batch"]
Whether to delete columns using individual requests or batch requests.
ids : Collection[str]
List of primary IDs to delete. Takes precedence if passed.
filter : str
Filter statement for targeting specific records in Entity for deletion.
Use `filter="all"` to delete all records.
"""
if ids is None and filter is None:
raise DataverseError("Function requires either ids to delete or a string passed as filter.")
if filter == "all":
filter = None
if ids is None:
records = self.read(select=[self.primary_id_attr], filter=filter)
ids = {row[self.primary_id_attr] for row in records}
length = len(ids) * len(columns) # Total number of deletion requests
output: list[requests.Response] = []
if mode == "individual":
logging.debug("%d properties to delete. Using individual deletes.", length)
for col in columns:
output.extend(self.__delete_column_singles(data=ids, column=col, threading=threading))
return output
if mode == "batch":
logging.debug("%d properties to delete. Using batch deletes.", length)
for col in columns:
batch_commands = transform_to_batch_for_delete(url=self.entity_set_name, data=ids, column=col)
output.extend(
self._batch_api_call(
batch_commands=batch_commands,
batch_size=batch_size or 500,
threading=threading,
)
)
return output
raise DataverseModeError(mode, "individual", "batch")
def __upsert_singles(
self,
data: Collection[Mapping[str, Any]],
keys: Iterable[str],
is_primary_id: bool,
threading: bool,
match: Literal["prevent_create", "prevent_update"] | None = None,
) -> list[requests.Response]:
"""
Upsert row by individual requests.
"""
check_altkey_support(keys=keys, data=data)
headers: dict[str, str] | None = None
if match == "prevent_create":
headers = {"If-Match": "*"}
elif match == "prevent_update":
headers = {"If-None-Match": "*"}
calls = [
APICommand(
method=RequestMethod.PATCH,
url=f"{self.entity_set_name}({key})",
json=payload,
headers=headers,
)
for key, payload in transform_upsert_data(data=data, keys=keys, is_primary_id=is_primary_id)
]
if threading:
return self._threaded_call(calls=calls)
return self._individual_call(calls=calls)
@overload
def upsert(
self,
data: Collection[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["individual"] = "individual",
altkey_name: str | None = None,
threading: bool = False,
match: Literal["prevent_create", "prevent_update"] | None = None,
) -> list[requests.Response]: ...
@overload
def upsert(
self,
data: Collection[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["batch"],
altkey_name: str | None = None,
threading: bool = False,
batch_size: int | None = None,
) -> list[requests.Response]: ...
def upsert(
self,
data: Collection[MutableMapping[str, Any]] | IntoDataFrame,
*,
mode: Literal["individual", "batch"] = "individual",
altkey_name: str | None = None,
threading: bool = False,
batch_size: int | None = None,
match: Literal["prevent_create", "prevent_update"] | None = None,
) -> list[requests.Response]:
"""
Upsert data into Entity.
Parameters
----------
data : Collection[MutableMapping[str, Any]] | IntoDataFrame
The data to upsert.
mode : Literal["individual", "batch"]
Whether to upsert data using individual requests or batch requests.
altkey_name : str
The alternate key to use as ID (if any).
Will assume entity primary ID attribute if not given.
threading : bool
Whether to use threading for individual requests.
batch_size : int
Optional override if batch mode is specified, useful for tuning workloads
if 429s or timeouts occur.
match : Literal["prevent_create", "prevent_update"] | None
Controls upsert behavior using If-Match headers.
Only supported for individual mode, not batch mode.
- None (default): Standard upsert behavior (create or update)
- "prevent_create": Only update existing records (If-Match: *)
- "prevent_update": Only create new records (If-None-Match: *)
"""
if match is not None and mode == "batch":
raise DataverseError("The 'match' parameter is only supported for individual mode, not batch mode.")
if altkey_name is not None:
try:
key_columns = self.alternate_keys[altkey_name]
except KeyError:
raise DataverseError(f"Altkey '{altkey_name}' is not valid for Entity '{self.logical_name}'.")
is_primary_id = False
else:
key_columns = [self.primary_id_attr]
is_primary_id = True
if is_into_dataframe(data):
data = convert_dataframe_to_dict(data)
assert isinstance(data, Collection)
if mode == "individual":
logging.debug("%d rows to upsert. Using individual upserts.", len(data))
return self.__upsert_singles(
data=data, keys=key_columns, is_primary_id=is_primary_id, threading=threading, match=match
)
if mode == "batch":
logging.debug("%d rows to upsert. Using batch upserts.", len(data))
batch_commands = transform_to_batch_for_upsert(
url=self.entity_set_name,
data=data,
keys=key_columns,
is_primary_id=is_primary_id,
)
return self._batch_api_call(
batch_commands=batch_commands,
threading=threading,
batch_size=batch_size or 500,
)
raise DataverseModeError(mode, "individual", "batch")
def add_attribute(
self,
attribute: MetadataDumper,
solution_name: str | None = None,
return_representation: bool = False,
) -> requests.Response:
"""
Add attribute to Entity.
Parameters
----------
attribute : MetadataDumper
Dumpable metadata for new Attribute.
solution_name : str
Unique name for solution attribute is part of.
return_representation : bool
Whether to include the metadata representation after
creation in the response from server.
Returns
-------
requests.Response
The response from the server.
"""
headers: dict[str, str] = dict()
if solution_name is not None:
headers["MSCRM.SolutionUniqueName"] = solution_name
if return_representation:
headers["Prefer"] = "return=representation"
return self._api_call(
method=RequestMethod.POST,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Attributes",
headers=headers,
json=attribute.dump_to_dataverse(),
)
@overload
def remove_attribute(self, *, attribute_id: str) -> requests.Response: ...
@overload
def remove_attribute(self, *, logical_name: str) -> requests.Response: ...
def remove_attribute(
self,
*,
attribute_id: str | None = None,
logical_name: str | None = None,
) -> requests.Response:
"""
Remove Attribute from Entity.
Parameters
----------
attribute_id : str
GUID of Attribute.
logical_name : str
LogicalName of Attribute.
Returns
-------
requests.Response
The response from the server.
"""
if attribute_id is None and logical_name is None:
raise DataverseError("Supply either 'id' or 'logical_name' kwarg.")
if attribute_id:
return self._api_call(
method=RequestMethod.DELETE,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Attributes({attribute_id})",
)
return self._api_call(
method=RequestMethod.DELETE,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Attributes(LogicalName='{logical_name}')",
)
def add_alternate_key(
self,
schema_name: str,
display_name: str | Label,
key_attributes: Collection[str],
return_representation: bool = False,
) -> requests.Response:
"""
Add an alternate key to Entity.
Parameters
----------
alternate_key : MetadataDumper
Dumpable metadata for new Alternate Key.
"""
headers: dict[str, str] = dict()
if return_representation:
headers["Prefer"] = "return_representation"
key = get_altkey_metadata(
schema_name=schema_name,
display_name=display_name,
key_attributes=key_attributes,
)
resp = self._api_call(
method=RequestMethod.POST,
url=f"EntityMetadata(LogicalName='{self.logical_name}')/Keys",
headers=headers,
json=key.dump_to_dataverse(),
)
self.update_schema("altkeys")
return resp
@overload
def remove_alternate_key(self, *, altkey_id: str) -> requests.Response: ...
@overload
def remove_alternate_key(self, *, logical_name: str) -> requests.Response: ...
def remove_alternate_key(
self,
*,
altkey_id: str | None = None,
logical_name: str | None = None,
) -> requests.Response:
"""
Remove Alternate Key from Entity.
Parameters
----------
attribute_id : str
GUID of Alternate Key.
logical_name : str
LogicalName of Alternate Key.
Returns
-------
requests.Response
The response from the server.
"""
if altkey_id is None and logical_name is None:
raise DataverseError("Supply either 'id' or 'logical_name' kwarg.")
if altkey_id:
resp = self._api_call(
method=RequestMethod.DELETE,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Attributes({altkey_id})",
)
resp = self._api_call(
method=RequestMethod.DELETE,
url=f"EntityDefinitions(LogicalName='{self.logical_name}')/Attributes(LogicalName='{logical_name}')",
)
self.update_schema("altkeys")
return resp