Any application that can be written in JavaScript, will eventually be written in JavaScript. ——Jeff Atwood(2007)
简介
PLV8提供由V8 Javascript引擎支持的PostgreSQL过程语言。提供了使用JavaScript语法可从 SQL 调用的函数,大大降低了存储过程的学习难度。
安装
PLV8没有提供可直接安装的二进制软件包,需要进行手动构建,下面以Ubuntu 22.04 ARM64 PostgreSQL-16为例,列出构建流程。
首先,克隆源代码到根目录,并切换到最新的release tag。
git clone https://github.com/plv8/plv8.git
cd plv8
git checkout tags/v3.2.2 # 文章编写时最新版为3.2.2
接下来,手动安装一些依赖。根据plv8的Github readme对于Ubuntu 22.04,需要安装以下软件包:
- libtinfo5
- build-essential
- pkg-config
- libstdc++-12-dev
- cmake
- git
若libtinfo5不存在,可考虑安装libtinfo5-dev
同时,还需要安装postgresql-server-dev-16以获取postgres.h头文件,这在github上没有被列出。
sudo apt install libtinfo5 build-essential pkg-config libstdc++-12-dev cmake postgresql-server-dev-16
安装完成后进行编译与安装。项目依赖v8,编译时间可能较长。
make # 编译,可使用-j参数加速
make install # 安装,可能需要sudo
测试
安装完成后,登录PostgreSQL数据库:
sudo su postgres
psql
\c your_database
创建PLV8扩展:
CREATE EXTENSION plv8;
验证可用性:
DO $ plv8.elog(NOTICE, "hello there!"); $ LANGUAGE plv8;
输出NOTICE: hello there!,说明安装成功。
导出TypeScript函数到plv8
PLV8ify提供了输入ts文件,输出使用PLV8编写的存储过程的能力。安装该软件需要NodeJS。
npm install -g plv8ify
创建ts文件input.ts:
/** @plv8ify_schema_name testschema */
export function hello() {
return 'world'
}
运行以下命令:
plv8ify generate
将生成plv8ify-dist/hello.plv8.sql:
DROP FUNCTION IF EXISTS testschema.hello();
CREATE OR REPLACE FUNCTION testschema.hello() RETURNS text AS $plv8ify$
// input.ts
function hello() {
return "world";
}
return hello()
$plv8ify$ LANGUAGE plv8 IMMUTABLE STRICT;

Comments NOTHING