使用自定义模式
默认情况下,你的数据库有一个 public 架构,会自动在数据 API 上暴露。
🌐 By default, your database has a public schema which is automatically exposed on data APIs.
创建自定义模式 #
🌐 Creating custom schemas
你可以通过运行以下 SQL 创建你自己的自定义模式,只需将 myschema 替换为你想要使用的模式名称:
🌐 You can create your own custom schema/s by running the following SQL, substituting myschema with the name you want to use for your schema:
CREATE SCHEMA myschema;公开自定义模式 #
🌐 Exposing custom schemas
你可以公开自定义数据库模式——要做到这一点,你需要按照以下步骤:
🌐 You can expose custom database schemas - to do so you need to follow these steps:
- 前往 API 设置 并将你的自定义 schema 添加到“公开的 schemas”。
- 运行以下 SQL,将
myschema替换为你的模式名:
GRANT USAGE ON SCHEMA myschema TO anon, authenticated, service_role;GRANT ALL ON ALL TABLES IN SCHEMA myschema TO anon, authenticated, service_role;GRANT ALL ON ALL ROUTINES IN SCHEMA myschema TO anon, authenticated, service_role;GRANT ALL ON ALL SEQUENCES IN SCHEMA myschema TO anon, authenticated, service_role;ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA myschema GRANT ALL ON TABLES TO anon, authenticated, service_role;ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA myschema GRANT ALL ON ROUTINES TO anon, authenticated, service_role;ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA myschema GRANT ALL ON SEQUENCES TO anon, authenticated, service_role;现在你可以通过数据 API 访问这些模式了:
🌐 Now you can access these schemas from data APIs:
// Initialize the JS clientimport { createClient } from '@supabase/supabase-js'const supabase = createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY, { db: { schema: 'myschema' },})// Make a requestconst { data: todos, error } = await supabase.from('todos').select('*')// You can also change the target schema on a per-query basisconst { data: todos, error } = await supabase.schema('myschema').from('todos').select('*')对于包含 public 的生成 Database 类型,createClient<Database>(...) 只检查 db.schema 是否符合 public,除非也将模式名称作为第二个泛型传入:createClient<Database, 'myschema'>(...)。supabase.schema('myschema').from(...) 会在每次调用时推断它的模式,不需要第二个泛型。在这两种情况下,生成的 Database 类型中都必须存在 myschema。