Struct Storage

Source
pub struct Storage { /* private fields */ }
Expand description

Storage client for file operations

Implementations§

Source§

impl Storage

Source

pub fn new( config: Arc<SupabaseConfig>, http_client: Arc<HttpClient>, ) -> Result<Self>

Create a new Storage instance

Source

pub async fn list_buckets(&self) -> Result<Vec<Bucket>>

List all storage buckets

Source

pub async fn get_bucket(&self, bucket_id: &str) -> Result<Bucket>

Get bucket information

Source

pub async fn create_bucket( &self, id: &str, name: &str, public: bool, ) -> Result<Bucket>

Create a new storage bucket

Source

pub async fn update_bucket(&self, id: &str, public: Option<bool>) -> Result<()>

Update bucket settings

Source

pub async fn delete_bucket(&self, id: &str) -> Result<()>

Delete a storage bucket

Source

pub async fn list( &self, bucket_id: &str, path: Option<&str>, ) -> Result<Vec<FileObject>>

List files in a bucket

Source

pub async fn upload( &self, bucket_id: &str, path: &str, file_body: Bytes, options: Option<FileOptions>, ) -> Result<UploadResponse>

Upload a file from bytes

Source

pub async fn upload_file<P: AsRef<Path>>( &self, bucket_id: &str, path: &str, file_path: P, options: Option<FileOptions>, ) -> Result<UploadResponse>

Upload a file from local filesystem (Native only, requires tokio)

Source

pub async fn download(&self, bucket_id: &str, path: &str) -> Result<Bytes>

Download a file

Source

pub async fn remove(&self, bucket_id: &str, paths: &[&str]) -> Result<()>

Delete a file

Source

pub async fn move( &self, bucket_id: &str, from_path: &str, to_path: &str, ) -> Result<()>

Move a file

Source

pub async fn copy( &self, bucket_id: &str, from_path: &str, to_path: &str, ) -> Result<()>

Copy a file

Source

pub fn get_public_url(&self, bucket_id: &str, path: &str) -> String

Get public URL for a file

Source

pub async fn create_signed_url( &self, bucket_id: &str, path: &str, expires_in: u32, transform: Option<TransformOptions>, ) -> Result<String>

Get signed URL for private file access

Source

pub fn get_public_url_transformed( &self, bucket_id: &str, path: &str, options: TransformOptions, ) -> Result<String>

Get transformed image URL

Source

pub async fn start_resumable_upload( &self, bucket_id: &str, path: &str, total_size: u64, config: Option<ResumableUploadConfig>, options: Option<FileOptions>, ) -> Result<UploadSession>

Start a resumable upload session for large files

§Examples
use supabase::storage::{ResumableUploadConfig, FileOptions};

let config = ResumableUploadConfig::default();
let file_opts = FileOptions {
    content_type: Some("video/mp4".to_string()),
    ..Default::default()
};

let session = storage.start_resumable_upload(
    "videos",
    "my-large-video.mp4",
    1024 * 1024 * 100, // 100MB
    Some(config),
    Some(file_opts)
).await?;

println!("Started upload session: {}", session.upload_id);
Source

pub async fn upload_chunk( &self, session: &UploadSession, part_number: u32, chunk_data: Bytes, ) -> Result<UploadedPart>

Upload a chunk for resumable upload

§Examples
use bytes::Bytes;

let chunk_data = Bytes::from(vec![0u8; 1024 * 1024]); // 1MB chunk

let part = storage.upload_chunk(
    session,
    1, // part number
    chunk_data
).await?;

println!("Uploaded part: {} etag: {}", part.part_number, part.etag);
Source

pub async fn complete_resumable_upload( &self, session: &UploadSession, ) -> Result<UploadResponse>

Complete a resumable upload after all chunks are uploaded

§Examples
// ... upload all chunks and collect parts ...

let response = storage.complete_resumable_upload(&session).await?;
println!("Upload completed: {}", response.key);
Source

pub async fn upload_large_file<P: AsRef<Path>>( &self, bucket_id: &str, path: &str, file_path: P, config: Option<ResumableUploadConfig>, options: Option<FileOptions>, progress_callback: Option<UploadProgressCallback>, ) -> Result<UploadResponse>

Upload a large file with automatic chunking and resume capability

This is a high-level method that handles the entire resumable upload process.

§Examples
use supabase::storage::{ResumableUploadConfig, FileOptions};
use std::sync::Arc;

let config = ResumableUploadConfig::default();
let file_opts = FileOptions {
    content_type: Some("video/mp4".to_string()),
    ..Default::default()
};

let progress_callback = Arc::new(|uploaded: u64, total: u64| {
    println!("Progress: {:.1}%", (uploaded as f64 / total as f64) * 100.0);
});

let response = storage.upload_large_file(
    "videos",
    "my-large-video.mp4",
    "/path/to/large-video.mp4",
    Some(config),
    Some(file_opts),
    Some(progress_callback)
).await?;

println!("Upload completed: {}", response.key);
Source

pub async fn get_upload_session(&self, upload_id: &str) -> Result<UploadSession>

Get resumable upload session status

Source

pub async fn cancel_upload_session(&self, upload_id: &str) -> Result<()>

Cancel a resumable upload session

Source

pub async fn update_file_metadata( &self, bucket_id: &str, path: &str, metadata: &FileMetadata, ) -> Result<()>

Update file metadata with tags and custom metadata

§Examples
use std::collections::HashMap;
use supabase::storage::FileMetadata;

let mut tags = HashMap::new();
tags.insert("category".to_string(), "documents".to_string());
tags.insert("project".to_string(), "web-app".to_string());

let mut custom_data = HashMap::new();
custom_data.insert("author".to_string(), serde_json::Value::String("john_doe".to_string()));
custom_data.insert("version".to_string(), serde_json::Value::Number(serde_json::Number::from(1)));

let metadata = FileMetadata {
    tags: Some(tags),
    custom_metadata: Some(custom_data),
    description: Some("Project documentation".to_string()),
    category: Some("documents".to_string()),
    searchable_content: Some("documentation project guide".to_string()),
};

storage.update_file_metadata("documents", "guide.pdf", &metadata).await?;
Source

pub async fn search_files( &self, bucket_id: &str, search_options: &SearchOptions, ) -> Result<Vec<FileObject>>

Search files by metadata

§Examples
use std::collections::HashMap;
use supabase::storage::SearchOptions;

let mut tag_filter = HashMap::new();
tag_filter.insert("category".to_string(), "documents".to_string());

let search_options = SearchOptions {
    tags: Some(tag_filter),
    category: Some("documents".to_string()),
    content_search: Some("project guide".to_string()),
    limit: Some(20),
    offset: Some(0),
};

let files = storage.search_files("documents", &search_options).await?;
println!("Found {} files", files.len());
Source

pub async fn create_policy(&self, policy: &StoragePolicy) -> Result<()>

Create a storage policy for Row Level Security (RLS)

§Examples
use supabase::storage::{StoragePolicy, PolicyOperation};

let policy = StoragePolicy {
    name: "user_files_policy".to_string(),
    bucket_id: "user-files".to_string(),
    operation: PolicyOperation::Select,
    definition: "auth.uid()::text = (storage.foldername(name))[1]".to_string(),
    check: None,
};

storage.create_policy(&policy).await?;
Source

pub async fn update_policy(&self, policy: &StoragePolicy) -> Result<()>

Update an existing storage policy

§Examples
use supabase::storage::{StoragePolicy, PolicyOperation};

let updated_policy = StoragePolicy {
    name: "user_files_policy".to_string(),
    bucket_id: "user-files".to_string(),
    operation: PolicyOperation::All,
    definition: "auth.uid()::text = (storage.foldername(name))[1] OR auth.role() = 'admin'".to_string(),
    check: Some("auth.uid() IS NOT NULL".to_string()),
};

storage.update_policy(&updated_policy).await?;
Source

pub async fn delete_policy( &self, bucket_id: &str, policy_name: &str, ) -> Result<()>

Delete a storage policy

§Examples
storage.delete_policy("user-files", "user_files_policy").await?;
Source

pub async fn list_policies(&self, bucket_id: &str) -> Result<Vec<StoragePolicy>>

List all storage policies for a bucket

§Examples
let policies = storage.list_policies("user-files").await?;
println!("Found {} policies", policies.len());
Source

pub async fn test_policy_access( &self, bucket_id: &str, object_path: &str, operation: PolicyOperation, user_id: &str, ) -> Result<bool>

Test if a user can access a file based on current policies

§Examples
use supabase::storage::PolicyOperation;

let can_access = storage.test_policy_access(
    "user-files",
    "user123/document.pdf",
    PolicyOperation::Select,
    "user123"
).await?;

if can_access {
    println!("User can access the file");
} else {
    println!("Access denied");
}
Source

pub fn generate_policy_template( &self, bucket_id: &str, policy_name: &str, template: PolicyTemplate, ) -> StoragePolicy

Generate a policy template for common use cases

§Examples
use supabase::storage::PolicyTemplate;

let policy = storage.generate_policy_template(
    "user-files",
    "user_files_access",
    PolicyTemplate::UserFolderAccess
);

println!("Generated policy: {:?}", policy);

Trait Implementations§

Source§

impl Clone for Storage

Source§

fn clone(&self) -> Storage

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Storage

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,