busbar-sf-api 0.0.3

Salesforce API client library for Rust
Documentation
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
//! Bulk API 2.0 integration tests using SF_AUTH_URL.

use super::common::get_credentials;
use busbar_sf_auth::Credentials;
use busbar_sf_bulk::{BulkApiClient, BulkOperation};
use busbar_sf_rest::{QueryBuilder, SalesforceRestClient};

// ============================================================================
// Bulk API 2.0 Tests
// ============================================================================

#[tokio::test]
async fn test_bulk_insert_lifecycle() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let csv_data = format!(
        "Name,Industry\nBulk Test 1 {},Technology\nBulk Test 2 {},Manufacturing",
        chrono::Utc::now().timestamp_millis(),
        chrono::Utc::now().timestamp_millis()
    );

    let result = client
        .execute_ingest("Account", BulkOperation::Insert, &csv_data, None)
        .await
        .expect("Bulk insert should succeed");

    assert_eq!(
        result.job.number_records_processed, 2,
        "Should process 2 records"
    );
    assert_eq!(
        result.job.number_records_failed, 0,
        "Should have 0 failures"
    );

    if let Some(success_results) = result.successful_results {
        let lines: Vec<&str> = success_results.lines().collect();
        if lines.len() > 1 {
            for line in &lines[1..] {
                if let Some(id) = line.split(',').next() {
                    if id.starts_with("001") {
                        let rest_client =
                            SalesforceRestClient::new(creds.instance_url(), creds.access_token())
                                .expect("Failed to create REST client");
                        let _ = rest_client.delete("Account", id).await;
                    }
                }
            }
        }
    }
}

#[tokio::test]
async fn test_bulk_query_operation() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name", "Industry"])
        .limit(100);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    assert!(
        result.job.number_records_processed >= 0,
        "Should process records"
    );

    if let Some(csv_results) = result.results {
        let lines: Vec<&str> = csv_results.lines().collect();
        assert!(!lines.is_empty(), "Should have at least header line");
        if let Some(header) = lines.first() {
            assert!(
                header.to_lowercase().contains("id"),
                "Header should contain Id"
            );
            assert!(
                header.to_lowercase().contains("name"),
                "Header should contain Name"
            );
        }
    }
}

#[tokio::test]
async fn test_bulk_update_operation() {
    let creds = get_credentials().await;

    let rest_client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_name = format!("Bulk Update Test {}", chrono::Utc::now().timestamp_millis());
    let account_data = serde_json::json!({
        "Name": test_name
    });

    let account_id = rest_client
        .create("Account", &account_data)
        .await
        .expect("Create should succeed");

    let bulk_client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let csv_data = format!("Id,Description\n{},Updated via Bulk API", account_id);

    let result = bulk_client
        .execute_ingest("Account", BulkOperation::Update, &csv_data, None)
        .await
        .expect("Bulk update should succeed");

    assert_eq!(
        result.job.number_records_processed, 1,
        "Should process 1 record"
    );
    assert_eq!(
        result.job.number_records_failed, 0,
        "Should have 0 failures"
    );

    let updated: serde_json::Value = rest_client
        .get("Account", &account_id, Some(&["Id", "Description"]))
        .await
        .expect("Get should succeed");

    assert_eq!(
        updated.get("Description").and_then(|v| v.as_str()),
        Some("Updated via Bulk API")
    );

    let _ = rest_client.delete("Account", &account_id).await;
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_bulk_error_invalid_sobject_ingest() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let csv_data = "Name\nBad";

    let result = client
        .execute_ingest("NoSuchObject__c", BulkOperation::Insert, csv_data, None)
        .await;

    assert!(result.is_err(), "Ingest with invalid SObject should fail");
}

#[tokio::test]
async fn test_bulk_error_invalid_query_field() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "DefinitelyNotAField__c"])
        .limit(10);

    let result = client.execute_query(query_builder).await;

    assert!(result.is_err(), "Bulk query with invalid field should fail");
}

#[tokio::test]
async fn test_bulk_error_invalid_job_id() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let result = client.get_ingest_job("750000000000000AAA").await;

    assert!(result.is_err(), "Invalid job ID should fail");
}

// ============================================================================
// Parallel Query Results Tests (API v62.0+)
// ============================================================================

#[tokio::test]
async fn test_parallel_query_results_basic() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    // Create a query job first
    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name", "Industry"])
        .limit(50);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    // Test get_parallel_query_results (may not be available in all orgs/API versions)
    match client
        .get_parallel_query_results(&result.job.id, None)
        .await
    {
        Ok(batch) => {
            // Should have at least one result URL if there are results
            if result.job.number_records_processed > 0 {
                assert!(
                    !batch.result_url.is_empty(),
                    "Should have at least one result URL when records exist"
                );

                // Each URL should be a valid string
                for url in &batch.result_url {
                    assert!(!url.is_empty(), "Result URL should not be empty");
                    assert!(
                        url.contains("/results/") || url.contains("/parallelResults"),
                        "URL should be a valid results endpoint"
                    );
                }
            }
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND"),
                "Expected NOT_FOUND error, got: {msg}"
            );
        }
    }
}

#[tokio::test]
async fn test_parallel_query_results_with_max_records() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    // Create a query job
    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name"])
        .limit(100);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    // Test with maxRecords parameter (may not be available in all orgs/API versions)
    match client
        .get_parallel_query_results(&result.job.id, Some(3))
        .await
    {
        Ok(batch) => {
            // Should have at most 3 result URLs
            if result.job.number_records_processed > 0 {
                assert!(
                    batch.result_url.len() <= 3,
                    "Should have at most 3 result URLs when maxRecords=3"
                );
            }
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND"),
                "Expected NOT_FOUND error, got: {msg}"
            );
        }
    }
}

#[tokio::test]
async fn test_get_all_query_results_parallel() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    // Create a query job with a reasonable number of records
    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name", "Industry"])
        .limit(100);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    // Test high-level parallel download (may not be available in all orgs/API versions)
    match client.get_all_query_results_parallel(&result.job.id).await {
        Ok(csv_data) => {
            // Validate CSV structure
            let lines: Vec<&str> = csv_data.lines().collect();
            assert!(!lines.is_empty(), "Should have at least header line");

            if result.job.number_records_processed > 0 {
                assert!(lines.len() > 1, "Should have data rows");

                // Check header
                let header = lines[0];
                assert!(
                    header.to_lowercase().contains("id"),
                    "Header should contain Id"
                );
                assert!(
                    header.to_lowercase().contains("name"),
                    "Header should contain Name"
                );

                // Verify we got the right number of data rows
                let data_rows = lines.len() - 1; // Subtract header
                assert!(
                    data_rows > 0 && data_rows as i64 <= result.job.number_records_processed,
                    "Should have correct number of data rows"
                );
            }
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND"),
                "Expected NOT_FOUND error, got: {msg}"
            );
        }
    }
}

#[tokio::test]
async fn test_parallel_vs_serial_results_consistency() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    // Create a query job
    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name"])
        .limit(50);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    assert!(
        result.job.number_records_processed > 0,
        "Should have Account records (created by setup-scratch-org). \
         Run: cargo run --bin setup-scratch-org"
    );

    // Get results using serial method
    let serial_results = client
        .get_all_query_results(&result.job.id)
        .await
        .expect("Serial results should succeed");

    // Get results using parallel method (may not be available in all orgs/API versions)
    match client.get_all_query_results_parallel(&result.job.id).await {
        Ok(parallel_results) => {
            // Both should return CSV data with same structure
            let serial_lines: Vec<&str> = serial_results.lines().collect();
            let parallel_lines: Vec<&str> = parallel_results.lines().collect();

            assert_eq!(
                serial_lines.len(),
                parallel_lines.len(),
                "Both methods should return same number of lines"
            );

            // Headers should match
            assert_eq!(serial_lines[0], parallel_lines[0], "Headers should match");

            // Data row count should match
            let serial_data_rows = serial_lines.len() - 1;
            let parallel_data_rows = parallel_lines.len() - 1;
            assert_eq!(
                serial_data_rows, parallel_data_rows,
                "Both methods should return same number of data rows"
            );
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND"),
                "Expected NOT_FOUND error, got: {msg}"
            );
        }
    }
}

#[tokio::test]
async fn test_parallel_query_results_empty_job() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    // Create a query that returns no results
    let query_builder: QueryBuilder<serde_json::Value> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name"])
        .where_eq("Id", "000000000000000AAA")
        .expect("Where clause should succeed") // Invalid ID that won't match
        .limit(10);

    let result = client
        .execute_query(query_builder)
        .await
        .expect("Bulk query should succeed");

    // Test parallel results on empty job (may not be available in all orgs/API versions)
    match client
        .get_parallel_query_results(&result.job.id, None)
        .await
    {
        Ok(_batch) => {
            // Should handle empty results gracefully
            match client.get_all_query_results_parallel(&result.job.id).await {
                Ok(csv_data) => {
                    // Should have at least header
                    let lines: Vec<&str> = csv_data.lines().collect();
                    assert!(!lines.is_empty(), "Should have at least header line");
                }
                Err(e) => {
                    let msg = e.to_string();
                    assert!(
                        msg.contains("NOT_FOUND"),
                        "Expected NOT_FOUND error, got: {msg}"
                    );
                }
            }
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND"),
                "Expected NOT_FOUND error, got: {msg}"
            );
        }
    }
}

// ============================================================================
// MetadataComponentDependency Tests (requires dependencies feature)
// ============================================================================

/// MetadataComponentDependency is not available via standard Bulk API 2.0
/// (it requires the Tooling API). These tests verify the client correctly
/// handles Salesforce's error response for unsupported sObject types.
#[cfg(feature = "dependencies")]
#[tokio::test]
async fn test_bulk_query_metadata_component_dependencies() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let query_builder: QueryBuilder<serde_json::Value> =
        QueryBuilder::new("MetadataComponentDependency")
            .expect("QueryBuilder creation should succeed")
            .select(&[
                "MetadataComponentId",
                "MetadataComponentName",
                "MetadataComponentType",
                "RefMetadataComponentId",
                "RefMetadataComponentName",
                "RefMetadataComponentType",
            ])
            .limit(1000);

    let result = client.execute_query(query_builder).await;
    assert!(
        result.is_err(),
        "MetadataComponentDependency should not be queryable via standard Bulk API"
    );
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("not supported") || err_msg.contains("API_ERROR"),
        "Error should indicate unsupported sObject type, got: {err_msg}"
    );
}

#[cfg(feature = "dependencies")]
#[tokio::test]
async fn test_bulk_query_metadata_component_dependencies_with_filter() {
    let creds = get_credentials().await;
    let client = BulkApiClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create Bulk client");

    let query_builder: QueryBuilder<serde_json::Value> =
        QueryBuilder::new("MetadataComponentDependency")
            .expect("QueryBuilder creation should succeed")
            .select(&[
                "MetadataComponentId",
                "MetadataComponentName",
                "MetadataComponentType",
            ])
            .where_eq("MetadataComponentType", "ApexClass")
            .expect("where_eq should succeed")
            .limit(100);

    let result = client.execute_query(query_builder).await;
    assert!(
        result.is_err(),
        "Filtered MetadataComponentDependency should not be queryable via standard Bulk API"
    );
}

#[cfg(feature = "dependencies")]
#[tokio::test]
async fn test_bulk_metadata_component_dependency_type_deserialization() {
    // Verify the MetadataComponentDependency type itself deserializes correctly
    // from a sample CSV-like response (unit-level verification since Bulk API
    // doesn't support this entity type).
    let sample = busbar_sf_client::MetadataComponentDependency {
        metadata_component_id: Some("0Adxx0000000001".to_string()),
        metadata_component_name: Some("MyClass".to_string()),
        metadata_component_namespace: None,
        metadata_component_type: Some("ApexClass".to_string()),
        ref_metadata_component_id: Some("0Adxx0000000002".to_string()),
        ref_metadata_component_name: Some("OtherClass".to_string()),
        ref_metadata_component_namespace: None,
        ref_metadata_component_type: Some("ApexClass".to_string()),
    };
    assert_eq!(
        sample.metadata_component_type,
        Some("ApexClass".to_string())
    );
    assert_eq!(
        sample.ref_metadata_component_name,
        Some("OtherClass".to_string())
    );
}