Postgresql 8.4 Ошибка триггера / сохраненного процесса: как это исправить? - PullRequest
2 голосов
/ 04 сентября 2010

INSERT в таблице запускает сохраненный процесс, в котором возникает следующая ошибка.

ERROR: column "targetedfamily" is of type boolean but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
  Where: PL/pgSQL function "fn_family_audit" line 19 at SQL statement

А вот хранимый процесс с ОШИБКОЙ (обратите внимание, что моя попытка исправить проблему с помощью CAST (NEW.targetedfamily AS BOOLEAN), похоже, не работает)

CREATE OR REPLACE FUNCTION fn_family_audit() RETURNS TRIGGER AS $tr_family_audit$
    BEGIN
        --
        -- Create a row in family_audit to reflect the operation performed on family,
        -- make use of the special variable TG_OP to work out the operation.
        --
        IF (TG_OP = 'DELETE') THEN
            INSERT INTO public.family_audit values (
         DEFAULT, 'D', OLD.family_id, OLD.familyserialno, OLD.node_id, OLD.sourcetype, OLD.familyname,  
        OLD.familynamelocallang, OLD.hofname, OLD.hofnamelocallang, OLD.targetedfamily, OLD.homeless,
        OLD.landless, OLD.dependentonlabour, OLD.womenprimaryearner, OLD.landlinenumber, OLD.username , now());
            RETURN OLD;
        ELSIF (TG_OP = 'UPDATE') THEN
            INSERT INTO public.family_audit values(
         DEFAULT, 'U',NEW.family_id, NEW.familyserialno, NEW.node_id, NEW.sourcetype, NEW.familyname,   
        NEW.familynamelocallang, NEW.hofname, NEW.hofnamelocallang, NEW.targetedfamily, NEW.homeless,
        NEW.landless, NEW.dependentonlabour, NEW.womenprimaryearner, NEW.landlinenumber, NEW.username , now());
            RETURN NEW;
        ELSIF (TG_OP = 'INSERT') THEN
            INSERT INTO public.family_audit values(
         DEFAULT, 'I',NEW.family_id, NEW.familyserialno, NEW.node_id, NEW.sourcetype, NEW.familyname,   
        NEW.familynamelocallang, NEW.hofname, NEW.hofnamelocallang, CAST(NEW.targetedfamily AS BOOLEAN), NEW.homeless,
        NEW.landless, NEW.dependentonlabour, NEW.womenprimaryearner, NEW.landlinenumber, NEW.username , now());
            RETURN NEW;
        END IF;
        RETURN NULL; -- result is ignored since this is an AFTER trigger
    END;
$tr_family_audit$ LANGUAGE plpgsql;

Вот определение таблицы

nucleus4=# \d family;
                                             Table "public.family"
       Column        |            Type             |                         Modifiers
---------------------+-----------------------------+------------------------------------------------------------
 family_id           | integer                     | not null default nextval('family_family_id_seq'::regclass)
 familyserialno      | integer                     | not null
 sourcetype          | character varying(20)       | not null
 familyname          | character varying(100)      |
 familynamelocallang | character varying(255)      |
 hofname             | character varying(100)      | not null
 hofnamelocallang    | character varying(255)      | not null
 targetedfamily      | boolean                     |
 homeless            | boolean                     |
 landless            | boolean                     |
 dependentonlabour   | boolean                     |
 womenprimaryearner  | boolean                     |
 landlinenumber      | character varying(20)       |
 username            | character varying(20)       | not null
 adddate             | timestamp without time zone | not null default now()
 updatedate          | timestamp without time zone | not null default now()
 node_id             | integer                     | not null
Indexes:
    "PK_family" PRIMARY KEY, btree (family_id)
    "family_idx" UNIQUE, btree (familyserialno, node_id)
Foreign-key constraints:
    "family_fk" FOREIGN KEY (node_id) REFERENCES hierarchynode_master(node_id)
Referenced by:
    TABLE "agriland" CONSTRAINT "FK_agriland_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "currentloans" CONSTRAINT "FK_currentloans_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "family_address" CONSTRAINT "FK_family_address_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "family_basic_info" CONSTRAINT "FK_family_basic_info_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "family_entitlement" CONSTRAINT "FK_family_entitlement_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "livestock" CONSTRAINT "FK_livestock_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "member" CONSTRAINT "FK_member_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
    TABLE "otherassets" CONSTRAINT "FK_otherassets_family" FOREIGN KEY (family_id) REFERENCES family(family_id) ON UPDATE RESTRICT ON DELETE RESTRICT
Triggers:
    tr_family_audit AFTER INSERT OR DELETE OR UPDATE ON family FOR EACH ROW EXECUTE PROCEDURE fn_family_audit()
    tr_family_updatedate BEFORE UPDATE ON family FOR EACH ROW EXECUTE PROCEDURE fn_modify_updatedate_column()


nucleus4=#

Вот семья_Аудит

nucleus4=# \d family_audit;
                                                Table "public.family_audit"
       Column        |            Type             |                               Mod
---------------------+-----------------------------+----------------------------------
 familyaudit_id      | integer                     | not null default nextval('family_
 operation           | character(1)                | not null
 family_id           | integer                     | not null
 familyserialno      | integer                     | not null
 sourcetype          | character varying(20)       | not null
 familyname          | character varying(100)      |
 familynamelocallang | character varying(255)      |
 hofname             | character varying(100)      | not null
 hofnamelocallang    | character varying(255)      | not null
 targetedfamily      | boolean                     |
 homeless            | boolean                     |
 landless            | boolean                     |
 dependentonlabour   | boolean                     |
 womenprimaryearner  | boolean                     |
 landlinenumber      | character varying(20)       |
 username            | character varying(20)       | not null
 adddate             | timestamp without time zone | not null default now()
 node_id             | integer                     | not null
Indexes:
    "PK_family_audit" PRIMARY KEY, btree (familyaudit_id)


nucleus4=#

Вот триггер

CREATE TRIGGER tr_family_audit
AFTER INSERT OR UPDATE OR DELETE ON public.family
    FOR EACH ROW EXECUTE PROCEDURE fn_family_audit();

Буду признателен за любые подсказки.

Спасибо,

BR
~ А

1 Ответ

0 голосов
/ 04 сентября 2010

Ваша проблема здесь:

NEW.hofnamelocallang

В вашей вставке есть один дополнительный столбец (очевидно, NEW.node_id).Попробуйте изменить вставку на:

INSERT INTO public.family_audit values(
         DEFAULT, 'I',NEW.family_id, NEW.familyserialno, 
         NEW.sourcetype, NEW.familyname,   
         NEW.familynamelocallang, NEW.hofname, NEW.hofnamelocallang,
         NEW.targetedfamily, NEW.homeless,
         NEW.landless, NEW.dependentonlabour, NEW.womenprimaryearner, 
         NEW.landlinenumber, NEW.username , now()
);

Полученная ошибка в основном говорит о том, что вы пытаетесь вставить NEW.hofnamelocallang в targetedfamily столбец (который является логическим, а не varchar) из-за дополнительного столбцаВы вставляли предложение вставки.

Я бы посоветовал, чтобы при выполнении вставки по соображениям здравого смысла всегда перечислялись столбцы, в которые вы помещаете значения.Примерно так:

insert into table foo
(col1, col2, col3) -- column enumeration here
values
(1, 2, 3);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...