Migrating tests

This commit is contained in:
Steve Ebersole 2021-06-11 14:15:31 -05:00
parent e4d61a7c62
commit 5617ce056d
22 changed files with 1354 additions and 1198 deletions

View File

@ -1,209 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.jdbc.dialect.internal;
import org.hibernate.dialect.*;
import org.hibernate.orm.test.dialect.resolver.TestingDialectResolutionInfo;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Unit test of the {@link StandardDialectResolver} class.
*
* @author Bryan Turner
*/
public class StandardDialectResolverTest extends BaseUnitTestCase {
@Test
public void testResolveDialectInternalForSQLServer2000()
throws SQLException {
runSQLServerDialectTest( 8, SQLServerDialect.class );
}
@Test
public void testResolveDialectInternalForSQLServer2005()
throws SQLException {
runSQLServerDialectTest( 9, SQLServer2005Dialect.class );
}
@Test
public void testResolveDialectInternalForSQLServer2008()
throws SQLException {
runSQLServerDialectTest( 10, SQLServer2008Dialect.class );
}
@Test
public void testResolveDialectInternalForSQLServer2012()
throws SQLException {
runSQLServerDialectTest( 11, SQLServer2012Dialect.class );
}
@Test
public void testResolveDialectInternalForSQLServer2014()
throws SQLException {
runSQLServerDialectTest( 12, SQLServer2012Dialect.class );
}
@Test
public void testResolveDialectInternalForUnknownSQLServerVersion()
throws SQLException {
runSQLServerDialectTest( 7, SQLServerDialect.class );
}
@Test
public void testResolveDialectInternalForPostgres81()
throws SQLException {
runPostgresDialectTest( 8, 1, PostgreSQL81Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres82()
throws SQLException {
runPostgresDialectTest( 8, 2, PostgreSQL82Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres83() throws SQLException {
runPostgresDialectTest( 8, 3, PostgreSQL82Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres84() throws SQLException {
runPostgresDialectTest( 8, 4, PostgreSQL82Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres9() throws SQLException {
runPostgresDialectTest( 9, 0, PostgreSQL9Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres91() throws SQLException {
runPostgresDialectTest( 9, 1, PostgreSQL9Dialect.class );
}
@Test
public void testResolveDialectInternalForPostgres92() throws SQLException {
runPostgresDialectTest( 9, 2, PostgreSQL92Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB103() throws SQLException {
runMariaDBDialectTest( 10, 3, MariaDB103Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB102() throws SQLException {
runMariaDBDialectTest( 10, 2, MariaDB102Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB101() throws SQLException {
runMariaDBDialectTest( 10, 1, MariaDB10Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB100() throws SQLException {
runMariaDBDialectTest( 10, 0, MariaDB10Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB55() throws SQLException {
runMariaDBDialectTest( 5, 5, MariaDB53Dialect.class );
}
@Test
public void testResolveDialectInternalForMariaDB52() throws SQLException {
runMariaDBDialectTest( 5, 2, MariaDBDialect.class );
}
@Test
public void testResolveDialectInternalForMySQL57() throws SQLException {
runMySQLDialectTest( 5, 7, MySQL57Dialect.class );
}
@Test
public void testResolveDialectInternalForMySQL6() throws SQLException {
runMySQLDialectTest( 6, 0, MySQL57Dialect.class );
}
@Test
public void testResolveDialectInternalForMySQL7() throws SQLException {
runMySQLDialectTest( 7, 0, MySQL57Dialect.class );
}
@Test
public void testResolveDialectInternalForMySQL8() throws SQLException {
runMySQLDialectTest( 8, 0, MySQL8Dialect.class );
}
private static void runMariaDBDialectTest(
int majorVersion, int minorVersion, Class<? extends MariaDBDialect> expectedDialect)
throws SQLException {
runDialectTest( "MariaDB", "MariaDB connector/J", majorVersion, minorVersion, expectedDialect );
}
private static void runMySQLDialectTest(
int majorVersion, int minorVersion, Class<? extends MySQLDialect> expectedDialect)
throws SQLException {
runDialectTest( "MySQL", "MySQL connector/J", majorVersion, minorVersion, expectedDialect );
}
private static void runSQLServerDialectTest(
int version, Class<? extends SQLServerDialect> expectedDialect)
throws SQLException {
runDialectTest( "Microsoft SQL Server", version, 0,
expectedDialect );
}
private static void runPostgresDialectTest(
int majorVersion, int minorVersion,
Class<? extends Dialect> expectedDialect) throws SQLException {
runDialectTest( "PostgreSQL", majorVersion, minorVersion,
expectedDialect );
}
private static void runDialectTest(
String productName,
int majorVersion,
int minorVersion,
Class<? extends Dialect> expectedDialect) {
runDialectTest( productName, null, majorVersion, minorVersion, expectedDialect );
}
private static void runDialectTest(
String productName,
String driverName,
int majorVersion,
int minorVersion,
Class<? extends Dialect> expectedDialect) {
TestingDialectResolutionInfo info = TestingDialectResolutionInfo.forDatabaseInfo( productName, driverName, majorVersion, minorVersion );
Dialect dialect = new StandardDialectResolver().resolveDialect( info );
StringBuilder builder = new StringBuilder( productName ).append( " " )
.append( majorVersion );
if ( minorVersion > 0 ) {
builder.append( "." ).append( minorVersion );
}
String dbms = builder.toString();
assertNotNull( "Dialect for " + dbms + " should not be null", dialect );
// Make sure to test that the actual dialect class is as expected
// (not just an instance of the expected dialect.
assertEquals( "Dialect for " + dbms + " should be " + expectedDialect.getSimpleName(),
expectedDialect,
dialect.getClass()
);
}
}

View File

@ -1,193 +0,0 @@
package org.hibernate.engine.query;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.dialect.InformixDialect;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Vlad Mihalcea
*/
@RequiresDialect(InformixDialect.class)
public class InformixFunctionTest extends BaseCoreFunctionalTestCase {
private Event event;
@Override
protected void prepareTest() throws Exception {
doInHibernate( this::sessionFactory, session -> {
event = new Event();
event.country = "Romania";
event.city = "Cluj-Napoca";
session.persist( event );
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testConcat() throws Exception {
doInHibernate( this::sessionFactory, session -> {
String location = (String) session.createQuery(
"select concat(e.country, ' - ', e.city) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Romania - Cluj-Napoca", location);
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testSubstring() throws Exception {
doInHibernate( this::sessionFactory, session -> {
String location = (String) session.createQuery(
"select substring(e.city, 0, 5) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Cluj", location);
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testSubstr() throws Exception {
doInHibernate( this::sessionFactory, session -> {
String location = (String) session.createQuery(
"select substr(e.city, 0, 4) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Cluj", location);
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testCoalesceAndNvl() throws Exception {
doInHibernate( this::sessionFactory, session -> {
String location = (String) session.createQuery(
"select coalesce(e.district, 'N/A') " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "N/A", location);
location = (String) session.createQuery(
"select nvl(e.district, 'N/A') " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "N/A", location);
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10800" )
public void testCurrentDate() throws Exception {
doInHibernate( this::sessionFactory, session -> {
Date date = (Date) session.createQuery(
"select current_date() " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertNotNull( date );
assertTrue( date.getTime() > 0 );
Calendar resultCalendar = Calendar.getInstance();
resultCalendar.setTime(date);
assertEquals( 0, todayCalendar().compareTo(resultCalendar) );
} );
}
@Test
@TestForIssue( jiraKey = "HHH-10800" )
public void testCurrentTimestamp() throws Exception {
doInHibernate( this::sessionFactory, session -> {
int tries = 2;
while ( tries-- > 0 ) {
Timestamp timestamp = (Timestamp) session.createQuery(
"select current_timestamp() " +
"from Event e " +
"where e.id = :id" )
.setParameter( "id", event.id )
.getSingleResult();
assertNotNull( timestamp );
assertTrue( timestamp != null && timestamp.getTime() > 0 );
Calendar resultCalendar = Calendar.getInstance();
resultCalendar.setTime( timestamp );
long millis = resultCalendar.getTime().getTime() - todayCalendar().getTime().getTime();
if(millis == 0) {
//What are the odds that ou've run this test exactly at midnight?
try {
Thread.sleep( 1000 );
}
catch ( InterruptedException ignore ) {}
continue;
}
assertTrue( millis > 0 );
}
} );
}
private Calendar todayCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Event.class
};
}
@Entity(name = "Event")
public static class Event {
@Id
@GeneratedValue
private Long id;
@Column
private String country;
private String city;
private String district;
}
}

View File

@ -1,66 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.query;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.Session;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.jdbc.Work;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Vlad Mihalcea
*/
@RequiresDialect(MySQL5Dialect.class)
@TestForIssue( jiraKey = "HHH-1237")
public class MySQLSetVariableEscapeColonTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { };
}
@Test
public void testBoundedLongStringAccess() {
Session s = openSession();
s.beginTransaction();
try {
s.doWork( new Work() {
@Override
public void execute(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
try {
statement.executeUpdate( "SET @a='test'" );
}
finally {
statement.close();
}
}
} );
Object[] result = (Object[]) session.createNativeQuery( "SELECT @a, (@a::=20) FROM dual" ).uniqueResult();
assertEquals("test", result[0]);
assertEquals(20, ((Number) result[1]).intValue());
s.getTransaction().commit();
}
finally {
s.close();
}
}
}

View File

@ -1,126 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.internal.SessionImpl;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
* Test for making sure that any set entity entry extra state is propagated from temporary to final entity entries.
*
* @author Gunnar Morling
*/
@RequiresDialectFeature( value = DialectChecks.SupportsIdentityColumns.class, jiraKey = "HHH-9918")
public class ExtraStateTest extends BaseCoreFunctionalTestCase {
/**
* Storing it as a field so it can be accessed from the entity setter.
*/
private Session session;
@Test
@TestForIssue(jiraKey = "HHH-9451")
public void shouldMaintainExtraStateWhenUsingIdentityIdGenerationStrategy() {
session = openSession();
session.getTransaction().begin();
ChineseTakeawayRestaurant mrKim = new ChineseTakeawayRestaurant();
mrKim.setGobelinStars( 3 );
// As a side-effect, the id setter will populate the test extra state
session.persist( mrKim );
session.getTransaction().commit();
TestExtraState extraState = getEntityEntry( mrKim ).getExtraState( TestExtraState.class );
assertNotNull( "Test extra state was not propagated from temporary to final entity entry", extraState );
assertEquals( 311, extraState.getValue() );
session.close();
}
private EntityEntry getEntityEntry(Object object) {
return ( (SessionImpl) session ).getPersistenceContext().getEntry( object );
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { ChineseTakeawayRestaurant.class };
}
@Entity
@Table(name = "ChineseTakeawayRestaurant")
public class ChineseTakeawayRestaurant {
private long id;
private int gobelinStars;
public ChineseTakeawayRestaurant() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return id;
}
/**
* Sets the test extra state as a side effect
*/
public void setId(long id) {
getEntityEntry( this ).addExtraState( new TestExtraState( 311 ) );
this.id = id;
}
public int getGobelinStars() {
return gobelinStars;
}
public void setGobelinStars(int gobelinStars) {
this.gobelinStars = gobelinStars;
}
}
private static class TestExtraState implements EntityEntryExtraState {
private final long value;
public TestExtraState(long value) {
this.value = value;
}
public long getValue() {
return value;
}
@Override
public void addExtraState(EntityEntryExtraState extraState) {
throw new UnsupportedOperationException();
}
@Override
public <T extends EntityEntryExtraState> T getExtraState(Class<T> extraStateType) {
throw new UnsupportedOperationException();
}
}
}

View File

@ -1,255 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.spi;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author Anton Marsden
* @author Gail Badner
*/
public class NonSortedExecutableListTest extends BaseUnitTestCase {
// For testing, we need an Executable that is also Comparable and Serializable
private static class AnExecutable implements Executable, Comparable, Serializable {
private final int n;
private Serializable[] spaces;
private transient boolean afterDeserializeCalled;
public AnExecutable(int n, String... spaces) {
this.n = n;
this.spaces = spaces;
}
@Override
public int compareTo(Object o) {
return new Integer(n).compareTo( new Integer(( (AnExecutable) o ).n ));
}
@Override
public int hashCode() {
return n;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true;
if ( obj == null )
return false;
AnExecutable other = (AnExecutable) obj;
return n == other.n;
}
@Override
public Serializable[] getPropertySpaces() {
return spaces;
}
@Override
public void beforeExecutions() throws HibernateException {
}
@Override
public void execute() throws HibernateException {
}
@Override
public AfterTransactionCompletionProcess getAfterTransactionCompletionProcess() {
return null;
}
@Override
public BeforeTransactionCompletionProcess getBeforeTransactionCompletionProcess() {
return null;
}
@Override
public void afterDeserialize(SharedSessionContractImplementor session) {
this.afterDeserializeCalled = true;
}
public String toString() {
return String.valueOf(n);
}
}
private ExecutableList<AnExecutable> l;
private AnExecutable action1 = new AnExecutable( 0, "a" );
private AnExecutable action2 = new AnExecutable( 1, "b", "c" );
private AnExecutable action3 = new AnExecutable( 2, "b", "d" );
private AnExecutable action4 = new AnExecutable( 3 );
@Before
public void setUp() {
// false indicates sorting is not required.
l = new ExecutableList<AnExecutable>( false );
}
@After
public void tearDown() {
l = null;
}
@Test
public void testAdd() {
Assert.assertEquals( 0, l.size() );
l.add( action1 );
Assert.assertEquals( action1, l.get( 0 ) );
Assert.assertEquals( 1, l.size() );
l.add( action2 );
Assert.assertEquals( action2, l.get( 1 ) );
l.add( action3 );
Assert.assertEquals( action3, l.get( 2 ) );
Assert.assertEquals( 3, l.size() );
}
@Test
public void testClear() {
Assert.assertTrue( l.isEmpty() );
l.add( action1 );
Assert.assertFalse( l.isEmpty() );
l.add( action2 );
l.clear();
Assert.assertTrue( l.isEmpty() );
Assert.assertEquals( 0, l.size() );
}
@Test
public void testIterator() {
l.add( action1 );
l.add( action2 );
l.add( action3 );
Iterator<AnExecutable> iterator = l.iterator();
Assert.assertEquals(action1, iterator.next());
Assert.assertEquals(action2, iterator.next());
Assert.assertEquals(action3, iterator.next());
Assert.assertFalse(iterator.hasNext());
}
@Test
public void testRemoveLastN() {
l.add( action1 );
l.add( action2 );
l.add( action3 );
l.removeLastN( 0 );
Assert.assertEquals( 3, l.size() );
l.removeLastN( 2 );
Assert.assertEquals( 1, l.size() );
Assert.assertEquals( action1, l.get( 0 ) );
}
@Test
public void testGetSpaces() {
l.add( action1 );
Set<Serializable> ss = l.getQuerySpaces();
Assert.assertEquals( 1, ss.size() );
Assert.assertTrue( ss.contains( "a" ) );
l.add( action2 );
l.add( action3 );
l.add( action4 );
Set<Serializable> ss2 = l.getQuerySpaces();
Assert.assertEquals( 4, ss2.size() );
Assert.assertTrue( ss2.contains( "a" ) );
Assert.assertTrue( ss2.contains( "b" ) );
Assert.assertTrue( ss2.contains( "c" ) );
Assert.assertTrue( ss2.contains( "d" ) );
Assert.assertTrue( ss == ss2 ); // same Set (cached)
// now remove action4
l.remove( 3 );
ss2 = l.getQuerySpaces();
Assert.assertTrue( ss == ss2 ); // same Set (action4 has no spaces)
Assert.assertEquals( 4, ss2.size() );
l.remove( 2 );
ss2 = l.getQuerySpaces();
Assert.assertTrue( ss != ss2 ); // Different Set because it has been rebuilt. This would be incorrect if
// Set.clear() was used
}
@Test
public void testSort() {
l.add( action4 );
l.add( action3 );
l.add( action2 );
l.add( action1 );
// sort should have no affect
l.sort();
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
}
@Test
public void testSerializeDeserialize() throws IOException, ClassNotFoundException {
l.add( action4 );
l.add( action3 );
l.add( action2 );
l.add( action1 );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
l.writeExternal( oos );
// this OOS stream needs to be flushed...
oos.flush();
ByteArrayInputStream bin = new ByteArrayInputStream( baos.toByteArray() );
ObjectInputStream ois = new ObjectInputStream( bin );
l = new ExecutableList<NonSortedExecutableListTest.AnExecutable>( false );
l.readExternal( ois );
Assert.assertEquals( 4, l.size() );
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
Assert.assertFalse( l.get( 0 ).afterDeserializeCalled );
Assert.assertFalse( l.get( 1 ).afterDeserializeCalled );
Assert.assertFalse( l.get( 2 ).afterDeserializeCalled );
Assert.assertFalse( l.get( 3 ).afterDeserializeCalled );
l.afterDeserialize( null );
Assert.assertTrue( l.get( 0 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 1 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 2 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 3 ).afterDeserializeCalled );
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
// sort after deserializing; it should still have no affect
l.sort();
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
}
}

View File

@ -1,252 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.spi;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author Anton Marsden
*/
public class SortedExecutableListTest extends BaseUnitTestCase {
// For testing, we need an Executable that is also Comparable and Serializable
private static class AnExecutable implements Executable, Comparable, Serializable {
private final int n;
private Serializable[] spaces;
private transient boolean afterDeserializeCalled;
public AnExecutable(int n, String... spaces) {
this.n = n;
this.spaces = spaces;
}
@Override
public int compareTo(Object o) {
return new Integer(n).compareTo( new Integer(( (AnExecutable) o ).n ));
}
@Override
public int hashCode() {
return n;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true;
if ( obj == null )
return false;
AnExecutable other = (AnExecutable) obj;
return n == other.n;
}
@Override
public Serializable[] getPropertySpaces() {
return spaces;
}
@Override
public void beforeExecutions() throws HibernateException {
}
@Override
public void execute() throws HibernateException {
}
@Override
public AfterTransactionCompletionProcess getAfterTransactionCompletionProcess() {
return null;
}
@Override
public BeforeTransactionCompletionProcess getBeforeTransactionCompletionProcess() {
return null;
}
@Override
public void afterDeserialize(SharedSessionContractImplementor session) {
this.afterDeserializeCalled = true;
}
public String toString() {
return String.valueOf(n);
}
}
private ExecutableList<AnExecutable> l;
private AnExecutable action1 = new AnExecutable( 0, "a" );
private AnExecutable action2 = new AnExecutable( 1, "b", "c" );
private AnExecutable action3 = new AnExecutable( 2, "b", "d" );
private AnExecutable action4 = new AnExecutable( 3 );
@Before
public void setUp() {
l = new ExecutableList<AnExecutable>();
}
@After
public void tearDown() {
l = null;
}
@Test
public void testAdd() {
Assert.assertEquals( 0, l.size() );
l.add( action1 );
Assert.assertEquals( action1, l.get( 0 ) );
Assert.assertEquals( 1, l.size() );
l.add( action2 );
Assert.assertEquals( action2, l.get( 1 ) );
l.add( action3 );
Assert.assertEquals( action3, l.get( 2 ) );
Assert.assertEquals( 3, l.size() );
}
@Test
public void testClear() {
Assert.assertTrue( l.isEmpty() );
l.add( action1 );
Assert.assertFalse( l.isEmpty() );
l.add( action2 );
l.clear();
Assert.assertTrue( l.isEmpty() );
Assert.assertEquals( 0, l.size() );
}
@Test
public void testIterator() {
l.add( action1 );
l.add( action2 );
l.add( action3 );
Iterator<AnExecutable> iterator = l.iterator();
Assert.assertEquals(action1, iterator.next());
Assert.assertEquals(action2, iterator.next());
Assert.assertEquals(action3, iterator.next());
Assert.assertFalse(iterator.hasNext());
}
@Test
public void testRemoveLastN() {
l.add( action1 );
l.add( action2 );
l.add( action3 );
l.removeLastN( 0 );
Assert.assertEquals( 3, l.size() );
l.removeLastN( 2 );
Assert.assertEquals( 1, l.size() );
Assert.assertEquals( action1, l.get( 0 ) );
}
@Test
public void testGetSpaces() {
l.add( action1 );
Set<Serializable> ss = l.getQuerySpaces();
Assert.assertEquals( 1, ss.size() );
Assert.assertTrue( ss.contains( "a" ) );
l.add( action2 );
l.add( action3 );
l.add( action4 );
Set<Serializable> ss2 = l.getQuerySpaces();
Assert.assertEquals( 4, ss2.size() );
Assert.assertTrue( ss2.contains( "a" ) );
Assert.assertTrue( ss2.contains( "b" ) );
Assert.assertTrue( ss2.contains( "c" ) );
Assert.assertTrue( ss2.contains( "d" ) );
Assert.assertTrue( ss == ss2 ); // same Set (cached)
// now remove action4
l.remove( 3 );
ss2 = l.getQuerySpaces();
Assert.assertTrue( ss == ss2 ); // same Set (action4 has no spaces)
Assert.assertEquals( 4, ss2.size() );
l.remove( 2 );
ss2 = l.getQuerySpaces();
Assert.assertTrue( ss != ss2 ); // Different Set because it has been rebuilt. This would be incorrect if
// Set.clear() was used
}
@Test
public void testSort() {
l.add( action4 );
l.add( action3 );
l.add( action2 );
l.add( action1 );
l.sort();
Assert.assertEquals( action1, l.get( 0 ) );
Assert.assertEquals( action2, l.get( 1 ) );
Assert.assertEquals( action3, l.get( 2 ) );
Assert.assertEquals( action4, l.get( 3 ) );
}
@Test
public void testSerializeDeserialize() throws IOException, ClassNotFoundException {
l.add( action4 );
l.add( action3 );
l.add( action2 );
l.add( action1 );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
l.writeExternal( oos );
// this OOS stream needs to be flushed...
oos.flush();
ByteArrayInputStream bin = new ByteArrayInputStream( baos.toByteArray() );
ObjectInputStream ois = new ObjectInputStream( bin );
l = new ExecutableList<SortedExecutableListTest.AnExecutable>();
l.readExternal( ois );
Assert.assertEquals( 4, l.size() );
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
Assert.assertFalse(l.get(0).afterDeserializeCalled);
Assert.assertFalse(l.get(1).afterDeserializeCalled);
Assert.assertFalse(l.get(2).afterDeserializeCalled);
Assert.assertFalse( l.get( 3 ).afterDeserializeCalled );
l.afterDeserialize( null );
Assert.assertTrue( l.get( 0 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 1 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 2 ).afterDeserializeCalled );
Assert.assertTrue( l.get( 3 ).afterDeserializeCalled );
Assert.assertEquals( action4, l.get( 0 ) );
Assert.assertEquals( action3, l.get( 1 ) );
Assert.assertEquals( action2, l.get( 2 ) );
Assert.assertEquals( action1, l.get( 3 ) );
// sort after deserializing
l.sort();
Assert.assertEquals( action1, l.get( 0 ) );
Assert.assertEquals( action2, l.get( 1 ) );
Assert.assertEquals( action3, l.get( 2 ) );
Assert.assertEquals( action4, l.get( 3 ) );
}
}

View File

@ -1,76 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.engine.spi.delegation;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.spi.SessionDelegatorBaseImpl;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Andrea Boriero
*/
@RequiresDialect(H2Dialect.class)
public class SessionDelegatorBaseImplTest extends BaseCoreFunctionalTestCase {
@Before
public void init() {
inTransaction( session -> {
session.doWork( connection -> {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate( "DROP ALIAS findOneUser IF EXISTS" );
statement.executeUpdate(
"CREATE ALIAS findOneUser AS $$\n" +
"import org.h2.tools.SimpleResultSet;\n" +
"import java.sql.*;\n" +
"@CODE\n" +
"ResultSet findOneUser() {\n" +
" SimpleResultSet rs = new SimpleResultSet();\n" +
" rs.addColumn(\"ID\", Types.INTEGER, 10, 0);\n" +
" rs.addColumn(\"NAME\", Types.VARCHAR, 255, 0);\n" +
" rs.addRow(1, \"Steve\");\n" +
" return rs;\n" +
"}\n" +
"$$"
);
}
} );
} );
}
@After
public void tearDown() {
inTransaction( session -> {
session.doWork( connection -> {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate( "DROP ALIAS findOneUser IF EXISTS" );
}
catch (SQLException e) {
//Do not ignore as failure to cleanup might lead to other tests to fail:
throw new RuntimeException( e );
}
} );
} );
}
@Test
public void testcreateStoredProcedureQuery() {
inTransaction(
session -> {
SessionDelegatorBaseImpl delegator = new SessionDelegatorBaseImpl( session );
delegator.createStoredProcedureQuery( "findOneUser" );
}
);
}
}

View File

@ -0,0 +1,84 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.delegation;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.engine.spi.SessionDelegatorBaseImpl;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author Andrea Boriero
*/
@RequiresDialect(H2Dialect.class)
@DomainModel
@SessionFactory
public class SessionDelegatorBaseImplTest {
@BeforeEach
public void init(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> session.doWork(
(connection) -> {
try ( Statement statement = connection.createStatement() ) {
statement.executeUpdate( "DROP ALIAS findOneUser IF EXISTS" );
statement.executeUpdate(
"CREATE ALIAS findOneUser AS $$\n" +
"import org.h2.tools.SimpleResultSet;\n" +
"import java.sql.*;\n" +
"@CODE\n" +
"ResultSet findOneUser() {\n" +
" SimpleResultSet rs = new SimpleResultSet();\n" +
" rs.addColumn(\"ID\", Types.INTEGER, 10, 0);\n" +
" rs.addColumn(\"NAME\", Types.VARCHAR, 255, 0);\n" +
" rs.addRow(1, \"Steve\");\n" +
" return rs;\n" +
"}\n" +
"$$"
);
}
}
)
);
}
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> session.doWork(
(connection) -> {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate( "DROP ALIAS findOneUser IF EXISTS" );
}
catch (SQLException e) {
//Do not ignore as failure to cleanup might lead to other tests to fail:
throw new RuntimeException( e );
}
}
)
);
}
@Test
public void testCreateStoredProcedureQuery(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
SessionDelegatorBaseImpl delegator = new SessionDelegatorBaseImpl( session );
delegator.createStoredProcedureQuery( "findOneUser" );
}
);
}
}

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.engine.spi.delegation; package org.hibernate.orm.test.delegation;
import org.hibernate.SessionBuilder; import org.hibernate.SessionBuilder;
import org.hibernate.engine.spi.AbstractDelegatingSessionBuilder; import org.hibernate.engine.spi.AbstractDelegatingSessionBuilder;
@ -13,8 +13,12 @@ import org.hibernate.engine.spi.AbstractDelegatingSessionBuilder;
* If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding * If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding
* methods to the parent class. * methods to the parent class.
* *
* NOTE: Do not remove!!! Used to verify that delegating SessionBuilder impls compile (aka, validates binary
* compatibility against previous versions)
*
* @author Guillaume Smet * @author Guillaume Smet
*/ */
@SuppressWarnings("unused")
public class TestDelegatingSessionBuilder extends AbstractDelegatingSessionBuilder<TestDelegatingSessionBuilder> { public class TestDelegatingSessionBuilder extends AbstractDelegatingSessionBuilder<TestDelegatingSessionBuilder> {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.engine.spi.delegation; package org.hibernate.orm.test.delegation;
import org.hibernate.engine.spi.AbstractDelegatingSessionBuilderImplementor; import org.hibernate.engine.spi.AbstractDelegatingSessionBuilderImplementor;
import org.hibernate.engine.spi.SessionBuilderImplementor; import org.hibernate.engine.spi.SessionBuilderImplementor;
@ -13,8 +13,12 @@ import org.hibernate.engine.spi.SessionBuilderImplementor;
* If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding * If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding
* methods to the parent class. * methods to the parent class.
* *
* NOTE: Do not remove!!! Used to verify that delegating SessionBuilder impls compile (aka, validates binary
* compatibility against previous versions)
*
* @author Guillaume Smet * @author Guillaume Smet
*/ */
@SuppressWarnings("unused")
public class TestDelegatingSessionBuilderImplementor extends AbstractDelegatingSessionBuilderImplementor<TestDelegatingSessionBuilderImplementor> { public class TestDelegatingSessionBuilderImplementor extends AbstractDelegatingSessionBuilderImplementor<TestDelegatingSessionBuilderImplementor> {
public TestDelegatingSessionBuilderImplementor(SessionBuilderImplementor<TestDelegatingSessionBuilderImplementor> delegate) { public TestDelegatingSessionBuilderImplementor(SessionBuilderImplementor<TestDelegatingSessionBuilderImplementor> delegate) {

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.engine.spi.delegation; package org.hibernate.orm.test.delegation;
import org.hibernate.SharedSessionBuilder; import org.hibernate.SharedSessionBuilder;
import org.hibernate.engine.spi.AbstractDelegatingSharedSessionBuilder; import org.hibernate.engine.spi.AbstractDelegatingSharedSessionBuilder;
@ -14,8 +14,12 @@ import org.hibernate.engine.spi.AbstractDelegatingSharedSessionBuilder;
* If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding * If this class does not compile anymore due to unimplemented methods, you should probably add the corresponding
* methods to the parent class. * methods to the parent class.
* *
* NOTE: Do not remove!!! Used to verify that delegating SessionBuilder impls compile (aka, validates binary
* compatibility against previous versions)
*
* @author Guillaume Smet * @author Guillaume Smet
*/ */
@SuppressWarnings("unused")
public class TestDelegatingSharedSessionBuilder extends AbstractDelegatingSharedSessionBuilder<TestDelegatingSharedSessionBuilder> { public class TestDelegatingSharedSessionBuilder extends AbstractDelegatingSharedSessionBuilder<TestDelegatingSharedSessionBuilder> {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")

View File

@ -0,0 +1,11 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
/**
* Tests for various delegations used by non-ORM Hibernate projects
*/
package org.hibernate.orm.test.delegation;

View File

@ -0,0 +1,197 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.dialect.resolver;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MariaDBDialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.jdbc.dialect.internal.StandardDialectResolver;
import org.hibernate.orm.test.dialect.resolver.TestingDialectResolutionInfo;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Unit test of the {@link StandardDialectResolver} class.
*
* @author Bryan Turner
*/
public class StandardDialectResolverTest extends BaseUnitTestCase {
@Test
public void testResolveDialectInternalForSQLServer2000() {
runSQLServerDialectTest( 8 );
}
@Test
public void testResolveDialectInternalForSQLServer2005() {
runSQLServerDialectTest( 9 );
}
@Test
public void testResolveDialectInternalForSQLServer2008() {
runSQLServerDialectTest( 10 );
}
@Test
public void testResolveDialectInternalForSQLServer2012() {
runSQLServerDialectTest( 11 );
}
@Test
public void testResolveDialectInternalForSQLServer2014() {
runSQLServerDialectTest( 12 );
}
@Test
public void testResolveDialectInternalForUnknownSQLServerVersion() {
runSQLServerDialectTest( 7 );
}
@Test
public void testResolveDialectInternalForPostgres81() {
runPostgresDialectTest( 8, 1 );
}
@Test
public void testResolveDialectInternalForPostgres82() {
runPostgresDialectTest( 8, 2 );
}
@Test
public void testResolveDialectInternalForPostgres83() {
runPostgresDialectTest( 8, 3 );
}
@Test
public void testResolveDialectInternalForPostgres84() {
runPostgresDialectTest( 8, 4 );
}
@Test
public void testResolveDialectInternalForPostgres9() {
runPostgresDialectTest( 9, 0 );
}
@Test
public void testResolveDialectInternalForPostgres91() {
runPostgresDialectTest( 9, 1 );
}
@Test
public void testResolveDialectInternalForPostgres92() {
runPostgresDialectTest( 9, 2 );
}
@Test
public void testResolveDialectInternalForMariaDB103() {
runMariaDBDialectTest( 10, 3 );
}
@Test
public void testResolveDialectInternalForMariaDB102() {
runMariaDBDialectTest( 10, 2 );
}
@Test
public void testResolveDialectInternalForMariaDB101() {
runMariaDBDialectTest( 10, 1 );
}
@Test
public void testResolveDialectInternalForMariaDB100() {
runMariaDBDialectTest( 10, 0 );
}
@Test
public void testResolveDialectInternalForMariaDB55() {
runMariaDBDialectTest( 5, 5 );
}
@Test
public void testResolveDialectInternalForMariaDB52() {
runMariaDBDialectTest( 5, 2 );
}
@Test
public void testResolveDialectInternalForMySQL57() {
runMySQLDialectTest( 5, 7 );
}
@Test
public void testResolveDialectInternalForMySQL6() {
runMySQLDialectTest( 6, 0 );
}
@Test
public void testResolveDialectInternalForMySQL7() {
runMySQLDialectTest( 7, 0 );
}
@Test
public void testResolveDialectInternalForMySQL8() {
runMySQLDialectTest( 8, 0 );
}
private static void runMariaDBDialectTest(int majorVersion, int minorVersion) {
runDialectTest( "MariaDB", "MariaDB connector/J", majorVersion, minorVersion, MariaDBDialect.class );
}
private static void runMySQLDialectTest(int majorVersion, int minorVersion) {
runDialectTest( "MySQL", "MySQL connector/J", majorVersion, minorVersion, MySQLDialect.class );
}
private static void runSQLServerDialectTest(int version) {
runDialectTest( "Microsoft SQL Server", version, 0, SQLServerDialect.class );
}
private static void runPostgresDialectTest(
int majorVersion,
int minorVersion) {
runDialectTest( "PostgreSQL", majorVersion, minorVersion, PostgreSQLDialect.class );
}
private static void runDialectTest(
String productName,
int majorVersion,
int minorVersion,
Class<? extends Dialect> expectedDialect) {
runDialectTest( productName, null, majorVersion, minorVersion, expectedDialect );
}
private static void runDialectTest(
String productName,
String driverName,
int majorVersion,
int minorVersion,
Class<? extends Dialect> expectedDialect) {
TestingDialectResolutionInfo info = TestingDialectResolutionInfo.forDatabaseInfo( productName, driverName, majorVersion, minorVersion );
Dialect dialect = new StandardDialectResolver().resolveDialect( info );
StringBuilder builder = new StringBuilder( productName ).append( " " )
.append( majorVersion );
if ( minorVersion > 0 ) {
builder.append( "." ).append( minorVersion );
}
String dbms = builder.toString();
assertNotNull( "Dialect for " + dbms + " should not be null", dialect );
// Make sure to test that the actual dialect class is as expected
// (not just an instance of the expected dialect.
assertEquals( "Dialect for " + dbms + " should be " + expectedDialect.getSimpleName(),
expectedDialect,
dialect.getClass()
);
}
}

View File

@ -0,0 +1,305 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.engine.action;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable;
import org.hibernate.engine.spi.ExecutableList;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Anton Marsden
* @author Gail Badner
*/
@BaseUnitTest
public class NonSortedExecutableListTest {
// For testing, we need an Executable that is also Comparable and Serializable
private static class AnExecutable implements Executable, Comparable<AnExecutable>, Serializable {
private final int n;
private final Serializable[] spaces;
private transient boolean afterDeserializeCalled;
public AnExecutable(int n, String... spaces) {
this.n = n;
this.spaces = spaces;
}
public boolean wasAfterDeserializeCalled() {
return afterDeserializeCalled;
}
@Override
public int compareTo(AnExecutable o) {
return Integer.compare( n, o.n );
}
@Override
public int hashCode() {
return n;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true;
if ( obj == null )
return false;
AnExecutable other = (AnExecutable) obj;
return n == other.n;
}
@Override
public Serializable[] getPropertySpaces() {
return spaces;
}
@Override
public void beforeExecutions() throws HibernateException {
}
@Override
public void execute() throws HibernateException {
}
@Override
public AfterTransactionCompletionProcess getAfterTransactionCompletionProcess() {
return null;
}
@Override
public BeforeTransactionCompletionProcess getBeforeTransactionCompletionProcess() {
return null;
}
@Override
public void afterDeserialize(SharedSessionContractImplementor session) {
this.afterDeserializeCalled = true;
}
public String toString() {
return String.valueOf(n);
}
}
private ExecutableList<AnExecutable> actionList;
private final AnExecutable action1 = new AnExecutable( 0, "a" );
private final AnExecutable action2 = new AnExecutable( 1, "b", "c" );
private final AnExecutable action3 = new AnExecutable( 2, "b", "d" );
private final AnExecutable action4 = new AnExecutable( 3 );
@BeforeEach
public void setUp() {
// false indicates sorting is not required.
actionList = new ExecutableList<>( false );
}
@AfterEach
public void tearDown() {
actionList = null;
}
@Test
public void testAdd() {
assertThat( actionList ).hasSize( 0 );
actionList.add( action1 );
assertThat( actionList ).hasSize( 1 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
actionList.add( action2 );
assertThat( actionList ).hasSize( 2 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
assertThat( actionList ).element( 1 ).isSameAs( action2 );
actionList.add( action3 );
assertThat( actionList ).hasSize( 3 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
assertThat( actionList ).element( 1 ).isSameAs( action2 );
assertThat( actionList ).element( 2 ).isSameAs( action3 );
}
@Test
public void testClear() {
assertThat( actionList ).hasSize( 0 );
actionList.add( action1 );
assertThat( actionList ).hasSize( 1 );
actionList.add( action2 );
assertThat( actionList ).hasSize( 2 );
actionList.clear();
assertThat( actionList ).hasSize( 0 );
}
@Test
public void testIterator() {
actionList.add( action1 );
actionList.add( action2 );
actionList.add( action3 );
final Iterator<AnExecutable> iterator = actionList.iterator();
assertThat( iterator.next() ).isEqualTo( action1 );
assertThat( iterator.next() ).isEqualTo( action2 );
assertThat( iterator.next() ).isEqualTo( action3 );
assertThat( iterator.hasNext() ).isEqualTo( false );
}
@Test
public void testRemoveLastN() {
actionList.add( action1 );
actionList.add( action2 );
actionList.add( action3 );
actionList.removeLastN( 0 );
assertThat( actionList ).hasSize( 3 );
actionList.removeLastN( 2 );
assertThat( actionList ).hasSize( 1 );
assertThat( actionList ).element( 0 ).isEqualTo( action1 );
}
@Test
public void testGetSpaces() {
actionList.add( action1 );
final Set<Serializable> initialSpaces = actionList.getQuerySpaces();
{
assertThat( initialSpaces ).hasSize( 1 );
assertThat( initialSpaces ).containsOnly( "a" );
}
actionList.add( action2 );
actionList.add( action3 );
actionList.add( action4 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
// same Set (cached)
assertThat( spaces ).isSameAs( initialSpaces );
assertThat( spaces ).hasSize( 4 );
assertThat( spaces ).containsOnly( "a", "b", "c", "d" );
}
// now remove action4
actionList.remove( 3 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
// same Set (cached)
assertThat( spaces ).isSameAs( initialSpaces );
assertThat( spaces ).hasSize( 4 );
}
actionList.remove( 2 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
// Different Set because it has been rebuilt. This would be incorrect if
// Set.clear() was used
assertThat( spaces ).isNotSameAs( initialSpaces );
}
}
@Test
public void testSort() {
actionList.add( action4 );
actionList.add( action3 );
actionList.add( action2 );
actionList.add( action1 );
assertThat( actionList ).element( 0 ).isSameAs( action4 );
assertThat( actionList ).element( 1 ).isSameAs( action3 );
assertThat( actionList ).element( 2 ).isSameAs( action2 );
assertThat( actionList ).element( 3 ).isSameAs( action1 );
// sort should have no affect
actionList.sort();
assertThat( actionList ).element( 0 ).isSameAs( action4 );
assertThat( actionList ).element( 1 ).isSameAs( action3 );
assertThat( actionList ).element( 2 ).isSameAs( action2 );
assertThat( actionList ).element( 3 ).isSameAs( action1 );
}
@Test
public void testSerializeDeserialize() throws IOException, ClassNotFoundException {
actionList.add( action4 );
actionList.add( action3 );
actionList.add( action2 );
actionList.add( action1 );
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream( baos );
actionList.writeExternal( oos );
oos.flush();
final ByteArrayInputStream bin = new ByteArrayInputStream( baos.toByteArray() );
final ObjectInputStream ois = new ObjectInputStream( bin );
actionList = new ExecutableList<>( false );
actionList.readExternal( ois );
assertThat( actionList ).hasSize( 4 );
assertThat( actionList ).element( 0 ).isEqualTo( action4 );
assertThat( actionList ).element( 1 ).isEqualTo( action3 );
assertThat( actionList ).element( 2 ).isEqualTo( action2 );
assertThat( actionList ).element( 3 ).isEqualTo( action1 );
assertThat( actionList ).element( 0 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 1 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 2 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 3 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
actionList.afterDeserialize( null );
assertThat( actionList ).hasSize( 4 );
assertThat( actionList ).element( 0 ).isEqualTo( action4 );
assertThat( actionList ).element( 1 ).isEqualTo( action3 );
assertThat( actionList ).element( 2 ).isEqualTo( action2 );
assertThat( actionList ).element( 3 ).isEqualTo( action1 );
assertThat( actionList ).element( 0 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 1 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 2 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 3 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
// sort after deserializing; it should still have no affect
actionList.sort();
assertThat( actionList ).hasSize( 4 );
assertThat( actionList ).element( 0 ).isEqualTo( action4 );
assertThat( actionList ).element( 1 ).isEqualTo( action3 );
assertThat( actionList ).element( 2 ).isEqualTo( action2 );
assertThat( actionList ).element( 3 ).isEqualTo( action1 );
assertThat( actionList ).element( 0 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 1 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 2 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 3 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
}
}

View File

@ -0,0 +1,290 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.engine.action;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.action.spi.AfterTransactionCompletionProcess;
import org.hibernate.action.spi.BeforeTransactionCompletionProcess;
import org.hibernate.action.spi.Executable;
import org.hibernate.engine.spi.ExecutableList;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.testing.orm.junit.BaseUnitTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Anton Marsden
*/
@BaseUnitTest
public class SortedExecutableListTest {
// For testing, we need an Executable that is also Comparable and Serializable
private static class AnExecutable implements Executable, Comparable<AnExecutable>, Serializable {
private final int n;
private Serializable[] spaces;
private transient boolean afterDeserializeCalled;
public AnExecutable(int n, String... spaces) {
this.n = n;
this.spaces = spaces;
}
public boolean wasAfterDeserializeCalled() {
return afterDeserializeCalled;
}
@Override
public int compareTo(AnExecutable o) {
return Integer.compare( n, o.n );
}
@Override
public int hashCode() {
return n;
}
@Override
public boolean equals(Object obj) {
if ( this == obj )
return true;
if ( obj == null )
return false;
AnExecutable other = (AnExecutable) obj;
return n == other.n;
}
@Override
public Serializable[] getPropertySpaces() {
return spaces;
}
@Override
public void beforeExecutions() throws HibernateException {
}
@Override
public void execute() throws HibernateException {
}
@Override
public AfterTransactionCompletionProcess getAfterTransactionCompletionProcess() {
return null;
}
@Override
public BeforeTransactionCompletionProcess getBeforeTransactionCompletionProcess() {
return null;
}
@Override
public void afterDeserialize(SharedSessionContractImplementor session) {
this.afterDeserializeCalled = true;
}
public String toString() {
return String.valueOf(n);
}
}
private ExecutableList<AnExecutable> actionList;
private final AnExecutable action1 = new AnExecutable( 0, "a" );
private final AnExecutable action2 = new AnExecutable( 1, "b", "c" );
private final AnExecutable action3 = new AnExecutable( 2, "b", "d" );
private final AnExecutable action4 = new AnExecutable( 3 );
@BeforeEach
public void setUp() {
actionList = new ExecutableList<>();
}
@AfterEach
public void tearDown() {
actionList = null;
}
@Test
public void testAdd() {
assertThat( actionList ).isEmpty();
actionList.add( action1 );
assertThat( actionList ).hasSize( 1 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
actionList.add( action3 );
assertThat( actionList ).hasSize( 2 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
assertThat( actionList ).element( 1 ).isSameAs( action3 );
}
@Test
public void testClear() {
assertThat( actionList ).isEmpty();
actionList.add( action1 );
assertThat( actionList ).hasSize( 1 );
actionList.add( action2 );
assertThat( actionList ).hasSize( 2 );
actionList.clear();
assertThat( actionList ).isEmpty();
}
@Test
public void testIterator() {
actionList.add( action1 );
actionList.add( action2 );
actionList.add( action3 );
final Iterator<AnExecutable> iterator = actionList.iterator();
assertThat( iterator.next() ).isEqualTo( action1 );
assertThat( iterator.next() ).isEqualTo( action2 );
assertThat( iterator.next() ).isEqualTo( action3 );
assertThat( iterator.hasNext() ).isEqualTo( false );
}
@Test
public void testRemoveLastN() {
actionList.add( action1 );
actionList.add( action2 );
actionList.add( action3 );
assertThat( actionList ).hasSize( 3 );
actionList.removeLastN( 0 );
assertThat( actionList ).hasSize( 3 );
actionList.removeLastN( 2 );
assertThat( actionList ).hasSize( 1 );
assertThat( actionList ).element( 0 ).isSameAs( action1 );
}
@Test
public void testGetSpaces() {
actionList.add( action1 );
final Set<Serializable> initialQuerySpaces = actionList.getQuerySpaces();
assertThat( initialQuerySpaces ).containsOnly( "a" );
actionList.add( action2 );
actionList.add( action3 );
actionList.add( action4 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
assertThat( spaces ).isSameAs( initialQuerySpaces );
assertThat( spaces ).hasSize( 4 );
assertThat( spaces ).containsOnly( "a", "b", "c", "d" );
}
// now remove action4
actionList.remove( 3 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
// same Set (action4 has no spaces)
assertThat( spaces ).isSameAs( initialQuerySpaces );
assertThat( spaces ).containsAll( initialQuerySpaces );
assertThat( spaces ).hasSize( 4 );
}
actionList.remove( 2 );
{
final Set<Serializable> spaces = actionList.getQuerySpaces();
// Different Set because it has been rebuilt. This would be incorrect if Set.clear() was used
assertThat( spaces ).isNotSameAs( initialQuerySpaces );
assertThat( spaces ).hasSize( 3 );
}
}
@Test
public void testSort() {
actionList.add( action4 );
actionList.add( action3 );
actionList.add( action2 );
actionList.add( action1 );
assertThat( actionList ).element( 0 ).isSameAs( action4 );
assertThat( actionList ).element( 1 ).isSameAs( action3 );
assertThat( actionList ).element( 2 ).isSameAs( action2 );
assertThat( actionList ).element( 3 ).isSameAs( action1 );
actionList.sort();
assertThat( actionList ).element( 0 ).isSameAs( action1 );
assertThat( actionList ).element( 1 ).isSameAs( action2 );
assertThat( actionList ).element( 2 ).isSameAs( action3 );
assertThat( actionList ).element( 3 ).isSameAs( action4 );
}
@Test
public void testSerializeDeserialize() throws IOException, ClassNotFoundException {
actionList.add( action4 );
actionList.add( action3 );
actionList.add( action2 );
actionList.add( action1 );
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream( baos );
actionList.writeExternal( oos );
oos.flush();
final ByteArrayInputStream bin = new ByteArrayInputStream( baos.toByteArray() );
final ObjectInputStream ois = new ObjectInputStream( bin );
actionList = new ExecutableList<>();
actionList.readExternal( ois );
assertThat( actionList ).hasSize( 4 );
assertThat( actionList ).element( 0 ).isEqualTo( action4 );
assertThat( actionList ).element( 1 ).isEqualTo( action3 );
assertThat( actionList ).element( 2 ).isEqualTo( action2 );
assertThat( actionList ).element( 3 ).isEqualTo( action1 );
assertThat( actionList ).element( 0 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 1 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 2 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
assertThat( actionList ).element( 3 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( false );
actionList.afterDeserialize( null );
assertThat( actionList ).hasSize( 4 );
assertThat( actionList ).element( 0 ).isEqualTo( action4 );
assertThat( actionList ).element( 1 ).isEqualTo( action3 );
assertThat( actionList ).element( 2 ).isEqualTo( action2 );
assertThat( actionList ).element( 3 ).isEqualTo( action1 );
assertThat( actionList ).element( 0 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 1 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 2 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
assertThat( actionList ).element( 3 ).extracting( AnExecutable::wasAfterDeserializeCalled ).isEqualTo( true );
actionList.sort();
assertThat( actionList ).element( 0 ).isEqualTo( action1 );
assertThat( actionList ).element( 1 ).isEqualTo( action2 );
assertThat( actionList ).element( 2 ).isEqualTo( action3 );
assertThat( actionList ).element( 3 ).isEqualTo( action4 );
}
}

View File

@ -0,0 +1,11 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
/**
* Tests related to Hibernate's ActionQueue
*/
package org.hibernate.orm.test.engine.action;

View File

@ -0,0 +1,131 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.engine.spi;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityEntryExtraState;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DialectFeatureChecks;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialectFeature;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Test for making sure that any set entity entry extra state is propagated from temporary to final entity entries.
*
* @author Gunnar Morling
*/
@RequiresDialectFeature( feature = DialectFeatureChecks.SupportsIdentityColumns.class, jiraKey = "HHH-9918")
@DomainModel( annotatedClasses = ExtraStateTest.ChineseTakeawayRestaurant.class )
@SessionFactory
public class ExtraStateTest {
private SessionImplementor sessionRef;
@Test
@TestForIssue(jiraKey = "HHH-9451")
public void shouldMaintainExtraStateWhenUsingIdentityIdGenerationStrategy(SessionFactoryScope scope) {
scope.inSession(
(nonTransactedSession) -> {
sessionRef = nonTransactedSession;
final ChineseTakeawayRestaurant persisted = scope.fromTransaction(
nonTransactedSession,
(session) -> {
ChineseTakeawayRestaurant mrKim = new ChineseTakeawayRestaurant();
mrKim.setGobelinStars( 3 );
// As a side-effect, the id setter will populate the test extra state
session.persist( mrKim );
return mrKim;
}
);
TestExtraState extraState = getEntityEntry( persisted, nonTransactedSession ).getExtraState( TestExtraState.class );
assertNotNull( extraState, "Test extra state was not propagated from temporary to final entity entry" );
assertEquals( 311, extraState.getValue() );
sessionRef = null;
}
);
}
private EntityEntry getEntityEntry(Object object, SessionImplementor nonTransactedSession) {
return nonTransactedSession.getPersistenceContext().getEntry( object );
}
@SuppressWarnings("unused")
@Entity
@Table(name = "ChineseTakeawayRestaurant")
public class ChineseTakeawayRestaurant {
private long id;
private int gobelinStars;
public ChineseTakeawayRestaurant() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return id;
}
/**
* Sets the test extra state as a side effect
*/
public void setId(long id) {
getEntityEntry( this, sessionRef ).addExtraState( new TestExtraState( 311 ) );
this.id = id;
}
public int getGobelinStars() {
return gobelinStars;
}
public void setGobelinStars(int gobelinStars) {
this.gobelinStars = gobelinStars;
}
}
private static class TestExtraState implements EntityEntryExtraState {
private final long value;
public TestExtraState(long value) {
this.value = value;
}
public long getValue() {
return value;
}
@Override
public void addExtraState(EntityEntryExtraState extraState) {
throw new UnsupportedOperationException();
}
@Override
public <T extends EntityEntryExtraState> T getExtraState(Class<T> extraStateType) {
throw new UnsupportedOperationException();
}
}
}

View File

@ -1,4 +1,10 @@
package org.hibernate.engine.jdbc.internal; /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.jdbc;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.sql.Connection; import java.sql.Connection;
@ -9,6 +15,7 @@ import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters; import org.hibernate.engine.config.spi.StandardConverters;
import org.hibernate.engine.jdbc.batch.spi.Batch; import org.hibernate.engine.jdbc.batch.spi.Batch;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.resource.jdbc.spi.JdbcObserver; import org.hibernate.resource.jdbc.spi.JdbcObserver;

View File

@ -1,14 +1,16 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.engine.jdbc.cursor.internal; package org.hibernate.orm.test.jdbc.refcursor;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.SQLException; import java.sql.SQLException;
import org.hibernate.engine.jdbc.cursor.internal.StandardRefCursorSupport;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.junit.Test; import org.junit.Test;

View File

@ -0,0 +1,212 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.query.hql;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.dialect.InformixDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Vlad Mihalcea
*/
@RequiresDialect(InformixDialect.class)
@DomainModel( annotatedClasses = InformixFunctionTest.Event.class )
@SessionFactory
public class InformixFunctionTest {
private Event event;
@BeforeEach
protected void prepareTest(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
event = new Event();
event.country = "Romania";
event.city = "Cluj-Napoca";
session.persist( event );
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testConcat(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
String location = (String) session.createQuery(
"select concat(e.country, ' - ', e.city) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Romania - Cluj-Napoca", location);
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testSubstring(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
String location = (String) session.createQuery(
"select substring(e.city, 0, 5) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Cluj", location);
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testSubstr(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
String location = (String) session.createQuery(
"select substr(e.city, 0, 4) " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "Cluj", location);
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10846" )
public void testCoalesceAndNvl(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
String location = (String) session.createQuery(
"select coalesce(e.district, 'N/A') " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "N/A", location);
location = (String) session.createQuery(
"select nvl(e.district, 'N/A') " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertEquals( "N/A", location);
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10800" )
public void testCurrentDate(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
Date date = (Date) session.createQuery(
"select current_date() " +
"from Event e " +
"where e.id = :id")
.setParameter( "id", event.id )
.getSingleResult();
assertNotNull( date );
assertTrue( date.getTime() > 0 );
Calendar resultCalendar = Calendar.getInstance();
resultCalendar.setTime(date);
assertEquals( 0, todayCalendar().compareTo(resultCalendar) );
}
);
}
@Test
@TestForIssue( jiraKey = "HHH-10800" )
public void testCurrentTimestamp(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
int tries = 2;
while ( tries-- > 0 ) {
Timestamp timestamp = (Timestamp) session.createQuery(
"select current_timestamp() " +
"from Event e " +
"where e.id = :id" )
.setParameter( "id", event.id )
.getSingleResult();
assertNotNull( timestamp );
assertTrue( timestamp.getTime() > 0 );
Calendar resultCalendar = Calendar.getInstance();
resultCalendar.setTime( timestamp );
long millis = resultCalendar.getTime().getTime() - todayCalendar().getTime().getTime();
if(millis == 0) {
//What are the odds that ou've run this test exactly at midnight?
try {
Thread.sleep( 1000 );
}
catch ( InterruptedException ignore ) {}
continue;
}
assertTrue( millis > 0 );
}
}
);
}
private Calendar todayCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
@SuppressWarnings("unused")
@Entity(name = "Event")
public static class Event {
@Id
@GeneratedValue
private Long id;
@Column
private String country;
private String city;
private String district;
}
}

View File

@ -0,0 +1,47 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.query.sql;
import java.sql.Statement;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.orm.junit.RequiresDialect;
import org.hibernate.testing.orm.junit.SessionFactory;
import org.hibernate.testing.orm.junit.SessionFactoryScope;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vlad Mihalcea
*/
@RequiresDialect(MySQLDialect.class)
@TestForIssue( jiraKey = "HHH-1237")
@SessionFactory
public class MySQLSetVariableEscapeColonTest {
@Test
public void testBoundedLongStringAccess(SessionFactoryScope scope) {
scope.inTransaction(
(session) -> {
session.doWork(
(connection) -> {
try ( final Statement statement = connection.createStatement() ) {
statement.executeUpdate( "SET @a='test'" );
}
}
);
Object[] result = (Object[]) session.createNativeQuery( "SELECT @a, (@a::=20) FROM dual" ).uniqueResult();
assertEquals("test", result[0]);
assertEquals(20, ((Number) result[1]).intValue());
}
);
}
}

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* License: GNU Lesser General Public License (LGPL), version 2.1 or later. * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.engine.query; package org.hibernate.orm.test.query.sql;
import org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl; import org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl;
import org.hibernate.engine.query.spi.ParamLocationRecognizer; import org.hibernate.engine.query.spi.ParamLocationRecognizer;
@ -12,11 +12,12 @@ import org.hibernate.query.sql.internal.ParameterParser;
import org.hibernate.query.sql.spi.ParameterRecognizer; import org.hibernate.query.sql.spi.ParameterRecognizer;
import org.hibernate.testing.TestForIssue; import org.hibernate.testing.TestForIssue;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* Unit tests of the ParameterParser class * Unit tests of the ParameterParser class
@ -47,6 +48,9 @@ public class ParameterParserTest {
recognizer recognizer
); );
recognizer.complete();
recognizer.validate();
assertTrue( recognizer.getNamedParameterDescriptionMap().containsKey("param")); assertTrue( recognizer.getNamedParameterDescriptionMap().containsKey("param"));
} }
@ -59,6 +63,9 @@ public class ParameterParserTest {
recognizer recognizer
); );
recognizer.complete();
recognizer.validate();
assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() ); assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() );
} }
@ -71,6 +78,9 @@ public class ParameterParserTest {
recognizer recognizer
); );
recognizer.complete();
recognizer.validate();
assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() ); assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() );
} }
@ -83,6 +93,9 @@ public class ParameterParserTest {
recognizer recognizer
); );
recognizer.complete();
recognizer.validate();
assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("param")); assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("param"));
} }
@ -91,7 +104,8 @@ public class ParameterParserTest {
public void testParseColonCharacterEscaped() { public void testParseColonCharacterEscaped() {
final StringBuilder captured = new StringBuilder(); final StringBuilder captured = new StringBuilder();
ParameterRecognizer recognizer = new ParameterRecognizer() { ParameterRecognizer recognizer = new ParameterRecognizer() {
@Override @SuppressWarnings("deprecation")
@Override
public void outParameter(int position) { public void outParameter(int position) {
fail(); fail();
} }
@ -121,6 +135,7 @@ public class ParameterParserTest {
} }
}; };
ParameterParser.parse("SELECT @a,(@a::=20) FROM tbl_name", recognizer); ParameterParser.parse("SELECT @a,(@a::=20) FROM tbl_name", recognizer);
recognizer.complete();
assertEquals("SELECT @a,(@a:=20) FROM tbl_name", captured.toString()); assertEquals("SELECT @a,(@a:=20) FROM tbl_name", captured.toString());
} }
@ -128,6 +143,9 @@ public class ParameterParserTest {
public void testParseNamedParameter() { public void testParseNamedParameter() {
ParamLocationRecognizer recognizer = new ParamLocationRecognizer( 0 ); ParamLocationRecognizer recognizer = new ParamLocationRecognizer( 0 );
NativeQueryInterpreterStandardImpl.INSTANCE.recognizeParameters("from Stock s where s.stockCode = :stockCode and s.xyz = :pxyz", recognizer); NativeQueryInterpreterStandardImpl.INSTANCE.recognizeParameters("from Stock s where s.stockCode = :stockCode and s.xyz = :pxyz", recognizer);
recognizer.complete();
recognizer.validate();
assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("stockCode")); assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("stockCode"));
assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("pxyz")); assertTrue(recognizer.getNamedParameterDescriptionMap().containsKey("pxyz"));
assertEquals( 2, recognizer.getNamedParameterDescriptionMap().size() ); assertEquals( 2, recognizer.getNamedParameterDescriptionMap().size() );
@ -137,9 +155,15 @@ public class ParameterParserTest {
public void testParseJPAPositionalParameter() { public void testParseJPAPositionalParameter() {
ParamLocationRecognizer recognizer = new ParamLocationRecognizer( 0 ); ParamLocationRecognizer recognizer = new ParamLocationRecognizer( 0 );
NativeQueryInterpreterStandardImpl.INSTANCE.recognizeParameters("from Stock s where s.stockCode = ?1 and s.xyz = ?1", recognizer); NativeQueryInterpreterStandardImpl.INSTANCE.recognizeParameters("from Stock s where s.stockCode = ?1 and s.xyz = ?1", recognizer);
recognizer.complete();
recognizer.validate();
assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() ); assertEquals( 1, recognizer.getOrdinalParameterDescriptionMap().size() );
ParameterParser.parse("from Stock s where s.stockCode = ?1 and s.xyz = ?2", recognizer); ParameterParser.parse("from Stock s where s.stockCode = ?1 and s.xyz = ?2", recognizer);
recognizer.complete();
recognizer.validate();
assertEquals( 2, recognizer.getOrdinalParameterDescriptionMap().size() ); assertEquals( 2, recognizer.getOrdinalParameterDescriptionMap().size() );
} }