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.

1
create table place(
2
x float,
3
y float
4
);
5
6
create or replace function public.some_func()
7
returns void
8
language plpgsql
9
as $$
10
declare
11
rec record;
12
begin
13
for rec in select * from place
14
loop
15
-- Bug: There is no column `created_at` on table `place`
16
raise notice '%', rec.created_at;
17
end loop;
18
end;
19
$$;

注意,执行这个函数不会捕获无效引用错误,因为如果表中没有行,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.

1
select public.some_func();
2
some_func
3
───────────
4
5
(1 row)

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

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

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

资源 #

🌐 Resources