increasing entry number automatically for every insert on the entry table - postgresql

i tried using this code:
CREATE OR REPLACE FUNCTION eno_inc() RETURNS trigger AS $eno_inc$
BEGIN
NEW.eno := OLD.eno + 1;
END;
$eno_inc$
LANGUAGE plpgsql;
but anytime i run it generates this error:
ERROR: record "old" is not assigned yet
DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
CONTEXT: PL/pgSQL function "eno_inc" line 4 at assignment
*** Error ***
ERROR: record "old" is not assigned yet
SQL state: 55000
P.S i am very new to SQL

You are missing a
RETURN NEW;
at the end.
The error
ERROR: record "old" is not assigned yet SQL state: 55000
does show that this MIGHT not be a trigger (OLD and NEW are only used in trigger context). You need to define a trigger for that to work. I suggest you read the docs about trigger functions.
As the comment by Steve C notes, make sure you don't just need a SERIAL (auto-increment in MySQL terms).

In addition to what #DrColossos already wrote ..
OLD and NEW are only defined in a trigger ON UPDATE. In a trigger on INSERT you would get this error message. In a trigger on DELETE you only have OLD at your disposal.
Also, for a trigger to work you need a trigger function plus a trigger. You may be missing that, too. Start by reading the excellent manual here.
But I suspect your problems are more basic than that. First of all, as #Steve commented, you are probably just looking for a serial column or a sequence and a DEFAULT to your already existing column.

Related

How to roll back a transaction on error in PostgreSQL?

I'm writing a script for PostgreSQL and since I want it to be executed atomically, I'm wrapping it inside a transaction.
I expected the script to look something like this:
BEGIN
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
END; -- A.k.a. COMMIT;
However, in this case pgAdmin warns me about a syntax error right after the initial BEGIN. If I terminate the command there by appending a semicolon like so: BEGIN; it instead informs me about error near EXCEPTION.
I realize that perhaps I'm mixing up syntax for control structures and transactions, however I couldn't find any mention of how to roll back a failed transaction in the docs (nor in SO for that matter).
I also considered that perhaps the transaction is rolled back automatically on error, but it doesn't seem to be the case since the following script:
BEGIN;
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
COMMIT;
warns me that: ERROR: current transaction is aborted, commands ignored until end of transaction block and I have to then manually ROLLBACK; the transaction.
It seems I'm missing something fundamental here, but what?
EDIT:
I tried using DO as well like so:
DO $$
BEGIN
-- 1) Execute some valid actions;
-- 2) Execute some action that causes an error.
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
END; $$
pgAdmin hits me back with a: ERROR: cannot begin/end transactions in PL/pgSQL. HINT: Use a BEGIN block with an EXCEPTION clause instead. which confuses me to no end, because that is exactly what I am (I think) doing.
POST-ACCEPT EDIT:
Regarding Laurenz's comment: "Your SQL script would contain a COMMIT. That ends the transaction and rolls it back." - this is not the behavior that I observe. Please consider the following example (which is just a concrete version of an example I already provided in my original question):
BEGIN;
-- Just a simple, self-referencing table.
CREATE TABLE "Dummy" (
"Id" INT GENERATED ALWAYS AS IDENTITY,
"ParentId" INT NULL,
CONSTRAINT "PK_Dummy" PRIMARY KEY ("Id"),
CONSTRAINT "FK_Dummy_Dummy" FOREIGN KEY ("ParentId") REFERENCES "Dummy" ("Id")
);
-- Foreign key violation terminates the transaction.
INSERT INTO "Dummy" ("ParentId")
VALUES (99);
COMMIT;
When I execute the script above, I'm greeted with: ERROR: insert or update on table "Dummy" violates foreign key constraint "FK_Dummy_Dummy". DETAIL: Key (ParentId)=(99) is not present in table "Dummy". which is as expected.
However, if I then try to check whether my Dummy table was created or rolled back like so:
SELECT EXISTS (
SELECT FROM information_schema."tables"
WHERE "table_name" = 'Dummy');
instead of a simple false, I get the same error that I already mentioned twice: ERROR: current transaction is aborted, commands ignored until end of transaction block. Then I have to manually terminate the transaction via issuing ROLLBACK;.
So to me it seems that either the comment mentioned above is false or at least I'm heavily misinterpreting something here.
You cannot use ROLLBACK in PL/pgSQL, except in certain limited cases inside procedures.
You don't need to explicitly roll back in your PL/pgSQL code. Just let the exception propagate out of the PL/pgSQL code, and it will cause an error, which will cause the whole transaction to be rolled back.
Your comments suggest that this code is called from an SQL script. Then the solution would be to have a COMMIT in that SQL script at some place after the PL/pgSQL code. That would end the transaction and roll it back.
I think you must be using an older version, as the exact code from your question works without error for me:
(The above is with PostgreSQL 13.1, and pgAdmin 4.28.)
It also works fine for me, without the exception block:
As per this comment, you can remove the exception block within a function, and if an error occurs, the transaction run within it will automatically be rolled back. That appears to be the case, from my limited testing.

Create History Trigger Db2

I am trying to create a trigger that copys a newly INSERTED and/or UPDATED record from one table to a History version of this table. The purpose is to keep a record every time a record in a table is inserted and/or updated.
This is the Create Trigger statement syntax that I have, following the IBM Db2 Trigger site.
CREATE TRIGGER "TADB2"."HIST_CSEMASTER_Z_LOG"
AFTER UPDATE ON TADB2.CSEMASTER_Z
REFERENCING NEW AS N
FOR EACH ROW
BEGIN ATOMIC
INSERT INTO TADB2.HIST_CSEMASTER_Z
values (N.CSEMASTERID, N.CURRID, N.SUBCURRID, N.EXPIREDATE, N.CREATEDATE, N.CUSTVIEWNUM, N.CSEMSTRNAME, N.JOINCODE, N.CONTACTCOUNTRYCD, N.CONTACTSERIALNUM, N.AUDIENCECD, N.SPONSORNAME, N.AVAILABLEDATE, N.OWNERCOUNTRYCD, N.OWNERSERIALNUM, N.PRMWWCHAPTERID, N.PRMWWSUBCHAPTERID, N.SECWWCHAPTERID, N.SECWWSUBCHAPTERID, N.INTRANETIND, N.TINSERTTS, N.TLASTUPDTS, N.IBM_TRADEMARK, N.OTHER_TRADEMARK, N.INTERNETIND, N.BRANDID, N.BUSINESSID, N.LIFECYCLE_STATUS);
END;
The error I am receiving is:
[Code: -104, SQL State: 42601] An unexpected token "END-OF-STATEMENT" was found following "N.LIFECYCLE_STATUS)". Expected tokens may include: "".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.72.44
I've tried:
Removing the END
Removing the semi-colon after the END
Removing the semi-colon after the N.LIFECYCLE_STATUS);
Any help would be great! Thank you.
I highly recommend Db2 Temporal Tables for that. If you just use System Temporal functionality it would provide already the functionality you describe.
Worth to check it out
You must use different from ';' statement terminator in your tool.
Below is an example for DB2 Command Line Processor, which understands the first line as a directive to do this.
--#SET TERMINATOR #
CREATE TRIGGER "TADB2"."HIST_CSEMASTER_Z_LOG"
AFTER UPDATE ON TADB2.CSEMASTER_Z
REFERENCING NEW AS N
FOR EACH ROW
BEGIN ATOMIC
INSERT INTO TADB2.HIST_CSEMASTER_Z
values (N.CSEMASTERID, N.CURRID, N.SUBCURRID, N.EXPIREDATE, N.CREATEDATE, N.CUSTVIEWNUM, N.CSEMSTRNAME, N.JOINCODE, N.CONTACTCOUNTRYCD, N.CONTACTSERIALNUM, N.AUDIENCECD, N.SPONSORNAME, N.AVAILABLEDATE, N.OWNERCOUNTRYCD, N.OWNERSERIALNUM, N.PRMWWCHAPTERID, N.PRMWWSUBCHAPTERID, N.SECWWCHAPTERID, N.SECWWSUBCHAPTERID, N.INTRANETIND, N.TINSERTTS, N.TLASTUPDTS, N.IBM_TRADEMARK, N.OTHER_TRADEMARK, N.INTERNETIND, N.BRANDID, N.BUSINESSID, N.LIFECYCLE_STATUS);
END#

Creating a trigger gives "function does not exist" error in PostgreSQL

I'm working on a project right now where I'm trying to build a trigger that updates a column "lastedit" (in the table Person), which is a timestamp storing when the last change was made to the table in the schema specified in the trigger creation (in this case Certifications).
Now, my problem is that when I try to create the trigger, after creating the function "update_lastedit()", it gives me an error saying that the function does not exist. I think I might have a mismatch in my function somewhere, but I cannot seem to find it.
Could any of you help me out? I'm running PostgreSQL 9.5.5. Please let me know if I need to give a more extensive explanation, this is my first question, so I might have overlooked something important.
My code for the trigger and the function are as follows:
CREATE OR REPLACE FUNCTION update_lastedit() RETURNS TRIGGER AS
$update_edit$
BEGIN
UPDATE ovsoftware.person
SET lastedit = now();
END;
$update_edit$
LANGUAGE plpgsql;
and
CREATE TRIGGER cert_edit_trigger
BEFORE INSERT OR UPDATE ON ovsoftware.certifications
FOR EACH ROW
EXECUTE PROCEDURE update_lastedit();
The exact error:
SQL fout:
ERROR: function update_lastedit() does not exist
In statement:
CREATE TRIGGER cert_edit_trigger
BEFORE INSERT OR UPDATE ON ovsoftware.certifications
FOR EACH ROW
EXECUTE PROCEDURE update_lastedit();
The solution was to use a fully qualified name for the function as follows: ovsoftware.update_lastedit(). I am not sure why that is the case, as I did not need to do so in other cases.
Either way, the scope apparently did not include the ovsoftware schema, leading to the error.

Replacing trigger procedure without deleting triggers

I have trigger procedure:
CREATE OR REPLACE FUNCTION my_func() RETURNS trigger AS
$BODY$
// Do something :-)
RAISE NOTICE 'Done';
RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql;
It is used for auditing and every single table in my DB have trigger which calls the procedure.
What I'm trying to do is to remove "raise notice" line - seems to be simple, but it is not.. I tried to insert new procedure to database without the line, thinking that "create od REPLACE" would do the work, but there was still only old version in my DB.
I think that the problem is caused by triggers connected with the procedure.
Do I have to 1. remove all of the triggers (over 80 tables => 80 triggers :( ), 2. replace procedure with new version, 3. re-create triggers?
Or is there another way to make "force replace"?
DBMS: PostgreSQL 9.2.6
What I'm trying to do is to remove "raise notice" line - seems to be simple, but it is not.. I tried to insert new procedure to database without the line, thinking that "create od REPLACE" would do the work, but there was still only old version in my DB.
Nope. Either you've installed the new function in the wrong database, wrong schema, with a typo in the name, failed to commit the change or missed an error message.
I replace trigger functions frequently and they're no different to any other function - CREATE OR REPLACE works just fine.

debugging postgresql trigger

I have this Trigger in Postgresql that I can't just get to work (does nothing). For understanding, there's how I defined it:
CREATE TABLE documents (
...
modification_time timestamp with time zone DEFAULT now()
);
CREATE FUNCTION documents_update_mod_time() RETURNS trigger
AS $$
begin
new.modification_time := now();
return new;
end
$$
LANGUAGE plpgsql;
CREATE TRIGGER documents_modification_time
BEFORE INSERT OR UPDATE ON documents
FOR EACH ROW
EXECUTE PROCEDURE documents_update_mod_time();
Now to make it a bit more interesting.. How do you debug triggers?
Use the following code within a trigger function, then watch the 'messages' tab in pgAdmin3 or the output in psql:
RAISE NOTICE 'myplpgsqlval is currently %', myplpgsqlval; -- either this
RAISE EXCEPTION 'failed'; -- or that
To see which triggers actually get called, how many times etc, the following statement is the life-saver of choice:
EXPLAIN ANALYZE UPDATE table SET foo='bar'; -- shows the called triggers
Note that if your trigger is not getting called and you use inheritance, it may be that you've only defined a trigger on the parent table, whereas triggers are not inherited by child tables automatically.
To step through the function, you can use the debugger built into pgAdmin3, which on Windows is enabled by default; all you have to do is execute the code found in ...\8.3\share\contrib\pldbgapi.sql against the database you're debugging, restart pgAdmin3, right-click your trigger function, hit 'Set Breakpoint', and then execute a statement that would cause the trigger to fire, such as the UPDATE statement above.
Turns out I was using inheritance in the above problem and forgot to mention it. Now for everybody who might run into this as well, here's some debugging hints:
Use the following code to debug what a trigger is doing:
RAISE NOTICE 'test'; -- either this
RAISE EXCEPTION 'failed'; -- or that
To see which triggers actually get called, how many times etc, the following statement is the life-saver of choice:
EXPLAIN ANALYZE UPDATE table SET foo='bar'; -- shows the called triggers
Then there's the one thing I didn't know before: triggers only fire when updating the exact table they're defined on. If you use inheritance, you MUST define them on the child tables as well!
You can use 'raise notice' statements inside your trigger function to debug it. To debug the trigger not being called at all is another story.
If you add a 'raise exception' inside your trigger function, can you still do inserts/updates?
Also, if your update test occurs in the same transaction as your insert test, now() will be the same (since it's only calculated once per transaction) and therefore the update won't seem to do anything. If that's the case, either do them in separate transactions, or if this is a unit test and you can't do that, use clock_timestamp().
I have a unit test that depends on some time going by between transactions, so at the beginning of the unit test I have something like:
ALTER TABLE documents
ALTER COLUMN modification_time SET DEFAULT clock_timestamp();
Then in the trigger, use "set modification_time = default".
So normally it doesn't do the extra calculation, but during a unit test this allows me to do inserts with pg_sleep in between to simulate time passing and actually have that be reflected in the data.