plv8:JavaScript 语言
在使用 Postgres 17 的项目中,plv8 扩展已被弃用。在使用 Postgres 15 的项目中仍然支持,但在将这些项目升级到 Postgres 17 之前需要先移除它。更多信息请参见 升级到 Postgres 17 说明。
🌐 The plv8 extension is deprecated in projects using Postgres 17. It continues to be supported in projects using Postgres 15, but will need to dropped before those projects are upgraded to Postgres 17. See the Upgrading to Postgres 17 notes for more information.
plv8 扩展允许你在 Postgres 中使用 JavaScript。
🌐 The plv8 extension allows you use JavaScript within Postgres.
概览 #
🌐 Overview
虽然 Postgres 原生运行 SQL,但它也可以运行其他的过程语言。
plv8 允许你运行 JavaScript 代码——具体来说,是任何可以在 V8 JavaScript 引擎 上运行的代码。
🌐 While Postgres natively runs SQL, it can also run other procedural languages.
plv8 allows you to run JavaScript code - specifically any code that runs on the V8 JavaScript engine.
它可以用于数据库函数、触发器、查询等等。
🌐 It can be used for database functions, triggers, queries and more.
启用扩展 #
🌐 Enable the extension
- 在仪表板中转到数据库页面。
- 点击侧边栏的 扩展。
- 搜索“plv8”并启用扩展。
创建 plv8#
🌐 Create plv8 functions
用 plv8 编写的函数就像其他 Postgres 函数一样,只是 language 标识符设置为 plv8。
🌐 Functions written in plv8 are written like any other Postgres functions, only
with the language identifier set to plv8.
1create or replace function function_name()2returns void as $$3 // V8 JavaScript4 // code5 // here6$$ language plv8;你可以像调用其他 Postgres 函数一样调用 plv8 函数:
🌐 You can call plv8 functions like any other Postgres function:
1select function_name();示例 #
🌐 Examples
标量函数 #
🌐 Scalar functions
一个标量函数就是任何接收用户输入并返回单一结果的东西。
🌐 A scalar function is anything that takes in some user input and returns a single result.
1create or replace function hello_world(name text)2returns text as $$34 let output = `Hello, ${name}!`;5 return output;67$$ language plv8;执行 SQL #
🌐 Executing SQL
你可以在 plv8 代码中使用 plv8.execute 函数 执行 SQL。
🌐 You can execute SQL within plv8 code using the plv8.execute function.
1create or replace function update_user(id bigint, first_name text)2returns smallint as $$34 var num_affected = plv8.execute(5 'update profiles set first_name = $1 where id = $2',6 [first_name, id]7 );89 return num_affected;10$$ language plv8;返回集合的函数 #
🌐 Set-returning functions
一个返回集合的函数是指任何返回完整结果集的函数——例如,表中的行。
🌐 A set-returning function is anything that returns a full set of results - for example, rows in a table.
1create or replace function get_messages()2returns setof messages as $$34 var json_result = plv8.execute(5 'select * from messages'6 );78 return json_result;9$$ language plv8;1011select * from get_messages();资源 #
🌐 Resources