PostgreSQL与Rust的聚合实现比较


在使用PostgreSQL时,使用SUM(vals)或AVG(vals)这样的函数是一种常见的习惯。这些聚合函数为用户提供了一种简单、有效的方法来计算一组输入的结果。
定义一个聚合是通过CREATE AGGREGATE和CREATE FUNCTION,这里是一个只针对整数的sum的重新实现:

CREATE FUNCTION example_sum_state(
    state integer,
    next  integer
) RETURNS integer
LANGUAGE SQL
STRICT
AS $$
    SELECT $1 + $2;
$$;

CREATE AGGREGATE example_sum(integer)
(
    SFUNC    = example_sum_state, -- State function
    STYPE    = integer,           -- State type
    INITCOND = '0'                -- Must be a string or null
);

SELECT example_sum(value) FROM UNNEST(ARRAY [1, 2, 3]) as value;
--  example_sum 
-- -------------
--            6
-- (1 row)

从概念上讲,聚合循环了输入中的每个项目,并对当前状态以及每个值运行SFUNC函数。这段代码类似于:

fn example_sum(values: Vec<isize>) -> isize {
    let mut sum = 0;
    for value in values {
        sum += value;
    }
    sum
}

更多点击标题