-
-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathdata-export.js
More file actions
2211 lines (2118 loc) · 99.2 KB
/
data-export.js
File metadata and controls
2211 lines (2118 loc) · 99.2 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
/* global React ReactDOM */
import {sfConn, apiVersion} from "./inspector.js";
import {getLinkTarget, nullToEmptyString, isOptionEnabled, PromptTemplate, Constants, UserInfoModel, createSpinForMethod, copyToClipboard, downloadCsvFile, StorageHistory, formatDateCell, getDateFormatOptions} from "./utils.js";
/* global initButton */
import {Enumerable, DescribeInfo, initScrollTable, s} from "./data-load.js";
import {PageHeader} from "./components/PageHeader.js";
function createQueryHistory(storageKey, max) {
const isSaved = storageKey === "insextSavedQueryHistory";
return new StorageHistory(storageKey, max, {
isValidEntry: (e) => typeof e === "object",
matchAdd: (e, ent) => e.query === ent.query && e.useToolingApi === ent.useToolingApi,
matchRemove: (e, ent) => e.query === ent.query && e.useToolingApi === ent.useToolingApi,
sortComparator: isSaved ? (a, b) => (a.query > b.query ? 1 : b.query > a.query ? -1 : 0) : null,
addToFront: true
});
}
class Model {
static QUERY_TAB_PREFIX = "Query";
constructor({sfHost, args}) {
this.sfHost = sfHost;
this.customFaviconColor = localStorage.getItem(this.sfHost + "_customFavicon") || "";
this.orgName = this.sfHost.split(".")[0]?.toUpperCase() || "";
this.queryInput = null;
this.filterColumn = ""; // Default filter column
this.initialQuery = "";
this.spinnerCount = 0;
// Initialize spinFor method early - needed by describeInfo and userInfoModel
this.spinFor = createSpinForMethod(this);
this.describeInfo = new DescribeInfo(this.spinFor.bind(this), () => {
this.queryAutocompleteHandler({newDescribe: true});
this.didUpdate();
});
this.sfLink = "https://" + sfHost;
this.showHelp = false;
this.winInnerHeight = 0;
this.queryAll = false;
this.queryTooling = false;
this.prefHideRelations = localStorage.getItem("hideObjectNameColumnsDataExport") == "true"; // default to false
this.prefPreventLineWrap = localStorage.getItem("preventLineWrapDataExport") !== "false"; // default to true (matches v1.27 behavior)
this.autocompleteResults = {sobjectName: "", title: "\u00A0", results: []};
this.autocompleteClick = null;
this.isWorking = false;
this.exportStatus = "Ready";
this.exportError = null;
this.exportedData = null;
let historyNb = localStorage.getItem("numberOfQueriesInHistory");
this.queryHistory = createQueryHistory("insextQueryHistory", historyNb ? historyNb : 100);
this.selectedHistoryEntry = null;
let savedNb = localStorage.getItem("numberOfQueriesSaved");
this.savedHistory = createQueryHistory("insextSavedQueryHistory", savedNb ? savedNb : 50);
this.selectedSavedEntry = null;
this.expandAutocomplete = false;
this.expandSavedOptions = false;
this.resultsFilter = "";
this.displayPerformance = localStorage.getItem("displayQueryPerformance") !== "false"; // default to true
this.performancePoints = [];
this.startTime = null;
this.lastStartTime = null;
this.totalTime = 0;
this.autocompleteState = "";
this.autocompleteProgress = {};
this.exportProgress = {};
this.queryName = "";
this.queryTemplates = localStorage.getItem("queryTemplates") ? this.queryTemplates = localStorage.getItem("queryTemplates").split("//") : [
"SELECT Id FROM ",
'FIND {""}\nIN Name Fields\nRETURNING Contact(Name, Phone)',
"{\n\tuiapi {\n\t\tquery {\n\t\t\tContact {\n\t\t\t\tedges {\n\t\t\t\t\t node {\n\t\t\t\t\t\tId\n\t\t\t\t\t\tName { value }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"SELECT Id FROM WHERE",
"SELECT Id FROM WHERE IN",
"SELECT Id FROM WHERE LIKE",
"SELECT Id FROM WHERE ORDER BY"
];
this.separator = getSeparator();
this.soqlPrompt = "";
this.enableQueryTypoFix = localStorage.getItem("enableQueryTypoFix") == "true";
// Initialize user info model - handles all user-related properties
this.userInfoModel = new UserInfoModel(this.spinFor.bind(this));
let queryFromUrl = false;
if (args.has("query")) {
this.initialQuery = args.get("query");
this.queryTooling = args.has("useToolingApi");
queryFromUrl = true;
} else if (this.queryHistory.list[0]) {
this.initialQuery = this.queryHistory.list[0].query;
this.queryTooling = this.queryHistory.list[0].useToolingApi;
} else {
this.initialQuery = "SELECT Id FROM Account LIMIT 200";
this.queryTooling = false;
}
if (args.has("error")) {
this.exportError = args.get("error") + " " + args.get("error_description");
}
this.queryTabs = [];
this.activeTabIndex = 0;
this.loadQueryTabs(queryFromUrl);
}
updatedExportedData() {
if (this.exportedData) {
this.exportedData.updateColumnsVisibility();
}
this.resultTableCallback(this.exportedData);
}
setResultsFilter(value) {
this.resultsFilter = value;
if (this.exportedData == null) {
return;
}
// Recalculate visibility
this.exportedData.updateVisibility();
this.updatedExportedData();
}
setQueryMethod(data, query, vm){
let method;
let queryParams = "/?q=" + encodeURIComponent(query);
const baseParams = {progressHandler: vm.exportProgress};
let params = baseParams;
if (data.isTooling){
method = "tooling/query";
} else if (this.queryAll){
method = "queryAll";
} else if (this.queryInput.value.toLowerCase().startsWith("find")){
method = "search";
} else if (this.queryInput.value.trim().startsWith("{")){
method = "graphql";
queryParams = "";
params = {...baseParams, method: "POST", body: {"query": "query objects " + query}};
} else {
method = "query";
}
data.endpoint = "/services/data/v" + apiVersion + "/" + method + queryParams;
data.params = params;
data.queryMethod = method;
}
setQueryName(value) {
this.queryName = value;
}
setQueryInput(queryInput) {
this.queryInput = queryInput;
queryInput.value = this.initialQuery;
this.initialQuery = null;
}
toggleHelp() {
this.showHelp = !this.showHelp;
}
toggleAI() {
this.showAI = !this.showAI;
}
toggleExpand() {
this.expandAutocomplete = !this.expandAutocomplete;
}
toggleSavedOptions() {
this.expandSavedOptions = !this.expandSavedOptions;
}
showDescribeUrl() {
let args = new URLSearchParams();
args.set("host", this.sfHost);
args.set("objectType", this.autocompleteResults.sobjectName);
if (this.queryTooling) {
args.set("useToolingApi", "1");
}
return "inspect.html?" + args;
}
selectHistoryEntry() {
if (this.selectedHistoryEntry != null) {
this.queryInput.value = this.selectedHistoryEntry.query;
this.queryTooling = this.selectedHistoryEntry.useToolingApi;
this.queryAutocompleteHandler();
this.selectedHistoryEntry = null;
}
}
selectQueryTemplate() {
this.queryInput.value = this.selectedQueryTemplate.trimStart();
this.queryInput.focus();
let indexPos = this.queryInput.value.toLowerCase().indexOf("from ");
if (indexPos !== -1) {
this.queryInput.setRangeText("", indexPos + 5, indexPos + 5, "end");
}
}
initPerf() {
if (!this.displayPerformance) {
return;
}
this.performancePoints = [];
this.startTime = performance.now();
this.lastStartTime = this.startTime;
}
markPerf() {
if (!this.displayPerformance) {
return;
}
const now = performance.now();
const perfPoint = now - this.lastStartTime;
this.lastStartTime = now;
this.performancePoints.push(perfPoint);
this.totalTime = now - this.startTime;
}
perfStatus() {
if (!this.displayPerformance || !this.startTime || this.performancePoints.length === 0) {
return null;
}
const batches = this.performancePoints.length;
let batchStats = "";
let batchCount = "";
if (batches > 1) {
const avgTime = this.performancePoints.reduce((a, b) => a + b, 0) / batches;
const maxTime = Math.max(...this.performancePoints);
const minTime = Math.min(...this.performancePoints);
const avg = `Avg ${avgTime.toFixed(1)}ms`;
const max = `Max ${maxTime.toFixed(1)}ms`;
const min = `Min ${minTime.toFixed(1)}ms`;
batchStats = `Batch Performance: ${avg}, ${min}, ${max}`;
batchCount = `${batches} Batches / `;
}
return {text: `${batchCount}${this.totalTime.toFixed(1)}ms`, batchStats};
}
clearHistory() {
this.queryHistory.clear();
}
selectSavedEntry() {
let delimiter = ":";
if (this.selectedSavedEntry != null) {
let queryStr = "";
if (this.selectedSavedEntry.query.includes(delimiter) && (this.selectedSavedEntry.query.toLowerCase().indexOf(":select") >= 0 || this.selectedSavedEntry.query.toLowerCase().indexOf(":find") >= 0)) {
let query = this.selectedSavedEntry.query.split(delimiter);
this.queryName = query[0];
queryStr = this.selectedSavedEntry.query.substring(this.selectedSavedEntry.query.indexOf(delimiter) + 1);
} else {
queryStr = this.selectedSavedEntry.query;
}
this.queryInput.value = queryStr;
this.queryTooling = this.selectedSavedEntry.useToolingApi;
this.queryAutocompleteHandler();
this.selectedSavedEntry = null;
}
}
clearSavedHistory() {
this.savedHistory.clear();
}
addToHistory() {
this.savedHistory.add({query: this.getQueryToSave(), useToolingApi: this.queryTooling});
}
removeFromHistory() {
this.savedHistory.remove({query: this.getQueryToSave(), useToolingApi: this.queryTooling});
}
getQueryToSave() {
return this.queryName != "" ? this.queryName + ":" + this.queryInput.value.trim() : this.queryInput.value.trim();
}
autocompleteReload() {
this.describeInfo.reloadAll();
}
canCopy() {
return this.exportedData != null;
}
canDelete() {
//In order to allow deletion, we should have at least 1 element and the Id field should have been included in the query
return this.exportedData
&& (this.exportedData.countOfVisibleRecords === null /* no filtering has been done yet*/ || this.exportedData.countOfVisibleRecords > 0)
&& this.exportedData.records.length < 20001 && !this.exportStatus.includes("Exporting") && this.exportedData?.table?.at(0)?.find(header => header.toLowerCase() === "id");
}
copyAsExcel() {
copyToClipboard(this.exportedData.csvSerialize("\t"));
}
copyAsCsv() {
copyToClipboard(this.exportedData.csvSerialize(this.separator));
}
copyAsJson() {
copyToClipboard(JSON.stringify(this.exportedData.records, null, " "));
}
downloadAsCsv(){
const csvContent = this.exportedData.csvSerialize(this.separator);
const filename = `${this.exportedData.records[0].attributes.type}-${new Date().toLocaleDateString()}.csv`;
downloadCsvFile(csvContent, filename);
}
deleteRecords(e) {
let data = this.exportedData.csvSerialize(this.separator);
let encodedData = btoa(data);
let args = new URLSearchParams();
args.set("host", this.sfHost);
args.set("data", encodedData);
if (this.queryTooling) args.set("apitype", "Tooling");
window.open("data-import.html?" + args, getLinkTarget(e, false));
}
/**
* Notify React that we changed something, so it will rerender the view.
* Should only be called once at the end of an event or asynchronous operation, since each call can take some time.
* All event listeners (functions starting with "on") should call this function if they update the model.
* Asynchronous operations should use the spinFor function, which will call this function after the asynchronous operation completes.
* Other functions should not call this function, since they are called by a function that does.
* @param cb A function to be called once React has processed the update.
*/
didUpdate(cb) {
if (this.reactCallback) {
this.reactCallback(cb);
}
if (this.testCallback) {
this.testCallback();
}
}
/**
* SOQL query autocomplete handling.
* Put caret at the end of a word or select some text to autocomplete it.
* Searches for both label and API name.
* Autocompletes sobject names after the "from" keyword.
* Autocompletes field names, if the "from" keyword exists followed by a valid object name.
* Supports relationship fields.
* Autocompletes field values (picklist values, date constants, boolean values).
* Autocompletes any textual field value by performing a Salesforce API query when Ctrl+Space is pressed.
* Inserts all autocomplete field suggestions when Ctrl+Space is pressed.
* Supports subqueries in where clauses, but not in select clauses.
*/
queryAutocompleteHandler(e = {}) {
let vm = this; // eslint-disable-line consistent-this
let useToolingApi = vm.queryTooling;
let query = vm.queryInput.value;
let selStart = vm.queryInput.selectionStart;
let selEnd = vm.queryInput.selectionEnd;
let ctrlSpace = e.ctrlSpace;
// Skip the calculation when no change is made. This improves performance and prevents async operations (Ctrl+Space) from being canceled when they should not be.
let newAutocompleteState = [useToolingApi, query, selStart, selEnd].join("$");
if (newAutocompleteState == vm.autocompleteState && !ctrlSpace && !e.newDescribe) {
return;
}
vm.autocompleteState = newAutocompleteState;
// Cancel any async operation since its results will no longer be relevant.
if (vm.autocompleteProgress.abort) {
vm.autocompleteProgress.abort();
}
vm.autocompleteClick = ({value, suffix, link}) => {
if (link){
window.open(link, "_blank");
} else {
vm.queryInput.focus();
//handle when selected field is the last one before "FROM" keyword, or if an existing comma is present after selection
let indexFrom = query.toLowerCase().indexOf("from");
if (suffix.trim() == "," && (query.substring(selEnd + 1, indexFrom).trim().length == 0 || query.substring(selEnd).trim().startsWith(",") || query.substring(selEnd).trim().toLowerCase().startsWith("from"))) {
suffix = "";
}
vm.queryInput.setRangeText(value + suffix, selStart, selEnd, "end");
//add query suffix if needed
if (value.startsWith("FIELDS") && !query.toLowerCase().includes("limit")) {
vm.queryInput.value += " LIMIT 200";
}
// Persist the updated query to the current tab
vm.updateCurrentTabQuery(vm.queryInput.value);
vm.queryAutocompleteHandler();
}
};
// Find the token we want to autocomplete. This is the selected text, or the last word before the cursor.
let searchTerm = selStart != selEnd
? query.substring(selStart, selEnd)
: query.substring(0, selStart).match(/[a-zA-Z0-9_]*$/)[0];
selStart = selEnd - searchTerm.length;
function sortRank({value, title}) {
let i = 0;
if (value.toLowerCase() == searchTerm.toLowerCase()) {
return i;
}
i++;
if (title.toLowerCase() == searchTerm.toLowerCase()) {
return i;
}
i++;
if (value.toLowerCase().startsWith(searchTerm.toLowerCase())) {
return i;
}
i++;
if (title.toLowerCase().startsWith(searchTerm.toLowerCase())) {
return i;
}
i++;
if (value.toLowerCase().includes("__" + searchTerm.toLowerCase())) {
return i;
}
i++;
if (value.toLowerCase().includes("_" + searchTerm.toLowerCase())) {
return i;
}
i++;
if (title.toLowerCase().includes(" " + searchTerm.toLowerCase())) {
return i;
}
i++;
return i;
}
function resultsSort(a, b) {
return sortRank(a) - sortRank(b) || a.rank - b.rank || a.value.localeCompare(b.value);
}
// If we are just after the "from" keyword, autocomplete the sobject name
if (query.substring(0, selStart).match(/(^|\s)from\s*$/i)) {
let {globalStatus, globalDescribe} = vm.describeInfo.describeGlobal(useToolingApi);
if (!globalDescribe) {
switch (globalStatus) {
case "loading":
vm.autocompleteResults = {
sobjectName: "",
title: "Loading metadata...",
results: []
};
return;
case "loadfailed":
vm.autocompleteResults = {
sobjectName: "",
title: "Loading metadata failed.",
results: [{value: "Retry", title: "Retry"}]
};
vm.autocompleteClick = vm.autocompleteReload.bind(vm);
return;
default:
vm.autocompleteResults = {
sobjectName: "",
title: "Unexpected error: " + globalStatus,
results: []
};
return;
}
}
vm.autocompleteResults = {
sobjectName: "",
title: "Objects suggestions:",
results: new Enumerable(globalDescribe.sobjects)
.filter(sobjectDescribe => sobjectDescribe.name.toLowerCase().includes(searchTerm.toLowerCase()) || sobjectDescribe.label.toLowerCase().includes(searchTerm.toLowerCase()))
.map(sobjectDescribe => ({value: sobjectDescribe.name, title: sobjectDescribe.label, suffix: " ", rank: 1, autocompleteType: "object", dataType: ""}))
.toArray()
.sort(resultsSort)
};
return;
}
let sobjectName, isAfterFrom;
// Find out what sobject we are querying, by using the word after the "from" keyword.
// Assuming no subqueries in the select clause, we should find the correct sobjectName. There should be only one "from" keyword, and strings (which may contain the word "from") are only allowed after the real "from" keyword.
let fromKeywordMatch = /(^|\s)from\s+([a-z0-9_]*)/i.exec(query);
let findKeywordMatch = /(^|\s)find\s+([a-z0-9_]*)/i.exec(query);
let graphKeywordMatch = /(^|\s)uiapi\s+([a-z0-9_]*)/i.exec(query);
if (fromKeywordMatch) {
sobjectName = fromKeywordMatch[2];
isAfterFrom = selStart > fromKeywordMatch.index + 1;
} else {
// We still want to find the from keyword if the user is typing just before the keyword, and there is no space.
fromKeywordMatch = /^from\s+([a-z0-9_]*)/i.exec(query.substring(selEnd));
if (fromKeywordMatch) {
sobjectName = fromKeywordMatch[1];
isAfterFrom = false;
} else {
let title = findKeywordMatch || graphKeywordMatch ? "" : "\"from\" keyword not found";
vm.autocompleteResults = {
sobjectName: "",
title,
results: []
};
return;
}
}
// If we are in a subquery, try to detect that.
fromKeywordMatch = /\(\s*select.*\sfrom\s+([a-z0-9_]*)/i.exec(query);
if (fromKeywordMatch && fromKeywordMatch.index < selStart) {
let subQuery = query.substring(fromKeywordMatch.index, selStart);
// Try to detect if the subquery ends before the selection
if (subQuery.split(")").length < subQuery.split("(").length) {
sobjectName = fromKeywordMatch[1];
isAfterFrom = selStart > fromKeywordMatch.index + fromKeywordMatch[0].length;
}
}
vm.updateCurrentTabName(sobjectName);
let {sobjectStatus, sobjectDescribe} = vm.describeInfo.describeSobject(useToolingApi, sobjectName);
if (!sobjectDescribe) {
switch (sobjectStatus) {
case "loading":
vm.autocompleteResults = {
sobjectName,
title: "Loading " + sobjectName + " metadata...",
results: []
};
return;
case "loadfailed":
vm.autocompleteResults = {
sobjectName,
title: "Loading " + sobjectName + " metadata failed.",
results: [{value: "Retry", title: "Retry"}]
};
vm.autocompleteClick = vm.autocompleteReload.bind(vm);
return;
case "notfound":
vm.autocompleteResults = {
sobjectName,
title: "Unknown object: " + sobjectName,
results: []
};
return;
default:
vm.autocompleteResults = {
sobjectName,
title: "Unexpected error for object: " + sobjectName + ": " + sobjectStatus,
results: []
};
return;
}
}
/*
* The context of a field is used to support queries on relationship fields.
*
* For example: If the cursor is at the end of the query "select Id from Contact where Account.Owner.Usern"
* then the the searchTerm we want to autocomplete is "Usern", the contextPath is "Account.Owner." and the sobjectName is "Contact"
*
* When autocompleting field values in the query "select Id from Contact where Account.Type = 'Cus"
* then the searchTerm we want to autocomplete is "Cus", the fieldName is "Type", the contextPath is "Account." and the sobjectName is "Contact"
*/
let contextEnd = selStart;
// If we are on the right hand side of a comparison operator, autocomplete field values
let isFieldValue = query.substring(0, selStart).match(/\s*[<>=!]+\s*('?[^'\s]*)$/);
// In clause on picklist field
let isInWithValues = query.substring(0, selStart).match(/\s*in\s*\(\s*(?:(?:'[^']*'\s*,\s*)+|')('?[^'\s]*)$/i);
let inValuesUtilized = "";
if (isInWithValues){
if (isInWithValues[0] && isInWithValues[0].match(/\s*in\s*\(\s*(?:')$/i)){ // extra single quote
selStart -= 1;
isInWithValues[0] = isInWithValues[0].substring(0, isInWithValues[0].length - 1);
}
isFieldValue = isInWithValues;
inValuesUtilized = isInWithValues[0].toLowerCase();
}
let fieldName = null;
if (isFieldValue) {
let fieldEnd = selStart - isFieldValue[0].length;
fieldName = query.substring(0, fieldEnd).match(/[a-zA-Z0-9_]*$/)[0];
contextEnd = fieldEnd - fieldName.length;
selStart -= isFieldValue[1].length;
}
/*
contextSobjectDescribes is a set of describe results for the relevant context sobjects.
Example: "select Subject, Who.Name from Task"
The context sobjects for "Subject" is {"Task"}.
The context sobjects for "Who" is {"Task"}.
The context sobjects for "Name" is {"Contact", "Lead"}.
*/
let contextSobjectDescribes = new Enumerable([sobjectDescribe]);
let contextPath = query.substring(0, contextEnd).match(/[a-zA-Z0-9_.]*$/)[0];
let sobjectStatuses = new Map(); // Keys are error statuses, values are an object name with that status. Only one object name in the value, since we only show one error message.
if (contextPath) {
let contextFields = contextPath.split(".");
contextFields.pop(); // always empty
for (let referenceFieldName of contextFields) {
let newContextSobjectDescribes = new Set();
for (let referencedSobjectName of contextSobjectDescribes
.flatMap(contextSobjectDescribe => contextSobjectDescribe.fields)
.filter(field => field.relationshipName && field.relationshipName.toLowerCase() == referenceFieldName.toLowerCase())
.flatMap(field => field.referenceTo)
) {
let {sobjectStatus, sobjectDescribe} = vm.describeInfo.describeSobject(useToolingApi, referencedSobjectName);
if (sobjectDescribe) {
newContextSobjectDescribes.add(sobjectDescribe);
} else {
sobjectStatuses.set(sobjectStatus, referencedSobjectName);
}
}
contextSobjectDescribes = new Enumerable(newContextSobjectDescribes);
}
}
if (!contextSobjectDescribes.some()) {
if (sobjectStatuses.has("loading")) {
vm.autocompleteResults = {
sobjectName,
title: "Loading " + sobjectStatuses.get("loading") + " metadata...",
results: []
};
return;
}
if (sobjectStatuses.has("loadfailed")) {
vm.autocompleteResults = {
sobjectName,
title: "Loading " + sobjectStatuses.get("loadfailed") + " metadata failed.",
results: [{value: "Retry", title: "Retry"}]
};
vm.autocompleteClick = vm.autocompleteReload.bind(vm);
return;
}
if (sobjectStatuses.has("notfound")) {
vm.autocompleteResults = {
sobjectName,
title: "Unknown object: " + sobjectStatuses.get("notfound"),
results: []
};
return;
}
if (sobjectStatuses.size > 0) {
vm.autocompleteResults = {
sobjectName,
title: "Unexpected error: " + sobjectStatus,
results: []
};
return;
}
vm.autocompleteResults = {
sobjectName,
title: "Unknown field: " + sobjectName + "." + contextPath,
results: []
};
return;
}
if (isFieldValue) {
// Autocomplete field values
let contextValueFields = contextSobjectDescribes
.flatMap(sobjectDescribe => sobjectDescribe.fields
.filter(field => field.name.toLowerCase() == fieldName.toLowerCase())
.map(field => ({sobjectDescribe, field}))
)
.toArray();
if (contextValueFields.length == 0) {
vm.autocompleteResults = {
sobjectName,
title: "Unknown field: " + sobjectDescribe.name + "." + contextPath + fieldName,
results: []
};
return;
}
let fieldNames = contextValueFields.map(contextValueField => contextValueField.sobjectDescribe.name + "." + contextValueField.field.name).join(", ");
if (ctrlSpace) {
// Since this performs a Salesforce API call, we ask the user to opt in by pressing Ctrl+Space
if (contextValueFields.length > 1) {
vm.autocompleteResults = {
sobjectName,
title: "Multiple possible fields: " + fieldNames,
results: []
};
return;
}
let contextValueField = contextValueFields[0];
let queryMethod = useToolingApi ? "tooling/query" : vm.queryAll ? "queryAll" : "query";
let whereClause = contextValueField.field.name + " like '%" + searchTerm.replace(/([\\'])/g, "\\$1") + "%'";
if (contextValueField.sobjectDescribe.name.toLowerCase() === "recordtype"){
let sobject = contextPath.split(".")[0];
sobject = sobject.toLowerCase() === "recordtype" ? vm.autocompleteResults.sobjectName : sobject;
whereClause += vm.autocompleteResults.sobjectName ? " AND SobjectType = '" + sobject + "'" : "";
}
let acQuery = "SELECT " + contextValueField.field.name + " FROM " + contextValueField.sobjectDescribe.name + " WHERE " + whereClause + " GROUP BY " + contextValueField.field.name + " LIMIT 100";
vm.spinFor(sfConn.rest("/services/data/v" + apiVersion + "/" + queryMethod + "/?q=" + encodeURIComponent(acQuery), {progressHandler: vm.autocompleteProgress})
.catch(err => {
if (err.name != "AbortError") {
vm.autocompleteResults = {
sobjectName,
title: "Error: " + err.message,
results: []
};
}
return null;
})
.then(data => {
vm.autocompleteProgress = {};
if (!data) {
return;
}
vm.autocompleteResults = {
sobjectName,
title: fieldNames + " values suggestions:",
results: new Enumerable(data.records)
.map(record => record[contextValueField.field.name])
.filter(value => value)
.map(value => ({value: "'" + value + "'", title: value, suffix: " ", rank: 1, autocompleteType: "fieldValue"}))
.toArray()
.sort(resultsSort)
};
}));
vm.autocompleteResults = {
sobjectName,
title: "Loading " + fieldNames + " values...",
results: []
};
return;
}
let ar = new Enumerable(contextValueFields).flatMap(function* ({field}) {
yield* field.picklistValues.filter(
pickVal => !inValuesUtilized.includes(pickVal.value.toLowerCase())
).map(
pickVal => ({value: "'" + pickVal.value + "'", title: pickVal.label, suffix: " ", rank: 1, autocompleteType: "picklistValue", dataType: ""})
);
if (field.type == "boolean") {
yield {value: "true", title: "true", suffix: " ", rank: 1};
yield {value: "false", title: "false", suffix: " ", rank: 1};
}
if (field.type == "date" || field.type == "datetime") {
let pad = (n, d) => ("000" + n).slice(-d);
let d = new Date();
if (field.type == "date") {
yield {value: pad(d.getFullYear(), 4) + "-" + pad(d.getMonth() + 1, 2) + "-" + pad(d.getDate(), 2), title: "Today", suffix: " ", rank: 1};
}
if (field.type == "datetime") {
yield {
value: pad(d.getFullYear(), 4) + "-" + pad(d.getMonth() + 1, 2) + "-" + pad(d.getDate(), 2) + "T"
+ pad(d.getHours(), 2) + ":" + pad(d.getMinutes(), 2) + ":" + pad(d.getSeconds(), 2) + "." + pad(d.getMilliseconds(), 3)
+ (d.getTimezoneOffset() <= 0 ? "+" : "-") + pad(Math.floor(Math.abs(d.getTimezoneOffset()) / 60), 2)
+ ":" + pad(Math.abs(d.getTimezoneOffset()) % 60, 2),
title: "Now",
suffix: " ",
rank: 1
};
}
// from https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm Winter 24
yield {value: "YESTERDAY", title: "Starts 12:00:00 the day before and continues for 24 hours.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "TODAY", title: "Starts 12:00:00 of the current day and continues for 24 hours.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "TOMORROW", title: "Starts 12:00:00 after the current day and continues for 24 hours.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_WEEK", title: "Starts 12:00:00 on the first day of the week before the most recent first day of the week and continues for seven full days. First day of the week is determined by your locale.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_WEEK", title: "Starts 12:00:00 on the most recent first day of the week before the current day and continues for seven full days. First day of the week is determined by your locale.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_WEEK", title: "Starts 12:00:00 on the most recent first day of the week after the current day and continues for seven full days. First day of the week is determined by your locale.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_MONTH", title: "Starts 12:00:00 on the first day of the month before the current day and continues for all the days of that month.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_MONTH", title: "Starts 12:00:00 on the first day of the month that the current day is in and continues for all the days of that month.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_MONTH", title: "Starts 12:00:00 on the first day of the month after the month that the current day is in and continues for all the days of that month.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_90_DAYS", title: "Starts 12:00:00 of the current day and continues for the last 90 days.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_90_DAYS", title: "Starts 12:00:00 of the current day and continues for the next 90 days.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_DAYS:n", title: "For the number n provided, starts 12:00:00 of the current day and continues for the last n days.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_DAYS:n", title: "For the number n provided, starts 12:00:00 of the current day and continues for the next n days.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_WEEKS:n", title: "For the number n provided, starts 12:00:00 of the first day of the next week and continues for the next n weeks.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_DAYS_AGO:n", title: "Starts at 12:00:00 AM on the day n days before the current day and continues for 24 hours. (The range doesn't include today.)", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_WEEKS:n", title: "For the number n provided, starts 12:00:00 of the last day of the previous week and continues for the last n weeks.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_WEEKS_AGO:n", title: "Starts at 12:00:00 AM on the first day of the month that started n months before the start of the current month and continues for all the days of that month.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_MONTHS:n", title: "For the number n provided, starts 12:00:00 of the first day of the next month and continues for the next n months.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_MONTHS:n", title: "For the number n provided, starts 12:00:00 of the last day of the previous month and continues for the last n months.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_MONTHS_AGO:n", title: "For the number n provided, starts 12:00:00 of the last day of the previous month and continues for the last n months.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_QUARTER", title: "Starts 12:00:00 of the current quarter and continues to the end of the current quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_QUARTER", title: "Starts 12:00:00 of the previous quarter and continues to the end of that quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_QUARTER", title: "Starts 12:00:00 of the next quarter and continues to the end of that quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_QUARTERS:n", title: "Starts 12:00:00 of the next quarter and continues to the end of the nth quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_QUARTERS:n", title: "Starts 12:00:00 of the previous quarter and continues to the end of the previous nth quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_QUARTERS_AGO:n", title: "Starts at 12:00:00 AM on the first day of the calendar quarter n quarters before the current calendar quarter and continues to the end of that quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_YEAR", title: "Starts 12:00:00 on January 1 of the current year and continues through the end of December 31 of the current year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_YEAR", title: "Starts 12:00:00 on January 1 of the previous year and continues through the end of December 31 of that year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_YEAR", title: "Starts 12:00:00 on January 1 of the following year and continues through the end of December 31 of that year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_YEARS:n", title: "Starts 12:00:00 on January 1 of the following year and continues through the end of December 31 of the nth year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_YEARS:n", title: "Starts 12:00:00 on January 1 of the previous year and continues through the end of December 31 of the previous nth year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_YEARS_AGO:n", title: "Starts at 12:00:00 AM on January 1 of the calendar year n years before the current calendar year and continues through the end of December 31 of that year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_FISCAL_QUARTER", title: "Starts 12:00:00 on the first day of the current fiscal quarter and continues through the end of the last day of the fiscal quarter. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_FISCAL_QUARTER", title: "Starts 12:00:00 on the first day of the last fiscal quarter and continues through the end of the last day of that fiscal quarter. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_FISCAL_QUARTER", title: "Starts 12:00:00 on the first day of the next fiscal quarter and continues through the end of the last day of that fiscal quarter. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_FISCAL_QUARTERS:n", title: "Starts 12:00:00 on the first day of the next fiscal quarter and continues through the end of the last day of the nth fiscal quarter. The fiscal year is defined in the company profile under Setup atCompany Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_FISCAL_QUARTERS:n", title: "Starts 12:00:00 on the first day of the last fiscal quarter and continues through the end of the last day of the previous nth fiscal quarter. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_FISCAL_QUARTERS_AGO:n", title: "Starts at 12:00:00 AM on the first day of the fiscal quarter n fiscal quarters before the current fiscal quarter and continues through the end of the last day of that fiscal quarter.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "THIS_FISCAL_YEAR", title: "Starts 12:00:00 on the first day of the current fiscal year and continues through the end of the last day of the fiscal year. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_FISCAL_YEAR", title: "Starts 12:00:00 on the first day of the last fiscal year and continues through the end of the last day of that fiscal year. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_FISCAL_YEAR", title: "Starts 12:00:00 on the first day of the next fiscal year and continues through the end of the last day of that fiscal year. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "NEXT_N_FISCAL_YEARS:n", title: "Starts 12:00:00 on the first day of the next fiscal year and continues through the end of the last day of the nth fiscal year. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "LAST_N_FISCAL_YEARS:n", title: "Starts 12:00:00 on the first day of the last fiscal year and continues through the end of the last day of the previous nth fiscal year. The fiscal year is defined in the company profile under Setup at Company Profile | Fiscal Year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
yield {value: "N_FISCAL_YEARS_AGO:n", title: "Starts at 12:00:00 AM on the first day of the fiscal year n fiscal years ago and continues through the end of the last day of that fiscal year.", suffix: " ", rank: 1, autocompleteType: "variable", dataType: ""};
}
if (field.nillable) {
yield {value: "null", title: "null", suffix: " ", rank: 1, autocompleteType: "null", dataType: ""};
}
})
.filter(res => res.value.toLowerCase().includes(searchTerm.toLowerCase()) || res.title.toLowerCase().includes(searchTerm.toLowerCase()))
.toArray()
.sort(resultsSort);
vm.autocompleteResults = {
sobjectName,
title: fieldNames + (ar.length == 0 ? " values (Press Ctrl+Space to load suggestions):" : " values:"),
results: ar
};
return;
} else {
// Autocomplete field names and functions
if (ctrlSpace) {
let includeFormula = localStorage.getItem("includeFormulaFieldsFromExportAutocomplete") !== "false";
let ar = contextSobjectDescribes
.flatMap(sobjectDescribe => sobjectDescribe.fields)
.filter(field => (field.name.toLowerCase().includes(searchTerm.toLowerCase()) || field.label.toLowerCase().includes(searchTerm.toLowerCase())) && (includeFormula || !field.calculated))
.map(field => contextPath + field.name)
.toArray();
if (ar.length > 0) {
vm.queryInput.focus();
vm.queryInput.setRangeText(ar.join(", ") + (isAfterFrom ? " " : ""), selStart - contextPath.length, selEnd, "end");
vm.updateCurrentTabQuery(vm.queryInput.value);
}
vm.queryAutocompleteHandler();
return;
}
vm.autocompleteResults = {
sobjectName,
title: contextSobjectDescribes.map(sobjectDescribe => sobjectDescribe.name).toArray().join(", ") + " fields suggestions:",
results: contextSobjectDescribes
.flatMap(sobjectDescribe => sobjectDescribe.fields)
.filter(field => field.name.toLowerCase().includes(searchTerm.toLowerCase()) || field.label.toLowerCase().includes(searchTerm.toLowerCase()))
.flatMap(function* (field) {
yield {value: field.name, title: field.label, suffix: isAfterFrom ? " " : ", ", rank: 1, autocompleteType: "fieldName", dataType: field.type};
if (field.relationshipName) {
yield {value: field.relationshipName + ".", title: field.label, suffix: "", rank: 1, autocompleteType: "relationshipName", dataType: ""};
}
})
.concat(
new Enumerable(["FIELDS(ALL)", "FIELDS(STANDARD)", "FIELDS(CUSTOM)", "AVG", "COUNT", "COUNT_DISTINCT", "MIN", "MAX", "SUM", "CALENDAR_MONTH", "CALENDAR_QUARTER", "CALENDAR_YEAR", "DAY_IN_MONTH", "DAY_IN_WEEK", "DAY_IN_YEAR", "DAY_ONLY", "FISCAL_MONTH", "FISCAL_QUARTER", "FISCAL_YEAR", "HOUR_IN_DAY", "WEEK_IN_MONTH", "WEEK_IN_YEAR", "toLabel", "convertTimezone", "convertCurrency", "FORMAT", "GROUPING"])
.filter(fn => fn.toLowerCase().startsWith(searchTerm.toLowerCase()))
.map(fn => {
if (fn.includes(")")) { //Exception to easily support functions with hardcoded parameter options
return {value: fn, title: fn, suffix: "", rank: 2, autocompleteType: "variable", dataType: ""};
} else {
return {value: fn, title: fn + "()", suffix: "(", rank: 2, autocompleteType: "variable", dataType: ""};
}
})
)
.toArray()
.sort(resultsSort)
};
return;
}
}
removeTypo(query) {
// Remove double commas
query = query.replace(/,\s*,/g, ",");
// Remove comma before FROM
query = query.replace(/,\s+FROM\s+/gi, " FROM ");
// Remove trailing comma before FROM
query = query.replace(/,\s*FROM\s+/gi, " FROM ");
// Remove multiple spaces
query = query.replace(/\s+/g, " ");
return query.trim();
}
doExport() {
let vm = this; // eslint-disable-line consistent-this
let exportedData = new RecordTable(vm);
exportedData.isTooling = vm.queryTooling;
exportedData.describeInfo = vm.describeInfo;
exportedData.sfHost = vm.sfHost;
vm.initPerf();
let query = vm.enableQueryTypoFix ? vm.removeTypo(vm.queryInput.value) : vm.queryInput.value;
vm.queryInput.value = query; // Update the input value with the cleaned query
function batchHandler(batch) {
return batch.catch(err => {
if (err.name == "AbortError") {
return {records: [], done: true, totalSize: -1};
}
throw err;
}).then(data => {
let fieldsResponses = {query: "records", queryAll: "records", "tooling/query": "records", search: "searchRecords", graphql: "data"};
let isSoql = fieldsResponses[exportedData.queryMethod] === "records";
if (exportedData.queryMethod === "graphql"){
exportedData.sobject = Object.keys(data.data.uiapi.query)[0];
let dataGraph = data.data.uiapi.query[exportedData.sobject].edges.map(record => {
const firstProperty = Object.keys(record.node)[0];
const transformed = {};
if (firstProperty) {
for (const key in record.node) {
if (Object.prototype.hasOwnProperty.call(record.node, key)) {
transformed[key] = (typeof record.node[key] === "object" && "value" in record.node[key]) ? record.node[key].value : record.node[key];
transformed.attributes = {type: exportedData.sobject};
}
}
}
return transformed;
});
exportedData.addToTable(dataGraph);
} else {
exportedData.addToTable(data[fieldsResponses[exportedData.queryMethod]]);
}
let recs = exportedData.records.length;
let total = exportedData.totalSize;
if (data.totalSize != -1) {
exportedData.totalSize = isSoql ? data.totalSize : recs;
total = exportedData.totalSize;
}
if (!data.done && isSoql) {
let pr = batchHandler(sfConn.rest(data.nextRecordsUrl, {progressHandler: vm.exportProgress}));
vm.isWorking = true;
vm.exportStatus = `Exporting... Completed ${recs} of ${total} record${s(total)}.`;
vm.exportError = null;
vm.exportedData = exportedData;
vm.markPerf();
vm.updatedExportedData();
vm.didUpdate();
return pr;
}
vm.queryHistory.add({query, useToolingApi: exportedData.isTooling});
if (recs == 0) {
vm.isWorking = false;
vm.exportStatus = "No data exported." + (total > 0 ? ` ${total} record${s(total)}.` : "");
vm.exportError = null;
vm.exportedData = exportedData;
vm.markPerf();
vm.updatedExportedData();
return null;
} else {
vm.updateCurrentTabName(exportedData.records[0].attributes.type);
}
vm.isWorking = false;
vm.exportStatus = `Exported ${recs}${recs !== total ? (" of " + total) : ""} record${s(recs)}`;
vm.exportError = null;
vm.exportedData = exportedData;
vm.markPerf();
vm.updatedExportedData();
// Store the results in the current tab
if (vm.queryTabs[vm.activeTabIndex]) {
vm.queryTabs[vm.activeTabIndex].results = exportedData;
vm.saveQueryTabs();
}
return null;
}, err => {
if (err.name != "SalesforceRestError") {
throw err; // not a SalesforceRestError
}
let recs = exportedData.records.length;
let total = exportedData.totalSize;
if (total != -1) {
// We already got some data. Show it, and indicate that not all data was exported
vm.isWorking = false;
vm.exportStatus = `Exported ${recs} of ${total} record${s(total)}. Stopped by error.`;
vm.exportError = null;
vm.exportedData = exportedData;
vm.updatedExportedData();
vm.markPerf();
return null;
}
vm.isWorking = false;
vm.exportStatus = "Error";
vm.exportError = err.message;
vm.exportedData = null;
vm.updatedExportedData();
return null;
});
}
this.setQueryMethod(exportedData, query, vm);
vm.spinFor(batchHandler(sfConn.rest(exportedData.endpoint, exportedData.params))
.catch(error => {
console.error(error);
vm.isWorking = false;
vm.exportStatus = "Error";
vm.exportError = "UNEXPECTED EXCEPTION:" + error;
vm.exportedData = null;
vm.markPerf();
vm.updatedExportedData();
}));
vm.setResultsFilter("");
vm.isWorking = true;
vm.exportStatus = "Exporting...";
vm.exportError = null;
vm.exportedData = exportedData;
vm.updatedExportedData();
}
async generateSoql() {
this.isWorking = true;
let promptTemplateName = localStorage.getItem(this.sfHost + "_exportAgentForcePrompt");
const promptTemplate = new PromptTemplate(promptTemplateName ? promptTemplateName : Constants.PromptTemplateSOQL);
this.spinFor(
promptTemplate.generate({
Description: this.soqlPrompt.value
}).then(result => {
if (result.result){
// Extract SOQL from the result
const soqlMatch = result.result.match(/<soql>(.*?)<\/soql>/);
const extractedSoql = soqlMatch ? soqlMatch[1] : result.result;
this.updateCurrentTabQuery(extractedSoql);
this.queryAutocompleteHandler();
if (this.queryInput) {
this.queryInput.value = extractedSoql;
}
this.saveQueryTabs();
this.isWorking = false;
this.didUpdate();
} else {
throw new Error(result.error);
}
}).catch(error => {
console.error(error);
this.isWorking = false;
this.exportStatus = "Error";
this.exportError = "Failed to generate SOQL: " + error;
this.didUpdate();
})
);
}
stopExport() {
this.exportProgress.abort();
}
doQueryPlan(){