1. Features
  2. Database

Features

Database

Setup your Supabase database

Naming Conventions

  • plural table names
  • singular column names
  • no prefixes
  • lowercase
  • one word if possible

Setup

Head to your the SQL Editor on the Supabase Dashboard and enter the following commands. You can add fields here to fit your app.

Create Tables

sql
        create table public.profiles (
  id uuid not null references auth.users on delete cascade,
  name text,
  avatar text,
  bio text,

  primary key (id)
);

      
sql
        create table public.subscriptions (
  id bigint generated by default as identity,
  customer_id text,
  subscription_id text,
  session_id text,
  email varchar,
  active boolean,

  primary key (id)
);

      

Automatically Create Profiles

sql
        CREATE FUNCTION public.create_profile() 
RETURNS trigger 
LANGUAGE plpgsql 
SECURITY DEFINER SET search_path = public
AS $$
BEGIN 
  INSERT INTO public.profiles (id, name, bio, avatar) 
  VALUES 
  (
    NEW.id,
    NEW.raw_user_meta_data ->> 'name', 
    NEW.raw_user_meta_data ->> 'bio',
    NEW.raw_user_meta_data ->> 'avatar'
  );
  RETURN NEW;
END;
$$;


      
sql
        CREATE TRIGGER create_profile_trigger 
AFTER INSERT ON auth.users
  FOR each ROW EXECUTE PROCEDURE public.create_profile();

      

Secure your database

Securing your database will prevent unauthorized data leaks. You should never go live without completing this step.

sql
        ALTER TABLE public.profiles ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscriptions ENABLE ROW LEVEL SECURITY;

      
sql
        CREATE POLICY "Can only view own profile data."
  ON public.profiles
  FOR SELECT
  USING ( auth.uid() = id );

CREATE POLICY "Can only update own profile data."
  ON public.profiles
  FOR UPDATE
  USING ( auth.uid() = id );

CREATE POLICY "Can only view own subscription"
  ON public.subscriptions
  FOR SELECT
  TO authenticated
  USING ( auth.email() = email );