HAWQ是否在循环中不支持SQL(或者for,for,使用plpgsql)?

时间:2016-01-14 09:24:14

标签: sql database loops hawq

今天,我使用循环中的insert语句定义了一个函数。但是HAWQ返回了一个错误:

ERROR:  could not serialize unrecognized node type: 43983632 (outfast.c:4742)
CONTEXT:  SQL statement "insert into t(id,value) values(1,0.1)"
PL/pgSQL function "test_function" line 6 at SQL statement

我做了一些测试,发现当我在循环中使用'insert statements'时,它会被报告为错误。 如果我删除相关的“插入语句”,它可以正常运行。

以下是测试的示例:

 CREATE OR REPLACE FUNCTION test_function()
  RETURNS int AS
$BODY$
declare 
	number int;
begin		
	number := 1;
	while number <= 10 loop
		insert into t(id,value) values(1,0.1);
		number := number+1;
	end loop;
	return number;
end
$BODY$
  LANGUAGE plpgsql ;

然后我使用'select test_function();'调用该函数。它将返回上述错误。

这是否意味着我不能在带有plpgsql的循环中使用SQL语句?

感谢。 最好的问候。

2 个答案:

答案 0 :(得分:1)

你会想避免使用HAWQ的单例语句,但我有点意外,它不起作用。您将需要使用基于集合的操作。

    CREATE TABLE t (id int, value numeric);

    CREATE OR REPLACE FUNCTION test_function() RETURNS int AS
    $BODY$
    declare 
            number int;
    begin       
            insert into t (id, value) select 1, 0.1 from generate_series(1, 10);
            return 10;
    end
    $BODY$
    LANGUAGE plpgsql;

对于这样一个简单的例子,你可以使用一个sql函数,它的开销比plpgsql少。

    DROP FUNCTION test_function();

    CREATE OR REPLACE FUNCTION test_function() RETURNS void AS
    $BODY$
            insert into t (id, value) select 1, 0.1 from generate_series(1, 10);
    $BODY$
    LANGUAGE sql;

这两个函数都在一个语句中完成所有工作,而不是执行10个单独的语句。我在HAWQ和两个都工作过。

如果必须在使用HAWQ的循环中执行单例插入语句,这是一种解决方法。

    CREATE OR REPLACE FUNCTION test_function()
      RETURNS int AS
    $BODY$
    declare 
            number int;
            v_sql text;
    begin       
            number := 1;
            while number <= 10 loop
                    v_sql := 'insert into t(id,value) values(1,0.1)';
                    execute v_sql;
                    number := number+1;
            end loop;
            return number;
    end
    $BODY$
      LANGUAGE plpgsql ;

答案 1 :(得分:1)

这实际上是hawq 2.0中已经解决的问题。您可以参考最新的https://github.com/apache/incubator-hawq作为参考。

结果如下:

CREATE TABLE t (id INT, value DOUBLE PRECISION);
CREATE TABLE

CREATE OR REPLACE FUNCTION test_function()
RETURNS int AS
$BODY$
declare
    number int;
begin
    number := 1;
    while number <= 10 loop
        insert into t(id, value) values(1, 0.1);
        number := number+1;
    end loop;

    return number;
end
$BODY$
LANGUAGE plpgsql;
CREATE FUNCTION



SELECT test_function();
 test_function
---------------
            11
(1 row)

SELECT * FROM t;
 id | value
----+-------
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
(10 rows)



SELECT * FROM test_function();
 test_function
---------------
            11
(1 row)

SELECT * FROM t;
 id | value
----+-------
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
  1 |   0.1
(10 rows)