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
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
# Remote Procedure Call (RPC) Support

## Overview

The RPC (Remote Procedure Call) module provides comprehensive support for calling PostgreSQL functions via PostgREST's RPC endpoints. This enables executing stored procedures, functions, and custom SQL operations with full parameter support and result filtering capabilities.

## 🎯 Implementation Summary

### Architecture
The RPC implementation integrates seamlessly into the existing `supabase_rs` architecture:

1. **`RpcBuilder`**: A fluent builder pattern that parallels the existing `QueryBuilder` for consistent developer experience
2. **`SupabaseClient` Extension**: Added `rpc()` method as the main entry point
3. **Reused Components**: Leverages existing `Query` infrastructure for filtering and `Headers` for schema support
4. **Feature-Gated**: RPC functionality is behind the `rpc` feature flag for optional inclusion

### Key Features
- **Full Parameter Support**: Type-safe serialization of function arguments using `serde`
- **Multiple Execution Modes**: Support for void, scalar, single row, and set-returning functions
- **Result Filtering**: Post-execution filtering of returned data sets using standard PostgREST query parameters
- **Schema Support**: Multi-schema support via `Content-Profile` and `Accept-Profile` headers
- **Type Generation**: Automatic generation of argument structs for RPC functions
- **Comprehensive Testing**: Integration tests covering all execution modes and edge cases

### 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

## 🔧 Feature Flags

RPC functionality is feature-gated. To enable it, add the `rpc` feature to your `Cargo.toml`:

```toml
[dependencies]
supabase_rs = { version = "0.5.1", features = ["rpc"] }
```

### Available Features
| Feature | Description | Default |
|---------|-------------|---------|
| `rpc` | Enables RPC functionality | ❌ Disabled |
| `storage` | File operations with Supabase Storage | ❌ Disabled |
| `rustls` | Use rustls instead of OpenSSL for TLS | ❌ Disabled |
| `nightly` | Experimental GraphQL support | ❌ Disabled |

### Default Features
The default feature set includes `native_tls` and `nightly`. To use RPC without nightly features:

```toml
supabase_rs = { version = "0.5.1", features = ["rpc", "native_tls"], default-features = false }
```

## 📚 API Reference

### `SupabaseClient` Extension

#### `rpc()`
```rust
pub fn rpc<T>(&self, function_name: &str, params: T) -> crate::rpc::RpcBuilder
where
    T: serde::Serialize,
```

**Description**: Creates a new `RpcBuilder` for calling a PostgreSQL function.

**Parameters**:
- `function_name`: Name of the PostgreSQL function to call
- `params`: Function arguments (must implement `Serialize`)

**Returns**: `RpcBuilder` for further chaining and execution

**Example**:
```rust
let builder = client.rpc("my_function", json!({ "param": "value" }));
```

### `RpcBuilder` Methods

#### Execution Methods

##### `execute()`
```rust
pub async fn execute(self) -> Result<Vec<Value>>
```

**Description**: Executes the RPC call expecting an array of results (SETOF records).

**Returns**: `Result<Vec<Value>>` - Array of JSON objects representing returned rows

**Use Case**: Functions that return multiple rows:
- `RETURNS SETOF table_name`
- `RETURNS TABLE(...)`
- `RETURNS SETOF record`

##### `execute_single()`
```rust
pub async fn execute_single(self) -> Result<Value>
```

**Description**: Executes the RPC call expecting a single result (scalar or single row).

**Returns**: `Result<Value>` - Single returned value (scalar, object, or null)

**Use Case**: Functions that return a single value:
- `RETURNS integer`, `RETURNS text`, etc. (scalar)
- `RETURNS table_name` (single row)
- `RETURNS record` (single composite)

##### `execute_void()`
```rust
pub async fn execute_void(self) -> Result<()>
```

**Description**: Executes the RPC call expecting no return value (void function).

**Returns**: `Result<()>` - Success if function executed without error

**Use Case**: Functions that return `void` or have no return value.

#### Filter Methods

All filter methods return `Self` for method chaining.

##### Equality Filters
```rust
pub fn eq(self, column: &str, value: &str) -> Self
pub fn neq(self, column: &str, value: &str) -> Self
```

**Description**: Filter results where column equals/does not equal value.

##### Comparison Filters
```rust
pub fn gt(self, column: &str, value: &str) -> Self
pub fn lt(self, column: &str, value: &str) -> Self
pub fn gte(self, column: &str, value: &str) -> Self
pub fn lte(self, column: &str, value: &str) -> Self
```

**Description**: Filter results using greater-than, less-than comparisons.

##### Set Operations
```rust
pub fn in_<T>(self, column: &str, values: &[T]) -> Self
where
    T: ToString,
```

**Description**: Filter results where column matches any of the given values.

##### Text Search
```rust
pub fn text_search(self, column: &str, value: &str) -> Self
```

**Description**: Full-text search on column.

##### Pagination & Sorting
```rust
pub fn limit(self, limit: usize) -> Self
pub fn offset(self, offset: usize) -> Self
pub fn range(self, from: usize, to: usize) -> Self
pub fn order(self, column: &str, ascending: bool) -> Self
```

**Description**: Control result set size, position, and ordering.

##### Column Selection
```rust
pub fn columns(self, columns: Vec<&str>) -> Self
```

**Description**: Select specific columns from results.

##### Counting
```rust
pub fn count(self) -> Self
```

**Description**: Request exact row count with results.

## 🚀 Usage Examples

### Basic RPC Calls

#### Scalar Function
```rust
use supabase_rs::SupabaseClient;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = SupabaseClient::new(
        std::env::var("SUPABASE_URL")?,
        std::env::var("SUPABASE_KEY")?,
    )?;

    // Call a function that returns a single value
    let count = client.rpc("count_users", json!({}))
        .execute_single()
        .await?;
    
    println!("User count: {}", count.as_i64().unwrap());
    Ok(())
}
```

#### Set-Returning Function
```rust
// Get all active users
let users = client.rpc("get_active_users", json!({ "active": true }))
    .execute()
    .await?;

for user in users {
    println!("User: {} ({})", user["name"], user["email"]);
}
```

#### Void Function
```rust
// Clean up old sessions
client.rpc("cleanup_old_sessions", json!({ "days": 30 }))
    .execute_void()
    .await?;
```

### Advanced Filtering

#### Filtering Results
```rust
// Get active users over 18, sorted by name, limited to 10
let active_adults = client.rpc("get_users", json!({}))
    .eq("status", "active")
    .gte("age", "18")
    .order("name", true)
    .limit(10)
    .execute()
    .await?;
```

#### Complex Filtering
```rust
// Get posts in specific categories with text search
let posts = client.rpc("search_posts", json!({ "query": "rust" }))
    .in_("category", &["tech", "programming", "rust"])
    .text_search("content", "async await")
    .eq("published", "true")
    .order("created_at", false)
    .range(0, 24)  // Pagination: first 25 items
    .execute()
    .await?;
```

#### Column Selection
```rust
// Select only specific columns for efficiency
let user_summaries = client.rpc("get_users", json!({}))
    .columns(vec!["id", "name", "email"])
    .limit(50)
    .execute()
    .await?;
```

### Query Builder: Joins & Nested Selects

For REST table queries (not RPC), use `select_with_joins` to embed related resources:

```rust
use supabase_rs::query::JoinSpec;

// Left join: sections with nested instruments
let sections = client
    .from("orchestral_sections")
    .select_with_joins(&["id", "name"], &[JoinSpec::new("instruments", &["id", "name"])])
    .execute()
    .await?;

// Inner join: filter parent rows by nested match
let filtered = client
    .from("orchestral_sections")
    .select_with_joins(
        &["id", "name"],
        &[JoinSpec::new("instruments", &["id", "name"]).inner()],
    )
    .eq("instruments.name", "flute")
    .execute()
    .await?;
```

### Type-Safe Parameters

#### Using Structs
```rust
use serde::Serialize;

#[derive(Serialize)]
struct CreateUserParams {
    name: String,
    email: String,
    age: u32,
}

let params = CreateUserParams {
    name: "Alice".to_string(),
    email: "alice@example.com".to_string(),
    age: 28,
};

let user_id = client.rpc("create_user", params)
    .execute_single()
    .await?;
```

#### Using Generated Types
```rust
// Assuming types were generated with type_gen
use supabase_types::rpc::CreateUserArgs;

let args = CreateUserArgs {
    name: "Bob".to_string(),
    email: "bob@example.com".to_string(),
    age: 32,
};

let result = client.rpc("create_user", args)
    .execute_single()
    .await?;
```

### Schema Support

#### Non-Public Schema
```rust
// Connect to a custom schema
let client = SupabaseClient::new(
    std::env::var("SUPABASE_URL")?,
    std::env::var("SUPABASE_KEY")?,
)?
.schema("custom_schema");

// Call function in custom schema
let result = client.rpc("custom_function", json!({}))
    .execute()
    .await?;
```

## 🔧 Type Generation Guide

### Overview
The type generation system automatically creates Rust structs for RPC function arguments, providing type safety and IDE support.

### Generating Types

#### Basic Generation
```rust
use supabase_rs::type_gen::generate_supabase_types;

#[tokio::main]
async fn main() {
    generate_supabase_types(
        "postgres",          // Database username
        "password",          // Database password
        true,                // Singularize struct names
        &["users", "posts"], // Tables to include (empty for all)
    ).await;
}
```

#### With Schema Support
```rust
use supabase_rs::type_gen::generate_supabase_types_with_schema;

#[tokio::main]
async fn main() {
    generate_supabase_types_with_schema(
        "postgres",
        "password",
        true,
        &["users", "posts"],
        "public",  // Schema name
    ).await;
}
```

### Generated Output

#### RPC Argument Structs
For a function `create_user(name text, age integer)`, the generator creates:

```rust
pub mod rpc {
    use serde::Serialize;

    #[derive(Debug, Serialize, Clone)]
    pub struct CreateUserArgs {
        pub name: String,
        pub age: i32,
    }
}
```

#### Usage with Generated Types
```rust
use supabase_types::rpc::CreateUserArgs;

let args = CreateUserArgs {
    name: "Alice".to_string(),
    age: 28,
};

let result = client.rpc("create_user", args)
    .execute_single()
    .await?;
```

### Type Mapping

PostgreSQL types are mapped to Rust types as follows:

| PostgreSQL Type | Rust Type | Notes |
|----------------|-----------|-------|
| `integer` | `i32` | |
| `bigint` | `i64` | |
| `smallint` | `i16` | |
| `text`, `varchar`, `char` | `String` | |
| `boolean` | `bool` | |
| `real`, `double precision` | `f64` | |
| `numeric`, `decimal` | `Decimal` | Requires `rust_decimal` |
| `timestamp without time zone` | `NaiveDateTime` | Requires `chrono` |
| `timestamp with time zone` | `DateTime<Utc>` | Requires `chrono` |
| `date` | `NaiveDate` | Requires `chrono` |
| `uuid` | `Uuid` | Requires `uuid` |
| `json`, `jsonb` | `Value` | Requires `serde_json` |

### Integration with Existing Code

The generator automatically:
1. Creates `src/supabase_types.rs` with all generated types
2. Adds `pub mod supabase_types;` to `src/lib.rs` if not present
3. Organizes RPC argument structs in a `rpc` module

## 🧪 Testing Guide

### Test Setup

#### Environment Configuration
Create a `.env` file for testing:
```env
SUPABASE_URL=https://your-test-project.supabase.co
SUPABASE_KEY=your-test-key
SUPABASE_RS_NO_NIGHTLY_MSG=true
```

#### Database Setup
Run the RPC test setup script:
```sql
-- src/tests/setup_rpc.sql
-- This creates test functions for RPC testing
```

### Running Tests

#### All Tests
```bash
cargo test --features rpc
```

#### RPC-Specific Tests
```bash
cargo test test_rpc --features rpc
cargo test test_rpc_single --features rpc
cargo test test_rpc_void --features rpc
cargo test test_rpc_with_filters --features rpc
cargo test test_rpc_type_generation --features rpc
```

#### With Output
```bash
cargo test --features rpc -- --nocapture
```

### Test Categories

#### 1. Basic RPC Functionality
Tests basic RPC calls with different return types:
- Scalar functions (`test_echo`)
- Set-returning functions (`test_get_test_rows`)
- Void functions (`test_void_func`)

#### 2. Filter Integration
Tests RPC with filter methods:
- Equality filters (`.eq()`)
- Range filters (`.gte()`, `.lte()`)
- Pagination (`.limit()`, `.offset()`)
- Sorting (`.order()`)

#### 3. Type Generation
Tests type generation integration:
- Parameter struct generation
- Default parameter handling
- Type mapping validation

#### 4. Error Handling
Tests error scenarios:
- Non-existent functions
- Invalid parameters
- Schema errors
- Network failures

### Writing Custom Tests

#### Example Test Structure
```rust
#[tokio::test]
async fn test_custom_rpc() -> Result<(), String> {
    let client = create_test_client();
    
    // Test scalar function
    let result = client.rpc("test_add_numbers", json!({"a": 5, "b": 3}))
        .execute_single()
        .await
        .map_err(|e| format!("RPC failed: {:?}", e))?;
    
    assert_eq!(result.as_i64().unwrap(), 8);
    Ok(())
}
```

#### Test Client Creation
```rust
fn create_test_client() -> SupabaseClient {
    SupabaseClient::new(
        std::env::var("SUPABASE_URL").expect("SUPABASE_URL required"),
        std::env::var("SUPABASE_KEY").expect("SUPABASE_KEY required"),
    ).expect("Failed to create client")
}
```

## 🚚 Migration Guide

### For Existing Users

#### From Previous Versions
RPC support is additive and non-breaking. Existing code continues to work without modification.

#### Enabling RPC
1. Update `Cargo.toml`:
   ```toml
   supabase_rs = { version = "0.5.1", features = ["rpc"] }
   ```

2. Update imports if using generated types:
   ```rust
   // Before (if using custom types)
   use my_types::UserParams;
   
   // After (using generated types)
   use supabase_types::rpc::CreateUserArgs;
   ```

#### Code Migration Examples

##### Before (Manual JSON)
```rust
let params = json!({
    "name": "Alice",
    "email": "alice@example.com",
    "age": 28
});

// Manual HTTP call
let response = client.client.post("/rest/v1/rpc/create_user")
    .json(&params)
    .send()
    .await?;
```

##### After (Using RPC Builder)
```rust
use supabase_types::rpc::CreateUserArgs;

let params = CreateUserArgs {
    name: "Alice".to_string(),
    email: "alice@example.com".to_string(),
    age: 28,
};

let result = client.rpc("create_user", params)
    .execute_single()
    .await?;
```

### Breaking Changes

#### None
The RPC implementation introduces no breaking changes to existing APIs.

### Deprecations

#### None
No APIs have been deprecated.

## ⚠️ Known Limitations

### Current Limitations

#### 1. Parameter Mode Support
- **Status**: Partial
- **Details**: Only `IN` and `INOUT` parameters are fully supported. `OUT` parameters are excluded from generated structs as they are not passed as arguments.
- **Workaround**: For functions with `OUT` parameters, use manual JSON parameter construction.

#### 2. Default Parameter Detection
- **Status**: Limited
- **Details**: The type generator cannot reliably detect default parameter values from `information_schema.parameters`.
- **Workaround**: Manually handle default parameters in application code.

#### 3. Complex Return Types
- **Status**: Basic support
- **Details**: Complex PostgreSQL types (arrays, composites, domains) are mapped to `String` or `Value`.
- **Workaround**: Use `serde_json::Value` and manual parsing for complex types.

#### 4. Transaction Support
- **Status**: Not supported
- **Details**: RPC calls cannot be executed within database transactions via the current API.
- **Workaround**: Use PostgREST's transaction support directly or implement at the application level.

#### 5. Performance Considerations
- **Status**: Optimized for common cases
- **Details**: Large result sets may impact memory usage. Streaming responses are not supported.
- **Workaround**: Use pagination (`.limit()`, `.range()`) and filtering to manage result sizes.

#### 6. Error Detail Propagation
- **Status**: Basic
- **Details**: PostgreSQL error details may be lost in HTTP error responses.
- **Workaround**: Check PostgREST logs or implement custom error handling for detailed diagnostics.

### Future Improvements

#### Planned Enhancements
1. **Streaming Support**: Add support for streaming large result sets
2. **Enhanced Type Mapping**: Better support for PostgreSQL arrays and custom types
3. **Transaction Integration**: Support for transactional RPC calls
4. **Batch Operations**: Execute multiple RPC calls in a single request
5. **Advanced Parameter Handling**: Support for variadic functions and polymorphic types

#### Community Contributions
These limitations represent opportunities for community contributions. Refer to the [Contributing Guide](CONTRIBUTING.md) for information on how to help improve the RPC implementation.

## 📋 Summary

The RPC implementation in `supabase_rs` provides a comprehensive, type-safe interface for calling PostgreSQL functions via PostgREST. Key features include:

- **Fluent API**: Consistent with existing SDK patterns
- **Type Safety**: Compile-time validation through generated types
- **Flexible Execution**: Support for void, scalar, single row, and set-returning functions
- **Advanced Filtering**: Post-execution filtering using standard PostgREST query parameters
- **Schema Support**: Multi-schema support through proper header management
- **Comprehensive Testing**: Full test coverage across all execution modes

### Getting Started Checklist
- [ ] Enable the `rpc` feature in `Cargo.toml`
- [ ] Set up environment variables for your Supabase project
- [ ] Generate types for your database functions (optional but recommended)
- [ ] Start calling RPC functions using the fluent builder API

### Additional Resources
- [Supabase Documentation]https://supabase.io/docs - Official Supabase documentation
- [PostgREST API Reference]https://postgrest.org/en/stable/api.html - Detailed API reference
- [GitHub Repository]https://github.com/floris-xlx/supabase_rs - Source code and issue tracking
- [CONTRIBUTING.md]CONTRIBUTING.md - Contribution guidelines for the project

### Support
For issues, feature requests, or questions:
1. Check the [GitHub Issues]https://github.com/floris-xlx/supabase_rs/issues for existing discussions
2. Review the [RPC Design Documents]RPC_DESIGN_V2.md for implementation details
3. Submit a new issue with detailed reproduction steps if needed

---

*Documentation last updated: January 2026*
*RPC Implementation Version: 1.0*
*Supabase RS Version: 0.5.1*