我目前正在尝试编写一个 Flutter 应用程序来跟踪学校成绩。每当新用户注册时,我都会尝试在 Supabase 中创建一个新表。该表将存储他们的数据。触发器有效,但不幸的是,我无法让该函数执行它应该执行的操作。
我的触发器看起来像这样:
create trigger create_database_for_new_user
after insert on auth.users for each row
execute function create_database_for_new_user ();
这是我的职责:
BEGIN
DECLARE
new_table_name TEXT;
BEGIN
new_table_name := 'user_' || NEW.id;
EXECUTE format('CREATE TABLE IF NOT EXISTS %I (
id bigint generated by default as identity primary key,
inserted_at timestamp with time zone default timezone(''utc''::text, now()) not null,
updated_at timestamp with time zone default timezone(''utc''::text, now()) not null,
date timestamp with time zone not null,
grade numeric not null,
type text not null
);', new_table_name);
RETURN NEW;
END;
END;
如果可行的话那就太好了,因为这样我就可以将每个用户的所有成绩保存在一张表中。以这种方式解决它可能有点复杂,但该项目通常不是为许多用户设计的。由于我将来会更多地使用 Supabase,所以我对如何实现这个功能非常感兴趣。我对 SQL 还不是很熟悉,提前感谢您的帮助!
您的触发器和函数处于正确的轨道上,但是您的 SQL 函数中存在一些问题,可能导致它无法按预期工作。您可能需要执行以下操作:
1。避免嵌套 BEGIN/END 块 您在另一个 BEGIN 中有一个 BEGIN 块。在 PostgreSQL 中,如果您已经位于主函数块中,则函数不需要此嵌套 BEGIN。把里面的去掉,保留主的。
2。新回归 回归新;仅当您使用行级触发器来修改要插入的行时,才应使用该语句。但是,由于您没有修改 auth.users 表本身(只是使用它来创建新表),因此不需要返回 NEW。您可以简单地 RETURN NULL;.
3.权限 确保执行此函数的角色具有动态创建表的必要权限。在 Supabase 中,可能需要调整某些权限才能允许这样做。
这是您的函数的正确版本
CREATE OR REPLACE FUNCTION create_database_for_new_user()
RETURNS TRIGGER AS $$
DECLARE
new_table_name TEXT;
BEGIN
-- Concatenate the new user's ID to create a unique table name
new_table_name := 'user_' || NEW.id;
-- Create the table for the new user if it doesn't exist
EXECUTE format('CREATE TABLE IF NOT EXISTS %I (
id bigint generated by default as identity primary key,
inserted_at timestamp with time zone default timezone(''utc''::text, now()) not null,
updated_at timestamp with time zone default timezone(''utc''::text, now()) not null,
date timestamp with time zone not null,
grade numeric not null,
type text not null
);', new_table_name);
-- Since you're not changing any rows in the users table, just return NULL
RETURN NULL;
END;
$$ LANGUAGE plpgsql;