spo-postgrest 1.6.0

PostgREST client-side library (forked)
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
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
use reqwest::{
    header::{HeaderMap, HeaderValue},
    Client, Error, Method, Response,
};
use serde::{Deserialize, Serialize};

pub mod headers_serde {
    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
    use serde::{
        de::{Deserialize, Error},
        ser::SerializeSeq,
    };

    pub fn serialize<S: serde::Serializer>(map: &HeaderMap, s: S) -> Result<S::Ok, S::Error> {
        struct Bytes<'a>(&'a [u8]);

        impl<'a> serde::Serialize for Bytes<'a> {
            fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                s.serialize_bytes(self.0)
            }
        }

        let mut seq = s.serialize_seq(Some(map.len()))?;
        for (k, v) in map.iter() {
            match v.to_str() {
                Ok(s) => seq.serialize_element(&(k.as_str(), s))?,
                Err(_) => seq.serialize_element(&(k.as_str(), &Bytes(v.as_bytes())))?,
            }
        }
        seq.end()
    }

    pub struct Name(HeaderName);

    pub struct NameVisitor;

    impl<'de> serde::de::Visitor<'de> for NameVisitor {
        type Value = Name;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("string")
        }

        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(Name(HeaderName::from_bytes(v).map_err(E::custom)?))
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: Error,
        {
            self.visit_bytes(v.as_bytes())
        }
    }

    impl<'de> Deserialize<'de> for Name {
        fn deserialize<D>(d: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            d.deserialize_str(NameVisitor)
        }
    }

    pub struct Value(HeaderValue);

    pub struct ValueVisitor;

    impl<'de> serde::de::Visitor<'de> for ValueVisitor {
        type Value = Value;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("string or bytes")
        }

        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(Value(HeaderValue::from_bytes(v).map_err(E::custom)?))
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(Value(HeaderValue::from_str(v).map_err(E::custom)?))
        }
    }

    impl<'de> Deserialize<'de> for Value {
        fn deserialize<D>(d: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            d.deserialize_any(ValueVisitor)
        }
    }

    pub struct Visitor;

    impl<'de> serde::de::Visitor<'de> for Visitor {
        type Value = HeaderMap;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("[(string, string|bytes)]")
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: serde::de::SeqAccess<'de>,
        {
            let mut map = HeaderMap::with_capacity(seq.size_hint().unwrap_or(0));
            while let Some((name, value)) = seq.next_element::<(Name, Value)>()? {
                map.insert(name.0, value.0);
            }
            Ok(map)
        }
    }

    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<HeaderMap, D::Error> {
        d.deserialize_seq(Visitor)
    }
}

pub mod method_serde {
    use reqwest::Method;
    use serde::de::{Deserialize, Error};

    pub fn serialize<S: serde::Serializer>(method: &Method, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(method.as_str())
    }

    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Method, D::Error> {
        String::deserialize(d)?.parse().map_err(D::Error::custom)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Query {
    #[serde(with = "method_serde")]
    pub method: Method,
    pub url: String,
    pub schema: Option<String>,
    // Need this to allow access from `filter.rs`
    pub queries: Vec<(String, String)>,
    #[serde(with = "headers_serde")]
    pub headers: HeaderMap,
    pub body: Option<String>,
    pub is_rpc: bool,
}

impl From<Builder> for Query {
    fn from(
        Builder {
            method,
            url,
            schema,
            queries,
            headers,
            body,
            is_rpc,
            ..
        }: Builder,
    ) -> Self {
        Self {
            method,
            url,
            schema,
            queries,
            headers,
            body,
            is_rpc,
        }
    }
}

/// QueryBuilder struct
#[derive(Clone, Debug)]
pub struct Builder {
    method: Method,
    url: String,
    schema: Option<String>,
    // Need this to allow access from `filter.rs`
    pub(crate) queries: Vec<(String, String)>,
    headers: HeaderMap,
    body: Option<String>,
    is_rpc: bool,
    // sharing a client is a good idea, performance wise
    // the client has to live at least as much as the builder
    pub client: Client,
}

// TODO: Test Unicode support
impl Builder {
    pub fn from_query(
        Query {
            method,
            url,
            schema,
            queries,
            headers,
            body,
            is_rpc,
        }: Query,
        client: Client,
    ) -> Self {
        Self {
            method,
            url,
            schema,
            queries,
            headers,
            body,
            is_rpc,
            client,
        }
    }

    /// Creates a new `Builder` with the specified `schema`.
    pub fn new<T>(url: T, schema: Option<String>, headers: HeaderMap, client: Client) -> Self
    where
        T: Into<String>,
    {
        let url = url.into().trim_end_matches('/').to_string();

        let mut builder = Builder {
            method: Method::GET,
            url,
            schema,
            queries: Vec::new(),
            headers,
            body: None,
            is_rpc: false,
            client,
        };
        builder
            .headers
            .insert("Accept", HeaderValue::from_static("application/json"));
        builder
    }

    /// Authenticates the request with JWT.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("table")
    ///     .auth("supers.ecretjw.ttoken");
    /// ```
    pub fn auth<T>(mut self, token: T) -> Self
    where
        T: AsRef<str>,
    {
        self.headers.insert(
            "Authorization",
            HeaderValue::from_str(&format!("Bearer {}", token.as_ref())).unwrap(),
        );
        self
    }

    /// Performs horizontal filtering with SELECT.
    ///
    /// # Note
    ///
    /// `columns` is whitespace-sensitive, so you need to omit them unless your
    /// column name contains whitespaces.
    ///
    /// # Example
    ///
    /// Simple example:
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// let resp = client
    ///     .from("table")
    ///     .select("*")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Renaming columns:
    ///
    /// ```
    /// # use postgrest::Postgrest;
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = Postgrest::new("https://your.postgrest.endpoint");
    /// let resp = client
    ///     .from("users")
    ///     .select("name:very_very_long_column_name")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Casting columns:
    ///
    /// ```
    /// # use postgrest::Postgrest;
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = Postgrest::new("https://your.postgrest.endpoint");
    /// let resp = client
    ///     .from("users")
    ///     .select("age::text")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// SELECTing JSON fields:
    ///
    /// ```
    /// # use postgrest::Postgrest;
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = Postgrest::new("https://your.postgrest.endpoint");
    /// let resp = client
    ///     .from("users")
    ///     .select("id,json_data->phones->0->>number")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Embedded filters (assume there is a foreign key constraint between
    /// tables `users` and `tweets`):
    ///
    /// ```
    /// # use postgrest::Postgrest;
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// # let client = Postgrest::new("https://your.postgrest.endpoint");
    /// let resp = client
    ///     .from("users")
    ///     .select("*,tweets(*)")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn select<T>(mut self, columns: T) -> Self
    where
        T: Into<String>,
    {
        self.queries.push(("select".to_string(), columns.into()));
        self
    }

    /// Orders the result with the specified `columns`.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .order("username.desc.nullsfirst,age_range");
    /// ```
    pub fn order<T>(mut self, columns: T) -> Self
    where
        T: Into<String>,
    {
        self.queries.push(("order".to_string(), columns.into()));
        self
    }

    /// Orders the result of a foreign table with the specified `columns`.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("countries")
    ///     .select("name, cities(name)")
    ///     .order_with_options("name", Some("cities"), true, false);
    /// ```
    pub fn order_with_options<T, U>(
        mut self,
        columns: T,
        foreign_table: Option<U>,
        ascending: bool,
        nulls_first: bool,
    ) -> Self
    where
        T: Into<String>,
        U: Into<String>,
    {
        let mut key = "order".to_string();
        if let Some(foreign_table) = foreign_table {
            let foreign_table = foreign_table.into();
            if !foreign_table.is_empty() {
                key = format!("{}.order", foreign_table);
            }
        }

        let mut ascending_string = "desc";
        if ascending {
            ascending_string = "asc";
        }

        let mut nulls_first_string = "nullslast";
        if nulls_first {
            nulls_first_string = "nullsfirst";
        }

        let existing_order = self.queries.iter().find(|(k, _)| k == &key);
        match existing_order {
            Some((_, v)) => {
                let new_order = format!(
                    "{},{}.{}.{}",
                    v,
                    columns.into(),
                    ascending_string,
                    nulls_first_string
                );
                self.queries.push((key, new_order));
            }
            None => {
                self.queries.push((
                    key,
                    format!(
                        "{}.{}.{}",
                        columns.into(),
                        ascending_string,
                        nulls_first_string
                    ),
                ));
            }
        }
        self
    }

    /// Limits the result with the specified `count`.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .limit(20);
    /// ```
    pub fn limit(mut self, count: usize) -> Self {
        self.headers
            .insert("Range-Unit", HeaderValue::from_static("items"));
        self.headers.insert(
            "Range",
            HeaderValue::from_str(&format!("0-{}", count - 1)).unwrap(),
        );
        self
    }

    /// Limits the result of a foreign table with the specified `count`.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("countries")
    ///     .select("name, cities(name)")
    ///     .foreign_table_limit(1, "cities");
    /// ```
    pub fn foreign_table_limit<T>(mut self, count: usize, foreign_table: T) -> Self
    where
        T: Into<String>,
    {
        self.queries
            .push((format!("{}.limit", foreign_table.into()), count.to_string()));
        self
    }

    /// Limits the result to rows within the specified range, inclusive.
    ///
    /// # Example
    ///
    /// This retrieves the 2nd to 5th entries in the result:
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .range(1, 4);
    /// ```
    pub fn range(mut self, low: usize, high: usize) -> Self {
        self.headers
            .insert("Range-Unit", HeaderValue::from_static("items"));
        self.headers.insert(
            "Range",
            HeaderValue::from_str(&format!("{}-{}", low, high)).unwrap(),
        );
        self
    }

    fn count(mut self, method: &str) -> Self {
        self.headers
            .insert("Range-Unit", HeaderValue::from_static("items"));
        // Value is irrelevant, we just want the size
        self.headers
            .insert("Range", HeaderValue::from_static("0-0"));
        self.headers.insert(
            "Prefer",
            HeaderValue::from_str(&format!("count={}", method)).unwrap(),
        );
        self
    }

    /// Retrieves the (accurate) total size of the result.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .exact_count();
    /// ```
    pub fn exact_count(self) -> Self {
        self.count("exact")
    }

    /// Estimates the total size of the result using PostgreSQL statistics. This
    /// is faster than using `exact_count()`.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .planned_count();
    /// ```
    pub fn planned_count(self) -> Self {
        self.count("planned")
    }

    /// Retrieves the total size of the result using some heuristics:
    /// `exact_count` for smaller sizes, `planned_count` for larger sizes.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .estimated_count();
    /// ```
    pub fn estimated_count(self) -> Self {
        self.count("estimated")
    }

    /// Retrieves only one row from the result.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .select("*")
    ///     .single();
    /// ```
    pub fn single(mut self) -> Self {
        self.headers.insert(
            "Accept",
            HeaderValue::from_static("application/vnd.pgrst.object+json"),
        );
        self
    }

    /// Performs an INSERT of the `body` (in JSON) into the table.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .insert(r#"[{ "username": "soedirgo", "status": "online" },
    ///                 { "username": "jose", "status": "offline" }]"#);
    /// ```
    pub fn insert<T>(mut self, body: T) -> Self
    where
        T: Into<String>,
    {
        self.method = Method::POST;
        self.headers
            .insert("Prefer", HeaderValue::from_static("return=representation"));
        self.body = Some(body.into());
        self
    }

    /// Performs an upsert of the `body` (in JSON) into the table.
    ///
    /// # Note
    ///
    /// This merges duplicates by default. Ignoring duplicates is possible via
    /// PostgREST, but is currently unsupported.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .upsert(r#"[{ "username": "soedirgo", "status": "online" },
    ///                 { "username": "jose", "status": "offline" }]"#);
    /// ```
    pub fn upsert<T>(mut self, body: T) -> Self
    where
        T: Into<String>,
    {
        self.method = Method::POST;
        self.headers.insert(
            "Prefer",
            HeaderValue::from_static("return=representation,resolution=merge-duplicates"),
        );
        self.body = Some(body.into());
        self
    }

    /// Resolve upsert conflicts on unique columns other than the primary key.
    ///
    /// # Note
    ///
    /// This informs PostgREST to resolve upsert conflicts through an
    /// alternative, unique index other than the primary key of the table.
    /// See the related
    /// [PostgREST documentation](https://postgrest.org/en/stable/api.html?highlight=upsert#on-conflict).
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// // Suppose `users` are keyed an SERIAL primary key,
    /// // but have a unique index on `username`.
    /// client
    ///     .from("users")
    ///     .upsert(r#"[{ "username": "soedirgo", "status": "online" },
    ///                 { "username": "jose", "status": "offline" }]"#)
    ///     .on_conflict("username");
    /// ```
    pub fn on_conflict<T>(mut self, columns: T) -> Self
    where
        T: Into<String>,
    {
        self.queries
            .push(("on_conflict".to_string(), columns.into()));
        self
    }

    /// Performs an UPDATE using the `body` (in JSON) on the table.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .eq("username", "soedirgo")
    ///     .update(r#"{ "status": "offline" }"#);
    /// ```
    pub fn update<T>(mut self, body: T) -> Self
    where
        T: Into<String>,
    {
        self.method = Method::PATCH;
        self.headers
            .insert("Prefer", HeaderValue::from_static("return=representation"));
        self.body = Some(body.into());
        self
    }

    /// Performs a DELETE on the table.
    ///
    /// # Example
    ///
    /// ```
    /// use postgrest::Postgrest;
    ///
    /// let client = Postgrest::new("https://your.postgrest.endpoint");
    /// client
    ///     .from("users")
    ///     .eq("username", "soedirgo")
    ///     .delete();
    /// ```
    pub fn delete(mut self) -> Self {
        self.method = Method::DELETE;
        self.headers
            .insert("Prefer", HeaderValue::from_static("return=representation"));
        self
    }

    /// Performs a stored procedure call. This should only be used through the
    /// `rpc()` method in `Postgrest`.
    pub fn rpc<T>(mut self, params: T) -> Self
    where
        T: Into<String>,
    {
        self.method = Method::POST;
        self.body = Some(params.into());
        self.is_rpc = true;
        self
    }

    /// Build the PostgREST request.
    pub fn build(mut self) -> reqwest::RequestBuilder {
        if let Some(schema) = self.schema {
            let key = match self.method {
                Method::GET | Method::HEAD => "Accept-Profile",
                _ => "Content-Profile",
            };
            self.headers
                .insert(key, HeaderValue::from_str(&schema).unwrap());
        }
        match self.method {
            Method::GET | Method::HEAD => {}
            _ => {
                self.headers
                    .insert("Content-Type", HeaderValue::from_static("application/json"));
            }
        };
        self.client
            .request(self.method, self.url)
            .headers(self.headers)
            .query(&self.queries)
            .body(self.body.unwrap_or_default())
    }

    /// Executes the PostgREST request.
    pub async fn execute(self) -> Result<Response, Error> {
        self.build().send().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TABLE_URL: &str = "http://localhost:3000/table";
    const RPC_URL: &str = "http://localhost:3000/rpc";

    #[test]
    fn only_accept_json() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client);
        assert_eq!(
            builder.headers.get("Accept").unwrap(),
            HeaderValue::from_static("application/json")
        );
    }

    #[test]
    fn auth_with_token() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).auth("$Up3rS3crET");
        assert_eq!(
            builder.headers.get("Authorization").unwrap(),
            HeaderValue::from_static("Bearer $Up3rS3crET")
        );
    }

    #[test]
    fn select_assert_query() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).select("some_table");
        assert_eq!(builder.method, Method::GET);
        assert_eq!(
            builder
                .queries
                .contains(&("select".to_string(), "some_table".to_string())),
            true
        );
    }

    #[test]
    fn order_assert_query() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).order("id");
        assert_eq!(
            builder
                .queries
                .contains(&("order".to_string(), "id".to_string())),
            true
        );
    }

    #[test]
    fn order_with_options_assert_query() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).order_with_options(
            "name",
            Some("cities"),
            true,
            false,
        );
        assert_eq!(
            builder
                .queries
                .contains(&("cities.order".to_string(), "name.asc.nullslast".to_string())),
            true
        );
    }

    #[test]
    fn limit_assert_range_header() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).limit(20);
        assert_eq!(
            builder.headers.get("Range").unwrap(),
            HeaderValue::from_static("0-19")
        );
    }

    #[test]
    fn foreign_table_limit_assert_query() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client)
            .foreign_table_limit(20, "some_table");
        assert_eq!(
            builder
                .queries
                .contains(&("some_table.limit".to_string(), "20".to_string())),
            true
        );
    }

    #[test]
    fn range_assert_range_header() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).range(10, 20);
        assert_eq!(
            builder.headers.get("Range").unwrap(),
            HeaderValue::from_static("10-20")
        );
    }

    #[test]
    fn single_assert_accept_header() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).single();
        assert_eq!(
            builder.headers.get("Accept").unwrap(),
            HeaderValue::from_static("application/vnd.pgrst.object+json")
        );
    }

    #[test]
    fn upsert_assert_prefer_header() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).upsert("ignored");
        assert_eq!(
            builder.headers.get("Prefer").unwrap(),
            HeaderValue::from_static("return=representation,resolution=merge-duplicates")
        );
    }

    #[test]
    fn not_rpc_should_not_have_flag() {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client).select("ignored");
        assert_eq!(builder.is_rpc, false);
    }

    #[test]
    fn rpc_should_have_body_and_flag() {
        let client = Client::new();
        let builder =
            Builder::new(RPC_URL, None, HeaderMap::new(), client).rpc("{\"a\": 1, \"b\": 2}");
        assert_eq!(builder.body.unwrap(), "{\"a\": 1, \"b\": 2}");
        assert_eq!(builder.is_rpc, true);
    }

    #[test]
    fn chain_filters() -> Result<(), Box<dyn std::error::Error>> {
        let client = Client::new();
        let builder = Builder::new(TABLE_URL, None, HeaderMap::new(), client)
            .eq("username", "supabot")
            .neq("message", "hello world")
            .gte("channel_id", "1")
            .select("*");

        let queries = builder.queries;
        assert_eq!(queries.len(), 4);
        assert!(queries.contains(&("username".into(), "eq.supabot".into())));
        assert!(queries.contains(&("message".into(), "neq.hello world".into())));
        assert!(queries.contains(&("channel_id".into(), "gte.1".into())));

        Ok(())
    }
}