DbUnit does not update postgresql sequences on insert DbUnit does not update postgresql sequences on insert postgresql postgresql

DbUnit does not update postgresql sequences on insert


The function below finds all sequences in a database, extracts the name of the corresponding table from the sequence name and finally updates the current value of the sequences based on the maximum id value in the corresponding table. As there has been no better solution yet, this seems to be the way to go. Hope, this helps someone.

Simple solution based on harmic's suggestion

@Beforepublic void resetSequence() {    Connection conn = null;    try {        // Establish a database connection.        conn = DriverManager.getConnection(                this.props.getProperty("database.jdbc.connectionURL"),                this.props.getProperty("database.jdbc.username"),                 this.props.getProperty("database.jdbc.password"));        // Select all sequence names ...        Statement seqStmt = conn.createStatement();        ResultSet rs = seqStmt.executeQuery("SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';");        // ... and update the sequence to match max(id)+1.        while (rs.next()) {            String sequence = rs.getString("relname");            String table = sequence.substring(0, sequence.length()-7);            Statement updStmt = conn.createStatement();            updStmt.executeQuery("SELECT SETVAL('" + sequence + "', (SELECT MAX(id)+1 FROM '" + table + "'));");        }    } catch (SQLException e) {        e.printStackTrace();    } finally {        try {            conn.close();        } catch (SQLException e) {        }    }}


You can set the value of a sequence using setval, for example

SELECT SETVAL('sequence_name', 1000);

Where sequence_name is the name of the sequence, visible in psql using /dt on the table, and 1000 is the value you want to set it to. You would probably want to set it to the Max value of Id in the table.

What I don't really know is how to get DbUnit to emit this SQL.