Crate supabase

Source
Expand description

ยงSupabase Rust Client Library

A comprehensive, production-ready Rust client library for Supabase with full cross-platform support (native + WASM).

ยง๐Ÿš€ Version 0.3.1 - Enhanced Authentication

This release introduces a comprehensive authentication system with OAuth providers, phone authentication, magic links, anonymous sign-in, and real-time auth state events, plus advanced cross-platform error handling with detailed context and retry logic.

ยงโœจ Features

  • ๐Ÿ” Authentication: Complete auth system with OAuth, phone, magic links, anonymous sign-in
  • ๐Ÿ—„๏ธ Database: Advanced PostgreSQL operations with joins, transactions, logical operators
  • ๐Ÿ“ Storage: File upload, download, and management
  • โšก Realtime: WebSocket subscriptions for live data
  • ๐Ÿ”ง Functions: Edge Functions invocation
  • ๐ŸŒ Cross-Platform: Native (Tokio) and WASM support
  • ๐Ÿ›ก๏ธ Type Safe: Full type safety with comprehensive error handling
  • ๐Ÿ“š Well Documented: Extensive documentation with examples

ยง๐Ÿš€ Quick Start

use supabase::auth::AuthEvent;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: i32,
    name: String,
    email: String,
}

    let client = supabase::Client::new("https://example.supabase.co", "valid-key")?;

    // Set up authentication event listener
    let _handle = client.auth().on_auth_state_change(|event, session| {
        match event {
            AuthEvent::SignedIn => println!("User signed in!"),
            AuthEvent::SignedOut => println!("User signed out!"),
            AuthEvent::TokenRefreshed => println!("Token refreshed!"),
            _ => {}
        }
    });

    // Sign up a new user
    let auth_response = client.auth()
        .sign_up_with_email_and_password("user@example.com", "secure_password")
        .await?;

    println!("User created: {:?}", auth_response.user);

    // Complex database query with JOIN
    let posts_with_users: Vec<serde_json::Value> = client.database()
        .from("posts")
        .select("title, content, users(name, email)")
        .inner_join("users", "name, email")
        .eq("published", "true")
        .execute()
        .await?;

    println!("Found {} posts with users", posts_with_users.len());

    Ok(())
}

ยง๐Ÿ” Authentication Examples

ยงOAuth Providers

use supabase::auth::{OAuthProvider, OAuthOptions};

// Google OAuth
let options = OAuthOptions {
    redirect_to: Some("https://myapp.com/callback".to_string()),
    scopes: Some(vec!["email".to_string(), "profile".to_string()]),
    ..Default::default()
};

let response = client.auth()
    .sign_in_with_oauth(OAuthProvider::Google, Some(options))
    .await?;

println!("Redirect to: {}", response.url);

ยงPhone Authentication

// Sign up with phone
let auth_response = client.auth()
    .sign_up_with_phone("+1234567890", "secure_password", None)
    .await?;

// Verify OTP
let verified = client.auth()
    .verify_otp("+1234567890", "123456", "sms")
    .await?;
// Send magic link
client.auth()
    .sign_in_with_magic_link(
        "user@example.com",
        Some("https://myapp.com/callback".to_string()),
        None
    )
    .await?;

println!("Magic link sent!");

ยงAnonymous Sign-in

// Create anonymous user
let auth_response = client.auth()
    .sign_in_anonymously(None)
    .await?;

if let Some(user) = auth_response.user {
    println!("Anonymous user created: {}", user.id);
}

ยง๐Ÿ—„๏ธ Advanced Database Operations

ยงComplex Queries

  let posts: Vec<Value> = client.database()
      .from("posts")
      .select("*")
      .and(|q| q.eq("published", "true").gte("created_at", "2024-01-01"))
      .or(|q| q.eq("author", "admin").eq("status", "featured"))
      .not(|q| q.eq("deleted", "true"))
      .order("created_at", OrderDirection::Descending)
      .limit(10)
      .execute()
      .await?;

ยงQuery Joins

  let posts_with_authors: Vec<Value> = client.database()
      .from("posts")
      .select("id, title, users(name, email)")
      .inner_join_as("users", "name", "author_name")
      .execute()
      .await?;

ยงTransactions

  let result: Vec<User> = client.database()
      .begin_transaction()
      .insert("users", json!({"name": "John", "email": "john@example.com"}))
      .update("profiles", json!({"updated_at": "now()"}), "user_id = $1")
      .commit()
      .await?;

ยง๐ŸŒ Cross-Platform Support

This library works seamlessly across different platforms:

ยงNative Applications (Tokio)

// Full async/await support with Tokio runtime
#[tokio::main]
async fn main() -> supabase::Result<()> {
    let client = supabase::Client::new("https://example.supabase.co", "your-anon-key")?;
    // All operations available
    Ok(())
}

ยงWebAssembly (WASM)

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub async fn initialize_supabase() -> Result<(), JsValue> {
    let client = supabase::Client::new("https://example.supabase.co", "your-anon-key")
        .map_err(|e| JsValue::from_str(&e.to_string()))?;

    // Enhanced error handling with platform-specific context
    match client.database().from("users").select("*").execute::<serde_json::Value>().await {
        Ok(users) => web_sys::console::log_1(&format!("Found {} users", users.len()).into()),
        Err(e) => {
            let error_msg = format!("Database error: {}", e);
            web_sys::console::error_1(&error_msg.clone().into());
            return Err(JsValue::from_str(&error_msg));
        }
    }
    Ok(())
}

ยง๐Ÿ›ก๏ธ Enhanced Error Handling

v0.3.1 introduces comprehensive error context with platform-specific information:

use supabase::error::{ErrorContext, PlatformContext};

match client.auth().sign_in_with_email_and_password("user@example.com", "password").await {
    Ok(response) => println!("Success!"),
    Err(e) => {
        // Check if error is retryable
        if e.is_retryable() {
            if let Some(retry_after) = e.retry_after() {
                println!("Retry after {} seconds", retry_after);
            }
        }

        // Get platform-specific context
        if let Some(context) = e.context() {
            match &context.platform {
                Some(PlatformContext::Wasm { user_agent, available_apis, .. }) => {
                    println!("WASM environment: {:?}", user_agent);
                    println!("Available APIs: {:?}", available_apis);
                }
                Some(PlatformContext::Native { os_info, .. }) => {
                    println!("Native environment: {:?}", os_info);
                }
                None => {}
            }
        }

        // Get HTTP status code if available
        if let Some(status) = e.status_code() {
            println!("HTTP Status: {}", status);
        }
    }
}

ยง๐Ÿ“š Module Organization

  • auth - Authentication operations and OAuth providers
  • database - PostgreSQL database operations with advanced querying
  • storage - File upload, download, and management
  • realtime - WebSocket subscriptions for live data
  • functions - Edge Functions invocation
  • error - Enhanced error types with platform-specific context
  • types - Common type definitions and configurations

ยง๐Ÿ”ง Configuration

use supabase::{Client, types::{SupabaseConfig, HttpConfig, AuthConfig}};
use std::time::Duration;

let client = Client::new("YOUR_URL", "YOUR_KEY")?;

ยง๐Ÿšง Version History

  • v0.3.1: Enhanced Authentication with OAuth, phone auth, magic links, anonymous sign-in, improved error context
  • v0.3.0: Advanced Database Operations with joins, transactions, logical operators, C FFI foundation
  • v0.2.0: Production-ready client with comprehensive testing and documentation

ยง๐Ÿ“„ License

This project is licensed under the MIT License.

Re-exportsยง

pub use client::Client;
pub use error::Error;
pub use error::Result;
pub use auth::Auth;
pub use database::Database;
pub use realtime::Realtime;
pub use storage::Storage;
pub use functions::Functions;

Modulesยง

auth
Authentication module for Supabase client
client
Main Supabase client
database
Database module for Supabase REST API
error
Error handling for the Supabase client
ffi
Enhanced C FFI (Foreign Function Interface) bindings
functions
Edge Functions module for Supabase
performance
Performance optimization module
prelude
Commonly used types and traits for convenient importing
realtime
Realtime module for Supabase WebSocket subscriptions
session
Advanced Session Management for Supabase
storage
Storage module for Supabase file operations
types
Common types and data structures for Supabase operations