Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are my queries deadlocking?
    primarykey
    data
    text
    <p>I'm trying to insert some files into a Postgres database. Since lots of duplication is expected, we put the files themselves into the <code>file</code> table, then link them to the section of the database we're using with the <code>output_file</code> table. As the <code>file</code> table is also referenced by tables other than <code>output_file</code> (for example, the similar <code>input_file</code> table), one of its columns is a reference count, which is updated by a trigger when rows are inserted into <code>output_file</code> (and the other tables, too, although they aren't being used at the times the problem occurs).</p> <pre><code>CREATE TABLE file ( file_id serial PRIMARY KEY, --other columns occurences integer NOT NULL DEFAULT 0 ); CREATE TABLE output_file ( output_file_id serial PRIMARY KEY, --other columns file_id integer REFERENCES file NOT NULL ); CREATE OR REPLACE FUNCTION file_insert() RETURNS opaque AS ' BEGIN UPDATE file SET occurences = occurences + 1 WHERE file.file_id = NEW.file_id; RETURN NEW; END; ' LANGUAGE plpgsql; CREATE TRIGGER output_file_insert AFTER INSERT ON output_file FOR EACH ROW EXECUTE PROCEDURE file_insert(); </code></pre> <p>The code that inserts the files is shown below, and is all one transaction.</p> <pre><code>private void insertFiles(Set&lt;File&gt; files){ SortedSet&lt;Integer&gt; outputFileIDs = new TreeSet&lt;Integer&gt;(); PreparedStatement fileExistsStatement = getFileExistsStatement(); for(File file : files) { try { int fileID = -1; ResultSet rs = /* Query to see if file already present in file table */ if(rs.next()) { // File found fileID = rs.getInt(1); } if(fileID &lt; 0) { /* File does not exist, upload it */ rs = /* Query to get file ID */ fileID = rs.getInt(1); } outputFileIDs.add(fileID); } catch(FileNotFoundException e){ /* handle errors */ } } Iterator&lt;Integer&gt; it = outputFileIDs.iterator(); while(it.hasNext()){ /* Insert reference in output file table */ PreparedStatement outputFileStatement = "INSERT INTO output_file (file_id, /*...*/) VALUES (?, /*...*/);"; outputFileStatement.setInt(1, it.next()); outputFileStatement.executeUpdate(); } } </code></pre> <p>My problem is that code deadlocks (exception shown below) <em>a lot</em>. It'll chunter along fairly happily for a while, then deadlocks will start happening all over the place, to the extent that nothing makes it into the database at all when we roll back and retry. I'm mystified as to why it's deadlocking in the first place, though. The file IDs are stored in a sorted set, and so the locks on the <code>file</code> table should be acquired in a consistent order for all transactions, as suggested in the Postgres manual, preventing any deadlock. What am I doing wrong? Does Postgres run its triggers in an undefined order?</p> <pre><code>org.postgresql.util.PSQLException: ERROR: deadlock detected Detail: Process 8949 waits for ShareLock on transaction 256629; blocked by process 8924. Process 8924 waits for ExclusiveLock on tuple (4148,40) of relation 30265 of database 16384; blocked by process 8949. Hint: See server log for query details. Where: SQL statement "UPDATE file SET occurences = occurences + 1 WHERE file.file_id = NEW.file_id" PL/pgSQL function "file_insert" line 2 at SQL statement 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:500) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105) at [outputFileStatement.executeUpdate(), above] </code></pre> <p>[edit] As requested by axtavt, transactions are managed by the code which calls the method shown.</p> <pre><code>public void run(){ /* connection.setAutoCommit(false) has already been called elsewhere */ try{ boolean committed = false; boolean deadlocked = false; synchronized(connection){ do{ deadlocked = false; try { /* insert lots of other stuff */ if(!files.isEmpty()){ insertFiles(files); } /* insert some more stuff */ connection.commit(); committed = true; closeStatements(); } catch(PSQLException e){ if(e.getSQLState() != null){ if(e.getSQLState().equals("40P01")){ /* Log the fact that we're deadlocked */ deadlocked = true; } else{ throw e; } } else{ throw e; } } finally { try { if(!committed) { connection.rollback(); } } catch (SQLException e) { /* Log exceptions */ } } }while(deadlocked); } } catch(Exception e){ /* Log exceptions */ } finally{ try { connection.close(); } catch (SQLException e) { /* Log exceptions */ } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload