Postgres聚合函数返回错误值,状态转换函数正常

时间:2019-06-25 10:15:29

标签: postgresql aggregate-functions

我已经在postgresql中创建了一个聚合函数,即使过渡函数按预期运行,该聚合函数也不返回预期结果。这些是定义:

-- State: _hil overrides non hil

CREATE TYPE conversion_state AS (
  source text,
  source_hil text,
  ai text,
  ai_hil text,
  expert text
);
-- final state function:
-- if coalesced source is repair -> false
-- if expert is replace -> false
-- if coalesced ai is reapir -> true
CREATE OR REPLACE FUNCTION conversion_final(conversion conversion_state)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
DECLARE
  source text;
  ai_hil text;
BEGIN
    source = COALESCE(conversion.source_hil, conversion.source);
    IF source = 'REPAIR' THEN RETURN false; END IF;
    IF conversion.expert = 'REPLACE' THEN RETURN false; END IF;
    ai_hil := COALESCE(conversion.ai_hil, conversion.ai);
    RETURN ai_hil = 'REPAIR';
END;
$function$;

此功能正常工作。

CREATE OR REPLACE FUNCTION conversion_state_transition(
  state conversion_state, stage enum_assessments_stage, assess text
) RETURNS organizer.rr_conversion_state
LANGUAGE plpgsql
AS $function$
DECLARE
  r conversion_state;
BEGIN
    IF stage = 'source'
    THEN
        SELECT assess , state.source_hil, state.ai, state.ai_hil, state.expert INTO r.source, r.source_hil, r.ai, r.ai_hil, r.expert;
    END IF;
    IF stage = 'source_hil'
    THEN
        SELECT state.source, assess, state.ai, state.ai_hil, state.expert INTO r.source, r.source_hil, r.ai, r.ai_hil, r.expert;
    END IF;
    IF stage = 'ai'
    THEN
        SELECT state.source, state.source_hil, assess, state.ai_hil, state.expert INTO r.source, r.source_hil, r.ai, r.ai_hil, r.expert;
    END IF;
    IF stage = 'ai_hil'
    THEN
        SELECT state.source, state.source_hil, state.ai, assess, state.expert INTO r.source, r.source_hil, r.ai, r.ai_hil, r.expert;
    END IF;
    IF stage = 'expert'
    THEN
        SELECT state.source, state.source_hil, state.ai, state.ai_hil, assess INTO  r.source, r.source_hil, r.ai, r.ai_hil, r.expert;
    END IF;
    RETURN r;
END;
$function$;

状态转换函数也可以按预期方式工作,并根据阶段值用评估值填充各个状态字段。

现在,聚合函数的定义和使用很简单:

-- Aggregate function. Use it to convert (stage, assessment_string) into conversion when assessments are group by (id, area)
CREATE AGGREGATE conversion_a(enum_assessments_stage, text)(
    SFUNC=conversion_state_transition,
    FINALFUNC=conversion_final,
    STYPE=conversion_state,
    INITCOND='(NULL, NULL, NULL, NULL, NULL)'
);


CREATE OR REPLACE VIEW conversion AS
  SELECT assessments.id,
         assessments.area,
         conversion_a(assessments.stage, assessments.assessment_string) AS conversion
  FROM assessments
  WHERE assessments.type = 'REPAIR_REPLACE'
  GROUP BY assessments.id, assessments.area;

当我检查该视图的结果时,得到了错误的结果。对可能发生的事情有任何想法吗?一方面,我怀疑分组会影响结果,但我不知道如何解决。

0 个答案:

没有答案