Skip to content

Commit

Permalink
[#1369] Test ConstraintViolationException SQLState code
Browse files Browse the repository at this point in the history
  • Loading branch information
DavideD committed Nov 29, 2023
1 parent 7ed6d24 commit 5736d60
Showing 1 changed file with 26 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
*/
package org.hibernate.reactive;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.reactive.containers.DatabaseConfiguration;
import org.hibernate.reactive.mutiny.Mutiny;

import org.junit.jupiter.api.Test;
Expand All @@ -21,8 +23,10 @@
import jakarta.persistence.Table;

import static java.util.concurrent.TimeUnit.MINUTES;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hibernate.reactive.containers.DatabaseConfiguration.DBType.SQLSERVER;
import static org.hibernate.reactive.containers.DatabaseConfiguration.dbType;
import static org.hibernate.reactive.testing.ReactiveAssertions.assertThrown;

@Timeout(value = 10, timeUnit = MINUTES)

Expand All @@ -33,25 +37,34 @@ protected Collection<Class<?>> annotatedEntities() {
return List.of( Person.class );
}

Class<?> getExpectedException() {
return ConstraintViolationException.class;
}

@Test
public void testDuplicateKeyException(VertxTestContext context) {
test( context, openMutinySession()
test( context, assertThrown( ConstraintViolationException.class, openMutinySession()
.call( session -> session.persist( new Person( "testFLush1", "unique" ) ) )
.call( Mutiny.Session::flush )
.call( session -> session.persist( new Person( "testFlush2", "unique" ) ) )
.call( Mutiny.Session::flush )
.invoke( ignore -> fail( "Expected exception not thrown" ) )
.onFailure().recoverWithItem( err -> {
assertEquals( getExpectedException(), err.getClass() );
return null;
} )
.call( Mutiny.Session::flush ) )
.invoke( MutinyExceptionsTest::testExceptionMessage )
);
}

private static void testExceptionMessage(ConstraintViolationException exception) {
assertThat( exception.getConstraintName() )
.as( "Failed constraint name should not be null" )
.isNotNull();
if ( dbType() == SQLSERVER ) {
// The SQL state code is always null in Sql Server (see https://github.com/eclipse-vertx/vertx-sql-client/issues/1385)
// We test the vendor code for now
SQLException sqlException = (SQLException) exception.getCause();
assertThat( sqlException.getErrorCode() ).isEqualTo( 2601 );
}
else {
assertThat( exception.getSQLState() )
.as( "Constraint violation SQL state code should start with 23" )
.matches( "23\\d{3}" );
}
}

@Entity(name = "Person")
@Table(name = "PersonForExceptionWithMutiny")
public static class Person {
Expand Down

0 comments on commit 5736d60

Please sign in to comment.