Skip to content

Certain operations are too complex to perform directly using the client libraries.

解决方案 在操作过于复杂或者无法直接用客户端库实现时,利用数据库中的存储函数可能会更有帮助。

按照这些步骤来创建并运行一个存储函数:

🌐 Follow these steps to create and run a stored function:

创建存储函数:

在你的数据库仪表板上,进入SQL 查询编辑器。 运行以下 SQL 脚本来创建一个针对你的特定复杂查询的存储函数:

🌐 Go to the SQL query editor on your database dashboard. Run the following SQL script to create a stored function tailored to your specific complex query:

1
DROP FUNCTION IF EXISTS get_my_complex_query;
2
CREATE FUNCTION get_my_complex_query(parameter INT)
3
RETURNS TABLE (column1 INTEGER, column2 VARCHAR, column3 DATE) AS
4
$$
5
BEGIN
6
RETURN QUERY
7
SELECT t1.column1, t1.column2, t2.column3
8
FROM "TableName1" AS t1
9
INNER JOIN "TableName2" AS t2 ON t1.column = t2.column
10
INNER JOIN "TableName3" AS t3 ON t2.another_column = t3.another_column
11
LEFT JOIN "TableName4" AS t4 ON t3.some_column = t4.some_column
12
WHERE t2.column = parameter
13
AND t3.column_name = 'some_value';
14
END;
15
$$
16
LANGUAGE plpgsql VOLATILE;

调用存储函数:

在你的应用代码中使用 supabase.rpc 方法来调用存储函数。把 "get_my_complex_query" 替换成合适的函数名,并提供必要的参数:

🌐 Use the supabase.rpc method to call the stored function from your application code. Replace "get_my_complex_query" with the appropriate function name and provide the necessary parameters:

1
supabase.rpc("get_my_complex_query", { parameter: 1 })
2
.then(response => {
3
// Handle the response
4
})
5
.catch(error => {
6
// Handle errors
7
});

更多资源:

想了解更多关于 Postgres 数据库函数的信息,请参考以下资源: Supabase 函数

🌐 For more information on Postgres database functions, refer to the following resource: Supabase Functions