Prisma-如何在模式中引用SQL视图



我正在为一个多租户项目设计一个数据库模式,其中单个用户可能有多个";简档";,一个适用于不同租户。我正在使用Suabase提供Postgres数据库以及他们的一些其他BaaS功能,并希望使用Prisma来帮助我管理模式、关系和迁移。

Suabase提供自己的身份验证服务,利用他们的auth.users表(在auth模式中(。我希望/需要我的public.profiles表与auth.users具有1-n关系,这样我就可以将我的用户链接到他们的所有配置文件。

有没有一种方法可以在我的schema.prisma文件中定义它?我曾尝试在数据库中手动创建VIEW,然后为其定义模型,但当我尝试应用其他Prisma模式更改(npx prisma db pushnpx prisma db migrate dev(时,我会得到一个错误,即视图/模型已经存在。

初始化数据库时,我在公共模式中创建AuthSQL视图。

CREATE VIEW "Auth" AS SELECT id, email, role, created_at, updated_at, invited_at from auth.users;

然后在我的Prisma模式中,我复制了模型。如果您使用内省,这似乎是一种方法,但我希望Prisma管理模式,而不是相反。

generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url      = env("DATABASE_URL")
}
// SQL view in public schema of Supabase "auth.users" table
model Auth {
id            Int         @unique
email         String
role          String
createdAt     DateTime    @map("created_at")
updatedAt     DateTime    @map("updated_at")
invitedAt     DateTime    @map("invited_at")
profiles      Profile[]
}
model Profile {
id            Int         @id @default(autoincrement())
// This relation should reference the "auth.users" table
user          Auth        @relation(fields: [uid], references: [id])
uid           Int
client        Client      @relation(fields: [clientId], references: [id])
clientId      Int
firstName     String
lastName      String
}
model Client {
id            Int         @id @default(autoincrement())
createdAt     DateTime    @default(now())
updatedAt     DateTime    @default(now())
name          String
type          String
preferences   Json
profiles      Profile[]
}

从本质上讲,我需要知道如何创建与Prisma无法控制的模式部分的关系。我可以定义一个仅供参考的模型吗?或者在pushmigrate操作期间应该忽略的模型?我可以在模型关系定义中定义一个显式表名吗?

有一个问题是关于增加对观点的支持,但尚不清楚是否/何时会发生任何事情。我想知道是否有人有不同的解决方案。如果这不起作用,我可能只需要考虑使用NextAuth这样的东西,这样我就可以完全管理身份验证模式,但如果我能帮助的话,我宁愿不重建身份验证系统。

您可以通过Prisma创建一个public.users表,并添加一个Postgres触发器,以便在用户注册时将auth.users数据复制到您的公共架构中:

/**
* This trigger automatically creates a user entry when a new user signs up via Supabase Auth.
*/ 
create function public.handle_new_user() 
returns trigger as $$
begin
insert into public.users (id, full_name, avatar_url)
values (new.id, new.raw_user_meta_data->>'full_name', new.raw_user_meta_data->>'avatar_url');
return new;
end;
$$ language plpgsql security definer;
create trigger on_auth_user_created
after insert on auth.users
for each row execute procedure public.handle_new_user();

这种方法对你有效吗?

最新更新