PSQLException: current transaction is aborted, commands ignored until end of transaction block
Asked Answered
Y

22

281

I am seeing the following (truncated) stacktrace in the server.log file of JBoss 7.1.1 Final:

Caused by: org.postgresql.util.PSQLException: 
ERROR: current transaction is aborted, commands ignored until end of 
transaction block

at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_23]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_23]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_23]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_23]
at org.postgresql.ds.jdbc23.AbstractJdbc23PooledConnection$StatementHandler.invoke(AbstractJdbc23PooledConnection.java:455)
at $Proxy49.executeUpdate(Unknown Source)   at org.jboss.jca.adapters.jdbc.WrappedStatement.executeUpdate(WrappedStatement.java:371)
at org.infinispan.loaders.jdbc.TableManipulation.executeUpdateSql(TableManipulation.java:154) [infinispan-cachestore-jdbc-5.1.2.FINAL.jar:5.1.2.FINAL]
... 154 more

Inspecting the Postgres log file reveals the following statements:

STATEMENT:  SELECT count(*) FROM ISPN_MIXED_BINARY_TABLE_configCache
ERROR:  current transaction is aborted, commands ignored until end of transaction block
STATEMENT:  CREATE TABLE ISPN_MIXED_BINARY_TABLE_configCache(ID_COLUMN VARCHAR(255) NOT NULL, DATA_COLUMN BYTEA, TIMESTAMP_COLUMN BIGINT, PRIMARY KEY (ID_COLUMN))
ERROR:  relation "ispn_mixed_binary_table_configcache" does not exist at character 22

I am using the Infinispan shipped with JBoss 7.1.1 Final, which is 5.1.2.Final.

So this is what I think is happening:

  • Infinispan attempts to run the SELECT count(*)... statement in order to see if there are any records in the ISPN_MIXED_BINARY_TABLE_configCache;
  • Postgres, for some reason, does not like this statement.
  • Infinispan ignores this and plows ahead with the CREATE TABLE statement.
  • Postgres barfs because it still thinks it's the same transaction, which Infinispan has failed to roll back, and this transaction is shafted from the first SELECT count(*)... statement.

What does this error mean and any idea how to work around it?

Yamamoto answered 1/5, 2012 at 15:11 Comment(4)
Just if you came here like me searching for the above PSQLException: current transaction is aborted... (25P02) and maybe also JPA or Hibernate. Finally it was due to our (nice!) Logback usage fed with a toString()-overloaded DAO object that caused the error and was nicely swallowed (but accidentially unnoticed by me): log.info( "bla bla: {}", obj ) produced bla bla: [FAILED toString()]. changing it to log.info( "bla bla: {}", String.valueOf( obj ) made it null-safe, but not swallowing it and thus leaving the transaction open failing on an unrelated query.Pejorative
I was getting same type of error. I had to release the connection before the sql. Mine code was connection.commit()Amendatory
I have answered here https://mcmap.net/q/92511/-databaseerror-current-transaction-is-aborted-commands-ignored-until-end-of-transaction-block and it works!Violoncellist
There are 2 ways to fix this. 1) run ROLLBACK; this will sort the issue with the current tab, 2) open a new tab and run the same command. Try to add try catch in the query running.Psychoneurotic
C
326

I got this error using Java and PostgreSQL doing an insert on a table. I will illustrate how you can reproduce this error:

org.postgresql.util.PSQLException: ERROR: 
current transaction is aborted, commands ignored until end of transaction block

Summary:

The reason you get this error is because you have entered a transaction and one of your SQL Queries failed, and you gobbled up that failure and ignored it. But that wasn't enough, THEN you used that same connection, using the SAME TRANSACTION to run another query. The exception gets thrown on the second, correctly formed query because you are using a broken transaction to do additional work. PostgreSQL by default stops you from doing this.

I'm using: PostgreSQL 9.1.6 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2), 64-bit".

My PostgreSQL driver is: postgresql-9.2-1000.jdbc4.jar

Using Java version: Java 1.7

Here is the table create statement to illustrate the Exception:

CREATE TABLE moobar
(
    myval   INT
);

Java program causes the error:

public void postgresql_insert()
{
    try  
    {
        connection.setAutoCommit(false);  //start of transaction.
        
        Statement statement = connection.createStatement();
        
        System.out.println("start doing statement.execute");
        
        statement.execute(
                "insert into moobar values(" +
                "'this SQL statement fails, and it " +
                "is gobbled up by the catch, okfine'); ");
     
        //The above line throws an exception because we try to cram
        //A string into an Int.  I Expect this, what happens is we gobble 
        //the Exception and ignore it like nothing is wrong.
        //But remember, we are in a TRANSACTION!  so keep reading.

        System.out.println("statement.execute done");
        
        statement.close();
        
    }
    catch (SQLException sqle)
    {
        System.out.println("keep on truckin, keep using " +
                "the last connection because what could go wrong?");
    }
    
    try{
        Statement statement = connection.createStatement();
        
        statement.executeQuery("select * from moobar");

        //This SQL is correctly formed, yet it throws the 
        //'transaction is aborted' SQL Exception, why?  Because:
        //A.  you were in a transaction.
        //B.  You ran a SQL statement that failed.
        //C.  You didn't do a rollback or commit on the affected connection.
        
    }
    catch (SQLException sqle)
    {
        sqle.printStackTrace();
    }   

}

The above code produces this output for me:

start doing statement.execute

keep on truckin, keep using the last connection because what could go wrong?

org.postgresql.util.PSQLException: 
  ERROR: current transaction is aborted, commands ignored until 
  end of transaction block

Workarounds:

You have a few options:

  1. Simplest solution: Don't be in a transaction. Set the connection.setAutoCommit(false); to connection.setAutoCommit(true);. It works because then the failed SQL is just ignored as a failed SQL statement. You are welcome to fail SQL statements all you want and PostgreSQL won't stop you.

  2. Stay being in a transaction, but when you detect that the first SQL has failed, either rollback/re-start or commit/restart the transaction. Then you can continue failing as many SQL queries on that database connection as you want.

  3. Don't catch and ignore the Exception that is thrown when a SQL statement fails. Then the program will stop on the malformed query.

  4. Get Oracle instead, Oracle doesn't throw an exception when you fail a query on a connection within a transaction and continue using that connection.

In defense of PostgreSQL's decision to do things this way... Oracle was making you soft in the middle letting you do dumb stuff and overlooking it.

Consols answered 1/5, 2012 at 15:11 Comment(7)
Lol @ Option 4... I had done quite a bit of development in Oracle, and recently started using Postgres... it's really annoying that Postgres does this, and now we have to be really rewrite a big bulk of our program that we are porting from Oracle to Postgres. Why isn't there an option like the first to make it behave like Oracle but without the auto-commit?Altruist
Found out after some trials that Option 2 is the closest you can get to Oracle behavior. If you need to issue multiple updates, and one failure should not stop subsequent updates, simply call rollback() on the Connection when an SQLException is caught. [Anyway I realized this is in-line with the PostgreSQL philosophy of forcing the user to make everything explicit, whereas Oracle has the philosophy of implicitly taking care of a lot of things.]Altruist
Is there a way of checking the Connection object (in Java) to see if a transaction has failed?Zadazadack
Option 2 contains impossible branch or commit/restart the transaction. As I can see there is no way to commit after exception. When I try to commit - PostgreSQL do rollbackChromyl
I can confirm the problem raised by @turbanoff. This can also be reproduced directly with psql. (1) start a transaction, (2) issue some valid statements, (3) issue an invalid statement, (4) commit --> psql will rollback rather than committing.Swanherd
postgresql.org/message-id/op.ur57x9ue33x80h%40insanity.lain.pl an interesting discussion of this topic. If this issue is triggered by a constraint violation, the PostgreSQL devs recommend checking for a conflict ahead of time (query before update/insert) or using savepoints to roll back to the point before the update/insert. See https://mcmap.net/q/107864/-psqlexception-current-transaction-is-aborted-commands-ignored-until-end-of-transaction-block for sample code.Saw
Not mentioning SavePoints as an option is a huge hole in this answerCoppage
B
50

Check the output before the statement that caused current transaction is aborted. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.

So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.

You should catch all exceptions and rollback transactions in such cases.

Here's a similar issue.

Bettyannbettye answered 1/5, 2012 at 15:36 Comment(5)
That's great, except in this case it would be Infinispan, a 3rd-party library, doing the talking to Postgres, and not my code.Yamamoto
Well, the situation still the same — transaction has to be rolled back. Maybe check if there's a newer version of the library you're using or rise the issue within their bug tracker. If you'll find the exact SQL that caused the issue, you'll have some field to eliminate the issue using PostgreSQL extensibility.Bettyannbettye
Seems like you've confirmed my suspicions - I am going to look at the Infinispan 5.1.2 source now.Yamamoto
To be fair, in the TableManipulation class, there is a try-catch around the attempt to run select count(*).... Perhaps the Postgres driver is not throwing one of the expected exceptions. I will hook up a debugger to JBoss to try to find out more.Yamamoto
The Infinispan code in question was suggested in this bug: issues.jboss.org/browse/… I have attached a debugger to it running on a live JBoss 7.1.1 instance and Postgres is throwing exceptions in the right places. Perhaps it is the JdbcUtil.safeClose() statements that are not doing their job. I shall raise it with Infinispan.Yamamoto
C
28

I think that the best solution is to use java.sql.Savepoint.

Before you execute a query which can throw SQLException, use the method Connection.setSavepoint(), and if an exception is thrown you only rollback to this savepoint, not the whole transaction.

Example code:

Connection conn = null;
Savepoint savepoint = null;
try {
    conn = getConnection();
    savepoint = conn.setSavepoint();
    //execute some query
} catch(SQLException e) {
    if(conn != null && savepoint != null) {
        conn.rollback(savepoint);
    }
} finally {
   if(conn != null) {
      try {
          conn.close();
      } catch(SQLException e) {}

   }
}
Closed answered 21/2, 2015 at 0:30 Comment(2)
I accidentally downvoted somehow, only just noticed. Wasn't intentional, I can't undo unless answer is edited.Retaretable
The savepoint way is the actual solution. Works for me also in environment of PHP, Doctrine2 and Postgres (9.5). ThanksInequitable
A
20

There's been some work done on the postgresql JDBC Driver, related to this behaviour:
see https://github.com/pgjdbc/pgjdbc/pull/477

It is now possible, by setting

autosave=always
in the connection (see https://jdbc.postgresql.org/documentation/head/connect.html) to avoid the 'current transaction is aborted' syndroma.
Overhead due to handling a savepoint around the statement execution is kept very low (see link above for details).
Anaesthesiology answered 13/2, 2018 at 16:28 Comment(2)
IMO, this should be accepted answer on this question. Also along with 'autosave=always', it's advisable to set 'cleanupSavepoints=true' to avoid running out of shared buffers.Buckshot
works like a charm. put in connection string like jdbc://localhost:5432/xxxx?autosave=alwaysEscalera
R
18

Try this COMMIT;

I run that in pgadmin4. It may help. It has to do with the previous command stopping prematurely

Ragucci answered 23/4, 2020 at 14:24 Comment(1)
Solved problem for me)Bankston
P
7

I faced this error in my DB application tool because there is one uncommited transaction. And i'm trying to run a select query. so that gave me this error. You can fix these either running

commit;

or

rollback;
Pasteurism answered 22/8, 2022 at 13:57 Comment(0)
H
6

You need to rollback. The JDBC Postgres driver is pretty bad. But if you want to keep your transaction, and just rollback that error, you can use savepoints:

try {
_stmt = connection.createStatement();
_savePoint = connection.setSavepoint("sp01");
_result = _stmt.executeUpdate(sentence) > 0;
} catch (Exception e){
 if (_savePoint!=null){
 connection.rollback(_savePoint);
}
}

Read more here:

http://www.postgresql.org/docs/8.1/static/sql-savepoint.html

Hinman answered 4/11, 2015 at 5:16 Comment(0)
C
6

In Ruby on Rails PG, I had created a migration, migrated my DB, but forgot to restart my development server. I restarted my server and it worked.

Contrasty answered 13/2, 2016 at 5:27 Comment(1)
That was my case as well. Thought it should be something stupid, because I didn't really try to do anything that complicated.Giaour
N
6

The reason for this error is that there are other database before the wrong operation led to the current database operation can not be carried out(i use google translation to translate my chinese to english)

Nina answered 9/6, 2017 at 2:37 Comment(0)
A
5

If you are using a SQL client like dbeaver or pgAdmin, just click on Disconnect and connect again from the squema or database.

Autobiography answered 20/4, 2023 at 23:54 Comment(1)
I was using Dbeaver, it works. Thanks for help.Brabazon
F
3

The issue has been fixed in Infinispan 5.1.5.CR1: ISPN-2023

Facsimile answered 30/5, 2012 at 10:26 Comment(0)
H
3

I had the same issue but then realised there is a table with the same name in the database. After deleting that I was able to import the file.

Hailstone answered 27/2, 2018 at 23:44 Comment(1)
This was my issue, the tables for me were across two different schemas.Chanson
D
1

This is very weird behavior of PostgreSQL, it is even not " in-line with the PostgreSQL philosophy of forcing the user to make everything explicit" - as the exception was caught and ignored explicitly. So even this defense does not hold. Oracle in this case behaves much more user-friendly and (as for me) correctly - it leaves a choice to the developer.

Dwell answered 15/1, 2014 at 15:19 Comment(0)
C
1

This can happen if you are out of disk space on the volume.

Crocidolite answered 11/5, 2015 at 19:34 Comment(1)
I realize this is not the most common cause, but this was the case on a server that I was asked to troubleshoot. So I think this should be listed as a potential cause.Crocidolite
F
1

For me issues was, driver wasn't installed. I downloaded the driver and pasted in ~/Library/Tableau/Driver(mac) folder & it worked.

Ferris answered 18/1, 2022 at 10:42 Comment(0)
A
0

I just encounter the same error. I was able to figure out the root cause by enabling the log_statement and log_min_error_statement in my local PostgreSQL.

I Referred this

Arman answered 15/8, 2016 at 6:42 Comment(0)
T
0

I am using JDBI with Postgres, and encountered the same problem, i.e. after a violation of some constraint from a statement of previous transaction, subsequent statements would fail (but after I wait for a while, say 20-30 seconds, the problem goes away).

After some research, I found the problem was I was doing transaction "manually" in my JDBI, i.e. I surrounded my statements with BEGIN;...COMMIT; and it turns out to be the culprit!

In JDBI v2, I can just add @Transaction annotation, and the statements within @SqlQuery or @SqlUpdate will be executed as a transaction, and the above mentioned problem doesn't happen any more!

Tolly answered 28/8, 2017 at 22:39 Comment(0)
J
0

In my case i was getting this error because my file was corrupt. While iterating the records of files it was giving me the same error.

May be in future it will help to anyone. That's the only reason to post this answer.

Jair answered 19/11, 2019 at 13:5 Comment(0)
F
0

I use spring with @Transactional annotation, and I catch the exception and for some exception I will retry 3 times.

For posgresql, when got exception, you can't use same Connection to commit any more.You must rollback first.

For my case, I use the DatasourceUtils to get current connection and call connection.rollback() manually. And the call the method recruive to retry.

Fetor answered 15/1, 2020 at 3:25 Comment(0)
O
-1

Change the isolation level from repeatable read to read committed.

Ontina answered 24/1, 2015 at 14:46 Comment(0)
K
-1

I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement

Attached file may help you.

Karrykarst answered 21/4, 2020 at 16:13 Comment(0)
K
-4

I was working with spring boot jpa and fixed by implementing @EnableTransactionManagement

Attached file may help you.enter image description here

Karrykarst answered 21/4, 2020 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.