是否可以使用 PostgreSQL plv8 扩展创建可重用的函数?

Is it possible to create a re-usable function with the PostgreSQL plv8 extension?

我想将 google 的开放位置代码 javascript 实现放到 PostgreSQL 中(使用 plv8 extension)并使其可用于 encode/decode 从 PostGIS geometry/geography 数据类型。

虽然我成功了,但我无法弄清楚如何只为 https://github.com/google/open-location-code/blob/master/js/src/openlocationcode.js 文件创建一个函数,最后我将该函数的副本放入我需要的每个函数中encode/decode 加上代码。当我试图将它拉出到它自己的函数中时,我可以得到一个包含 javascript 的字符串或一个 [Object],[object] 的字符串,而不是一个可调用函数。

PostgreSQL 中的 plv8 扩展是否可行?

不完整的代码片段示例 (full version here):

DROP FUNCTION IF EXISTS olc.encode(float,float,integer);

CREATE OR REPLACE FUNCTION olc.encode(
    p_latitude double precision,
    p_longitude double precision,
    p_code_length integer DEFAULT 10
)
  RETURNS text AS
$BODY$


 var f  =  function () {
    var OpenLocationCode = {};

    /**
     * Provides a normal precision code, approximately 14x14 meters.
     * @const {number}
     */
    OpenLocationCode.CODE_PRECISION_NORMAL = 10;

    /**
     * Provides an extra precision code, approximately 2x3 meters.
     * @const {number}
     */
    OpenLocationCode.CODE_PRECISION_EXTRA = 11;

    // A separator used to break the code into two parts to aid memorability.
    var SEPARATOR_ = '+';

    // The number of characters to place before the separator.
    var SEPARATOR_POSITION_ = 8;

    // The character used to pad codes.
    var PADDING_CHARACTER_ = '0';

你有两个选择。

  1. 将函数的源代码存储在一个特殊的数据库table中,并使用selecteval()加载它。阅读此答案中的详细信息:

  2. 将函数放在初始化模块中,并使用配置参数 plv8.start_proc 设置此模块,使其在 start-up 上自动执行。您可以在 the PL/v8 documentation.

  3. 中找到详细信息

第二个选项非常方便,不需要额外的 table,但可能看起来有点棘手。一个简单的例子:我们想要在我们所有的 plv8 函数中预定义一个函数 square_of_sum(a, b)。首先,创建初始化函数:

create or replace function plv8_init()
returns void language plv8 as $$

    square_of_sum = function(a, b) {
        return (a+ b)* (a+ b)
    }

$$;

设置数据库的初始化函数:

alter database my_database set plv8.start_proc to plv8_init;

并关闭当前连接。

在所有后续会话中,函数 square_of_sum(a, b) 在所有其他 plv8 函数中都是已知的,例如:

create or replace function js_test()
returns int language plv8 as $$
    return square_of_sum(3, 2)
$$;

select js_test();

 js_test
---------
      25
(1 row)