force 0.2.0

Production-ready Salesforce Platform API client with REST and Bulk API 2.0 support
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
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
//! Salesforce SOQL query result types.
//!
//! This module provides types for working with Salesforce query results,
//! including pagination support and cursor-based iteration.

use serde::{Deserialize, Serialize};

/// Result of a Salesforce SOQL query.
///
/// Query results may be paginated. Use the `done` flag to check if all
/// results have been retrieved, and `next_records_url` to fetch the next page.
///
/// # Examples
///
/// ```
/// use force::types::{QueryResult, DynamicSObject};
/// use serde_json::json;
///
/// let json = json!({
///     "totalSize": 2,
///     "done": true,
///     "records": [
///         {
///             "attributes": {
///                 "type": "Account",
///                 "url": "/services/data/v60.0/sobjects/Account/001"
///             },
///             "Name": "Acme"
///         }
///     ]
///});
///
/// let result: QueryResult<DynamicSObject> = serde_json::from_value(json).unwrap();
/// assert_eq!(result.total_size, 2);
/// assert!(result.is_done());
/// assert_eq!(result.records.len(), 1);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryResult<T> {
    /// Total number of records matching the query.
    ///
    /// This is the total count across all pages, not just the current page.
    pub total_size: usize,

    /// Whether all records have been retrieved.
    ///
    /// If false, use `next_records_url` to fetch the next page.
    pub done: bool,

    /// Records in the current page.
    pub records: Vec<T>,

    /// URL to fetch the next page of results (if `done` is false).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_records_url: Option<String>,
}

impl<T> QueryResult<T> {
    /// Creates a new query result.
    #[must_use]
    pub const fn new(total_size: usize, done: bool, records: Vec<T>) -> Self {
        Self {
            total_size,
            done,
            records,
            next_records_url: None,
        }
    }

    /// Creates a new paginated query result with a next page URL.
    #[must_use]
    pub fn with_next_page(total_size: usize, records: Vec<T>, next_records_url: String) -> Self {
        Self {
            total_size,
            done: false,
            records,
            next_records_url: Some(next_records_url),
        }
    }

    /// Returns true if all results have been retrieved.
    #[must_use]
    pub const fn is_done(&self) -> bool {
        self.done
    }

    /// Returns true if there are more results to fetch.
    #[must_use]
    pub const fn has_more(&self) -> bool {
        !self.done && self.next_records_url.is_some()
    }

    /// Returns the number of records in this page.
    #[must_use]
    pub fn len(&self) -> usize {
        self.records.len()
    }

    /// Returns true if this page contains no records.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    /// Returns an iterator over the records in this page.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.records.iter()
    }

    /// Consumes the result and returns an iterator over the records.
    ///
    /// Prefer using `for record in result { ... }` via [`IntoIterator`] instead
    /// of calling this directly.
    pub fn into_records(self) -> std::vec::IntoIter<T> {
        self.records.into_iter()
    }

    /// Maps the records to a new type.
    pub fn map<U, F>(self, f: F) -> QueryResult<U>
    where
        F: FnMut(T) -> U,
    {
        QueryResult {
            total_size: self.total_size,
            done: self.done,
            records: self.records.into_iter().map(f).collect(),
            next_records_url: self.next_records_url,
        }
    }

    /// Attempts to map the records to a new type.
    ///
    /// # Errors
    ///
    /// Returns an error if any mapping fails.
    pub fn try_map<U, E, F>(self, f: F) -> Result<QueryResult<U>, E>
    where
        F: FnMut(T) -> Result<U, E>,
    {
        let records: Result<Vec<U>, E> = self.records.into_iter().map(f).collect();
        Ok(QueryResult {
            total_size: self.total_size,
            done: self.done,
            records: records?,
            next_records_url: self.next_records_url,
        })
    }
}

impl<T> Default for QueryResult<T> {
    fn default() -> Self {
        Self::new(0, true, Vec::new())
    }
}

impl<T> IntoIterator for QueryResult<T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.records.into_iter()
    }
}

/// A query locator for paginated query results.
///
/// Used to track pagination state across multiple query calls.
///
/// # Examples
///
/// ```
/// use force::types::QueryLocator;
///
/// let locator = QueryLocator::from_url("/services/data/v60.0/query/01gxx0000000001-2000");
/// assert!(!locator.is_initial());
/// assert_eq!(locator.url(), "/services/data/v60.0/query/01gxx0000000001-2000");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct QueryLocator(String);

impl QueryLocator {
    /// Creates a new query locator from a URL.
    #[must_use]
    pub fn from_url(url: impl Into<String>) -> Self {
        Self(url.into())
    }

    /// Returns the URL for fetching the next page.
    #[must_use]
    pub fn url(&self) -> &str {
        &self.0
    }

    /// Returns true if this is the initial query (not a continuation).
    #[must_use]
    pub fn is_initial(&self) -> bool {
        !self.0.contains("/query/")
    }

    /// Returns true if this is a continuation query.
    #[must_use]
    pub fn is_continuation(&self) -> bool {
        self.0.contains("/query/")
    }
}

impl From<String> for QueryLocator {
    fn from(url: String) -> Self {
        Self::from_url(url)
    }
}

impl From<&str> for QueryLocator {
    fn from(url: &str) -> Self {
        Self::from_url(url)
    }
}

impl AsRef<str> for QueryLocator {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Iterator for paginated query results.
///
/// This provides a way to iterate over all pages of a query result.
/// Note: This is a synchronous iterator over already-fetched pages.
/// For async pagination, use the async client methods.
///
/// # Examples
///
/// ```
/// use force::types::{QueryResult, QueryIterator};
///
/// let page1: QueryResult<i32> = QueryResult::with_next_page(
///     10,
///     vec![1, 2, 3],
///     "/next".to_string()
/// );
///
/// let iter = QueryIterator::new(vec![page1]);
/// assert_eq!(iter.count(), 3);
/// ```
#[derive(Debug)]
pub struct QueryIterator<T> {
    /// Iterator over the pages of query results.
    pages: std::vec::IntoIter<QueryResult<T>>,
    /// Iterator over the records of the current page.
    current_page: std::vec::IntoIter<T>,
    /// Pre-calculated total page count.
    page_count: usize,
    /// Pre-calculated total record count.
    total_count: usize,
    /// Number of records yielded so far.
    yielded: usize,
}

impl<T> QueryIterator<T> {
    /// Creates a new iterator from a list of query result pages.
    #[must_use]
    pub fn new(pages: Vec<QueryResult<T>>) -> Self {
        let page_count = pages.len();
        let total_count = pages.iter().map(|p| p.records.len()).sum();

        Self {
            pages: pages.into_iter(),
            current_page: Vec::new().into_iter(),
            page_count,
            total_count,
            yielded: 0,
        }
    }

    /// Returns the total number of pages.
    #[must_use]
    pub fn page_count(&self) -> usize {
        self.page_count
    }

    /// Returns the total number of records across all pages.
    #[must_use]
    pub fn total_count(&self) -> usize {
        self.total_count
    }
}

impl<T> Iterator for QueryIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // 1. Try to yield from current page
            if let Some(record) = self.current_page.next() {
                self.yielded += 1;
                return Some(record);
            }

            // 2. If current page is exhausted, move to next page
            let next_page_result = self.pages.next()?;
            self.current_page = next_page_result.records.into_iter();
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.total_count.saturating_sub(self.yielded);
        (remaining, Some(remaining))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::Must;
    use serde_json::json;

    // RED PHASE - Write failing tests first

    #[test]
    fn test_query_result_new() {
        let result: QueryResult<i32> = QueryResult::new(5, true, vec![1, 2, 3]);

        assert_eq!(result.total_size, 5);
        assert!(result.is_done());
        assert_eq!(result.len(), 3);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_query_result_with_next_page() {
        let result: QueryResult<i32> =
            QueryResult::with_next_page(10, vec![1, 2, 3], "/next".to_string());

        assert_eq!(result.total_size, 10);
        assert!(!result.is_done());
        assert!(result.has_more());
        assert_eq!(result.next_records_url, Some("/next".to_string()));
    }

    #[test]
    fn test_query_result_empty() {
        let result: QueryResult<i32> = QueryResult::default();

        assert_eq!(result.total_size, 0);
        assert!(result.is_done());
        assert!(result.is_empty());
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_query_result_iter() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        let sum: i32 = result.iter().sum();
        assert_eq!(sum, 6);
    }

    #[test]
    fn test_query_result_into_iter() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        // IntoIterator trait: use `for` loop style
        let collected: Vec<i32> = result.into_iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }

    #[test]
    fn test_query_result_for_loop() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);
        let mut sum = 0;
        for record in result {
            sum += record;
        }
        assert_eq!(sum, 6);
    }

    #[test]
    fn test_query_result_map() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        let mapped: QueryResult<i32> = result.map(|x| x * 2);
        assert_eq!(mapped.records, vec![2, 4, 6]);
        assert_eq!(mapped.total_size, 3);
    }

    #[test]
    fn test_query_result_try_map_success() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        let mapped: Result<QueryResult<i32>, ()> = result.try_map(|x| Ok(x * 2));
        assert!(mapped.is_ok());
        assert_eq!(mapped.must().records, vec![2, 4, 6]);
    }

    #[test]
    fn test_query_result_try_map_failure() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        let mapped: Result<QueryResult<i32>, &str> =
            result.try_map(|x| if x == 2 { Err("error") } else { Ok(x) });
        assert!(mapped.is_err());
    }

    #[test]
    fn test_query_result_serialize() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);

        let json = serde_json::to_string(&result).must();
        assert!(json.contains("\"totalSize\":3"));
        assert!(json.contains("\"done\":true"));
        assert!(json.contains("\"records\":[1,2,3]"));
    }

    #[test]
    fn test_query_result_deserialize() {
        let json = json!({
            "totalSize": 5,
            "done": true,
            "records": [1, 2, 3]
        });

        let result: QueryResult<i32> = serde_json::from_value(json).must();
        assert_eq!(result.total_size, 5);
        assert!(result.is_done());
        assert_eq!(result.records, vec![1, 2, 3]);
    }

    #[test]
    fn test_query_result_with_next_url_serialize() {
        let result: QueryResult<i32> =
            QueryResult::with_next_page(10, vec![1, 2], "/next".to_string());

        let json = serde_json::to_string(&result).must();
        assert!(json.contains("\"nextRecordsUrl\":\"/next\""));
        assert!(json.contains("\"done\":false"));
    }

    #[test]
    fn test_query_locator_from_url() {
        let locator = QueryLocator::from_url("/services/data/v60.0/query/01gxx-2000");

        assert_eq!(locator.url(), "/services/data/v60.0/query/01gxx-2000");
        assert!(locator.is_continuation());
        assert!(!locator.is_initial());
    }

    #[test]
    fn test_query_locator_from_string() {
        let locator: QueryLocator = "/next".to_string().into();
        assert_eq!(locator.url(), "/next");
    }

    #[test]
    fn test_query_locator_from_str() {
        let locator: QueryLocator = "/next".into();
        assert_eq!(locator.url(), "/next");
    }

    #[test]
    fn test_query_locator_as_ref() {
        let locator = QueryLocator::from_url("/next");
        let s: &str = locator.as_ref();
        assert_eq!(s, "/next");
    }

    #[test]
    fn test_query_locator_serialize() {
        let locator = QueryLocator::from_url("/next");

        let json = serde_json::to_string(&locator).must();
        assert!(json.contains("\"/next\""));
    }

    #[test]
    fn test_query_locator_deserialize() {
        let json = "\"/services/data/v60.0/query/01gxx\"";

        let locator: QueryLocator = serde_json::from_str(json).must();
        assert!(locator.is_continuation());
    }

    #[test]
    fn test_query_iterator_new() {
        let page1: QueryResult<i32> = QueryResult::new(3, true, vec![1, 2, 3]);
        let iter = QueryIterator::new(vec![page1]);

        assert_eq!(iter.page_count(), 1);
        assert_eq!(iter.total_count(), 3);
    }

    #[test]
    fn test_query_iterator_iterates_records_in_order() {
        let page1: QueryResult<i32> = QueryResult::with_next_page(5, vec![1, 2, 3], "/next".into());
        let page2: QueryResult<i32> = QueryResult::new(5, true, vec![4, 5]);

        let iter = QueryIterator::new(vec![page1, page2]);
        let collected: Vec<i32> = iter.collect();

        assert_eq!(collected, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_query_iterator_multiple_pages() {
        let page1: QueryResult<i32> = QueryResult::new(5, false, vec![1, 2]);
        let page2: QueryResult<i32> = QueryResult::new(5, true, vec![3, 4, 5]);

        let iter = QueryIterator::new(vec![page1, page2]);

        assert_eq!(iter.page_count(), 2);
        assert_eq!(iter.total_count(), 5);
    }

    #[test]
    fn test_query_iterator_empty() {
        let iter: QueryIterator<i32> = QueryIterator::new(vec![]);

        assert_eq!(iter.page_count(), 0);
        assert_eq!(iter.total_count(), 0);
    }

    #[test]
    fn test_query_result_invalid_state_done_with_next_url() {
        // Demonstrate that the type allows invalid state: done=true but next_records_url is Some
        let result: QueryResult<i32> = QueryResult {
            total_size: 10,
            done: true,
            records: vec![],
            next_records_url: Some("/next".to_string()),
        };

        // API should prioritize 'done'
        assert!(result.is_done());
        assert!(!result.has_more());
        // Even though we have a URL, we shouldn't use it
        assert!(result.next_records_url.is_some());
    }

    #[test]
    fn test_query_result_invalid_state_not_done_without_next_url() {
        // Demonstrate dangerous state: done=false but next_records_url is None
        let result: QueryResult<i32> = QueryResult {
            total_size: 10,
            done: false, // implies has_more
            records: vec![],
            next_records_url: None,
        };

        assert!(!result.is_done());
        assert!(!result.has_more()); // Returns false now to prevent unwrap panics!
        assert!(result.next_records_url.is_none()); // No URL to fetch
    }

    // Property-based tests using proptest
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        // Strategy for generating QueryResult
        fn arbitrary_query_result() -> impl Strategy<Value = QueryResult<i32>> {
            (
                any::<usize>(),
                any::<bool>(),
                prop::collection::vec(any::<i32>(), 0..100),
                prop::option::of("[a-z/]{1,50}"),
            )
                .prop_map(|(total_size, done, records, next_records_url)| {
                    QueryResult {
                        total_size,
                        done,
                        records,
                        next_records_url,
                    }
                })
        }

        proptest! {
            // Property 1: has_more() logic verifies both done is false AND next url exists
            #[test]
            fn prop_has_more_requires_next_url_and_not_done(result in arbitrary_query_result()) {
                prop_assert_eq!(result.has_more(), !result.is_done() && result.next_records_url.is_some());
            }

            // Property 2: If done is true, has_more() is false (regardless of next_records_url)
            #[test]
            fn prop_done_implies_not_has_more(result in arbitrary_query_result()) {
                if result.is_done() {
                    prop_assert!(!result.has_more());
                    // Note: We deliberately do NOT assert result.next_records_url.is_none()
                    // because the type system allows done=true with a next_url (invalid state),
                    // and we want to ensure the API behaves safely (returning false) even then.
                }
            }

            // Property 3: len() matches records.len()
            #[test]
            fn prop_len_matches_records(result in arbitrary_query_result()) {
                prop_assert_eq!(result.len(), result.records.len());
            }

            // Property 4: is_empty() consistent with len()
            #[test]
            fn prop_is_empty_consistent(result in arbitrary_query_result()) {
                prop_assert_eq!(result.is_empty(), result.records.is_empty());
                prop_assert_eq!(result.is_empty(), result.is_empty());
            }

            // Property 5: map preserves metadata
            #[test]
            fn prop_map_preserves_metadata(result in arbitrary_query_result()) {
                let original_total = result.total_size;
                let original_done = result.done;
                let original_next = result.next_records_url.clone();

                // Use saturating_add to avoid overflow
                let mapped = result.map(|x| x.saturating_add(1));

                prop_assert_eq!(mapped.total_size, original_total);
                prop_assert_eq!(mapped.done, original_done);
                prop_assert_eq!(mapped.next_records_url, original_next);
            }

            // Property 6: map transforms records correctly
            #[test]
            fn prop_map_transforms_records(result in arbitrary_query_result()) {
                let expected: Vec<i32> = result.records.iter().map(|x| x.saturating_add(1)).collect();
                let mapped = result.map(|x| x.saturating_add(1));

                prop_assert_eq!(mapped.records, expected);
            }

            // Property 7: Default is empty and done
            #[test]
            fn prop_default_is_empty_and_done(_x in 0..1) {
                let default: QueryResult<i32> = QueryResult::default();

                prop_assert!(default.is_done());
                prop_assert!(default.is_empty());
                prop_assert_eq!(default.total_size, 0);
                prop_assert_eq!(default.next_records_url, None);
            }

            // Property 8: with_next_page always sets done=false
            #[test]
            fn prop_with_next_page_not_done(
                total in any::<usize>(),
                records in prop::collection::vec(any::<i32>(), 0..50),
                url in "[a-z/]{1,50}"
            ) {
                let result = QueryResult::with_next_page(total, records, url.clone());

                prop_assert!(!result.is_done());
                prop_assert!(result.has_more());
                prop_assert_eq!(result.next_records_url, Some(url));
            }
        }
    }

    #[test]
    fn test_query_result_into_records() {
        let result: QueryResult<i32> = QueryResult::new(3, true, vec![10, 20, 30]);
        let records: Vec<i32> = result.into_records().collect();
        assert_eq!(records, vec![10, 20, 30]);
    }

    #[test]
    fn test_query_iterator_size_hint() {
        let page1: QueryResult<i32> = QueryResult::with_next_page(5, vec![1, 2, 3], "/next".into());
        let page2: QueryResult<i32> = QueryResult::new(5, true, vec![4, 5]);

        let mut iter = QueryIterator::new(vec![page1, page2]);
        assert_eq!(iter.size_hint(), (5, Some(5)));

        let _ = iter.next(); // yields 1
        assert_eq!(iter.size_hint(), (4, Some(4)));

        let _ = iter.next(); // yields 2
        let _ = iter.next(); // yields 3
        assert_eq!(iter.size_hint(), (2, Some(2)));

        let _ = iter.next(); // yields 4
        let _ = iter.next(); // yields 5
        assert_eq!(iter.size_hint(), (0, Some(0)));

        assert!(iter.next().is_none());
    }

    #[test]
    fn test_query_iterator_empty_middle_page() {
        let page1: QueryResult<i32> = QueryResult::with_next_page(5, vec![1, 2], "/next1".into());
        let page2: QueryResult<i32> = QueryResult::with_next_page(5, vec![], "/next2".into());
        let page3: QueryResult<i32> = QueryResult::new(5, true, vec![4, 5]);

        let iter = QueryIterator::new(vec![page1, page2, page3]);
        let collected: Vec<i32> = iter.collect();

        assert_eq!(collected, vec![1, 2, 4, 5]);
    }
}