Skip to content
Database

plpgsql_check:PL/pgSQL 代码检查器

plpgsql_check 是一个 Postgres 扩展,用于检查 plpgsql 的语法、语义以及其他相关问题。这个工具可以帮助开发者在执行代码之前发现并纠正错误。对于处理大型或复杂 SQL 代码库的开发者来说,plpgsql_check 特别有用,因为它可以在开发早期就帮助发现和解决问题。

启用扩展 #

🌐 Enable the extension

  1. 在仪表板中转到数据库页面。
  2. 点击侧边栏的 扩展。
  3. 搜索“plpgsql_check”并启用该扩展。

应用接口 #

🌐 API

plpgsql_check_function 可高度自定义。有关可用参数的完整列表,请参见文档

用法 #

🌐 Usage

为了演示 plpgsql_check,我们可以创建一个带有已知错误的函数。在这种情况下,我们创建一个函数 some_func,它引用了一个不存在的列 place.created_at。

🌐 To demonstrate plpgsql_check we can create a function with a known error. In this case we create a function some_func, that references a non-existent column place.created_at.

create table place(
x float,
y float
);
create or replace function public.some_func()
returns void
language plpgsql
as $$
declare
rec record;
begin
for rec in select * from place
loop
-- Bug: There is no column `created_at` on table `place`
raise notice '%', rec.created_at;
end loop;
end;
$$;

注意,执行这个函数不会捕获无效引用错误,因为如果表中没有行,loop 就不会执行。

🌐 Note that executing the function would not catch the invalid reference error because the loop does not execute if no rows are present in the table.

select public.some_func();
some_func
───────────
(1 row)

现在我们可以使用 plpgsql_check 的 plpgsql_check_function 函数来识别已知错误。

🌐 Now we can use plpgsql_check's plpgsql_check_function function to identify the known error.

select plpgsql_check_function('public.some_func()');
plpgsql_check_function
------------------------------------------------------------
error:42703:8:RAISE:record "rec" has no field "created_at"
Context: SQL expression "rec.created_at"

资源 #

🌐 Resources