Update inside (Insert) Trigger and Unique constraint...

Поиск
Список
Период
Сортировка
От D. Dante Lorenso
Тема Update inside (Insert) Trigger and Unique constraint...
Дата
Msg-id 400ED785.1030804@lorenso.com
обсуждение исходный текст
Ответы Re: Update inside (Insert) Trigger and Unique constraint...  ("D. Dante Lorenso" <dante@lorenso.com>)
Список pgsql-general
I'm trying to build a table that will store a history of records
by enumerating the records.  I want the newest record to always
be number ZERO, so I created a trigger on my table to handle the
assignment of version numbers:

    CREATE TRIGGER "trg_audio_file_insert" BEFORE INSERT
    ON "public"."audio_file" FOR EACH ROW
    EXECUTE PROCEDURE "public"."trg_audio_file_insert"();

My trigger function looks like this...

    CREATE FUNCTION "public"."trg_audio_file_insert" () RETURNS trigger AS'
    BEGIN
       ...
        /* rollback the version number of previous versions of this
audio_id */
        UPDATE audio_file SET
            afile_version = afile_version + 1
        WHERE acct_id = NEW.acct_id
        AND audio_id = NEW.audio_id;

        /* newly inserted row is always the latest version ''0'' */
        NEW.afile_version := 0;

       ...
        /* yeah, that worked */
        RETURN NEW;
    END;
    'LANGUAGE 'plpgsql';

There exists a unique constraint on the 'the audio_id / audio_version'
columns.  However, when I insert records into this table, I'm getting an
error like:

    duplicate key violates unique constraint "idx_audio_file_id_version"
    CONTEXT:  PL/pgSQL function "trg_audio_file_insert" line 18 at SQL
statement

I don't understand WHY there could be a violation of the constraint when
I clearly asked for the update to be performed prior to the assigning of
NEW.afile_version := 0;.  Yes, there exist two records with my acct_id and
audio_id with versions 0 and 1 already.  The update should roll them to
1 and 2 then the insert at 0 should be unique still.

Why isn't this working?  What's the deal with ordering when it comes to
triggers?  Is the update not performed when I tell it to?

Dante




В списке pgsql-general по дате отправления:

Предыдущее
От: Tom Lane
Дата:
Сообщение: Re: Compiling postgres-7.4.1
Следующее
От: Alex Madon
Дата:
Сообщение: Re: postgresql + apache under heavy load