Search in sources :

Example 31 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class SchemaExportTest method testHibernateMappingSchemaPropertyIsNotIgnored.

@Test
@TestForIssue(jiraKey = "HHH-10678")
@RequiresDialectFeature(value = DialectChecks.SupportSchemaCreation.class)
public void testHibernateMappingSchemaPropertyIsNotIgnored() throws Exception {
    File output = File.createTempFile("update_script", ".sql");
    output.deleteOnExit();
    final MetadataImplementor metadata = (MetadataImplementor) new MetadataSources(serviceRegistry).addResource("org/hibernate/test/schemaupdate/mapping2.hbm.xml").buildMetadata();
    metadata.validate();
    final SchemaExport schemaExport = new SchemaExport();
    schemaExport.setOutputFile(output.getAbsolutePath());
    schemaExport.execute(EnumSet.of(TargetType.SCRIPT), SchemaExport.Action.CREATE, metadata);
    String fileContent = new String(Files.readAllBytes(output.toPath()));
    assertThat(fileContent, fileContent.toLowerCase().contains("create table schema1.version"), is(true));
}
Also used : MetadataSources(org.hibernate.boot.MetadataSources) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) File(java.io.File) SchemaExport(org.hibernate.tool.hbm2ddl.SchemaExport) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) TestForIssue(org.hibernate.testing.TestForIssue)

Example 32 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class CMTTest method testConcurrentCachedDirtyQueries.

@Test
@RequiresDialectFeature(value = DialectChecks.DoesReadCommittedNotCauseWritersToBlockReadersCheck.class, comment = "write locks block readers")
public void testConcurrentCachedDirtyQueries() throws Exception {
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s = openSession();
    Map foo = new HashMap();
    foo.put("name", "Foo");
    foo.put("description", "a big foo");
    s.persist("Item", foo);
    Map bar = new HashMap();
    bar.put("name", "Bar");
    bar.put("description", "a small bar");
    s.persist("Item", bar);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    synchronized (this) {
        wait(1000);
    }
    sessionFactory().getStatistics().clear();
    // we need a clean 2L cache here.
    cleanupCache();
    // open a TX and suspend it
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s4 = openSession();
    Transaction tx4 = TestingJtaPlatformImpl.INSTANCE.getTransactionManager().suspend();
    // open a new TX and execute a query, this would fill the query cache.
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s1 = openSession();
    List r1 = s1.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r1.size(), 2);
    foo = (Map) r1.get(0);
    // update data and make query cache stale, but TX is suspended
    foo.put("description", "a big red foo");
    s1.flush();
    Transaction tx1 = TestingJtaPlatformImpl.INSTANCE.getTransactionManager().suspend();
    // open a new TX and run query again
    // this TX is committed afterQuery query
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s2 = openSession();
    List r2 = s2.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r2.size(), 2);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(4, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(0, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(2, sessionFactory().getStatistics().getQueryCacheMissCount());
    // updateTimestampsCache put happens at two places
    // 1. {@link org.hibernate.engine.spi.ActionQueue#registerCleanupActions} calls preinvalidate
    // 2. {@link org.hibernate.engine.spi.ActionQueue.AfterTransactionCompletionProcessQueue#afterTransactionCompletion} calls invalidate
    // but since the TX which the update action happened is not committed yet, so there should be only 1 updateTimestamps put.
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCachePutCount());
    // updateTimestampsCache hit only happens when the query cache data's timestamp is newer
    // than the timestamp of when update happens
    // since there is only 1 update action
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().resume(tx1);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    // update action's TX committed, so, invalidate is called, put new timestamp into UpdateTimestampsCache
    assertEquals(2, sessionFactory().getStatistics().getUpdateTimestampsCachePutCount());
    // but no more query cache lookup here, so it should still 1
    assertEquals(1, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    Session s3 = openSession();
    s3.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(6, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(0, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCacheMissCount());
    // a new query cache hit and one more update timestamps cache hit, so should be 2
    assertEquals(2, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().resume(tx4);
    List r4 = s4.createCriteria("Item").addOrder(Order.asc("description")).setCacheable(true).list();
    assertEquals(r4.size(), 2);
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
    assertEquals(2, sessionFactory().getStatistics().getSecondLevelCacheHitCount());
    assertEquals(0, sessionFactory().getStatistics().getSecondLevelCacheMissCount());
    assertEquals(6, sessionFactory().getStatistics().getEntityLoadCount());
    assertEquals(0, sessionFactory().getStatistics().getEntityFetchCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryExecutionCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCachePutCount());
    assertEquals(1, sessionFactory().getStatistics().getQueryCacheHitCount());
    assertEquals(3, sessionFactory().getStatistics().getQueryCacheMissCount());
    assertEquals(3, sessionFactory().getStatistics().getUpdateTimestampsCacheHitCount());
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
    s = openSession();
    s.createQuery("delete from Item").executeUpdate();
    TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
Also used : Transaction(javax.transaction.Transaction) HashMap(java.util.HashMap) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Session(org.hibernate.Session) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Example 33 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class CustomRunner method convertSkipToIgnore.

protected Ignore convertSkipToIgnore(FrameworkMethod frameworkMethod) {
    // @Skip
    Skip skip = Helper.locateAnnotation(Skip.class, frameworkMethod, getTestClass());
    if (skip != null) {
        if (isMatch(skip.condition())) {
            return buildIgnore(skip);
        }
    }
    // @SkipForDialects & @SkipForDialect
    for (SkipForDialect skipForDialectAnn : Helper.collectAnnotations(SkipForDialect.class, SkipForDialects.class, frameworkMethod, getTestClass())) {
        for (Class<? extends Dialect> dialectClass : skipForDialectAnn.value()) {
            if (skipForDialectAnn.strictMatching()) {
                if (dialectClass.equals(dialect.getClass())) {
                    return buildIgnore(skipForDialectAnn);
                }
            } else {
                if (dialectClass.isInstance(dialect)) {
                    return buildIgnore(skipForDialectAnn);
                }
            }
        }
    }
    // @RequiresDialects & @RequiresDialect
    final List<RequiresDialect> requiresDialects = Helper.collectAnnotations(RequiresDialect.class, RequiresDialects.class, frameworkMethod, getTestClass());
    if (!requiresDialects.isEmpty() && !isDialectMatchingRequired(requiresDialects)) {
        return buildIgnore(requiresDialects);
    }
    // @RequiresDialectFeature
    RequiresDialectFeature requiresDialectFeatureAnn = Helper.locateAnnotation(RequiresDialectFeature.class, frameworkMethod, getTestClass());
    if (requiresDialectFeatureAnn != null) {
        try {
            for (Class<? extends DialectCheck> checkClass : requiresDialectFeatureAnn.value()) {
                if (!checkClass.newInstance().isMatch(dialect)) {
                    return buildIgnore(requiresDialectFeatureAnn);
                }
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate DialectCheck", e);
        }
    }
    return null;
}
Also used : SkipForDialect(org.hibernate.testing.SkipForDialect) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) Skip(org.hibernate.testing.Skip) RequiresDialect(org.hibernate.testing.RequiresDialect) NoTestsRemainException(org.junit.runner.manipulation.NoTestsRemainException)

Example 34 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testQueryTimeout.

@Test
@RequiresDialect(Oracle10gDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
@FailureExpected(jiraKey = "HHH-8001")
public void testQueryTimeout() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    final EntityManager em2 = createIsolatedEntityManager();
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testQueryTimeout");
        em.getTransaction().begin();
        em.persist(lock);
        em.getTransaction().commit();
        em.clear();
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.lock(lock, LockModeType.PESSIMISTIC_WRITE);
        final Integer id = lock.getId();
        // force entity to be read
        lock.getName();
        log.info("testQueryTimeout: got write lock");
        bgTask = new FutureTask<Boolean>(new Callable<Boolean>() {

            public Boolean call() {
                try {
                    // true (success) if LockTimeoutException occurred
                    boolean timedOut = false;
                    em2.getTransaction().begin();
                    log.info("testQueryTimeout: (BG) about to read write-locked entity");
                    // we should block on the following read
                    Lock lock2 = em2.getReference(Lock.class, id);
                    //  force entity to be read
                    lock2.getName();
                    log.info("testQueryTimeout: (BG) read write-locked entity");
                    try {
                        // we should block on the following read
                        Query query = em2.createQuery("select L from Lock_ L where L.id < 10000 ");
                        query.setLockMode(LockModeType.PESSIMISTIC_READ);
                        // 1 sec timeout
                        query.setHint(QueryHints.SPEC_HINT_TIMEOUT, 500);
                        List<Lock> resultList = query.getResultList();
                        //  force entity to be read
                        String name = resultList.get(0).getName();
                        log.info("testQueryTimeout: name read =" + name);
                    } catch (QueryTimeoutException e) {
                        // success
                        log.info("testQueryTimeout: (BG) got expected timeout exception");
                        timedOut = true;
                    } catch (Throwable e) {
                        log.info("testQueryTimeout: Expected LockTimeoutException but got unexpected exception", e);
                    }
                    em2.getTransaction().commit();
                    return timedOut;
                } finally {
                    // signal that we finished
                    latch.countDown();
                }
            }
        });
        t = new Thread(bgTask);
        t.setDaemon(true);
        t.setName("testQueryTimeout (bg)");
        t.start();
        // should return quickly on success
        boolean latchSet = latch.await(10, TimeUnit.SECONDS);
        assertTrue("background test thread finished (lock timeout is broken)", latchSet);
        assertTrue("background test thread timed out on lock attempt", bgTask.get());
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (t != null) {
            // wait for background thread to finish beforeQuery deleting entity
            t.join();
        }
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.remove(lock);
        em.getTransaction().commit();
        em.close();
        em2.close();
    }
}
Also used : Query(javax.persistence.Query) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) QueryTimeoutException(javax.persistence.QueryTimeoutException) EntityManager(javax.persistence.EntityManager) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) FailureExpected(org.hibernate.testing.FailureExpected) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 35 with RequiresDialectFeature

use of org.hibernate.testing.RequiresDialectFeature in project hibernate-orm by hibernate.

the class LockTest method testLockTimeoutEMProps.

@Test
@RequiresDialect(Oracle10gDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testLockTimeoutEMProps() throws Exception {
    EntityManager em = getOrCreateEntityManager();
    Map<String, Object> TimeoutProps = new HashMap<String, Object>();
    // 1 second timeout
    TimeoutProps.put(AvailableSettings.LOCK_TIMEOUT, 1000);
    final EntityManager em2 = createIsolatedEntityManager(TimeoutProps);
    Lock lock = new Lock();
    Thread t = null;
    FutureTask<Boolean> bgTask;
    final CountDownLatch latch = new CountDownLatch(1);
    try {
        lock.setName("testLockTimeoutEMProps");
        em.getTransaction().begin();
        em.persist(lock);
        em.getTransaction().commit();
        em.clear();
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.lock(lock, LockModeType.PESSIMISTIC_WRITE);
        final Integer id = lock.getId();
        // force entity to be read
        lock.getName();
        log.info("testLockTimeoutEMProps: got write lock");
        bgTask = new FutureTask<Boolean>(new Callable<Boolean>() {

            public Boolean call() {
                try {
                    // true (success) if LockTimeoutException occurred
                    boolean timedOut = false;
                    em2.getTransaction().begin();
                    log.info("testLockTimeoutEMProps: (BG) about to read write-locked entity");
                    // we should block on the following read
                    Lock lock2 = em2.getReference(Lock.class, id);
                    //  force entity to be read
                    lock2.getName();
                    log.info("testLockTimeoutEMProps: (BG) read write-locked entity");
                    // em2 already has AvailableSettings.LOCK_TIMEOUT of 1 second applied
                    try {
                        em2.lock(lock2, LockModeType.PESSIMISTIC_WRITE);
                    } catch (LockTimeoutException e) {
                        // success
                        log.info("testLockTimeoutEMProps: (BG) got expected timeout exception");
                        timedOut = true;
                    } catch (Throwable e) {
                        log.info("Expected LockTimeoutException but got unexpected exception", e);
                    }
                    em2.getTransaction().commit();
                    return timedOut;
                } finally {
                    // signal that we finished
                    latch.countDown();
                }
            }
        });
        t = new Thread(bgTask);
        t.setDaemon(true);
        t.setName("Lock timeout Test (bg)");
        t.start();
        // should return quickly on success
        boolean latchSet = latch.await(10, TimeUnit.SECONDS);
        assertTrue("background test thread finished (lock timeout is broken)", latchSet);
        assertTrue("background test thread timed out on lock attempt", bgTask.get());
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (t != null) {
            // wait for background thread to finish beforeQuery deleting entity
            t.join();
        }
        em.getTransaction().begin();
        lock = em.getReference(Lock.class, lock.getId());
        em.remove(lock);
        em.getTransaction().commit();
        em.close();
        em2.close();
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) EntityManager(javax.persistence.EntityManager) LockTimeoutException(javax.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Aggregations

RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)46 Test (org.junit.Test)45 Session (org.hibernate.Session)34 Transaction (org.hibernate.Transaction)17 TestForIssue (org.hibernate.testing.TestForIssue)10 EntityManager (javax.persistence.EntityManager)8 HashMap (java.util.HashMap)7 RequiresDialect (org.hibernate.testing.RequiresDialect)7 List (java.util.List)6 Callable (java.util.concurrent.Callable)6 CountDownLatch (java.util.concurrent.CountDownLatch)6 Query (org.hibernate.Query)6 LockTimeoutException (javax.persistence.LockTimeoutException)5 ArrayList (java.util.ArrayList)4 QuerySyntaxException (org.hibernate.hql.internal.ast.QuerySyntaxException)4 SkipForDialect (org.hibernate.testing.SkipForDialect)4 Query (javax.persistence.Query)3 BigDecimal (java.math.BigDecimal)2 Map (java.util.Map)2 QueryTimeoutException (javax.persistence.QueryTimeoutException)2