首頁 > web前端 > js教程 > 主體

SUPABASE 函數(非邊緣)

WBOY
發布: 2024-08-29 14:00:19
原創
303 人瀏覽過

蘇帕貝斯

Firebase 產品的開源替代品

  • 資料庫
  • 即時
  • 授權
  • 功能
  • 邊緣函數

但是等等,如果他們已經有了函數為什麼還需要邊緣函數?

supabase functions (not edge)

Supabase 函數:您的 PostgreSQL 工具箱

Supabase 函數,也稱為資料庫函數,本質上是 PostgreSQL 預存程序。它們是可執行的 SQL 程式碼區塊,可以從 SQL 查詢中呼叫。

邊緣函數:超越資料庫

相較之下,Edge 函數是在 Deno 運行時運行的伺服器端 TypeScript 函數。它們與 Firebase Cloud Functions 類似,但提供了更靈活和開源的替代方案。

Supabase:PostgreSQL 平台

除了作為 Firebase 的開源替代品之外,Supabase 已發展成為一個全面的 PostgreSQL 平台。它為 PostgreSQL 函數提供一流的支持,將它們無縫整合到其內建實用程式中,並允許您直接從 Supabase 儀表板建立和管理自訂函數。

基本 postgres 函數的結構

CREATE FUNCTION my_function() RETURNS int AS $$
BEGIN
    RETURN 42;
END;
$$ LANGUAGE sql;
登入後複製

細分:

  1. CREATE FUNCTION: 這個關鍵字表示我們正在定義一個新函數。
  2. my_function(): 這是函數的名稱。您可以選擇任何您喜歡的有意義的名稱。
  3. RETURNS int: 這指定函數的回傳型別。在這種情況下,函數將傳回一個整數值。
  4. AS $$: 這是函數體的開始,用雙美元符號 ($$) 括起來來分隔它。
  5. BEGIN: 這標誌著函數可執行程式碼的開始。
  6. RETURN 42;: 此語句指定函數將傳回的值。在本例中,它是整數 42。
  7. END;: 這標誌著函數可執行程式碼的結束。
  8. $$ LANGUAGE sql;: 這指定了寫函數所用的語言。在本例中,它是 SQL。

目的:

函數定義了一個名為 my_function 的簡單 SQL 函數,它會傳回整數值 42。這是一個示範 PostgreSQL 中函數定義的結構和語法的基本範例。

要記住的重點:

  • 您可以將 my_function 替換為任何所需的函數名稱。
  • 傳回類型可以是任何有效的資料類型,例如文字、布林值、日期或使用者定義的類型。
  • 函數體可以包含複雜的邏輯,包括條件語句、迴圈和對其他函數的呼叫。
  • $$ 分隔符號用於以與語言無關的方式包圍函數體。

  • Postgres 函數也可以由 postgres TRIGGERS 調用,它們類似於函數,但對特定事件做出反應,例如表上的插入、更新或刪除

  • 執行此函數

SELECT my_function();
登入後複製
  • 列出此功能
SELECT
    proname AS function_name,
    prokind AS function_type
FROM pg_proc
WHERE proname = 'my_function';
登入後複製
  • 刪除此功能
DROP FUNCTION my_function();
登入後複製

Supabase postgres 函數

內建函數

Supabase 使用 postgres 函數在資料庫中執行某些任務。

範例的簡短清單包括

--  list all the supabase functions
SELECT
    proname AS function_name,
    prokind AS function_type
FROM pg_proc;

--  filter for the session supabase functions function
SELECT
    proname AS function_name,
    prokind AS function_type
FROM pg_proc
WHERE proname ILIKE '%session%';

--  selects the curremt jwt
select auth.jwt()

-- select what role is callig the function (anon or authenticated)
select auth.role();

-- select the session user
select session_use;
登入後複製

儀表板上的 Supabase 功能視圖
要在 Supabase 中查看其中一些功能,您可以在資料庫 > 下查看功能

supabase functions (not edge)

有用的 Supabase PostgreSQL 函數

在使用者註冊時建立 user_profile 表

Supabase 將使用者資料儲存在 auth.users 表中,該表是私有的,不應直接存取或修改。建議的方法是建立一個公共 users 或 user_profiles 表並將其連結到 auth.users 表。

雖然這可以使用客戶端 SDK 透過將建立使用者請求與成功的註冊請求連結起來來完成,但在 Supabase 端處理它會更可靠、更有效率。這可以使用觸發器和函數的組合來實現。

--   create the user_profiles table
CREATE TABLE user_profiles (
  id uuid PRIMARY KEY,
  FOREIGN KEY (id) REFERENCES auth.users(id),
  name text,
  email text
);

-- create a function that returns a trigger on auth.users
CREATE 
OR REPLACE FUNCTION public.create_public_user_profile_table() 
RETURNS TRIGGER AS $$ 
BEGIN INSERT INTO public.user_profiles (id,name,email) 
VALUES 
  (
    NEW.id,
    NEW.raw_user_meta_data ->> 'name',
    NEW.raw_user_meta_data ->> 'email'
    -- other fields accessible here 
--     NEW.raw_user_meta_data ->> 'name',
-- NEW.raw_user_meta_data ->> 'picture',

);
RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- create the trigger that executes the function on every new user rowcteation(signup)
CREATE TRIGGER create_public_user_profiles_trigger 
AFTER INSERT ON auth.users FOR EACH ROW WHEN (
        NEW.raw_user_meta_data IS NOT NULL
    )
EXECUTE FUNCTION public.create_public_user_profile_table ();

登入後複製
let { data: user_profiles, error } = await supabase
  .from('user_profiles')
  .select('*')
登入後複製
  • 新增關於 jwt 建立的自訂聲明 (RBAC) supabse 有關於此的詳細文章和影片。

我們需要2塊

  • public.roles 與 public.role_permissions
-- Custom types
create type public.app_permission as enum ('channels.delete', 'channels.update', 'messages.update', 'messages.delete');
create type public.app_role as enum ('admin', 'moderator');

-- USER ROLES
create table public.user_roles (
  id        bigint generated by default as identity primary key,
  user_id   uuid references public.users on delete cascade not null,
  role      app_role not null,
  unique (user_id, role)
);
comment on table public.user_roles is 'Application roles for each user.';

-- ROLE PERMISSIONS
create table public.role_permissions (
  id           bigint generated by default as identity primary key,
  role         app_role not null,
  permission   app_permission not null,
  unique (role, permission)
);
comment on table public.role_permissions is 'Application permissions for each role.';
登入後複製

使用者角色範例

id user_id role
1 user-1 admin
2 user-2 moderator

example of a role permission table

id role permission
1 admin channels.update
2 admin messages.update
3 admin messages.delete
4 admin messages.delete
5 moderator channels.update
6 moderator messages.update

user with user_id = user-1 will have admin and moderator roles and can delete channels and messages

users with user_id = user-2 can only update channels and messages with the moderator role

-- Create the auth hook function
create or replace function public.custom_access_token_hook(event jsonb)
returns jsonb
language plpgsql
stable
as $$
  declare
    claims jsonb;
    user_role public.app_role;
  begin
    -- Fetch the user role in the user_roles table
    select role into user_role from public.user_roles where user_id = (event->>'user_id')::uuid;

    claims := event->'claims';

    if user_role is not null then
      -- Set the claim
      claims := jsonb_set(claims, '{user_role}', to_jsonb(user_role));
    else
      claims := jsonb_set(claims, '{user_role}', 'null');
    end if;

    -- Update the 'claims' object in the original event
    event := jsonb_set(event, '{claims}', claims);

    -- Return the modified or original event
    return event;
  end;
$$;

grant usage on schema public to supabase_auth_admin;

grant execute
  on function public.custom_access_token_hook
  to supabase_auth_admin;

revoke execute
  on function public.custom_access_token_hook
  from authenticated, anon, public;

grant all
  on table public.user_roles
to supabase_auth_admin;

revoke all
  on table public.user_roles
  from authenticated, anon, public;

create policy "Allow auth admin to read user roles" ON public.user_roles
as permissive for select
to supabase_auth_admin
using (true)

登入後複製

then create a function that will be called to authorize on RLS policies

create or replace function public.authorize(
  requested_permission app_permission
)
returns boolean as $$
declare
  bind_permissions int;
  user_role public.app_role;
begin
  -- Fetch user role once and store it to reduce number of calls
  select (auth.jwt() ->> 'user_role')::public.app_role into user_role;

  select count(*)
  into bind_permissions
  from public.role_permissions
  where role_permissions.permission = requested_permission
    and role_permissions.role = user_role;

  return bind_permissions > 0;
end;
$$ language plpgsql stable security definer set search_path = '';

--  example RLS policies
create policy "Allow authorized delete access" on public.channels for delete using ( (SELECT authorize('channels.delete')) );
create policy "Allow authorized delete access" on public.messages for delete using ( (SELECT authorize('messages.delete')) );


登入後複製

Improved Text:

Creating RPC Endpoints

Supabase functions can be invoked using the rpc function. This is especially useful for writing custom SQL queries when the built-in PostgreSQL APIs are insufficient, such as calculating vector cosine similarity using pg_vector.

create or replace function match_documents (
  query_embedding vector(384),
  match_threshold float,
  match_count int
)
returns table (
  id bigint,
  title text,
  body text,
  similarity float
)
language sql stable
as $$
  select
    documents.id,
    documents.title,
    documents.body,
    1 - (documents.embedding <=> query_embedding) as similarity
  from documents
  where 1 - (documents.embedding <=> query_embedding) > match_threshold
  order by (documents.embedding <=> query_embedding) asc
  limit match_count;
$$;

登入後複製

and call it client side

const { data: documents } = await supabaseClient.rpc('match_documents', {
  query_embedding: embedding, // Pass the embedding you want to compare
  match_threshold: 0.78, // Choose an appropriate threshold for your data
  match_count: 10, // Choose the number of matches
})
登入後複製

Improved Text:

Filtering Out Columns

To prevent certain columns from being modified on the client, create a simple function that triggers on every insert. This function can omit any extra fields the user might send in the request.

-- check if user with roles authenticated or anon submitted an updatedat column and replace it with the current time , if not (thta is an admin) allow it
CREATE
or REPLACE function public.omit_updated__at () returns trigger as 
$$ BEGIN 
IF auth.role() IS NOT NULL AND auth.role() IN ('anon', 'authenticated') 
THEN NEW.updated_at = now();
END IF; 
RETURN NEW; 
END; $$ language plpgsql;
登入後複製

Summary

With a little experimentation, you can unlock the power of Supabase functions and their AI-powered SQL editor. This lowers the barrier to entry for the niche knowledge required to get this working.

Why choose Supabase functions?

  • Extend Supabase's API: Supabase can only expose so much through its API. Postgres, however, is a powerful database. Any action you can perform with SQL statements can be wrapped in a function and called from the client or by a trigger.
  • Reduce the need for dedicated backends: Supabase functions can fill the simple gaps left by the client SDKs, allowing you to focus on shipping.
  • Avoid vendor lock-in: Supabase functions are just Postgres. If you ever need to move to another hosting provider, these functionalities will continue to work.

以上是SUPABASE 函數(非邊緣)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!