Getting SQL state: 25P02 while trying to update a table with data from another - postgresql

I am using a PostgreSQL DB. I have two tables, namely company and bl_location. I have a field location_id in both tables. Now I am trying to copy the value of location_id from bl_location to company. The primary key of company is company_id and it is stored in bl_location too. I am trying the following query:
UPDATE company
SET location_id = bl_location.location_id
from bl_location
where company.company_id = bl_location.company_id;
using the syntax I found online:
update table1
set col1 = . . .
from table2
where table1.id = table2.table1_id
But I am getting the following in the console of the pgAdmin tool:
ERROR: current transaction is aborted, commands ignored until end of transaction block
********** Error **********
ERROR: current transaction is aborted, commands ignored until end of transaction block
SQL state: 25P02
I cannot figure out what is wrong with my query.

RCA : This issue happens when last transitions ended up with error and not rolled back
FIX : psql > ROLLBACK
if you're using PGAdmin click on rollback & enable auto rollback option

Whether you are aware of it or not, your statement is running inside an explicit transaction, and one of the preceeding statements is the same transaction must have caused an error.
To debug this, consider setting log_statement = 'all' so that all statments get logged. By tracing all statements from the same backend PID you will be able to identify the culprit.

Related

Cannot rename database due to prepared transactions

I'm trying to rename a database using:
ALTER DATABASE xxx RENAME TO yyy
I got an error message saying there is another open session. I killed it using:
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'xxx' AND pid <> pg_backend_pid();
However, I then got an error message saying there are 2 prepared transactions pending. I made sure to kill all processes in the background with:
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid();
But still, I am not able to rename the database.
I then saw there is a view by postgres called pg_prepared_xacts that shows me the prepared transactions (shortened the gid for a better overview), and indeed, there are two of them:
transaction|gid |prepared |owner|database|
-----------+--------------+-----------------------------+-----+--------+
5697779 |4871251_EAAAAC|2022-08-05 15:50:59.782 +0200|xxx |xxx |
5487701 |4871251_DAAAAA|2022-07-08 08:05:36.066 +0200|xxx |xxx |
According to the Postgres documentation on prepared transactions, I can execute a Rollback on the transaction id - which is what I did:
ROLLBACK PREPARED '5697779';
I made sure to execute the ROLLBACK with the same user, but it shows an error message saying that the transaction does not exist...
How can I get rid of it / kill it in order to be able to rename the database?
Thank you for reading and taking time to respond.
From here Prepared transaction:
transaction_id
An arbitrary identifier that later identifies this transaction for COMMIT PREPARED or ROLLBACK PREPARED. The identifier must be written as a string literal, and must be less than 200 bytes long. It must not be the same as the identifier used for any currently prepared transaction.
and from here Rollback prepared:
transaction_id
The transaction identifier of the transaction that is to be rolled back.
Lastly from here pg_prepared_xacts:
gid text
Global transaction identifier that was assigned to the transaction
So to rollback the transaction you need the global identifier assigned in the PREPARE TRANSACTION as shown in the gid column in pg_prepared_xacts.

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.

Continue sql statement after an error in postgresql database

I am working on a view which this is its sql
-- DROP VIEW bd_segment_id;
CREATE OR REPLACE VIEW bd_segment_id AS
SELECT final.gid,
row_number() OVER (ORDER BY final.gid) AS row_number,
degrees(st_azimuth(ff.sp, ff.ep) - 1.57079633::double precision) AS az_deg,
st_length(ff.st_makeline) AS st_length,
ff.st_makeline
FROM bd_segment_geom ff
JOIN final ON st_touches(ff.st_makeline, final.geom)
GROUP BY final.gid, ff.sp, ff.ep, ff.st_makeline;
ALTER TABLE bd_segment_id
OWNER TO postgres;
while running each query of this table I have faced this error
ERROR: GEOSTouches: TopologyException: side location conflict at 553655.77720000315 3474241.5185000021
********** Error **********
ERROR: GEOSTouches: TopologyException: side location conflict at 553655.77720000315 3474241.5185000021
SQL state: XX000
Is there any way for sql to pass errors and continues to do the rest of sql?I know the problem is an internal error but I want sql jump of it..
I have searched and found this in section 39.6.6. Trapping Errors is says how we can use an EXCEPTION clause but I don't know how to write handler_statements that says sql to continue.
I need sth like try catch in C# or jave
can some one please help me with this problem?
thank you

Dreamfactory: Database connection to Postgres

First I set up the dream factory by "Bitnami Installer for Windows". Following to https://github.com/dreamfactorysoftware/dsp-core/wiki/Install-Microsoft-Windows
Then I follow this add-a-rest-api-to-any-sql-db-in-minutes to add Services to my Remote Postgres Database.
On the "API Docs" tab, it is success to call the GET /db operation. ( getTables() - List all table names).
I got the following error when trying to call GET /db/{table_name} operation ( getRecordsByFilter() - Retrieve one or more records by using a filter).
Please help
[app][ERROR ] CDbCommand::fetchAll() failed: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "field_name"
LINE 1: SELECT k.column_name field_name
^. The SQL statement executed was: SELECT k.column_name field_name
FROM "information_schema"."key_column_usage" k
LEFT JOIN "information_schema"."table_constraints" c
ON k.table_name = c.table_name
AND k.constraint_name = c.constraint_name
WHERE c.constraint_type ='PRIMARY KEY'
AND k.table_name = :table
AND k.table_schema = :schema.
Please check the version of PostgreSQL you are connecting to. It turns out that omission of as keyword is supported starting from 8.4.
Here's a quote from 8.4 release notes section E.23.3.3. Queries:
Allow AS to be optional when specifying a SELECT (or RETURNING) column
output label (Hiroshi Saito)
This works so long as the column label is not any PostgreSQL keyword;
otherwise AS is still needed.
Therefore SELECT k.column_name field_name is not valid for 8.3 and below, but SELECT k.column_name AS field_name would work.
If PostgreSQL version is the cause of your problem you have several options:
update the database to 8.4 and above;
patch the Dreamfactory codebase yourself to work around this problem;
raise a ticket in Dreamfactory's bug tracker and wait them to fix it for you.

Transaction context in use by another session

I have a table called MyTable on which I have defined a trigger, like so:
CREATE TRIGGER dbo.trg_Ins_MyTable
ON dbo.MyTable
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
insert SomeLinkedSrv.Catalog.dbo.OtherTable
(MyTableId, IsProcessing, ModifiedOn)
values (-1, 0, GETUTCDATE())
END
GO
Whenever I try to insert a row in MyTable, I get this error message:
Msg 3910, Level 16, State 2, Line 1
Transaction context in use by another session.
I have SomeLinkedSrv properly defined as a linked server (for example, select * from SomeLinkedSrv.Catalog.dbo.OtherTable works just fine).
How can I avoid the error and successfully insert record+execute the trigger?
Loopback linked servers can't be used in a distributed transaction if MARS is enabled.
Loopback linked servers cannot be used in a distributed transaction.
Trying a distributed query against a loopback linked server from
within a distributed transaction causes an error, such as error 3910:
"[Microsoft][ODBC SQL Server Driver][SQL Server]Transaction context in
use by another session." This restriction does not apply when an
INSERT...EXECUTE statement, issued by a connection that does not have
multiple active result sets (MARS) enabled, executes against a
loopback linked server. Note that the restriction still applies when
MARS is enabled on a connection.
http://msdn.microsoft.com/en-us/library/ms188716(SQL.105).aspx
I solve It.
I was using the same linked server to call the second procedure and then into the procedure I was using the same linked server.
It's very Easy, only we have to know the restricctions of linked servers.
I have resolved it by removing linked server used in the stored procedure and then called stored procedure by the same linked server. It wasnt working in DEV environement.
One of causes of this situation is a trigger that works for linked-sever database table. An also SQL version of SQL-Server which processes database matters. To avoid this ERROR during sql query execution we should temporarily disable and after execution enable triggers for tables updated. All with database name check. Here is an example:
Select * From People where PersonId In (#PersonId, #PersonIdRight)
IF 'DOUBLE' = DB_NAME()
ALTER TABLE [dbo].[PeopleSites] DISABLE TRIGGER [PeopleSites_ENTDB_UPDATE]
Update PeopleSites Set PersonId = #PersonIdRight Where PersonId = #PersonId
IF 'DOUBLE' = DB_NAME()
ALTER TABLE [dbo].[PeopleSites] ENABLE TRIGGER [PeopleSites_ENTDB_UPDATE]
Select * From PeopleSites where PersonId In (#PersonId, #PersonIdRight)
I also got the same error in our DEV environemnt, moving the linked databases to another sql instance resolved the issue. In our production environment these databases are already on separate instances
In my case I was using SQL 2005 and got "transaction context in use by another session" when running Insert....exec over a linked server. The fix for me was to patch from SP2 build 3161 to SP3. SP2 cumulative 5 is supposed to fix though.
https://support.microsoft.com/en-us/kb/947486
When remote database sits on the same server,configure the linked server without specifying the database server ip / hostname and port. Just the database name should be sufficient.
I was getting the same "transaction context in use by another session error" when trying to run an UPDATE query:
BEGIN TRAN
--ROLLBACK TRAN
--COMMIT TRAN
UPDATE did
SET did.IsProcessed = 0,
did.ProcessingLockID = NULL
FROM [proddb\production].DLP.dbo.tbl_DLPID did (NOLOCK)
WHERE did.dlpid IN ('bunch of GUIDs')
--WHERE did.DLPID IN (SELECT DLPID FROM #TableWithData)
However I didn't realize I was already trying to run this on the DLP database on the ProdDb\Production server. Once I removed that "[proddb\production].DLP.dbo." prefix from the query, it worked fine.