-
Notifications
You must be signed in to change notification settings - Fork 665
/
bulk2.py
1328 lines (1222 loc) · 43.5 KB
/
bulk2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" Classes for interacting with Salesforce Bulk 2.0 API """
import copy
import csv
import datetime
import http.client as http
import io
import json
import math
import os
import re
import sys
import tempfile
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from enum import Enum
from functools import partial
from time import sleep
from typing import Any, AnyStr, Dict, Generator, List, MutableMapping, \
Optional, Tuple, Union
from typing_extensions import Literal, NotRequired, TypedDict
import requests
from more_itertools import chunked
from requests import Session
from .exceptions import (
SalesforceBulkV2ExtractError,
SalesforceBulkV2LoadError,
SalesforceOperationError,
)
from .util import call_salesforce
# pylint: disable=missing-class-docstring,invalid-name,too-many-arguments,
# too-many-locals
class Operation(str,
Enum
):
insert = "insert"
upsert = "upsert"
update = "update"
delete = "delete"
hard_delete = "hardDelete"
query = "query"
query_all = "queryAll"
class JobState(str,
Enum
):
open = "Open"
aborted = "Aborted"
failed = "Failed"
upload_complete = "UploadComplete"
in_progress = "InProgress"
job_complete = "JobComplete"
class ColumnDelimiter(str,
Enum
):
BACKQUOTE = "BACKQUOTE" # (`)
CARET = "CARET" # (^)
COMMA = "COMMA" # (,)
PIPE = "PIPE" # (|)
SEMICOLON = "SEMICOLON" # (;)
TAB = "TAB" # (\t)
_delimiter_char = {
ColumnDelimiter.BACKQUOTE: "`",
ColumnDelimiter.CARET: "^",
ColumnDelimiter.COMMA: ",",
ColumnDelimiter.PIPE: "|",
ColumnDelimiter.SEMICOLON: ";",
ColumnDelimiter.TAB: "\t",
}
class LineEnding(str,
Enum
):
LF = "LF"
CRLF = "CRLF"
_line_ending_char = {
LineEnding.LF: "\n",
LineEnding.CRLF: "\r\n"
}
class ResultsType(str,
Enum
):
failed = "failedResults"
successful = "successfulResults"
unprocessed = "unprocessedRecords"
class QueryParameters(TypedDict,
total=False
):
maxRecords: int
locator: str
class QueryResult(TypedDict,
total=False
):
locator: str
number_of_records: int
records: NotRequired[str]
file: NotRequired[str]
# https://developer.salesforce.com/docs/atlas.en-us.242.0
# .salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet
# /salesforce_app_limits_platform_bulkapi.htm
# https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta
# /api_asynch/datafiles_prepare_csv.htm
MAX_INGEST_JOB_FILE_SIZE = 100 * 1024 * 1024
MAX_INGEST_JOB_PARALLELISM = 10 # TODO: ? Salesforce limits
DEFAULT_QUERY_PAGE_SIZE = 50000
def _split_csv(
filename: Optional[str] = None,
records: Optional[str] = None,
max_records: Optional[int] = None
) -> Generator[Tuple[int, str], None, None]:
"""Split a CSV file into chunks to avoid exceeding the Salesforce
bulk 2.0 API limits.
Arguments:
* filename -- csv file
* max_records -- the number of records per chunk, None for auto size
"""
total_records = _count_csv(filename=filename,
skip_header=True
) if \
filename else \
_count_csv(data=records,
skip_header=True
)
csv_data_size = os.path.getsize(filename) if filename else sys.getsizeof(
records
)
_max_records: int = max_records or total_records
_max_records = min(_max_records,
total_records
)
max_bytes = min(
csv_data_size,
MAX_INGEST_JOB_FILE_SIZE - 1 * 1024 * 1024
) # -1 MB for sentinel
records_size = 0
bytes_size = 0
buff: List[str] = []
if filename:
with open(filename,
encoding="utf-8"
) as bis:
header = bis.readline()
for line in bis:
records_size += 1
bytes_size += len(line.encode("utf-8"))
if records_size > _max_records or bytes_size > max_bytes:
if buff:
yield records_size - 1, header + "".join(buff)
buff = [line]
records_size = 1
bytes_size = len(line.encode("utf-8"))
else:
buff.append(line)
if buff:
yield records_size, header + "".join(buff)
else:
assert records is not None
header = records.splitlines(True)[0]
for line in records.splitlines(True)[1:]:
records_size += 1
bytes_size += len(line.encode("utf-8"))
if records_size > _max_records or bytes_size > max_bytes:
if buff:
yield records_size - 1, header + "".join(buff)
buff = [line]
records_size = 1
bytes_size = len(line.encode("utf-8"))
else:
buff.append(line)
if buff:
yield records_size, header + "".join(buff)
def _count_csv(
filename: Optional[str] = None,
data: Optional[str] = None,
skip_header: bool = False,
line_ending: LineEnding = LineEnding.LF
) -> int:
"""Count the number of records in a CSV file."""
if filename:
with open(filename,
encoding="utf-8"
) as bis:
count = sum(1 for _ in bis)
elif data:
pat = repr(_line_ending_char[line_ending])[1:-1]
count = sum(1 for _ in re.finditer(pat,
data
)
)
else:
raise ValueError("Either filename or data must be provided")
if skip_header:
count -= 1
return count
def _convert_dict_to_csv(
data: Optional[List[Dict[str, str]]],
column_delimiter: Union[ColumnDelimiter, str] = ColumnDelimiter.COMMA,
line_ending: Union[LineEnding, str] = LineEnding.LF
) -> Optional[str]:
"""Converts list of dicts to CSV like object."""
if not data:
return None
keys = set(i for s in [d.keys() for d in data] for i in s)
dict_to_csv_file = io.StringIO()
writer = csv.DictWriter(dict_to_csv_file,
fieldnames=keys,
delimiter=column_delimiter,
lineterminator=line_ending
)
writer.writeheader()
for row in data:
writer.writerow(row)
return dict_to_csv_file.getvalue()
class SFBulk2Handler:
"""Bulk 2.0 API request handler
Intermediate class which allows us to use commands,
such as 'sf.bulk2.Contacts.insert(...)'
This is really just a middle layer, whose sole purpose is
to allow the above syntax
"""
def __init__(
self,
session_id: str,
bulk2_url: str,
proxies: Optional[MutableMapping[str, str]] = None,
session: Optional[Session] = None
):
"""Initialize the instance with the given parameters.
Arguments:
* session_id -- the session ID for authenticating to Salesforce
* bulk2_url -- 2.0 API endpoint set in Salesforce instance
* proxies -- the optional map of scheme to proxy server
* session -- Custom requests session, created in calling code. This
enables the use of requests Session features not otherwise
exposed by simple_salesforce.
"""
self.session_id = session_id
self.session = session or requests.Session()
self.bulk2_url = bulk2_url
# don't wipe out original proxies with None
if not session and proxies is not None:
self.session.proxies = proxies
# Define these headers separate from Salesforce class,
# as bulk uses a slightly different format
self.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + self.session_id,
"X-PrettyPrint": "1",
}
def __getattr__(self,
name: str
) -> "SFBulk2Type":
return SFBulk2Type(
object_name=name,
bulk2_url=self.bulk2_url,
headers=self.headers,
session=self.session,
)
class _Bulk2Client:
"""Bulk 2.0 API client"""
JSON_CONTENT_TYPE = "application/json"
CSV_CONTENT_TYPE = "text/csv; charset=UTF-8"
DEFAULT_WAIT_TIMEOUT_SECONDS = 86400 # 24-hour bulk job running time
MAX_CHECK_INTERVAL_SECONDS = 2.0
def __init__(
self,
object_name: str,
bulk2_url: str,
headers: Dict[str, str],
session: Session
):
"""
Arguments:
* object_name -- the name of the type of SObject this represents,
e.g. `Lead` or `Contact`
* bulk2_url -- 2.0 API endpoint set in Salesforce instance
* headers -- bulk 2.0 API headers
* session -- Custom requests session, created in calling code. This
enables the use of requests Session features not otherwise
exposed by simple_salesforce.
"""
self.object_name = object_name
self.bulk2_url = bulk2_url
self.session = session
self.headers = headers
def _get_headers(
self,
request_content_type: Optional[str] = None,
accept_content_type: Optional[str] = None
) -> Dict[str, str]:
"""Get headers for bulk 2.0 API request"""
headers = copy.deepcopy(self.headers)
headers["Content-Type"] = request_content_type or self.JSON_CONTENT_TYPE
headers["ACCEPT"] = accept_content_type or self.JSON_CONTENT_TYPE
return headers
def _construct_request_url(
self,
job_id: Optional[str],
is_query: bool
) -> str:
"""Construct bulk 2.0 API request URL"""
if not job_id:
job_id = ""
url: str
if is_query:
url = self.bulk2_url + "query"
else:
url = self.bulk2_url + "ingest"
if job_id:
url = f"{url}/{job_id}"
return url
def create_job(
self,
operation: Operation,
query: Optional[str] = None,
column_delimiter: ColumnDelimiter = ColumnDelimiter.COMMA,
line_ending: LineEnding = LineEnding.LF,
external_id_field: Optional[str] = None,
) -> Any:
"""Create job
Arguments:
* operation -- Bulk operation to be performed by job
* query -- SOQL query to be performed by job
* column_delimiter -- The column delimiter used for CSV job data
* line_ending -- The line ending used for CSV job data
* external_id_field -- The external ID field in the object being updated
"""
payload = {
"operation": operation,
"columnDelimiter": column_delimiter,
"lineEnding": line_ending,
}
if external_id_field:
payload["externalIdFieldName"] = external_id_field
is_query = operation in (Operation.query, Operation.query_all)
url = self._construct_request_url(None,
is_query
)
if is_query:
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.CSV_CONTENT_TYPE
)
if not query:
raise SalesforceBulkV2ExtractError(
"Query is required for query jobs"
)
payload["query"] = query
else:
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.JSON_CONTENT_TYPE
)
payload["object"] = self.object_name
payload["contentType"] = "CSV"
result = call_salesforce(
url=url,
method="POST",
session=self.session,
headers=headers,
data=json.dumps(payload,
allow_nan=False
),
)
return result.json(object_pairs_hook=OrderedDict)
def wait_for_job(
self,
job_id: str,
is_query: bool,
wait: float = 0.5
) -> Literal[JobState.job_complete]:
"""Wait for job completion or timeout"""
expiration_time: datetime.datetime = (
datetime.datetime.now() +
datetime.timedelta(seconds=self.DEFAULT_WAIT_TIMEOUT_SECONDS)
)
job_status = JobState.in_progress if is_query else JobState.open
delay_timeout = 0.0
delay_cnt = 0
sleep(wait)
while datetime.datetime.now() < expiration_time:
job_info = self.get_job(job_id,
is_query
)
job_status = job_info["state"]
if job_status in [
JobState.job_complete,
JobState.aborted,
JobState.failed,
]:
if job_status != JobState.job_complete:
error_message = job_info.get("errorMessage") or job_info
raise SalesforceOperationError(
f"Job failure. Response content: {error_message}"
)
return job_status # JobComplete
if delay_timeout < self.MAX_CHECK_INTERVAL_SECONDS:
delay_timeout = wait + math.exp(delay_cnt) / 1000.0
delay_cnt += 1
sleep(delay_timeout)
raise SalesforceOperationError(f"Job timeout. Job status: {job_status}")
def abort_job(self,
job_id: str,
is_query: bool
) -> Any:
"""Abort query/ingest job"""
return self._set_job_state(job_id,
is_query,
JobState.aborted
)
def close_job(self,
job_id: str
) -> Any:
"""Close ingest job"""
return self._set_job_state(
job_id,
False,
JobState.upload_complete
)
def delete_job(self,
job_id: str,
is_query: bool
) -> Any:
"""Delete query/ingest job"""
url = self._construct_request_url(job_id,
is_query
)
headers = self._get_headers()
result = call_salesforce(
url=url,
method="DELETE",
session=self.session,
headers=headers
)
return result.json(object_pairs_hook=OrderedDict)
def _set_job_state(self,
job_id: str,
is_query: bool,
state: str
) -> Any:
"""Set job state"""
url = self._construct_request_url(job_id,
is_query
)
headers = self._get_headers()
payload = {
"state": state
}
result = call_salesforce(
url=url,
method="PATCH",
session=self.session,
headers=headers,
data=json.dumps(payload,
allow_nan=False
),
)
return result.json(object_pairs_hook=OrderedDict)
def get_job(self,
job_id: str,
is_query: bool
) -> Any:
"""Get job info"""
url = self._construct_request_url(job_id,
is_query
)
result = call_salesforce(
url=url,
method="GET",
session=self.session,
headers=self.headers
)
return result.json(object_pairs_hook=OrderedDict)
def filter_null_bytes(self,
b: AnyStr
) -> AnyStr:
"""
https://github.com/airbytehq/airbyte/issues/8300
"""
if isinstance(b,
str
):
return b.replace("\x00",
""
)
if isinstance(b,
bytes
):
return b.replace(b"\x00",
b""
)
raise TypeError("Expected str or bytes")
def get_query_results(
self,
job_id: str,
locator: str = "",
max_records: int = DEFAULT_QUERY_PAGE_SIZE
) -> QueryResult:
"""Get results for a query job"""
url = self._construct_request_url(job_id,
True
) + "/results"
params: QueryParameters = {
"maxRecords": max_records
}
if locator and locator != "null":
params["locator"] = locator
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.CSV_CONTENT_TYPE
)
result = call_salesforce(
url=url,
method="GET",
session=self.session,
headers=headers,
params=params,
)
locator = result.headers.get("Sforce-Locator",
""
)
if locator == "null":
locator = ""
number_of_records = int(result.headers["Sforce-NumberOfRecords"])
return {
"locator": locator,
"number_of_records": number_of_records,
"records": self.filter_null_bytes(result.content.decode('utf-8')),
}
def download_job_data(
self,
path: str,
job_id: str,
locator: str = "",
max_records: int = DEFAULT_QUERY_PAGE_SIZE,
chunk_size: int = 1024,
) -> QueryResult:
"""Get results for a query job"""
if not os.path.exists(path):
raise SalesforceBulkV2LoadError(f"Path does not exist: {path}")
url = self._construct_request_url(job_id,
True
) + "/results"
params: QueryParameters = {
"maxRecords": max_records
}
if locator and locator != "null":
params["locator"] = locator
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.CSV_CONTENT_TYPE
)
with closing(
call_salesforce(
url=url,
method="GET",
session=self.session,
headers=headers,
params=params,
stream=True,
)
) as result, tempfile.NamedTemporaryFile(
"wb",
dir=path,
suffix=".csv",
delete=False
) as bos:
locator = result.headers.get("Sforce-Locator",
""
)
if locator == "null":
locator = ""
number_of_records = int(
result.headers["Sforce-NumberOfRecords"]
)
for chunk in result.iter_content(chunk_size=chunk_size):
bos.write(self.filter_null_bytes(chunk))
# check the file exists
if os.path.isfile(bos.name):
return {
"locator": locator,
"number_of_records": number_of_records,
"file": bos.name,
}
raise SalesforceBulkV2LoadError(
f"The IO/Error occured while verifying binary data. "
f"File {bos.name} doesn't exist, url: {url}, "
)
def upload_job_data(
self,
job_id: str,
data: str,
content_url: Optional[str] = None
) -> None:
"""Upload job data"""
if not data:
raise SalesforceBulkV2LoadError("Data is required for ingest jobs")
# performance reduction here
data_size = len(data.encode("utf-8"))
if data_size > MAX_INGEST_JOB_FILE_SIZE:
raise SalesforceBulkV2LoadError(
f"Data size {data_size} exceeds the max file size accepted by "
"Bulk V2 (100 MB)"
)
url = (
content_url or
self._construct_request_url(job_id,
False
) + "/batches"
)
headers = self._get_headers(
self.CSV_CONTENT_TYPE,
self.JSON_CONTENT_TYPE
)
result = call_salesforce(
url=url,
method="PUT",
session=self.session,
headers=headers,
data=data.encode("utf-8"),
)
if result.status_code != http.CREATED:
raise SalesforceBulkV2LoadError(
f"Failed to upload job data. Error Code {result.status_code}. "
f"Response content: {result.content.decode()}"
)
def get_ingest_results(self,
job_id: str,
results_type: str
) -> str:
"""Get record results"""
url = self._construct_request_url(
job_id,
False
) + "/" + results_type
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.CSV_CONTENT_TYPE
)
result = call_salesforce(
url=url,
method="GET",
session=self.session,
headers=headers
)
return result.text
def download_ingest_results(
self,
file: str,
job_id: str,
results_type: str,
chunk_size: int = 1024
) -> None:
"""Download record results to a file"""
url = self._construct_request_url(
job_id,
False
) + "/" + results_type
headers = self._get_headers(
self.JSON_CONTENT_TYPE,
self.CSV_CONTENT_TYPE
)
with closing(
call_salesforce(
url=url,
method="GET",
session=self.session,
headers=headers
)
) as result, open(file,
"wb"
) as bos:
for chunk in result.iter_content(chunk_size=chunk_size):
bos.write(self.filter_null_bytes(chunk))
if not os.path.exists(file):
raise SalesforceBulkV2LoadError(
f"The IO/Error occured while verifying binary data. "
f"File {file} doesn't exist, url: {url}, "
)
class SFBulk2Type:
"""Interface to Bulk 2.0 API functions"""
def __init__(
self,
object_name: str,
bulk2_url: str,
headers: Dict[str, str],
session: Session
):
"""Initialize the instance with the given parameters.
Arguments:
* object_name -- the name of the type of SObject this represents,
e.g. `Lead` or `Contact`
* bulk2_url -- API endpoint set in Salesforce instance
* headers -- bulk API headers
* session -- Custom requests session, created in calling code. This
enables the use of requests Session features not otherwise
exposed by simple_salesforce.
"""
self.object_name = object_name
self.bulk2_url = bulk2_url
self.session = session
self.headers = headers
self._client = _Bulk2Client(object_name,
bulk2_url,
headers,
session
)
def _upload_data(
self,
operation: Operation,
data: Union[str, Tuple[int, str]],
column_delimiter: ColumnDelimiter = ColumnDelimiter.COMMA,
line_ending: LineEnding = LineEnding.LF,
external_id_field: Optional[str] = None,
wait: int = 5,
) -> Dict[str, int]:
"""Upload data to Salesforce"""
unpacked_data: str
if isinstance(data,
tuple
):
total, unpacked_data = data
else:
total = _count_csv(
data=data,
line_ending=line_ending,
skip_header=True
)
unpacked_data = data
res = self._client.create_job(
operation,
column_delimiter=column_delimiter,
line_ending=line_ending,
external_id_field=external_id_field,
)
job_id = res["id"]
try:
if res["state"] == JobState.open:
self._client.upload_job_data(job_id,
unpacked_data
)
self._client.close_job(job_id)
self._client.wait_for_job(job_id,
False,
wait
)
res = self._client.get_job(job_id,
False
)
return {
"numberRecordsFailed": int(res["numberRecordsFailed"]),
"numberRecordsProcessed": int(
res["numberRecordsProcessed"]
),
"numberRecordsTotal": int(total),
"job_id": job_id,
}
raise SalesforceBulkV2LoadError(
f"Failed to upload job data. Response content: {res}"
)
except Exception:
res = self._client.get_job(job_id,
False
)
if res["state"] in (
JobState.upload_complete,
JobState.in_progress,
JobState.open,
):
self._client.abort_job(job_id,
False
)
raise
# pylint:disable=too-many-locals
def _upload_file(
self,
operation: Operation,
csv_file: Optional[str] = None,
records: Optional[str] = None,
batch_size: Optional[int] = None,
column_delimiter: ColumnDelimiter = ColumnDelimiter.COMMA,
line_ending: LineEnding = LineEnding.LF,
external_id_field: Optional[str] = None,
concurrency: int = 1,
wait: int = 5,
) -> List[Dict[str, int]]:
"""Upload csv file to Salesforce"""
if csv_file and records:
raise SalesforceBulkV2LoadError("Cannot include both file and "
"records"
)
if not records and csv_file:
if not os.path.exists(csv_file):
raise SalesforceBulkV2LoadError(csv_file + " not found.")
if operation in (Operation.delete, Operation.hard_delete):
assert csv_file is not None
with open(csv_file,
"r",
encoding="utf-8"
) as bis:
header = (
bis.readline()
.rstrip()
.split(_delimiter_char[column_delimiter])
)
if len(header) != 1:
raise SalesforceBulkV2LoadError(
f"InvalidBatch: The '{operation}' batch must contain "
f"only ids, {header}"
)
results = []
workers = min(concurrency,
MAX_INGEST_JOB_PARALLELISM
)
split_data = _split_csv(filename=csv_file,
max_records=batch_size
) \
if \
csv_file else _split_csv(records=records,
max_records=batch_size
)
if workers == 1:
for data in split_data:
result = self._upload_data(
operation,
data,
column_delimiter,
line_ending,
external_id_field,
wait,
)
results.append(result)
else:
# OOM is possible if the file is too large
for chunks in chunked(split_data,
n=workers
):
workers = min(workers,
len(chunks)
)
with ThreadPoolExecutor(max_workers=workers) as pool:
multi_thread_worker = partial(
self._upload_data,
operation,
column_delimiter=column_delimiter,
line_ending=line_ending,
external_id_field=external_id_field,
wait=wait,
)
_results = pool.map(multi_thread_worker,
chunks
)
results.extend(list(_results))
return results
def delete(
self,
csv_file: Optional[str] = None,
records: Optional[List[Dict[str, str]]] = None,
batch_size: Optional[int] = None,
column_delimiter: ColumnDelimiter = ColumnDelimiter.COMMA,
line_ending: LineEnding = LineEnding.LF,
external_id_field: Optional[str] = None,
wait: int = 5,
) -> List[Dict[str, int]]:
"""soft delete records"""
return self._upload_file(
Operation.delete,
csv_file=csv_file,
records=_convert_dict_to_csv(
records,
column_delimiter=_delimiter_char.get(
column_delimiter,
ColumnDelimiter.COMMA
),
line_ending=_line_ending_char.get(
line_ending,
LineEnding.LF
)
),
batch_size=batch_size,
column_delimiter=column_delimiter,
line_ending=line_ending,
external_id_field=external_id_field,
wait=wait,
)
def insert(
self,
csv_file: Optional[str] = None,
records: Optional[List[Dict[str, str]]] = None,
batch_size: Optional[int] = None,
concurrency: int = 1,
column_delimiter: ColumnDelimiter = ColumnDelimiter.COMMA,
line_ending: LineEnding = LineEnding.LF,
wait: int = 5,
) -> List[Dict[str, int]]:
"""insert records"""
return self._upload_file(
Operation.insert,
csv_file=csv_file,
records=_convert_dict_to_csv(
records,
column_delimiter=_delimiter_char.get(
column_delimiter,
ColumnDelimiter.COMMA
),
line_ending=_line_ending_char.get(
line_ending,
LineEnding.LF
)
),
batch_size=batch_size,
column_delimiter=column_delimiter,
line_ending=line_ending,
concurrency=concurrency,
wait=wait,
)
def upsert(
self,
csv_file: Optional[str] = None,
records: Optional[List[Dict[str, str]]] = None,