Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Home

Initializing

Initializing a new client is pretty straightforward. Find your project url and public key from the admin panel and pass it into your client initialization function.

supabase-csharp is heavily dependent on Models deriving from BaseModel. To interact with the API, one must have the associated model (see example) specified.

Leverage Table, PrimaryKey, and Column attributes to specify names of classes/properties that are different from their C# Versions.


var url = Environment.GetEnvironmentVariable("SUPABASE_URL");
var key = Environment.GetEnvironmentVariable("SUPABASE_KEY");

var options = new Supabase.SupabaseOptions
{
    AutoConnectRealtime = true
};

var supabase = new Supabase.Client(url, key, options);
await supabase.InitializeAsync();

Fetch data

Performs vertical filtering with SELECT.

  • LINQ expressions do not currently support parsing embedded resource columns. For these cases, string will need to be used.
  • When using string Column Names to select, they must match names in database, not names specified on model properties.
  • Additional information on modeling + querying Joins and Inner Joins can be found in the postgrest-csharp README
  • By default, Supabase projects will return a maximum of 1,000 rows. This setting can be changed in Project API Settings. It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use range() queries to paginate through your data.
  • From() can be combined with Modifiers
  • From() can be combined with Filters
  • If using the Supabase hosted platform apikey is technically a reserved keyword, since the API gateway will pluck it out for authentication. It should be avoided as a column name.

// Given the following Model (City.cs)
[Table("cities")]
class City : BaseModel
{
    [PrimaryKey("id")]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; }

    [Column("country_id")]
    public int CountryId { get; set; }

    //... etc.
}

// A result can be fetched like so.
var result = await supabase.From<City>().Get();
var cities = result.Models

Insert data

Performs an INSERT into the table.


[Table("cities")]
class City : BaseModel
{
    [PrimaryKey("id", false)]
    public int Id { get; set; }

    [Column("name")]
    public string Name { get; set; }

    [Column("country_id")]
    public int CountryId { get; set; }
}

var model = new City
{
  Name = "The Shire",
  CountryId = 554
};

await supabase.From<City>().Insert(model);

Update data

Performs an UPDATE on the table.

  • Update() is typically called using a model as an argument or from a hydrated model.

var update = await supabase
  .From<City>()
  .Where(x => x.Name == "Auckland")
  .Set(x => x.Name, "Middle Earth")
  .Update();

Upsert data

Performs an UPSERT into the table.

  • Primary keys should be included in the data payload in order for an update to work correctly.
  • Primary keys must be natural, not surrogate. There are however, workarounds for surrogate primary keys.

var model = new City
{
  Id = 554,
  Name = "Middle Earth"
};

await supabase.From<City>().Upsert(model);

Delete data

Performs a DELETE on the table.

  • Delete() should always be combined with Filters to target the item(s) you wish to delete.

await supabase
  .From<City>()
  .Where(x => x.Id == 342)
  .Delete();

Call a Postgres function

You can call stored procedures as a "Remote Procedure Call".

That's a fancy way of saying that you can put some logic into your database then call it from anywhere. It's especially useful when the logic rarely changes - like password resets and updates.


await supabase.Rpc("hello_world", null);

Using filters

Filters allow you to only return rows that match certain conditions.

Filters can be used on Select(), Update(), and Delete() queries.

Note: LINQ expressions do not currently support parsing embedded resource columns. For these cases, string will need to be used.


var result = await supabase.From<City>()
      .Select(x => new object[] { x.Name, x.CountryId })
      .Where(x => x.Name == "The Shire")
      .Single();

Column is equal to a value

Finds all rows whose value on the stated column exactly matches the specified value.


var result = await supabase.From<City>()
  .Where(x => x.Name == "Bali")
  .Get();

Column is not equal to a value

Finds all rows whose value on the stated column doesn't match the specified value.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Where(x => x.Name != "Bali")
  .Get();

Column is greater than a value

Finds all rows whose value on the stated column is greater than the specified value.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Where(x => x.CountryId > 250)
  .Get();

Column is greater than or equal to a value

Finds all rows whose value on the stated column is greater than or equal to the specified value.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Where(x => x.CountryId >= 250)
  .Get();

Column is less than a value

Finds all rows whose value on the stated column is less than the specified value.


var result = await supabase.From<City>()
  .Select("name, country_id")
  .Where(x => x.CountryId < 250)
  .Get();

Column is less than or equal to a value

Finds all rows whose value on the stated column is less than or equal to the specified value.


var result = await supabase.From<City>()
  .Where(x => x.CountryId <= 250)
  .Get();

Column matches a pattern

Finds all rows whose value in the stated column matches the supplied pattern (case sensitive).


var result = await supabase.From<City>()
  .Filter(x => x.Name, Operator.Like, "%la%")
  .Get();

Column matches a case-insensitive pattern

Finds all rows whose value in the stated column matches the supplied pattern (case insensitive).


await supabase.From<City>()
  .Filter(x => x.Name, Operator.ILike, "%la%")
  .Get();

Column is a value

A check for exact equality (null, true, false), finds all rows whose value on the stated column exactly match the specified value.


var result = await supabase.From<City>()
  .Where(x => x.Name == null
  .Get();

Column is in an array

Finds all rows whose value on the stated column is found on the specified values.


var result = await supabase.From<City>()
  .Filter(x => x.Name, Operator.In, new List<object> { "Rio de Janiero", "San Francisco" })
  .Get();

Column contains every element in a value


var result = await supabase.From<City>()
  .Filter(x => x.MainExports, Operator.Contains, new List<object> { "oil", "fish" })
  .Get();

Contained by value


var result = await supabase.From<City>()
  .Filter(x => x.MainExports, Operator.ContainedIn, new List<object> { "oil", "fish" })
  .Get();

Match a string

Finds all rows whose tsvector value on the stated column matches to_tsquery(query).

Match an associated value

  • Finds a model given a class (useful when hydrating models and correlating with database)
  • Finds all rows whose columns match the specified Dictionary<string, string> object.

var city = new City
{
    Id = 224,
    Name = "Atlanta"
};

var model = supabase.From<City>().Match(city).Single();

Don't match the filter

Finds all rows which doesn't satisfy the filter.


var result = await supabase.From<Country>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Where(x => x.Name != "Paris")
  .Get();

Match at least one filter

Finds all rows satisfying at least one of the filters.


var result = await supabase.From<Country>()
  .Where(x => x.Id == 20 || x.Id == 30)
  .Get();

Using modifiers

Filters work on the row level—they allow you to return rows that only match certain conditions without changing the shape of the rows. Modifiers are everything that don't fit that definition—allowing you to change the format of the response (e.g., setting a limit or offset).

Order the results

Orders the result with the specified column.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Order(x => x.Id, Ordering.Descending)
  .Get();

Limit the number of rows returned

Limits the result with the specified count.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Limit(10)
  .Get();

Limit the query to a range

Limits the result to rows within the specified range, inclusive.


var result = await supabase.From<City>()
  .Select("name, country_id")
  .Range(0, 3)
  .Get();

Retrieve one row of data

Retrieves only one row from the result. Result must be one row (e.g. using limit), otherwise this will result in an error.


var result = await supabase.From<City>()
  .Select(x => new object[] { x.Name, x.CountryId })
  .Single();

Create a new user

Creates a new user.

  • By default, the user needs to verify their email address before logging in. To turn this off, disable Confirm email in your project.
  • Confirm email determines if users need to confirm their email address after signing up.
    • If Confirm email is enabled, a user is returned but session is null.
    • If Confirm email is disabled, both a user and a session are returned.
  • When the user confirms their email address, they are redirected to the SITE_URL by default. You can modify your SITE_URL or add additional redirect URLs in your project.
  • If SignUp() is called for an existing confirmed user:
    • When both Confirm email and Confirm phone (even when phone provider is disabled) are enabled in your project, an obfuscated/fake user object is returned.
    • When either Confirm email or Confirm phone (even when phone provider is disabled) is disabled, the error message, User already registered is returned.

var session = await supabase.Auth.SignUp(email, password);

Listen to auth events

Receive a notification every time an auth event happens.

  • Types of auth events: AuthState.SignedIn, AuthState.SignedOut, AuthState.UserUpdated, AuthState.PasswordRecovery, AuthState.TokenRefreshed

supabase.Auth.AddStateChangedListener((sender, changed) =>
{
    switch (changed)
    {
        case AuthState.SignedIn:
            break;
        case AuthState.SignedOut:
            break;
        case AuthState.UserUpdated:
            break;
        case AuthState.PasswordRecovery:
            break;
        case AuthState.TokenRefreshed:
            break;
    }
});

Sign in a user

Log in an existing user using email or phone number with password.

  • Requires either an email and password or a phone number and password.

var session = await supabase.Auth.SignIn(email, password);

Sign in a user through OTP

  • Requires either an email or phone number.
  • This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number.
  • If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP.
  • If you're using phone, you can configure whether you want the user to receive a OTP.
  • The magic link's destination URL is determined by the SITE_URL. You can modify the SITE_URL or add additional redirect urls in your project.

var options = new SignInOptions { RedirectTo = "http://myredirect.example" };
var didSendMagicLink = await supabase.Auth.SendMagicLink("joseph@supabase.io", options);

Sign in a user through OAuth

Signs the user in using third party OAuth providers.

  • This method is used for signing in using a third-party provider.
  • Supabase supports many different third-party providers.

var signInUrl = supabase.Auth.SignIn(Provider.Github);

Sign out a user

Signs out the current user, if there is a logged in user.

  • In order to use the SignOut() method, the user needs to be signed in first.

await supabase.Auth.SignOut();

Verify and log in through OTP

  • The VerifyOtp method takes in different verification types. If a phone number is used, the type can either be sms or phone_change. If an email address is used, the type can be one of the following: signup, magiclink, recovery, invite or email_change.
  • The verification type used should be determined based on the corresponding auth method called before VerifyOtp to sign up / sign-in a user.

var session = await supabase.Auth.VerifyOTP("+13334445555", TOKEN, MobileOtpType.SMS);

Retrieve a session

Returns the session data, if there is an active session.


var session = supabase.Auth.CurrentSession;

Retrieve a user

Returns the user data, if there is a logged in user.


var user = supabase.Auth.CurrentUser;

Update a user

Updates user data, if there is a logged in user.

  • In order to use the UpdateUser() method, the user needs to be signed in first.
  • By Default, email updates sends a confirmation link to both the user's current and new email. To only send a confirmation link to the user's new email, disable Secure email change in your project's email auth provider settings.

var attrs = new UserAttributes { Email = "new-email@example.com" };
var response = await supabase.Auth.Update(attrs);

Invokes a Supabase Edge Function.

Invokes a Supabase Function. See the guide for details on writing Functions.

  • Requires an Authorization header.
  • Invoke params generally match the Fetch API spec.

var options = new InvokeFunctionOptions
{
    Headers = new Dictionary<string, string> {{ "Authorization", "Bearer 1234" }},
    Body = new Dictionary<string, object> { { "foo", "bar" } }
};

await supabase.Functions.Invoke("hello", options: options);

Subscribe to channel

Subscribe to realtime changes in your database.

  • Realtime is disabled by default for new Projects for better database performance and security. You can turn it on by managing replication.
  • If you want to receive the "previous" data for updates and deletes, you will need to set REPLICA IDENTITY to FULL, like this: ALTER TABLE your_table REPLICA IDENTITY FULL;

class CursorBroadcast : BaseBroadcast
{
    [JsonProperty("cursorX")]
    public int CursorX {get; set;}

    [JsonProperty("cursorY")]
    public int CursorY {get; set;}
}

var channel = supabase.Realtime.Channel("any");
var broadcast = channel.Register<CursorBroadcast>();
broadcast.AddBroadcastEventHandler((sender, baseBroadcast) =>
{
    var response = broadcast.Current();
});

await channel.Subscribe();

// Send a broadcast
await broadcast.Send("cursor", new CursorBroadcast { CursorX = 123, CursorY = 456 });

Unsubscribe from a channel

Unsubscribes and removes Realtime channel from Realtime client.

  • Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed.

var channel = await supabase.From<City>().On(ChannelEventType.All, (sender, change) => { });
channel.Unsubscribe();

// OR

var channel = supabase.Realtime.Channel("realtime", "public", "*");
channel.Unsubscribe()

Retrieve all channels

Returns all Realtime channels.


var channels = supabase.Realtime.Subscriptions;

Create a bucket

Creates a new Storage bucket

  • Policy permissions required:
    • buckets permissions: insert
    • objects permissions: none

var bucket = await supabase.Storage.CreateBucket("avatars");

Retrieve a bucket

Retrieves the details of an existing Storage bucket.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: none

var bucket = await supabase.Storage.GetBucket("avatars");

List all buckets

Retrieves the details of all Storage buckets within an existing product.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: none

var buckets = await supabase.Storage.ListBuckets();

Update a bucket

Updates a new Storage bucket

  • Policy permissions required:
    • buckets permissions: update
    • objects permissions: none

var bucket = await supabase.Storage.UpdateBucket("avatars", new BucketUpsertOptions { Public = false });

Delete a bucket

Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. You must first empty() the bucket.

  • Policy permissions required:
    • buckets permissions: select and delete
    • objects permissions: none

var result = await supabase.Storage.DeleteBucket("avatars");

Empty a bucket

Removes all objects inside a single bucket.

  • Policy permissions required:
    • buckets permissions: select
    • objects permissions: select and delete

var bucket = await supabase.Storage.EmptyBucket("avatars");

Upload a file

Uploads a file to an existing bucket.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: insert

var imagePath = Path.Combine("Assets", "fancy-avatar.png");

await supabase.Storage
  .From("avatars")
  .Upload(imagePath, "fancy-avatar.png", new FileOptions { CacheControl = "3600", Upsert = false });

Download a file

Downloads a file.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

var bytes = await supabase.Storage.From("avatars").Download("public/fancy-avatar.png");

List all files in a bucket

Lists all the files within a bucket.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

var objects = await supabase.Storage.From("avatars").List();

Replace an existing file

Replaces an existing file at the specified path with a new one.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: update and select

var imagePath = Path.Combine("Assets", "fancy-avatar.png");
await supabase.Storage.From("avatars").Update(imagePath, "fancy-avatar.png");

Move an existing file

Moves an existing file, optionally renaming it at the same time.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: update and select

await supabase.Storage.From("avatars")
  .Move("public/fancy-avatar.png", "private/fancy-avatar.png");

Delete files in a bucket

Deletes files within the same bucket

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: delete and select

await supabase.Storage.From("avatars").Remove(new List<string> { "public/fancy-avatar.png" });

Create a signed URL

Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds.

  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: select

var url = await supabase.Storage.From("avatars").CreateSignedUrl("public/fancy-avatar.png", 60);

Retrieve public URL

Retrieve URLs for assets in public buckets

  • The bucket needs to be set to public, either via UpdateBucket() or by going to Storage on supabase.com/dashboard, clicking the overflow menu on a bucket and choosing "Make public"
  • Policy permissions required:
    • buckets permissions: none
    • objects permissions: none

var publicUrl = supabase.Storage.From("avatars").GetPublicUrl("public/fancy-avatar.png");