supabase_rs 0.7.0

Lightweight Rust client for Supabase REST and GraphQL
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
#![cfg(feature = "rpc")]

//! # Remote Procedure Call (RPC) Support
//!
//! This module provides support for calling PostgreSQL functions via PostgREST's RPC endpoints.
//! It enables executing stored procedures, functions, and custom SQL operations with full
//! parameter support and result filtering capabilities.
//!
//! ## 🏗️ Architecture
//!
//! The RPC implementation is built around several key components:
//! - **[`RpcBuilder`]**: Fluent API for constructing and executing RPC calls
//! - **Parameter Handling**: Type-safe serialization of function arguments
//! - **Header Management**: Schema-aware headers for multi-schema support
//! - **Result Filtering**: Post-execution filtering of returned data sets
//!
//! ## 🎯 Design Philosophy
//!
//! - **Consistent API**: Follows the same fluent pattern as other SDK operations
//! - **Type Safety**: Leverages Rust's type system for compile-time validation
//! - **Performance**: Efficient serialization and HTTP request handling
//! - **Flexibility**: Supports all PostgREST RPC features including filtering
//!
//! ## 📖 Usage Examples
//!
//! ### Basic RPC Call
//! ```rust,no_run
//! use supabase_rs::SupabaseClient;
//! use serde_json::json;
//!
//! # async fn example() -> Result<(), String> {
//! let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
//!
//! // Call a function that returns a set of records
//! let results = client.rpc("get_active_users", json!({ "active": true }))
//!     .execute()
//!     .await?;
//!
//! // Call a function that returns a single value
//! let count = client.rpc("count_users", json!({}))
//!     .execute_single()
//!     .await?;
//!
//! // Call a void function
//! client.rpc("cleanup_old_sessions", json!({ "days": 30 }))
//!     .execute_void()
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ### RPC with Filtering
//! ```rust,no_run
//! # use supabase_rs::SupabaseClient;
//! # use serde_json::json;
//! # async fn example() -> Result<(), String> {
//! # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
//! // Filter results after function execution
//! let filtered = client.rpc("get_users", json!({}))
//!     .eq("status", "active")
//!     .gte("age", "18")
//!     .order("name", true)
//!     .limit(10)
//!     .execute()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use serde::Serialize;
use serde_json::{json, Value};

use crate::errors::Result;
use crate::query::Query;
use crate::request::headers::HeadersTypes;
use crate::request::Headers;
use crate::success::handle_response;
use crate::SupabaseClient;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::Response;

/// Builder for constructing and executing RPC calls.
///
/// `RpcBuilder` provides a fluent interface for calling PostgreSQL functions via PostgREST's
/// RPC endpoints. It supports parameter passing, result filtering, and multiple execution modes.
///
/// # Execution Modes
///
/// RPC functions can return different types of results:
/// - **Set of records**: Use `.execute()` for array results
/// - **Single value/object**: Use `.execute_single()` for scalar/row results
/// - **Void**: Use `.execute_void()` for functions with no return value
///
/// # Filtering Support
///
/// PostgREST allows filtering the results of set-returning functions using standard query
/// parameters. The `RpcBuilder` reuses the existing `Query` infrastructure to provide
/// the same filtering capabilities as regular table queries.
///
/// # Examples
///
/// ## Basic Usage
/// ```rust,no_run
/// use supabase_rs::SupabaseClient;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), String> {
/// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
/// let results = client.rpc("my_function", json!({ "param": "value" }))
///     .execute()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// ## With Filtering
/// ```rust,no_run
/// # use supabase_rs::SupabaseClient;
/// # use serde_json::json;
/// # async fn example() -> Result<(), String> {
/// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
/// let active_users = client.rpc("get_users", json!({}))
///     .eq("status", "active")
///     .limit(10)
///     .execute()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct RpcBuilder {
    /// The Supabase client instance for executing requests
    client: SupabaseClient,
    /// Name of the RPC function to call
    function_name: String,
    /// Serialized function parameters
    params: Value,
    /// Query object for filtering results (for set-returning functions)
    query: Query,
}

impl RpcBuilder {
    /// Creates a new `RpcBuilder` for calling a PostgreSQL function.
    ///
    /// This constructor is typically called by [`SupabaseClient::rpc`] and not used directly.
    /// It immediately serializes the parameters to `Value` to simplify the builder's type signature.
    ///
    /// # Arguments
    ///
    /// * `client` - The Supabase client instance
    /// * `function_name` - Name of the PostgreSQL function to call
    /// * `params` - Function arguments (must implement `Serialize`)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use supabase_rs::{SupabaseClient, rpc::RpcBuilder};
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), String> {
    /// let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
    /// let builder = RpcBuilder::new(client, "my_function", json!({ "param": "value" }));
    /// # Ok(())
    /// # }
    /// ```
    pub fn new<T: Serialize>(client: SupabaseClient, function_name: &str, params: T) -> Self {
        Self {
            client,
            function_name: function_name.to_string(),
            params: serde_json::to_value(params).unwrap_or(json!({})),
            query: Query::new(),
        }
    }

    /// Executes the RPC call expecting an array of results (SETOF records).
    ///
    /// This method is for functions that return multiple rows, such as:
    /// - `RETURNS SETOF table_name`
    /// - `RETURNS TABLE(...)`
    /// - `RETURNS SETOF record`
    ///
    /// The results can be filtered using the query builder methods before execution.
    ///
    /// # Returns
    ///
    /// Returns `Result<Vec<Value>>` where:
    /// - `Ok(Vec<Value>)` - Array of JSON objects representing the returned rows
    /// - `Err(ErrorTypes)` - Request failed (network, authentication, function not found, etc.)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use supabase_rs::SupabaseClient;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), String> {
    /// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
    /// let users = client.rpc("get_active_users", json!({ "active": true }))
    ///     .execute()
    ///     .await?;
    ///
    /// for user in users {
    ///     println!("User: {}", user["name"]);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute(self) -> Result<Vec<Value>> {
        self.execute_internal(false).await
    }

    /// Executes the RPC call expecting a single result (scalar or single row).
    ///
    /// This method is for functions that return a single value, such as:
    /// - `RETURNS integer`, `RETURNS text`, etc. (scalar)
    /// - `RETURNS table_name` (single row)
    /// - `RETURNS record` (single composite)
    ///
    /// The method sets appropriate headers to request single-object response format
    /// from PostgREST when applicable.
    ///
    /// # Returns
    ///
    /// Returns `Result<Value>` where:
    /// - `Ok(Value)` - The single returned value (could be scalar, object, or null)
    /// - `Err(ErrorTypes)` - Request failed or returned multiple rows
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use supabase_rs::SupabaseClient;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), String> {
    /// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
    /// // Scalar return
    /// let count = client.rpc("count_users", json!({}))
    ///     .execute_single()
    ///     .await?;
    /// let count_num = count.as_i64().unwrap();
    ///
    /// // Single row return
    /// let user = client.rpc("get_user_by_id", json!({ "id": 123 }))
    ///     .execute_single()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute_single(self) -> Result<Value> {
        let results = self.execute_internal(true).await?;
        if results.len() == 1 {
            Ok(results.into_iter().next().unwrap())
        } else {
            Err(crate::errors::ErrorTypes::UnknownError)
        }
    }

    /// Executes the RPC call expecting no return value (void function).
    ///
    /// This method is for functions that return `void` or have no return value.
    /// It expects a 204 No Content response from PostgREST.
    ///
    /// # Returns
    ///
    /// Returns `Result<()>` where:
    /// - `Ok(())` - Function executed successfully
    /// - `Err(ErrorTypes)` - Request failed or returned unexpected content
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use supabase_rs::SupabaseClient;
    /// use serde_json::json;
    ///
    /// # async fn example() -> Result<(), String> {
    /// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
    /// client.rpc("cleanup_old_records", json!({ "days": 30 }))
    ///     .execute_void()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute_void(self) -> Result<()> {
        let response = self.execute_request(true).await?;
        let status = response.status();

        if status == 204 {
            Ok(())
        } else {
            // For non-204 responses, treat as error
            let _error_body = response.text().await.unwrap_or_default();
            Err(crate::errors::ErrorTypes::UnknownError)
        }
    }

    /// Internal implementation shared by execute and execute_single.
    async fn execute_internal(self, single: bool) -> Result<Vec<Value>> {
        let response = self.execute_request(single).await?;
        let status = response.status();

        if !status.is_success() {
            // For non-success responses, treat as error
            let _error_body = response.text().await.unwrap_or_default();
            return Err(crate::errors::ErrorTypes::UnknownError);
        }

        // Parse response
        handle_response(response)
            .await
            .map_err(|_e| crate::errors::ErrorTypes::UnknownError)
    }

    /// Internal method to execute the HTTP request.
    async fn execute_request(self, single: bool) -> Result<Response> {
        // Build endpoint URL
        let url = self.client.rpc_endpoint(&self.function_name);

        // Build query string from filters
        let query_string = self.query.build();
        let endpoint = if query_string.is_empty() {
            url
        } else {
            format!("{}?{}", url, query_string)
        };

        // create headers with default values
        let mut headers = Headers::with_defaults(&self.client.api_key, &self.client.api_key);

        // Content-Type is always application/json for RPC
        headers.insert(HeadersTypes::ContentType.as_str(), "application/json");

        // Handle schema headers
        if self.client.schema != "public" {
            headers.insert(HeadersTypes::ContentProfile.as_str(), &self.client.schema);
            headers.insert(HeadersTypes::AcceptProfile.as_str(), &self.client.schema);
        }

        // Handle single object response if requested
        if single {
            headers.insert("Accept", "application/vnd.pgrst.object+json");
        }

        // convert headers to HeaderMap
        let mut header_map = HeaderMap::new();
        for (key, value) in headers.get_headers() {
            header_map.insert(
                HeaderName::from_bytes(key.as_bytes())
                    .map_err(|_| crate::errors::ErrorTypes::UnknownError)?,
                HeaderValue::from_str(&value)
                    .map_err(|_| crate::errors::ErrorTypes::UnknownError)?,
            );
        }

        // send the request
        let response = self
            .client
            .client
            .post(&endpoint)
            .headers(header_map)
            .json(&self.params)
            .send()
            .await
            .map_err(crate::errors::ErrorTypes::ReqwestError)?;

        Ok(response)
    }
}

// Filter methods - reuse Query functionality
impl RpcBuilder {
    /// Adds an equality filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column equals the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The value to match (will be stringified)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use supabase_rs::SupabaseClient;
    /// # use serde_json::json;
    /// # async fn example() -> Result<(), String> {
    /// # let client = SupabaseClient::new("url".to_string(), "key".to_string()).unwrap();
    /// let results = client.rpc("get_users", json!({}))
    ///     .eq("status", "active")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn eq(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("eq.{value}"));
        self
    }

    /// Adds a not-equals filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to exclude rows where
    /// the specified column equals the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The value to exclude (will be stringified)
    pub fn neq(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("neq.{value}"));
        self
    }

    /// Adds a greater-than filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column is greater than the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The minimum value (exclusive)
    pub fn gt(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("gt.{value}"));
        self
    }

    /// Adds a less-than filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column is less than the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The maximum value (exclusive)
    pub fn lt(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("lt.{value}"));
        self
    }

    /// Adds a greater-than-or-equals filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column is greater than or equal to the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The minimum value (inclusive)
    pub fn gte(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("gte.{value}"));
        self
    }

    /// Adds a less-than-or-equals filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column is less than or equal to the given value.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `value` - The maximum value (inclusive)
    pub fn lte(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("lte.{value}"));
        self
    }

    /// Adds an "in" filter to the RPC results.
    ///
    /// Filters the results of a set-returning function to only include rows where
    /// the specified column matches any of the given values.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to filter on
    /// * `values` - Array of values to match
    pub fn in_<T>(mut self, column: &str, values: &[T]) -> Self
    where
        T: ToString,
    {
        let list = values
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(",");
        self.query.add_param(column, &format!("in.({})", list));
        self
    }

    /// Adds a full-text search filter to the RPC results.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to perform the text search on.
    /// * `value` - The value to search for within the column.
    pub fn text_search(mut self, column: &str, value: &str) -> Self {
        self.query.add_param(column, &format!("fts.{value}"));
        self
    }

    /// Adds a limit to the number of rows returned by the RPC results.
    ///
    /// # Arguments
    ///
    /// * `limit` - The maximum number of rows to return.
    pub fn limit(mut self, limit: usize) -> Self {
        self.query.add_param("limit", &limit.to_string());
        self
    }

    /// Adds an offset to the RPC results to skip a specified number of rows.
    ///
    /// # Arguments
    ///
    /// * `offset` - The number of rows to skip from the beginning of the result set.
    pub fn offset(mut self, offset: usize) -> Self {
        self.query.add_param("offset", &offset.to_string());
        self
    }

    /// Adds a range to the RPC results for pagination using PostgREST range syntax.
    ///
    /// # Arguments
    ///
    /// * `from` - The starting index (0-based) of the range.
    /// * `to` - The ending index (inclusive) of the range.
    pub fn range(mut self, from: usize, to: usize) -> Self {
        self.query.set_range(from, to);
        self
    }

    /// Adds sorting to the RPC results.
    ///
    /// # Arguments
    ///
    /// * `column` - The column name to sort by.
    /// * `ascending` - `true` for ascending order, `false` for descending.
    pub fn order(mut self, column: &str, ascending: bool) -> Self {
        let order_value: &str = if ascending { "asc" } else { "desc" };
        self.query
            .add_param("order", &format!("{column}.{order_value}"));
        self
    }

    /// Adds a parameter to count the exact number of rows that match the RPC results.
    pub fn count(mut self) -> Self {
        self.query.add_param("count", "exact");
        self
    }

    /// Selects specific columns from the RPC results.
    ///
    /// # Arguments
    ///
    /// * `columns` - Vector of column names to select.
    pub fn columns(mut self, columns: Vec<&str>) -> Self {
        let columns_str: String = columns.join(",");
        self.query.add_param("select", &columns_str);
        self
    }
}