supabase-rust-postgrest 0.4.0

PostgreSQL REST client for Supabase
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
//! Supabase PostgREST client for Rust
//!
//! This crate provides database functionality for Supabase,
//! allowing for querying, filtering, and manipulating data in PostgreSQL.
//!
//! # Features
//!
//! - Query API (`select`, `insert`, `update`, `delete`)
//! - Filtering (`eq`, `gt`, `lt`, etc.)
//! - Ordering and pagination
//! - Transactions
//! - RPC function calls
//! - CSV export

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use thiserror::Error;
use url::Url;

use serde_json::json;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// PostgREST APIエラーの詳細情報
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PostgrestApiErrorDetails {
    pub code: Option<String>,
    pub message: Option<String>,
    pub details: Option<String>,
    pub hint: Option<String>,
}

// エラー詳細を整形して表示するための Display 実装
impl fmt::Display for PostgrestApiErrorDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = Vec::new();
        if let Some(code) = &self.code {
            parts.push(format!("Code: {}", code));
        }
        if let Some(message) = &self.message {
            parts.push(format!("Message: {}", message));
        }
        if let Some(details) = &self.details {
            parts.push(format!("Details: {}", details));
        }
        if let Some(hint) = &self.hint {
            parts.push(format!("Hint: {}", hint));
        }
        write!(f, "{}", parts.join(", "))
    }
}

/// エラー型
#[derive(Error, Debug)]
pub enum PostgrestError {
    #[error("API error: {details} (Status: {status})")]
    ApiError {
        details: PostgrestApiErrorDetails,
        status: reqwest::StatusCode,
    },

    #[error("API error (unparsed): {message} (Status: {status})")]
    UnparsedApiError {
        message: String,
        status: reqwest::StatusCode,
    },

    #[error("Network error: {0}")]
    NetworkError(#[from] reqwest::Error),

    #[error("URL parse error: {0}")]
    UrlParseError(#[from] url::ParseError),

    #[error("JSON serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),

    #[error("Invalid parameters: {0}")]
    InvalidParameters(String),

    #[error("Transaction error: {0}")]
    TransactionError(String),

    #[error("Deserialization error: {0}")]
    DeserializationError(String),
}

/// ソート方向
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
    Ascending,
    Descending,
}

/// トランザクションの分離レベル
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    ReadCommitted,
    RepeatableRead,
    Serializable,
}

impl IsolationLevel {
    /// 分離レベルを文字列に変換
    fn display(&self) -> &'static str {
        match self {
            IsolationLevel::ReadCommitted => "read committed",
            IsolationLevel::RepeatableRead => "repeatable read",
            IsolationLevel::Serializable => "serializable",
        }
    }
}

/// トランザクションの読み取り/書き込みモード
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionMode {
    ReadWrite,
    ReadOnly,
}

impl TransactionMode {
    /// トランザクションモードを文字列に変換
    fn display(&self) -> &'static str {
        match self {
            TransactionMode::ReadWrite => "read write",
            TransactionMode::ReadOnly => "read only",
        }
    }
}

/// トランザクションの状態
#[allow(dead_code)]
enum TransactionState {
    Inactive,
    Active,
    Committed,
    RolledBack,
}

/// PostgreST クライアント
pub struct PostgrestClient {
    base_url: String,
    api_key: String,
    table: String,
    http_client: Client,
    headers: HeaderMap,
    query_params: HashMap<String, String>,
    #[allow(dead_code)]
    path: Option<String>,
    #[allow(dead_code)]
    is_rpc: bool,
    #[allow(dead_code)]
    rpc_params: Option<Value>,
}

impl PostgrestClient {
    /// 新しい PostgreST クライアントを作成
    pub fn new(base_url: &str, api_key: &str, table: &str, http_client: Client) -> Self {
        let mut headers = HeaderMap::new();
        headers.insert("apikey", HeaderValue::from_str(api_key).unwrap());
        headers.insert("Content-Type", HeaderValue::from_static("application/json"));

        Self {
            base_url: base_url.to_string(),
            api_key: api_key.to_string(),
            table: table.to_string(),
            http_client,
            headers,
            query_params: HashMap::new(),
            path: None,
            is_rpc: false,
            rpc_params: None,
        }
    }

    /// RPCリクエストを作成
    pub fn rpc(
        base_url: &str,
        api_key: &str,
        function_name: &str,
        params: Value,
        http_client: Client,
    ) -> Self {
        let mut headers = HeaderMap::new();
        headers.insert("apikey", HeaderValue::from_str(api_key).unwrap());
        headers.insert("Content-Type", HeaderValue::from_static("application/json"));

        Self {
            base_url: base_url.to_string(),
            api_key: api_key.to_string(),
            table: function_name.to_string(),
            http_client,
            headers,
            query_params: HashMap::new(),
            path: None,
            is_rpc: true,
            rpc_params: Some(params),
        }
    }

    /// ヘッダーを追加
    pub fn with_header(mut self, key: &str, value: &str) -> Result<Self, PostgrestError> {
        let header_value = HeaderValue::from_str(value).map_err(|_| {
            PostgrestError::InvalidParameters(format!("Invalid header value: {}", value))
        })?;

        // ヘッダー名を文字列として所有し、HeaderNameに変換する
        let header_name = HeaderName::from_bytes(key.as_bytes()).map_err(|_| {
            PostgrestError::InvalidParameters(format!("Invalid header name: {}", key))
        })?;

        self.headers.insert(header_name, header_value);
        Ok(self)
    }

    /// 認証トークンを設定
    pub fn with_auth(self, token: &str) -> Result<Self, PostgrestError> {
        self.with_header("Authorization", &format!("Bearer {}", token))
    }

    /// 取得するカラムを指定
    pub fn select(mut self, columns: &str) -> Self {
        self.query_params
            .insert("select".to_string(), columns.to_string());
        self
    }

    /// 結合クエリ: 参照テーブルとの内部結合
    pub fn inner_join(mut self, foreign_table: &str, column: &str, foreign_column: &str) -> Self {
        // 選択列にリレーションを追加
        let current_select = self
            .query_params
            .get("select")
            .cloned()
            .unwrap_or_else(|| "*".to_string());
        let new_select = if current_select == "*" {
            format!("*,{}!inner({})", foreign_table, foreign_column)
        } else {
            format!(
                "{},{},{}!inner({})",
                current_select, column, foreign_table, foreign_column
            )
        };

        self.query_params.insert("select".to_string(), new_select);
        self
    }

    /// 結合クエリ: 参照テーブルとの左外部結合
    pub fn left_join(mut self, foreign_table: &str, column: &str, foreign_column: &str) -> Self {
        // 選択列にリレーションを追加
        let current_select = self
            .query_params
            .get("select")
            .cloned()
            .unwrap_or_else(|| "*".to_string());
        let new_select = if current_select == "*" {
            format!("*,{}!left({})", foreign_table, foreign_column)
        } else {
            format!(
                "{},{},{}!left({})",
                current_select, column, foreign_table, foreign_column
            )
        };

        self.query_params.insert("select".to_string(), new_select);
        self
    }

    /// 結合クエリ: 一対多関係の子テーブルを含める
    pub fn include(
        mut self,
        foreign_table: &str,
        _foreign_column: &str,
        columns: Option<&str>,
    ) -> Self {
        // 選択列にリレーションを追加
        let current_select = self
            .query_params
            .get("select")
            .cloned()
            .unwrap_or_else(|| "*".to_string());
        let columns_str = columns.unwrap_or("*");
        let new_select = if current_select == "*" {
            format!("*,{}({})", foreign_table, columns_str)
        } else {
            format!("{},{}({})", current_select, foreign_table, columns_str)
        };

        self.query_params.insert("select".to_string(), new_select);
        self
    }

    /// 結合クエリ: 外部キーの参照先テーブルを含める
    pub fn referenced_by(mut self, foreign_table: &str, foreign_column: &str) -> Self {
        // 選択列にリレーションを追加
        let current_select = self
            .query_params
            .get("select")
            .cloned()
            .unwrap_or_else(|| "*".to_string());
        let new_select = if current_select == "*" {
            format!("*,{}!fk({})", foreign_table, foreign_column)
        } else {
            format!(
                "{},{}!fk({})",
                current_select, foreign_table, foreign_column
            )
        };

        self.query_params.insert("select".to_string(), new_select);
        self
    }

    /// 等価フィルター
    pub fn eq(mut self, column: &str, value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("eq.{}", value));
        self
    }

    /// より大きいフィルター
    pub fn gt(mut self, column: &str, value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("gt.{}", value));
        self
    }

    /// 以上フィルター
    pub fn gte(mut self, column: &str, value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("gte.{}", value));
        self
    }

    /// より小さいフィルター
    pub fn lt(mut self, column: &str, value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("lt.{}", value));
        self
    }

    /// 以下フィルター
    pub fn lte(mut self, column: &str, value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("lte.{}", value));
        self
    }

    /// LIKE フィルター
    pub fn like(mut self, column: &str, pattern: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("like.{}", pattern));
        self
    }

    /// ILIKE フィルター(大文字小文字を区別しない)
    pub fn ilike(mut self, column: &str, pattern: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("ilike.{}", pattern));
        self
    }

    /// IN フィルター
    pub fn in_list(mut self, column: &str, values: &[&str]) -> Self {
        let value_list = values.join(",");
        self.query_params
            .insert(column.to_string(), format!("in.({})", value_list));
        self
    }

    /// NOT フィルター
    pub fn not(mut self, column: &str, operator_with_value: &str) -> Self {
        self.query_params
            .insert(column.to_string(), format!("not.{}", operator_with_value));
        self
    }

    /// JSON/JSONB カラムが指定した値を含むか (`cs`, `@>`) フィルター
    /// value は serde_json::Value で指定します
    pub fn contains(mut self, column: &str, value: &Value) -> Result<Self, PostgrestError> {
        let value_str = serde_json::to_string(value)?;
        self.query_params
            .insert(column.to_string(), format!("cs.{}", value_str));
        Ok(self)
    }

    /// JSON/JSONB カラムが指定した値に含まれるか (`cd`, `<@`) フィルター
    /// value は serde_json::Value で指定します
    pub fn contained_by(mut self, column: &str, value: &Value) -> Result<Self, PostgrestError> {
        let value_str = serde_json::to_string(value)?;
        self.query_params
            .insert(column.to_string(), format!("cd.{}", value_str));
        Ok(self)
    }

    /// ソート順を指定
    pub fn order(mut self, column: &str, order: SortOrder) -> Self {
        let order_str = match order {
            SortOrder::Ascending => "asc",
            SortOrder::Descending => "desc",
        };
        self.query_params
            .insert("order".to_string(), format!("{}.{}", column, order_str));
        self
    }

    /// 取得件数を制限
    pub fn limit(mut self, count: i32) -> Self {
        self.query_params
            .insert("limit".to_string(), count.to_string());
        self
    }

    /// オフセットを指定
    pub fn offset(mut self, count: i32) -> Self {
        self.query_params
            .insert("offset".to_string(), count.to_string());
        self
    }

    /// 全文検索
    pub fn text_search(mut self, column: &str, query: &str, config: Option<&str>) -> Self {
        let search_param = match config {
            Some(cfg) => format!("fts({}).{}", cfg, query),
            None => format!("fts.{}", query),
        };

        self.query_params.insert(column.to_string(), search_param);
        self
    }

    /// 地理空間データの距離ベース検索
    pub fn geo_distance(
        mut self,
        column: &str,
        lat: f64,
        lng: f64,
        distance: f64,
        unit: &str,
    ) -> Self {
        self.query_params.insert(
            column.to_string(),
            format!("st_dwithin.POINT({} {}).{}.{}", lng, lat, distance, unit),
        );
        self
    }

    /// グループ化
    pub fn group_by(mut self, columns: &str) -> Self {
        self.query_params
            .insert("group".to_string(), columns.to_string());
        self
    }

    /// 行数カウント
    pub fn count(mut self, exact: bool) -> Self {
        let count_method = if exact { "exact" } else { "planned" };
        self.query_params
            .insert("count".to_string(), count_method.to_string());
        self
    }

    /// RLS(行レベルセキュリティ)ポリシーを無視
    pub fn ignore_rls(mut self) -> Self {
        self.headers.insert(
            reqwest::header::HeaderName::from_static("x-supabase-admin-role"),
            reqwest::header::HeaderValue::from_static("service_role"),
        );
        self
    }

    /// スキーマを指定(デフォルトのpublicスキーマではない場合)
    pub fn schema(mut self, schema_name: &str) -> Self {
        self.query_params
            .insert("schema".to_string(), schema_name.to_string());
        self
    }

    /// CSVとしてデータをエクスポート
    pub async fn export_csv(&self) -> Result<String, PostgrestError> {
        let mut url = self.build_url()?;

        // CSVフォーマットを指定
        if url.contains('?') {
            url.push('&');
        } else {
            url.push('?');
        }
        url.push_str("accept=text/csv");

        let mut headers = self.headers.clone();
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("text/csv"),
        );

        let response = self.http_client.get(url).headers(headers).send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await?;
            let details = serde_json::from_str::<PostgrestApiErrorDetails>(&error_text)
                .unwrap_or_else(|_| PostgrestApiErrorDetails {
                    code: None,
                    message: Some(error_text.clone()),
                    details: None,
                    hint: None,
                });
            return Err(PostgrestError::ApiError { details, status });
        }

        let csv_data = response.text().await?;

        Ok(csv_data)
    }

    /// データを取得
    pub async fn execute<T: for<'de> Deserialize<'de>>(&self) -> Result<Vec<T>, PostgrestError> {
        let url = self.build_url()?;

        let response = self
            .http_client
            .get(&url)
            .headers(self.headers.clone())
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            // Attempt to parse specific error details
            if let Ok(details) = serde_json::from_str::<PostgrestApiErrorDetails>(&error_text) {
                return Err(PostgrestError::ApiError { details, status });
            } else {
                // If parsing fails, return a less specific error with the raw message
                return Err(PostgrestError::UnparsedApiError {
                    message: error_text,
                    status,
                });
            }
        }

        response
            .json::<Vec<T>>()
            .await
            .map_err(|e| PostgrestError::DeserializationError(e.to_string()))
    }

    /// データを挿入
    pub async fn insert<T: Serialize>(&self, values: T) -> Result<Value, PostgrestError> {
        let url = self.build_url()?;

        // Clone headers and add the Prefer header
        let mut headers = self.headers.clone();
        headers.insert(
            HeaderName::from_static("prefer"),
            HeaderValue::from_static("return=representation"),
        );

        let response = self
            .http_client
            .post(&url)
            .headers(headers) // Use modified headers
            .json(&values)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();

        // Check for success first (e.g., 201 Created)
        if status.is_success() {
            // Read the body as text first to handle potential empty responses
            let body_text = response.text().await.map_err(|e| {
                PostgrestError::DeserializationError(format!("Failed to read response body: {}", e))
            })?;

            // If body is empty but status was success (e.g., 201), return Null.
            // PostgREST usually returns the inserted row(s), so empty is unexpected.
            if body_text.trim().is_empty() {
                // Consider returning Value::Array(vec![]) if an array is expected
                Ok(Value::Null)
            } else {
                // If body is not empty, try to parse it as JSON
                serde_json::from_str::<Value>(&body_text)
                    .map_err(|e| PostgrestError::DeserializationError(e.to_string()))
            }
        } else {
            // Handle non-success status codes as before
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            let details_result: Result<PostgrestApiErrorDetails, _> =
                serde_json::from_str(&error_text);
            match details_result {
                Ok(details) => Err(PostgrestError::ApiError { details, status }),
                Err(_) => Err(PostgrestError::UnparsedApiError {
                    message: error_text,
                    status,
                }),
            }
        }
    }

    /// データを更新
    pub async fn update<T: Serialize>(&self, values: T) -> Result<Value, PostgrestError> {
        let url = self.build_url()?;

        // Clone headers and add the Prefer header
        let mut headers = self.headers.clone();
        headers.insert(
            HeaderName::from_static("prefer"),
            HeaderValue::from_static("return=representation"),
        );

        let response = self
            .http_client
            .patch(&url)
            .headers(headers) // Use modified headers
            .json(&values)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();

        // Check for success (e.g., 200 OK, 204 No Content)
        if status.is_success() {
            // Read the body as text first
            let body_text = response.text().await.map_err(|e| {
                PostgrestError::DeserializationError(format!("Failed to read response body: {}", e))
            })?;

            // If body is empty, return Null. Update might return 204 No Content.
            if body_text.trim().is_empty() {
                Ok(Value::Null)
            } else {
                // If body is not empty, try to parse it as JSON
                serde_json::from_str::<Value>(&body_text)
                    .map_err(|e| PostgrestError::DeserializationError(e.to_string()))
            }
        } else {
            // Handle non-success status codes
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            let details_result: Result<PostgrestApiErrorDetails, _> =
                serde_json::from_str(&error_text);
            match details_result {
                Ok(details) => Err(PostgrestError::ApiError { details, status }),
                Err(_) => Err(PostgrestError::UnparsedApiError {
                    message: error_text,
                    status,
                }),
            }
        }
    }

    /// データを削除
    pub async fn delete(&self) -> Result<Value, PostgrestError> {
        let url = self.build_url()?;

        // Clone headers and add the Prefer header
        let mut headers = self.headers.clone();
        headers.insert(
            HeaderName::from_static("prefer"),
            HeaderValue::from_static("return=representation"),
        );

        let response = self
            .http_client
            .delete(&url)
            .headers(headers) // Use modified headers
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();

        // Check for success (e.g., 200 OK, 204 No Content)
        if status.is_success() {
            // Read the body as text first
            let body_text = response.text().await.map_err(|e| {
                PostgrestError::DeserializationError(format!("Failed to read response body: {}", e))
            })?;

            // If body is empty, return Null. Delete often returns 204 No Content.
            if body_text.trim().is_empty() {
                Ok(Value::Null)
            } else {
                // If body is not empty, try to parse it as JSON
                serde_json::from_str::<Value>(&body_text)
                    .map_err(|e| PostgrestError::DeserializationError(e.to_string()))
            }
        } else {
            // Handle non-success status codes
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            let details_result: Result<PostgrestApiErrorDetails, _> =
                serde_json::from_str(&error_text);
            match details_result {
                Ok(details) => Err(PostgrestError::ApiError { details, status }),
                Err(_) => Err(PostgrestError::UnparsedApiError {
                    message: error_text,
                    status,
                }),
            }
        }
    }

    /// RPC関数を呼び出す (POSTリクエスト)
    pub async fn call_rpc<T: for<'de> Deserialize<'de>>(&self) -> Result<T, PostgrestError> {
        if !self.is_rpc {
            return Err(PostgrestError::InvalidParameters(
                "Client was not created for RPC. Use PostgrestClient::rpc().".to_string(),
            ));
        }
        // RPCの場合はテーブル名が関数名として扱われる
        let url = format!("{}/rest/v1/rpc/{}", self.base_url, self.table);
        let params = self.rpc_params.as_ref().ok_or_else(|| {
            PostgrestError::InvalidParameters("RPC parameters are missing.".to_string())
        })?;

        let response = self
            .http_client
            .post(&url)
            .headers(self.headers.clone())
            .json(params)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            let details_result: Result<PostgrestApiErrorDetails, _> =
                serde_json::from_str(&error_text);
            return match details_result {
                Ok(details) => Err(PostgrestError::ApiError { details, status }),
                Err(_) => Err(PostgrestError::UnparsedApiError {
                    message: error_text,
                    status,
                }),
            };
        }

        response.json::<T>().await.map_err(|e| {
            PostgrestError::DeserializationError(format!(
                "Failed to deserialize RPC response: {}",
                e
            ))
        })
    }

    // URLを構築
    fn build_url(&self) -> Result<String, PostgrestError> {
        let mut url = Url::parse(&format!("{}/rest/v1/{}", self.base_url, self.table))?;

        for (key, value) in &self.query_params {
            url.query_pairs_mut().append_pair(key, value);
        }

        Ok(url.to_string())
    }

    /// トランザクションを開始
    pub async fn begin_transaction(
        &self,
        isolation_level: Option<IsolationLevel>,
        transaction_mode: Option<TransactionMode>,
        timeout_seconds: Option<u64>,
    ) -> Result<PostgrestTransaction, PostgrestError> {
        // トランザクションオプションを構築
        let isolation = isolation_level.unwrap_or(IsolationLevel::ReadCommitted);
        let mode = transaction_mode.unwrap_or(TransactionMode::ReadWrite);

        // トランザクション開始リクエストを構築
        let mut request_body = json!({
            "isolation_level": isolation.display(),
            "mode": mode.display(),
        });

        if let Some(timeout) = timeout_seconds {
            request_body["timeout_seconds"] = json!(timeout);
        }

        // トランザクション開始APIを呼び出し
        let transaction_url = format!("{}/rpc/begin_transaction", self.base_url);

        let response = self
            .http_client
            .post(&transaction_url)
            .headers(self.headers.clone())
            .json(&request_body)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            // Transaction begin might not return standard PostgREST JSON error, treat as TransactionError
            return Err(PostgrestError::TransactionError(format!(
                "Failed to begin transaction: {} (Status: {})",
                error_text, status
            )));
        }

        #[derive(Debug, Deserialize)]
        struct TransactionResponse {
            transaction_id: String,
        }

        let response_data = response
            .json::<TransactionResponse>()
            .await
            .map_err(|e| PostgrestError::DeserializationError(e.to_string()))?;

        // トランザクションオブジェクトを作成して返す
        Ok(PostgrestTransaction::new(
            &self.base_url,
            &self.api_key,
            self.http_client.clone(),
            self.headers.clone(),
            response_data.transaction_id,
        ))
    }
}

/// トランザクションクライアント
pub struct PostgrestTransaction {
    base_url: String,
    api_key: String,
    http_client: Client,
    headers: HeaderMap,
    transaction_id: String,
    state: Arc<AtomicBool>, // トランザクションがアクティブかどうか
}

impl PostgrestTransaction {
    /// 新しいトランザクションを作成
    fn new(
        base_url: &str,
        api_key: &str,
        http_client: Client,
        headers: HeaderMap,
        transaction_id: String,
    ) -> Self {
        Self {
            base_url: base_url.to_string(),
            api_key: api_key.to_string(),
            http_client,
            headers,
            transaction_id,
            state: Arc::new(AtomicBool::new(true)), // トランザクションは初期状態でアクティブ
        }
    }

    /// トランザクション内で指定したテーブルに対するクライアントを取得
    pub fn from(&self, table: &str) -> PostgrestClient {
        // トランザクションIDをクエリパラメータとして追加するクライアントを作成
        let mut client = PostgrestClient::new(
            &self.base_url,
            &self.api_key,
            table,
            self.http_client.clone(),
        );

        // トランザクションヘッダーを設定
        for (key, value) in self.headers.iter() {
            // HeaderNameをStr形式に変換
            if let Ok(value_str) = value.to_str() {
                if let Ok(client_with_header) = PostgrestClient::new(
                    &self.base_url,
                    &self.api_key,
                    table,
                    self.http_client.clone(),
                )
                .with_header(key.as_str(), value_str)
                {
                    client = client_with_header;
                }
            }
        }

        // トランザクションIDをクエリパラメータに追加
        client
            .query_params
            .insert("transaction".to_string(), self.transaction_id.clone());

        client
    }

    /// トランザクションをコミット
    pub async fn commit(&self) -> Result<(), PostgrestError> {
        // トランザクションがアクティブかチェック
        if !self.state.load(Ordering::SeqCst) {
            return Err(PostgrestError::TransactionError(
                "Cannot commit: transaction is no longer active".to_string(),
            ));
        }

        // コミットAPIを呼び出し
        let commit_url = format!("{}/rpc/commit_transaction", self.base_url);

        let commit_body = json!({
            "transaction_id": self.transaction_id
        });

        let response = self
            .http_client
            .post(&commit_url)
            .headers(self.headers.clone())
            .json(&commit_body)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());

            // Treat transaction commit/rollback errors specifically
            return Err(PostgrestError::TransactionError(format!(
                "Failed to commit transaction: {} (Status: {})",
                error_text, status
            )));
        }

        // トランザクションを非アクティブに設定
        self.state.store(false, Ordering::SeqCst);

        Ok(())
    }

    /// トランザクションをロールバック
    pub async fn rollback(&self) -> Result<(), PostgrestError> {
        // トランザクションがアクティブかチェック
        if !self.state.load(Ordering::SeqCst) {
            return Err(PostgrestError::TransactionError(
                "Cannot rollback: transaction is no longer active".to_string(),
            ));
        }

        // ロールバックAPIを呼び出し
        let rollback_url = format!("{}/rpc/rollback_transaction", self.base_url);

        let rollback_body = json!({
            "transaction_id": self.transaction_id
        });

        let response = self
            .http_client
            .post(&rollback_url)
            .headers(self.headers.clone())
            .json(&rollback_body)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());
            return Err(PostgrestError::TransactionError(format!(
                "Failed to rollback transaction: {} (Status: {})",
                error_text, status
            )));
        }

        // トランザクションを非アクティブに設定
        self.state.store(false, Ordering::SeqCst);

        Ok(())
    }

    /// セーブポイントを作成
    pub async fn savepoint(&self, name: &str) -> Result<(), PostgrestError> {
        // トランザクションがアクティブかチェック
        if !self.state.load(Ordering::SeqCst) {
            return Err(PostgrestError::TransactionError(
                "Cannot create savepoint: transaction is no longer active".to_string(),
            ));
        }

        // セーブポイントAPIを呼び出し
        let savepoint_url = format!("{}/rpc/create_savepoint", self.base_url);

        let savepoint_body = json!({
            "transaction_id": self.transaction_id,
            "name": name
        });

        let response = self
            .http_client
            .post(&savepoint_url)
            .headers(self.headers.clone())
            .json(&savepoint_body)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());
            return Err(PostgrestError::TransactionError(format!(
                "Failed to create savepoint '{}': {} (Status: {})",
                name, error_text, status
            )));
        }
        Ok(())
    }

    /// セーブポイントにロールバック
    pub async fn rollback_to_savepoint(&self, name: &str) -> Result<(), PostgrestError> {
        // トランザクションがアクティブかチェック
        if !self.state.load(Ordering::SeqCst) {
            return Err(PostgrestError::TransactionError(
                "Cannot rollback to savepoint: transaction is no longer active".to_string(),
            ));
        }

        // セーブポイントへのロールバックAPIを呼び出し
        let rollback_url = format!("{}/rpc/rollback_to_savepoint", self.base_url);

        let rollback_body = json!({
            "transaction_id": self.transaction_id,
            "name": name
        });

        let response = self
            .http_client
            .post(&rollback_url)
            .headers(self.headers.clone())
            .json(&rollback_body)
            .send()
            .await
            .map_err(PostgrestError::NetworkError)?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());
            return Err(PostgrestError::TransactionError(format!(
                "Failed to rollback to savepoint '{}': {} (Status: {})",
                name, error_text, status
            )));
        }
        Ok(())
    }
}

// デストラクタに相当する実装(トランザクションが終了するとロールバック)
impl Drop for PostgrestTransaction {
    fn drop(&mut self) {
        // トランザクションがまだアクティブな場合は自動ロールバック
        if self.state.load(Ordering::SeqCst) {
            eprintln!("Warning: Active transaction is being dropped without commit or rollback. Performing automatic rollback.");

            // ブロッキング呼び出しが推奨されませんが、Dropコンテキストでは非同期関数を呼び出せないため
            let url = format!("{}/rest/v1/rpc/rollback_transaction", self.base_url);

            let client = Client::new();
            // Using drop to explicitly drop the future and avoid the warning
            let future = client
                .post(url)
                .headers(self.headers.clone())
                .json(&json!({ "transaction_id": self.transaction_id }))
                .send();
            std::mem::drop(future);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{body_json, header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_select() {
        let mock_server = MockServer::start().await;
        println!("Mock server started at: {}", mock_server.uri());

        // Selectクエリのモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("select", "*")) // select=* を想定
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([
                { "id": 1, "name": "Test Item 1" },
                { "id": 2, "name": "Test Item 2" }
            ])))
            .mount(&mock_server)
            .await;
        println!("Select mock set up");

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items", // テーブル名
            reqwest::Client::new(),
        );
        println!("Client created for select test");

        let result = client.select("*").execute::<serde_json::Value>().await;

        if let Err(e) = &result {
            println!("Select query failed: {:?}", e);
        }

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.len(), 2);
        assert_eq!(
            data.first()
                .and_then(|v: &Value| v.get("name"))
                .and_then(Value::as_str),
            Some("Test Item 1")
        );
        assert_eq!(
            data.first()
                .and_then(|v: &Value| v.get("id"))
                .and_then(Value::as_i64),
            Some(1)
        );
    }

    #[tokio::test]
    async fn test_rpc() {
        let mock_server = MockServer::start().await;
        println!("Mock server started at: {}", mock_server.uri());

        // RPC呼び出しのモック (POST)
        let rpc_params = json!({ "arg1": "value1", "arg2": 123 });
        Mock::given(method("POST"))
            .and(path("/rest/v1/rpc/my_rpc_function"))
            .and(body_json(&rpc_params)) // リクエストボディを検証
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "result": "success",
                "data": 456
            })))
            .mount(&mock_server)
            .await;
        println!("RPC mock set up");

        // RPC 用クライアント作成
        let client = PostgrestClient::rpc(
            &mock_server.uri(),
            "fake-key",
            "my_rpc_function", // RPC関数名
            rpc_params.clone(),
            reqwest::Client::new(),
        );
        println!("Client created for RPC test");

        // RPC呼び出し
        #[derive(Deserialize, Debug, PartialEq)]
        struct RpcResponse {
            result: String,
            data: i32,
        }

        let result = client.call_rpc::<RpcResponse>().await; // 新しいメソッドを使用

        if let Err(e) = &result {
            println!("RPC call failed: {:?}", e);
        }

        assert!(result.is_ok());
        let response_data = result.unwrap();
        assert_eq!(
            response_data,
            RpcResponse {
                result: "success".to_string(),
                data: 456
            }
        );
    }

    #[tokio::test]
    async fn test_join_queries() {
        let mock_server = MockServer::start().await;
        println!("Mock server started at: {}", mock_server.uri());

        // 結合クエリの戻り値をモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/posts"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([
                {
                    "id": 1,
                    "title": "First Post",
                    "content": "Content",
                    "comments": [
                        { "id": 1, "text": "Comment 1", "user_id": 2 },
                        { "id": 2, "text": "Comment 2", "user_id": 3 }
                    ],
                    "users": { "id": 1 }
                }
            ])))
            .mount(&mock_server)
            .await;
        println!("Join query mock set up");

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "posts",
            reqwest::Client::new(),
        );
        println!("Client created");

        let result = client
            .select("id,title,content")
            .include("comments", "post_id", Some("id,text,user_id"))
            .inner_join("users", "user_id", "id")
            .execute::<serde_json::Value>()
            .await;

        if let Err(e) = &result {
            println!("Join query failed: {:?}", e);
        }

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.len(), 1);
        assert_eq!(
            data.first()
                .and_then(|v: &Value| v.get("title"))
                .and_then(Value::as_str),
            Some("First Post")
        );
        assert_eq!(
            data.first()
                .and_then(|v: &Value| v.get("comments"))
                .and_then(Value::as_array)
                .map(|a| a.len()),
            Some(2)
        );
    }

    #[tokio::test]
    async fn test_text_search() {
        let mock_server = MockServer::start().await;

        // 全文検索のモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/articles"))
            .and(query_param("content", "fts(english).search terms"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([
                { "id": 1, "title": "Search Result", "content": "This is a search result" }
            ])))
            .mount(&mock_server)
            .await;

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "articles",
            reqwest::Client::new(),
        );

        let result = client
            .text_search("content", "search terms", Some("english"))
            .execute::<serde_json::Value>()
            .await;

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.len(), 1);
        assert_eq!(
            data.first()
                .and_then(|v: &Value| v.get("title"))
                .and_then(Value::as_str),
            Some("Search Result")
        );
    }

    #[tokio::test]
    async fn test_csv_export() {
        let mock_server = MockServer::start().await;

        // CSVエクスポートのモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/users"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(
                        "id,name,email\n1,User 1,user1@example.com\n2,User 2,user2@example.com",
                    )
                    .append_header("Content-Type", "text/csv"),
            )
            .mount(&mock_server)
            .await;

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "users",
            reqwest::Client::new(),
        );

        let result = client.export_csv().await;

        assert!(result.is_ok());
        let csv_data = result.unwrap();
        assert!(csv_data.contains("id,name,email"));
        assert!(csv_data.contains("User 1"));
        assert!(csv_data.contains("User 2"));
    }

    #[tokio::test]
    async fn test_transaction() {
        let mock_server = MockServer::start().await;
        println!("Mock server started at: {}", mock_server.uri());

        // BEGIN トランザクションのモック
        Mock::given(method("POST"))
            .and(path("/rpc/begin_transaction"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "transaction_id": "tx-12345"
            })))
            .mount(&mock_server)
            .await;
        println!("Begin transaction mock set up");

        // トランザクション内のINSERTのモック
        Mock::given(method("POST"))
            .and(path("/rest/v1/users"))
            .and(query_param("transaction", "tx-12345"))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!([{
                "id": 1,
                "name": "テストユーザー"
            }])))
            .mount(&mock_server)
            .await;
        println!("Insert mock set up");

        // トランザクション内のSELECTのモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/users"))
            .and(query_param("transaction", "tx-12345"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([{
                "id": 1,
                "name": "テストユーザー"
            }])))
            .mount(&mock_server)
            .await;
        println!("Select mock set up");

        // COMMITのモック
        Mock::given(method("POST"))
            .and(path("/rpc/commit_transaction"))
            .and(body_json(json!({
                "transaction_id": "tx-12345"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": true
            })))
            .mount(&mock_server)
            .await;
        println!("Commit mock set up");

        // テスト実行
        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "users",
            reqwest::Client::new(),
        );
        println!("Client created");

        // トランザクション開始
        let transaction = client
            .begin_transaction(
                Some(IsolationLevel::ReadCommitted),
                Some(TransactionMode::ReadWrite),
                Some(30),
            )
            .await;

        if let Err(e) = &transaction {
            println!("Transaction failed: {:?}", e);
        }

        assert!(transaction.is_ok());
        let transaction = transaction.unwrap();

        // トランザクション内で挿入
        let insert_result = transaction
            .from("users")
            .insert(json!({
                "name": "テストユーザー"
            }))
            .await;

        assert!(insert_result.is_ok());

        // トランザクション内でクエリ
        let query_result = transaction
            .from("users")
            .select("id, name")
            .execute::<serde_json::Value>()
            .await;

        assert!(query_result.is_ok());
        let users = query_result.unwrap();
        assert_eq!(
            users
                .first()
                .and_then(|v: &Value| v.get("name"))
                .and_then(Value::as_str),
            Some("テストユーザー")
        );

        // トランザクションをコミット
        let commit_result = transaction.commit().await;
        assert!(commit_result.is_ok());
    }

    #[tokio::test]
    async fn test_transaction_rollback() {
        let mock_server = MockServer::start().await;

        // BEGIN トランザクションのモック
        Mock::given(method("POST"))
            .and(path("/rpc/begin_transaction"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "transaction_id": "tx-67890"
            })))
            .mount(&mock_server)
            .await;

        // ROLLBACKのモック
        Mock::given(method("POST"))
            .and(path("/rpc/rollback_transaction"))
            .and(body_json(json!({
                "transaction_id": "tx-67890"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": true
            })))
            .mount(&mock_server)
            .await;

        // テスト実行
        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "users",
            reqwest::Client::new(),
        );

        // トランザクション開始
        let transaction = client.begin_transaction(None, None, None).await;

        assert!(transaction.is_ok());
        let transaction = transaction.unwrap();

        // トランザクションをロールバック
        let rollback_result = transaction.rollback().await;
        assert!(rollback_result.is_ok());
    }

    #[tokio::test]
    async fn test_transaction_savepoint() {
        let mock_server = MockServer::start().await;

        // BEGIN トランザクションのモック
        Mock::given(method("POST"))
            .and(path("/rpc/begin_transaction"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "transaction_id": "tx-savepoint"
            })))
            .mount(&mock_server)
            .await;

        // SAVEPOINTのモック
        Mock::given(method("POST"))
            .and(path("/rpc/create_savepoint"))
            .and(body_json(json!({
                "transaction_id": "tx-savepoint",
                "name": "sp1"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": true
            })))
            .mount(&mock_server)
            .await;

        // ROLLBACK TO SAVEPOINTのモック
        Mock::given(method("POST"))
            .and(path("/rpc/rollback_to_savepoint"))
            .and(body_json(json!({
                "transaction_id": "tx-savepoint",
                "name": "sp1"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": true
            })))
            .mount(&mock_server)
            .await;

        // COMMITのモック
        Mock::given(method("POST"))
            .and(path("/rpc/commit_transaction"))
            .and(body_json(json!({
                "transaction_id": "tx-savepoint"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": true
            })))
            .mount(&mock_server)
            .await;

        // テスト実行
        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "users",
            reqwest::Client::new(),
        );

        // トランザクション開始
        let transaction = client.begin_transaction(None, None, None).await;

        assert!(transaction.is_ok());
        let transaction = transaction.unwrap();

        // セーブポイント作成
        let savepoint_result = transaction.savepoint("sp1").await;
        assert!(savepoint_result.is_ok());

        // セーブポイントにロールバック
        let rollback_to_savepoint_result = transaction.rollback_to_savepoint("sp1").await;
        assert!(rollback_to_savepoint_result.is_ok());

        // トランザクションをコミット
        let commit_result = transaction.commit().await;
        assert!(commit_result.is_ok());
    }

    #[tokio::test]
    async fn test_jsonb_filters() {
        let mock_server = MockServer::start().await;

        let contains_value = json!({ "key": "value" });
        let contained_by_value = json!(["a", "b"]);

        // contains のモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/data"))
            .and(query_param("metadata", format!("cs.{}", contains_value)))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([{"id": 1}])))
            .mount(&mock_server)
            .await;

        // contained_by のモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/data"))
            .and(query_param("tags", format!("cd.{}", contained_by_value)))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([{"id": 2}])))
            .mount(&mock_server)
            .await;

        let _base_client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "data",
            reqwest::Client::new(),
        );

        // contains テスト
        let result_contains = PostgrestClient::new(
            // Re-create or adjust structure if needed
            &mock_server.uri(),
            "fake-key",
            "data",
            reqwest::Client::new(), // Assuming new client instance is ok for test
        )
        .contains("metadata", &contains_value)
        .unwrap() // Result from contains
        .execute::<serde_json::Value>()
        .await;
        assert!(result_contains.is_ok());
        assert_eq!(result_contains.unwrap().len(), 1);

        // contained_by テスト
        let result_contained_by = PostgrestClient::new(
            // Re-create or adjust structure if needed
            &mock_server.uri(),
            "fake-key",
            "data",
            reqwest::Client::new(), // Assuming new client instance is ok for test
        )
        .contained_by("tags", &contained_by_value)
        .unwrap()
        .execute::<serde_json::Value>()
        .await;
        assert!(result_contained_by.is_ok());
        assert_eq!(result_contained_by.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_filter_on_related_table() {
        let mock_server = MockServer::start().await;

        // Related table filter のモック
        Mock::given(method("GET"))
            .and(path("/rest/v1/posts"))
            .and(query_param("author.name", "eq.Specific Author")) // authorテーブルのnameでフィルタ
            .and(query_param("select", "title,author!inner(name)")) // select句も設定
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([
                { "title": "Post by Specific Author", "author": { "name": "Specific Author" } }
            ])))
            .mount(&mock_server)
            .await;

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "posts",
            reqwest::Client::new(),
        );

        let result = client
            .select("title,author!inner(name)") // joinを含めておく
            .eq("author.name", "Specific Author") // 関連テーブルのカラムを指定してフィルタ
            .execute::<serde_json::Value>()
            .await;

        if let Err(e) = &result {
            println!("Join query failed: {:?}", e);
        }

        assert!(result.is_ok(), "Request failed: {:?}", result.err());
        let data = result.unwrap();
        assert_eq!(data.len(), 1);
        let post = data
            .first()
            .expect("Post should exist in related table test");
        assert_eq!(
            post.get("title").and_then(Value::as_str),
            Some("Post by Specific Author")
        );
        let author_obj: Option<&Value> = post.get("author");
        let name_val = author_obj
            .and_then(|a: &Value| a.get("name"))
            .and_then(Value::as_str);
        assert_eq!(name_val, Some("Specific Author"));
    }

    #[tokio::test]
    async fn test_insert() {
        let mock_server = MockServer::start().await;
        println!(
            "Mock server started for insert test at: {}",
            mock_server.uri()
        );

        let insert_data = json!({ "name": "New Item", "value": 10 });
        let expected_response = json!([{ "id": 3, "name": "New Item", "value": 10 }]);

        Mock::given(method("POST"))
            .and(path("/rest/v1/items"))
            .and(header("apikey", "fake-key"))
            .and(header("content-type", "application/json"))
            .and(header("Prefer", "return=representation"))
            .and(body_json(&insert_data))
            .respond_with(ResponseTemplate::new(201).set_body_json(&expected_response))
            .mount(&mock_server)
            .await;
        println!("Insert mock set up");

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        println!("Client created for insert test");

        let result = client.insert(&insert_data).await;

        if let Err(e) = &result {
            println!("Insert query failed: {:?}", e);
        }

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data, expected_response);
    }

    #[tokio::test]
    async fn test_update() {
        let mock_server = MockServer::start().await;
        println!(
            "Mock server started for update test at: {}",
            mock_server.uri()
        );

        let update_data = json!({ "value": 20 });
        let expected_response = json!([{ "id": 1, "name": "Updated Item", "value": 20 }]);

        Mock::given(method("PATCH"))
            .and(path("/rest/v1/items"))
            .and(query_param("id", "eq.1"))
            .and(header("apikey", "fake-key"))
            .and(header("content-type", "application/json"))
            .and(header("Prefer", "return=representation"))
            .and(body_json(&update_data))
            .respond_with(ResponseTemplate::new(200).set_body_json(&expected_response))
            .mount(&mock_server)
            .await;
        println!("Update mock set up");

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        println!("Client created for update test");

        let result = client.eq("id", "1").update(&update_data).await;

        if let Err(e) = &result {
            println!("Update query failed: {:?}", e);
        }

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data, expected_response);
    }

    #[tokio::test]
    async fn test_delete() {
        let mock_server = MockServer::start().await;
        println!(
            "Mock server started for delete test at: {}",
            mock_server.uri()
        );

        let expected_response = json!([{ "id": 1, "name": "Deleted Item", "value": 10 }]);

        Mock::given(method("DELETE"))
            .and(path("/rest/v1/items"))
            .and(query_param("id", "eq.1"))
            .and(header("apikey", "fake-key"))
            .and(header("content-type", "application/json"))
            .and(header("Prefer", "return=representation"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&expected_response))
            .mount(&mock_server)
            .await;
        println!("Delete mock set up");

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        println!("Client created for delete test");

        let result = client.eq("id", "1").delete().await;

        if let Err(e) = &result {
            println!("Delete query failed: {:?}", e);
        }

        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data, expected_response);
    }

    #[tokio::test]
    async fn test_filters() {
        let mock_server = MockServer::start().await;

        // Mock for gt filter
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("id", "gt.10"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 11, "name": "Item 11" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for like filter
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("name", "like.*test*"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 1, "name": "test item" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for in_list filter
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("status", "in.(active,pending)"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 5, "status": "active" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for gte
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("value", "gte.50"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 3, "value": 50 }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for lt
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("id", "lt.5"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 4, "name": "Item 4" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for lte
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("value", "lte.100"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 7, "value": 100 }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for ilike
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("name", "ilike.*CASE*"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 8, "name": "Case Test" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for not eq
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("status", "not.eq.archived"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 9, "status": "active" }])),
            )
            .mount(&mock_server)
            .await;

        let base_uri = mock_server.uri();
        let api_key = "fake-key";
        let table_name = "items";

        // Test gt
        let client_gt =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_gt = client_gt.gt("id", "10").execute::<Value>().await;
        assert!(result_gt.is_ok(), "GT filter failed: {:?}", result_gt.err());
        assert_eq!(result_gt.unwrap().len(), 1);

        // Test like
        let client_like =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_like = client_like.like("name", "*test*").execute::<Value>().await;
        assert!(
            result_like.is_ok(),
            "LIKE filter failed: {:?}",
            result_like.err()
        );
        assert_eq!(result_like.unwrap().len(), 1);

        // Test in_list
        let client_in =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_in = client_in
            .in_list("status", &["active", "pending"])
            .execute::<Value>()
            .await;
        assert!(result_in.is_ok(), "IN filter failed: {:?}", result_in.err());
        assert_eq!(result_in.unwrap().len(), 1);

        // Test gte
        let client_gte =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_gte = client_gte.gte("value", "50").execute::<Value>().await;
        assert!(
            result_gte.is_ok(),
            "GTE filter failed: {:?}",
            result_gte.err()
        );
        assert_eq!(result_gte.unwrap().len(), 1);

        // Test lt
        let client_lt =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_lt = client_lt.lt("id", "5").execute::<Value>().await;
        assert!(result_lt.is_ok(), "LT filter failed: {:?}", result_lt.err());
        assert_eq!(result_lt.unwrap().len(), 1);

        // Test lte
        let client_lte =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_lte = client_lte.lte("value", "100").execute::<Value>().await;
        assert!(
            result_lte.is_ok(),
            "LTE filter failed: {:?}",
            result_lte.err()
        );
        assert_eq!(result_lte.unwrap().len(), 1);

        // Test ilike
        let client_ilike =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_ilike = client_ilike
            .ilike("name", "*CASE*")
            .execute::<Value>()
            .await;
        assert!(
            result_ilike.is_ok(),
            "ILIKE filter failed: {:?}",
            result_ilike.err()
        );
        assert_eq!(result_ilike.unwrap().len(), 1);

        // Test not
        let client_not =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_not = client_not
            .not("status", "eq.archived")
            .execute::<Value>()
            .await;
        assert!(
            result_not.is_ok(),
            "NOT filter failed: {:?}",
            result_not.err()
        );
        assert_eq!(result_not.unwrap().len(), 1);
    }

    #[tokio::test]
    async fn test_modifiers() {
        let mock_server = MockServer::start().await;

        // Mock for ignore_rls
        Mock::given(method("GET"))
            .and(path("/rest/v1/protected_items"))
            .and(header("apikey", "fake-key"))
            .and(header("x-supabase-admin-role", "service_role")) // Expect admin role header
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 1, "data": "secret" }])),
            ) // Example response
            .mount(&mock_server)
            .await;

        // Mock for order
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("order", "name.desc"))
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 1, "name": "Zebra" }])),
            )
            .mount(&mock_server)
            .await;

        // Mock for limit
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("limit", "5"))
            .and(header("apikey", "fake-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([{}, {}, {}, {}, {}])))
            .mount(&mock_server)
            .await;

        // Mock for offset
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("offset", "10"))
            .and(header("apikey", "fake-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!([{ "id": 11 }])))
            .mount(&mock_server)
            .await;

        // Mock for limit and offset
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(query_param("limit", "2"))
            .and(query_param("offset", "3")) // Added matcher for offset
            .and(header("apikey", "fake-key"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!([{ "id": 4 }, { "id": 5 }])),
            )
            .mount(&mock_server)
            .await;

        let client = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "protected_items",
            reqwest::Client::new(),
        );

        // Test ignore_rls
        let result_rls = client.ignore_rls().execute::<Value>().await;
        assert!(result_rls.is_ok());
        assert_eq!(result_rls.unwrap().len(), 1);

        // Test order
        let client_order = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        let result_order = client_order
            .order("name", SortOrder::Descending)
            .execute::<Value>()
            .await;
        assert!(
            result_order.is_ok(),
            "Order modifier failed: {:?}",
            result_order.err()
        );
        assert_eq!(result_order.unwrap().len(), 1);

        // Test limit
        let client_limit = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        let result_limit = client_limit.limit(5).execute::<Value>().await;
        assert!(
            result_limit.is_ok(),
            "Limit modifier failed: {:?}",
            result_limit.err()
        );
        assert_eq!(result_limit.unwrap().len(), 5);

        // Test offset
        let client_offset = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        let result_offset = client_offset.offset(10).execute::<Value>().await;
        assert!(
            result_offset.is_ok(),
            "Offset modifier failed: {:?}",
            result_offset.err()
        );
        assert_eq!(result_offset.unwrap().len(), 1); // Based on mock

        // Test limit and offset
        let client_limit_offset = PostgrestClient::new(
            &mock_server.uri(),
            "fake-key",
            "items",
            reqwest::Client::new(),
        );
        let result_limit_offset = client_limit_offset
            .limit(2)
            .offset(3)
            .execute::<Value>()
            .await;
        assert!(
            result_limit_offset.is_ok(),
            "Limit/Offset modifier failed: {:?}",
            result_limit_offset.err()
        );
        assert_eq!(result_limit_offset.unwrap().len(), 2);

        // TODO: Add test for count() when execute() can return count information
    }

    #[tokio::test]
    async fn test_error_handling() {
        let mock_server = MockServer::start().await;
        let base_uri = mock_server.uri();
        let api_key = "fake-key";
        let table_name = "items";

        // Mock for 401 Unauthorized (select with bad key)
        Mock::given(method("GET"))
            .and(path("/rest/v1/items"))
            .and(header("apikey", "invalid-key")) // Expect invalid key
            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
                "message": "Invalid API key"
            })))
            .mount(&mock_server)
            .await;

        // Mock for 400 Bad Request (insert missing required field)
        let insert_bad_data = json!({ "value": 10 }); // Missing 'name'
        Mock::given(method("POST"))
            .and(path("/rest/v1/items"))
            .and(header("apikey", api_key))
            .and(header("content-type", "application/json"))
            .and(header("prefer", "return=representation"))
            .and(body_json(&insert_bad_data))
            .respond_with(ResponseTemplate::new(400).set_body_json(json!({
                "code": "23502",
                "message": "null value in column \"name\" violates not-null constraint",
                "details": null,
                "hint": null
            })))
            .mount(&mock_server)
            .await;

        // Mock for 500 Internal Server Error (select returning plain text)
        Mock::given(method("GET"))
            .and(path("/rest/v1/server_error"))
            .and(header("apikey", api_key))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&mock_server)
            .await;

        // Test 401 Unauthorized on select
        let client_401 =
            PostgrestClient::new(&base_uri, "invalid-key", table_name, reqwest::Client::new());
        let result_401 = client_401.select("*").execute::<Value>().await;
        assert!(result_401.is_err());
        match result_401.err().unwrap() {
            PostgrestError::ApiError { details, status } => {
                assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
                assert_eq!(details.message, Some("Invalid API key".to_string()));
            }
            PostgrestError::UnparsedApiError { message, status } => {
                // Handle case where details parsing might fail
                assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
                assert!(message.contains("Invalid API key"));
            }
            e => panic!("Expected ApiError or UnparsedApiError for 401, got {:?}", e),
        }

        // Test 400 Bad Request on insert
        let client_400 =
            PostgrestClient::new(&base_uri, api_key, table_name, reqwest::Client::new());
        let result_400 = client_400.insert(&insert_bad_data).await;
        assert!(result_400.is_err());
        match result_400.err().unwrap() {
            PostgrestError::ApiError { details, status } => {
                assert_eq!(status, reqwest::StatusCode::BAD_REQUEST);
                assert_eq!(details.code, Some("23502".to_string()));
                assert!(details
                    .message
                    .unwrap()
                    .contains("violates not-null constraint"));
            }
            e => panic!("Expected ApiError for 400, got {:?}", e),
        }

        // Test 500 Internal Server Error on select
        let client_500 =
            PostgrestClient::new(&base_uri, api_key, "server_error", reqwest::Client::new());
        let result_500 = client_500.select("*").execute::<Value>().await;
        assert!(result_500.is_err());
        match result_500.err().unwrap() {
            PostgrestError::UnparsedApiError { message, status } => {
                assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR);
                assert_eq!(message, "Internal Server Error");
            }
            e => panic!("Expected UnparsedApiError for 500, got {:?}", e),
        }
    }
}