paginator-rs 0.2.2

Pagination trait for Rust collections
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
use paginator_utils::{
    Cursor, CursorDirection, CursorValue, Filter, FilterOperator, FilterValue,
    IntoPaginationParams, PaginationParams, SearchParams, SortDirection,
};
use std::marker::PhantomData;

//
// ========================
//   PAGINATOR ROOT BUILDER
// ========================
//
pub struct Paginator<State = Ready> {
    params: PaginationParams,
    _state: PhantomData<State>,
}

/// Marker state
pub struct Ready;

impl Default for Paginator {
    fn default() -> Self {
        Self::new()
    }
}

impl Paginator {
    pub fn new() -> Self {
        Self {
            params: PaginationParams::default(),
            _state: PhantomData,
        }
    }

    //
    // -------------- BASIC CONFIG --------------
    //
    pub fn page(mut self, page: u32) -> Self {
        self.params.page = page.max(1);
        self
    }

    pub fn per_page(mut self, per_page: u32) -> Self {
        self.params.per_page = per_page.clamp(1, 100);
        self
    }

    //
    // -------------- SORT BUILDER --------------
    //
    pub fn sort(self) -> SortBuilder<Self> {
        SortBuilder::new(self)
    }

    //
    // -------------- FILTER BUILDER --------------
    //
    pub fn filter(self) -> FilterBuilder<Self> {
        FilterBuilder::with_parent(self)
    }

    //
    // -------------- SEARCH BUILDER --------------
    //
    pub fn search(self) -> SearchBuilder<Self> {
        SearchBuilder::with_parent(self)
    }

    //
    // -------------- CURSOR BUILDER --------------
    //
    pub fn cursor(self) -> CursorBuilder<Self> {
        CursorBuilder::with_parent(self)
    }

    pub fn disable_total_count(mut self) -> Self {
        self.params.disable_total_count = true;
        self
    }

    //
    // -------------- FINAL BUILD --------------
    //
    pub fn build(self) -> PaginationParams {
        self.params
    }
}

//
// ========================
//       SORT BUILDER
// ========================
//

pub struct SortBuilder<P> {
    parent: P,
}

impl<P> SortBuilder<P> {
    fn new(parent: P) -> Self {
        Self { parent }
    }

    pub fn asc(mut self, field: impl Into<String>) -> P
    where
        P: HasParams,
    {
        let mut p = self.parent;
        p.params_mut().sort_by = Some(field.into());
        p.params_mut().sort_direction = Some(SortDirection::Asc);
        p
    }

    pub fn desc(mut self, field: impl Into<String>) -> P
    where
        P: HasParams,
    {
        let mut p = self.parent;
        p.params_mut().sort_by = Some(field.into());
        p.params_mut().sort_direction = Some(SortDirection::Desc);
        p
    }
}

//
// ========================
//      FILTER BUILDER
// ========================
//

pub struct FilterBuilder<P = ()> {
    parent: Option<P>,
    filters: Vec<Filter>,
}

impl FilterBuilder<()> {
    /// Create as standalone (no parent)
    pub fn new() -> Self {
        Self {
            parent: None,
            filters: Vec::new(),
        }
    }

    /// Finish and return only the filters
    pub fn build(self) -> Vec<Filter> {
        self.filters
    }
}

impl<P> FilterBuilder<P> {
    /// Create with parent (Paginator, or any other)
    pub fn with_parent(parent: P) -> Self {
        Self {
            parent: Some(parent),
            filters: Vec::new(),
        }
    }

    // --- PRIMITIVES ---

    fn push(mut self, field: impl Into<String>, op: FilterOperator, value: FilterValue) -> Self {
        self.filters.push(Filter::new(field, op, value));
        self
    }

    pub fn eq(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Eq, value)
    }

    pub fn ne(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Ne, value)
    }

    pub fn gt(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Gt, value)
    }

    pub fn lt(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Lt, value)
    }

    pub fn gte(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Gte, value)
    }

    pub fn lte(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Lte, value)
    }

    pub fn like(self, field: impl Into<String>, pat: impl Into<String>) -> Self {
        self.push(field, FilterOperator::Like, FilterValue::String(pat.into()))
    }

    pub fn ilike(self, field: impl Into<String>, pat: impl Into<String>) -> Self {
        self.push(
            field,
            FilterOperator::ILike,
            FilterValue::String(pat.into()),
        )
    }

    pub fn r#in(self, field: impl Into<String>, values: Vec<FilterValue>) -> Self {
        self.push(field, FilterOperator::In, FilterValue::Array(values))
    }

    pub fn not_in(self, field: impl Into<String>, values: Vec<FilterValue>) -> Self {
        self.push(field, FilterOperator::NotIn, FilterValue::Array(values))
    }

    pub fn between(self, field: impl Into<String>, min: FilterValue, max: FilterValue) -> Self {
        self.push(
            field,
            FilterOperator::Between,
            FilterValue::Array(vec![min, max]),
        )
    }

    pub fn is_null(self, field: impl Into<String>) -> Self {
        self.push(field, FilterOperator::IsNull, FilterValue::Null)
    }

    pub fn is_not_null(self, field: impl Into<String>) -> Self {
        self.push(field, FilterOperator::IsNotNull, FilterValue::Null)
    }

    pub fn contains(self, field: impl Into<String>, value: FilterValue) -> Self {
        self.push(field, FilterOperator::Contains, value)
    }

    /// Finish and return to parent.
    ///
    /// Note: This method is only callable when the builder was created via a fluent chain
    /// (e.g., `Paginator::new().filter()`), not when created standalone via `FilterBuilder::new()`.
    /// The trait bound `P: HasParams` ensures this at compile time.
    pub fn apply(self) -> P
    where
        P: HasParams,
    {
        // SAFETY: When P: HasParams, the builder must have been created via `with_parent`,
        // which always sets parent to Some. Standalone builders (FilterBuilder<()>) cannot
        // call this method because () does not implement HasParams.
        let mut parent = self.parent.unwrap_or_else(|| {
            panic!("BUG: FilterBuilder::apply called without a parent. This should be prevented by type system.")
        });
        parent.params_mut().filters.extend(self.filters);
        parent
    }
}

//
// ========================
//      SEARCH BUILDER
// ========================
//

pub struct SearchBuilder<P = ()> {
    parent: Option<P>,
    query: Option<String>,
    fields: Vec<String>,
    exact: bool,
    case_sensitive: bool,
}

impl SearchBuilder<()> {
    pub fn new() -> Self {
        Self {
            parent: None,
            query: None,
            fields: Vec::new(),
            exact: false,
            case_sensitive: false,
        }
    }

    pub fn build(self) -> Option<SearchParams> {
        self.query.map(|q| {
            let mut params = SearchParams::new(q, self.fields);
            if self.exact {
                params = params.with_exact_match(true);
            }
            if self.case_sensitive {
                params = params.with_case_sensitive(true);
            }
            params
        })
    }
}

impl<P> SearchBuilder<P> {
    pub fn with_parent(parent: P) -> Self {
        Self {
            parent: Some(parent),
            query: None,
            fields: Vec::new(),
            exact: false,
            case_sensitive: false,
        }
    }

    pub fn query(mut self, q: impl Into<String>) -> Self {
        self.query = Some(q.into());
        self
    }

    pub fn fields<I, S>(mut self, fields: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.fields = fields.into_iter().map(Into::into).collect();
        self
    }

    pub fn exact(mut self, yes: bool) -> Self {
        self.exact = yes;
        self
    }

    pub fn case_sensitive(mut self, yes: bool) -> Self {
        self.case_sensitive = yes;
        self
    }

    /// Finish and return to parent.
    ///
    /// Note: This method is only callable when the builder was created via a fluent chain
    /// (e.g., `Paginator::new().search()`), not when created standalone via `SearchBuilder::new()`.
    /// The trait bound `P: HasParams` ensures this at compile time.
    pub fn apply(self) -> P
    where
        P: HasParams,
    {
        // SAFETY: When P: HasParams, the builder must have been created via `with_parent`,
        // which always sets parent to Some. Standalone builders (SearchBuilder<()>) cannot
        // call this method because () does not implement HasParams.
        let mut parent = self.parent.unwrap_or_else(|| {
            panic!("BUG: SearchBuilder::apply called without a parent. This should be prevented by type system.")
        });

        if let Some(q) = self.query {
            let mut s = SearchParams::new(q, self.fields);
            if self.exact {
                s = s.with_exact_match(true);
            }
            if self.case_sensitive {
                s = s.with_case_sensitive(true);
            }
            parent.params_mut().search = Some(s);
        }

        parent
    }
}

//
// ========================
//      CURSOR BUILDER
// ========================
//

pub struct CursorBuilder<P = ()> {
    parent: Option<P>,
    cursor: Option<Cursor>,
}

impl CursorBuilder<()> {
    pub fn new() -> Self {
        Self {
            parent: None,
            cursor: None,
        }
    }

    pub fn build(self) -> Option<Cursor> {
        self.cursor
    }
}

impl<P> CursorBuilder<P> {
    pub fn with_parent(parent: P) -> Self {
        Self {
            parent: Some(parent),
            cursor: None,
        }
    }

    pub fn after(mut self, field: impl Into<String>, value: CursorValue) -> Self {
        self.cursor = Some(Cursor::new(field.into(), value, CursorDirection::After));
        self
    }

    pub fn before(mut self, field: impl Into<String>, value: CursorValue) -> Self {
        self.cursor = Some(Cursor::new(field.into(), value, CursorDirection::Before));
        self
    }

    pub fn from_encoded(mut self, encoded: &str) -> Result<Self, String> {
        self.cursor = Some(Cursor::decode(encoded)?);
        Ok(self)
    }

    /// Finish and return to parent.
    ///
    /// Note: This method is only callable when the builder was created via a fluent chain
    /// (e.g., `Paginator::new().cursor()`), not when created standalone via `CursorBuilder::new()`.
    /// The trait bound `P: HasParams` ensures this at compile time.
    pub fn apply(self) -> P
    where
        P: HasParams,
    {
        // SAFETY: When P: HasParams, the builder must have been created via `with_parent`,
        // which always sets parent to Some. Standalone builders (CursorBuilder<()>) cannot
        // call this method because () does not implement HasParams.
        let mut parent = self.parent.unwrap_or_else(|| {
            panic!("BUG: CursorBuilder::apply called without a parent. This should be prevented by type system.")
        });
        if let Some(cursor) = self.cursor {
            parent.params_mut().cursor = Some(cursor);
        }
        parent
    }
}

/// Trait for types that have params
pub trait HasParams {
    fn params_mut(&mut self) -> &mut PaginationParams;
}

impl<S> HasParams for Paginator<S> {
    fn params_mut(&mut self) -> &mut PaginationParams {
        &mut self.params
    }
}

impl<S> IntoPaginationParams for Paginator<S> {
    fn into_pagination_params(self) -> PaginationParams {
        self.params
    }
}

impl IntoPaginationParams for FilterBuilder<()> {
    fn into_pagination_params(self) -> PaginationParams {
        PaginationParams {
            filters: self.filters,
            ..Default::default()
        }
    }
}

impl IntoPaginationParams for SearchBuilder<()> {
    fn into_pagination_params(self) -> PaginationParams {
        let mut params = PaginationParams::default();
        if let Some(query) = self.query {
            let mut search = SearchParams::new(query, self.fields);
            if self.exact {
                search = search.with_exact_match(true);
            }
            if self.case_sensitive {
                search = search.with_case_sensitive(true);
            }
            params.search = Some(search);
        }
        params
    }
}

impl IntoPaginationParams for CursorBuilder<()> {
    fn into_pagination_params(self) -> PaginationParams {
        PaginationParams {
            cursor: self.cursor,
            ..Default::default()
        }
    }
}

impl IntoPaginationParams for PaginatorBuilder {
    fn into_pagination_params(self) -> PaginationParams {
        self.params
    }
}

//
// ========================
//   BACKWARD COMPATIBILITY
// ========================
//

/// Legacy builder for backward compatibility
pub struct PaginatorBuilder {
    params: PaginationParams,
}

impl Default for PaginatorBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl PaginatorBuilder {
    pub fn new() -> Self {
        Self {
            params: PaginationParams::default(),
        }
    }

    pub fn page(mut self, page: u32) -> Self {
        self.params.page = page.max(1);
        self
    }

    pub fn per_page(mut self, per_page: u32) -> Self {
        self.params.per_page = per_page.clamp(1, 100);
        self
    }

    pub fn sort_by(mut self, field: impl Into<String>) -> Self {
        self.params.sort_by = Some(field.into());
        self
    }

    pub fn sort_asc(mut self) -> Self {
        self.params.sort_direction = Some(SortDirection::Asc);
        self
    }

    pub fn sort_desc(mut self) -> Self {
        self.params.sort_direction = Some(SortDirection::Desc);
        self
    }

    pub fn filter(
        mut self,
        field: impl Into<String>,
        operator: FilterOperator,
        value: FilterValue,
    ) -> Self {
        self.params
            .filters
            .push(Filter::new(field, operator, value));
        self
    }

    pub fn filter_eq(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Eq, value));
        self
    }

    pub fn filter_ne(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Ne, value));
        self
    }

    pub fn filter_gt(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Gt, value));
        self
    }

    pub fn filter_lt(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Lt, value));
        self
    }

    pub fn filter_gte(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Gte, value));
        self
    }

    pub fn filter_lte(mut self, field: impl Into<String>, value: FilterValue) -> Self {
        self.params
            .filters
            .push(Filter::new(field, FilterOperator::Lte, value));
        self
    }

    pub fn filter_like(mut self, field: impl Into<String>, pattern: impl Into<String>) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::Like,
            FilterValue::String(pattern.into()),
        ));
        self
    }

    pub fn filter_ilike(mut self, field: impl Into<String>, pattern: impl Into<String>) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::ILike,
            FilterValue::String(pattern.into()),
        ));
        self
    }

    pub fn filter_in(mut self, field: impl Into<String>, values: Vec<FilterValue>) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::In,
            FilterValue::Array(values),
        ));
        self
    }

    pub fn filter_between(
        mut self,
        field: impl Into<String>,
        min: FilterValue,
        max: FilterValue,
    ) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::Between,
            FilterValue::Array(vec![min, max]),
        ));
        self
    }

    pub fn filter_is_null(mut self, field: impl Into<String>) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::IsNull,
            FilterValue::Null,
        ));
        self
    }

    pub fn filter_is_not_null(mut self, field: impl Into<String>) -> Self {
        self.params.filters.push(Filter::new(
            field,
            FilterOperator::IsNotNull,
            FilterValue::Null,
        ));
        self
    }

    pub fn search(mut self, query: impl Into<String>, fields: Vec<String>) -> Self {
        self.params.search = Some(SearchParams::new(query, fields));
        self
    }

    pub fn search_exact(mut self, query: impl Into<String>, fields: Vec<String>) -> Self {
        self.params.search = Some(SearchParams::new(query, fields).with_exact_match(true));
        self
    }

    pub fn search_case_sensitive(mut self, query: impl Into<String>, fields: Vec<String>) -> Self {
        self.params.search = Some(SearchParams::new(query, fields).with_case_sensitive(true));
        self
    }

    pub fn disable_total_count(mut self) -> Self {
        self.params.disable_total_count = true;
        self
    }

    pub fn cursor(
        mut self,
        field: impl Into<String>,
        value: CursorValue,
        direction: CursorDirection,
    ) -> Self {
        self.params.cursor = Some(Cursor::new(field.into(), value, direction));
        self
    }

    pub fn cursor_after(mut self, field: impl Into<String>, value: CursorValue) -> Self {
        self.params.cursor = Some(Cursor::new(field.into(), value, CursorDirection::After));
        self
    }

    pub fn cursor_before(mut self, field: impl Into<String>, value: CursorValue) -> Self {
        self.params.cursor = Some(Cursor::new(field.into(), value, CursorDirection::Before));
        self
    }

    pub fn cursor_from_encoded(mut self, encoded: &str) -> Result<Self, String> {
        self.params.cursor = Some(Cursor::decode(encoded)?);
        Ok(self)
    }

    pub fn build(self) -> PaginationParams {
        self.params
    }
}