Hibernate SVN: r11090 - branches/Branch_3_2/Hibernate3.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-24 09:53:24 -0500 (Wed, 24 Jan 2007)
New Revision: 11090
Modified:
branches/Branch_3_2/Hibernate3/changelog.txt
Log:
prep 3.2.2 release
Modified: branches/Branch_3_2/Hibernate3/changelog.txt
===================================================================
--- branches/Branch_3_2/Hibernate3/changelog.txt 2007-01-24 14:34:22 UTC (rev 11089)
+++ branches/Branch_3_2/Hibernate3/changelog.txt 2007-01-24 14:53:24 UTC (rev 11090)
@@ -6,6 +6,51 @@
more about each case.
+Chages in version 3.2.2 (2007.12.24)
+-------------------------------------------
+
+** Bug
+ * [HHH-1471] - If the 'generated' attribute is set to 'insert' or 'always' on the property of a component it is ignored and the value is not read from the database.
+ * [HHH-1646] - Bad code in FastClass.equals
+ * [HHH-1889] - LockMode.UPGRADE not applied in all cases for SQL Server / Sybase
+ * [HHH-2112] - ClassCastException in StatefulPersistenceContext.getCachedDatabaseSnapshot(...)
+ * [HHH-2221] - MySQL temp table DDL and isolation
+ * [HHH-2238] - SQLQuery executeUpdate doesn't respect Query.setFlushMode()
+ * [HHH-2251] - Settings build unnecessary in schemaupdate/schemavalidate
+ * [HHH-2257] - Query.iterate() results differ from Query.list() 2
+ * [HHH-2259] - autoflush and autoclose not longer occur in JTA environment with hibernate 3.2
+ * [HHH-2264] - NPE when NamedQuery contains space before variable name
+ * [HHH-2274] - Collection ordering when many to many order by is used is not respected
+ * [HHH-2275] - Mapping a composite element as a map key using formulas can lead to AOOBE
+ * [HHH-2284] - HQL: selecting components inside components doesn't work
+ * [HHH-2291] - collection based on property-ref not handled correctly during reattch
+ * [HHH-2292] - merge detached instance fails to persist collection changes in case of bare collection reference
+ * [HHH-2356] - NullableType.toString(Object) should account for nulls
+ * [HHH-2366] - Changing a component's value does not trigger an update during flush
+ * [HHH-2378] - replicate() of non-versioned entiy can result in wrong value for version in entity cache
+
+** Improvement
+ * [HHH-1851] - relax special handling of 'id' property
+ * [HHH-2130] - SQLQuery does not autoflush all entities used in the query
+ * [HHH-2193] - Introduce a flag to avoid checking NamedQuery at startup
+ * [HHH-2242] - Consider Allowing Optimistic Lock Strategies other than 'Version' with joined-subclass
+ * [HHH-2250] - Create an appropriate error message if Query.setEntity is passed a NULL value
+ * [HHH-2282] - PersistentClass property lookups do not properly account for embedded composite identifiers
+ * [HHH-2286] - dialect informational metadata
+ * [HHH-2372] - Allow tooling to create Settings via SettingsFactory without contacting the db
+
+** New Feature
+ * [HHH-2246] - No way to specify CACHE_PROVIDER_CONFIG in HibernateServiceMBean
+
+** Patch
+ * [HHH-2300] - Updated dialect for H2 database engine
+ * [HHH-2371] - enhancements to C3P0ConnectionProvider
+
+** Task
+ * [HHH-2032] - update c3p0 to 0.9.1
+
+
+
Chages in version 3.2.1 (2006.11.16)
-------------------------------------------
18 years, 1 month
Hibernate SVN: r11089 - in trunk/Hibernate3: test/org/hibernate/test/legacy and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2007-01-24 09:34:22 -0500 (Wed, 24 Jan 2007)
New Revision: 11089
Modified:
trunk/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java
trunk/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java
Log:
HHH-2378 replicate() of non-versioned entiy can result in wrong value for version in entity cache
Modified: trunk/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java
===================================================================
--- trunk/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java 2007-01-24 14:29:43 UTC (rev 11088)
+++ trunk/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java 2007-01-24 14:34:22 UTC (rev 11089)
@@ -74,11 +74,10 @@
}
else {
//what is the version on the database?
- oldVersion = persister.getCurrentVersion( id, source );
+ oldVersion = persister.getCurrentVersion( id, source );
}
- if ( oldVersion != null ) {
- //existing row - do an update if appropriate
+ if ( oldVersion != null ) {
if ( log.isTraceEnabled() ) {
log.trace(
"found existing row for " +
@@ -86,16 +85,19 @@
);
}
+ /// HHH-2378
+ final Object realOldVersion = persister.isVersioned() ? oldVersion : null;
+
boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion(
entity,
- oldVersion,
+ realOldVersion,
persister.getVersion( entity, source.getEntityMode() ),
persister.getVersionType()
);
if ( canReplicate ) {
//will result in a SQL UPDATE:
- performReplication( entity, id, oldVersion, persister, replicationMode, source );
+ performReplication( entity, id, realOldVersion, persister, replicationMode, source );
}
else {
//else do nothing (don't even reassociate object!)
Modified: trunk/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java
===================================================================
--- trunk/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java 2007-01-24 14:29:43 UTC (rev 11088)
+++ trunk/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java 2007-01-24 14:34:22 UTC (rev 11089)
@@ -27,6 +27,8 @@
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.engine.EntityEntry;
+import org.hibernate.impl.SessionImpl;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -80,6 +82,12 @@
s.close();
s = openSession();
s.replicate(baz, ReplicationMode.OVERWRITE);
+
+ // HHH-2378
+ SessionImpl x = (SessionImpl)s;
+ EntityEntry entry = x.getPersistenceContext().getEntry( baz );
+ assertNull(entry.getVersion());
+
s.flush();
s.connection().commit();
s.close();
18 years, 1 month
Hibernate SVN: r11088 - in branches/Branch_3_2/Hibernate3: test/org/hibernate/test/legacy and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2007-01-24 09:29:43 -0500 (Wed, 24 Jan 2007)
New Revision: 11088
Modified:
branches/Branch_3_2/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java
Log:
HHH-2378 replicate() of non-versioned entiy can result in wrong value for version in entity cache
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java 2007-01-23 20:12:25 UTC (rev 11087)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/event/def/DefaultReplicateEventListener.java 2007-01-24 14:29:43 UTC (rev 11088)
@@ -74,11 +74,10 @@
}
else {
//what is the version on the database?
- oldVersion = persister.getCurrentVersion( id, source );
+ oldVersion = persister.getCurrentVersion( id, source );
}
- if ( oldVersion != null ) {
- //existing row - do an update if appropriate
+ if ( oldVersion != null ) {
if ( log.isTraceEnabled() ) {
log.trace(
"found existing row for " +
@@ -86,16 +85,19 @@
);
}
+ /// HHH-2378
+ final Object realOldVersion = persister.isVersioned() ? oldVersion : null;
+
boolean canReplicate = replicationMode.shouldOverwriteCurrentVersion(
entity,
- oldVersion,
+ realOldVersion,
persister.getVersion( entity, source.getEntityMode() ),
persister.getVersionType()
);
if ( canReplicate ) {
//will result in a SQL UPDATE:
- performReplication( entity, id, oldVersion, persister, replicationMode, source );
+ performReplication( entity, id, realOldVersion, persister, replicationMode, source );
}
else {
//else do nothing (don't even reassociate object!)
Modified: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java 2007-01-23 20:12:25 UTC (rev 11087)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/legacy/ParentChildTest.java 2007-01-24 14:29:43 UTC (rev 11088)
@@ -27,6 +27,8 @@
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.engine.EntityEntry;
+import org.hibernate.impl.SessionImpl;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -80,6 +82,12 @@
s.close();
s = openSession();
s.replicate(baz, ReplicationMode.OVERWRITE);
+
+ // HHH-2378
+ SessionImpl x = (SessionImpl)s;
+ EntityEntry entry = x.getPersistenceContext().getEntry( baz );
+ assertNull(entry.getVersion());
+
s.flush();
s.connection().commit();
s.close();
18 years, 1 month
Hibernate SVN: r11087 - branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-23 15:12:25 -0500 (Tue, 23 Jan 2007)
New Revision: 11087
Added:
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/DirectoryProviderHelper.java
Log:
ANN-519 pluggable worker
ANN-523 JMS implementation
Added: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/DirectoryProviderHelper.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/DirectoryProviderHelper.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/DirectoryProviderHelper.java 2007-01-23 20:12:25 UTC (rev 11087)
@@ -0,0 +1,80 @@
+//$Id: $
+package org.hibernate.search.util;
+
+import java.util.Properties;
+import java.io.File;
+import java.io.IOException;
+import java.text.MessageFormat;
+
+import org.hibernate.HibernateException;
+import org.hibernate.AssertionFailure;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class DirectoryProviderHelper {
+ private static Log log = LogFactory.getLog( DirectoryProviderHelper.class );
+ /**
+ * Build a directory name out of a root and relative path, guessing the significant part
+ * and checking for the file availability
+ *
+ */
+ public static String getSourceDirectory(String rootPropertyName, String relativePropertyName, Properties properties) {
+ //TODO check that it's a directory
+ String root = properties.getProperty( rootPropertyName );
+ String relative = properties.getProperty( relativePropertyName );
+ if ( log.isTraceEnabled() ) {
+ log.trace(
+ "Guess source directory from " + rootPropertyName + " " + root != null ? root : "<null>"
+ + " and " + relativePropertyName + " " + relative != null ? relative : "<null>"
+ );
+ }
+ if (relative == null) throw new HibernateException("source property mandatory");
+ if (root == null) {
+ log.debug( "No root directory, go with relative " + relative );
+ File sourceFile = new File(relative);
+ if ( ! sourceFile.exists() ) {
+ throw new HibernateException("Unable to read source directory: " + relative);
+ }
+ //else keep source as it
+ }
+ else {
+ File sourceFile = new File(root, relative);
+ if ( sourceFile.exists() ) {
+ log.debug( "Get directory from root + relative");
+ try {
+ relative = sourceFile.getCanonicalPath();
+ }
+ catch (IOException e) {
+ throw new AssertionFailure("Unable to get canonical path: " + root + " + " + relative);
+ }
+ }
+ else {
+ sourceFile = new File(relative);
+ log.debug( "Get directory from relative only");
+ if ( ! sourceFile.exists() ) {
+ throw new HibernateException("Unable to read source directory: " + relative);
+ }
+ //else keep source as it
+ }
+ }
+ return relative;
+ }
+
+ public static File determineIndexDir(String directoryProviderName, Properties properties) {
+ String indexBase = properties.getProperty( "indexBase", "." );
+ File indexDir = new File( indexBase );
+ if ( !( indexDir.exists() && indexDir.isDirectory() ) ) {
+ //TODO create the directory?
+ throw new HibernateException( MessageFormat.format( "Index directory does not exists: {0}", indexBase ) );
+ }
+ if ( !indexDir.canWrite() ) {
+ throw new HibernateException( "Cannot write into index directory: " + indexBase );
+ }
+
+ indexDir = new File( indexDir, directoryProviderName );
+ return indexDir;
+ }
+}
18 years, 1 month
Hibernate SVN: r11086 - branches/Branch_3_2/HibernateExt/metadata/lib.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-23 15:07:51 -0500 (Tue, 23 Jan 2007)
New Revision: 11086
Added:
branches/Branch_3_2/HibernateExt/metadata/lib/jms.jar
Log:
ANN-519 pluggable worker
ANN-523 JMS implementation
Added: branches/Branch_3_2/HibernateExt/metadata/lib/jms.jar
===================================================================
(Binary files differ)
Property changes on: branches/Branch_3_2/HibernateExt/metadata/lib/jms.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
18 years, 1 month
Hibernate SVN: r11085 - in branches/Branch_3_2/HibernateExt/metadata/src: java/org/hibernate/search/backend/impl/jms and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-23 14:26:42 -0500 (Tue, 23 Jan 2007)
New Revision: 11085
Added:
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSHibernateSearchController.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSSwitchableDirectoryProvider.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/FileHelper.java
branches/Branch_3_2/HibernateExt/metadata/src/test/org/hibernate/search/test/util/
branches/Branch_3_2/HibernateExt/metadata/src/test/org/hibernate/search/test/util/FileHelperTest.java
Modified:
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/SearchFactory.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSQueueWorker.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProvider.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProviderFactory.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSDirectoryProvider.java
branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/RAMDirectoryProvider.java
Log:
ANN-519 pluggable worker
ANN-523 JMS implementation
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/SearchFactory.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/SearchFactory.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/SearchFactory.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -82,7 +82,7 @@
if ( mappedClass != null ) {
XClass mappedXClass = reflectionManager.toXClass( mappedClass );
if ( mappedXClass != null && mappedXClass.isAnnotationPresent( Indexed.class ) ) {
- DirectoryProvider provider = factory.createDirectoryProvider( mappedXClass, cfg );
+ DirectoryProvider provider = factory.createDirectoryProvider( mappedXClass, cfg, this );
if ( !lockableDirectoryProviders.containsKey( provider ) ) {
lockableDirectoryProviders.put( provider, new ReentrantLock() );
}
Added: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSHibernateSearchController.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSHibernateSearchController.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSHibernateSearchController.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -0,0 +1,71 @@
+//$Id: $
+package org.hibernate.search.backend.impl.jms;
+
+import java.util.List;
+import java.util.Properties;
+import javax.jms.MessageListener;
+import javax.jms.Message;
+import javax.jms.ObjectMessage;
+import javax.jms.JMSException;
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.logging.Log;
+import org.hibernate.search.backend.Work;
+import org.hibernate.search.backend.QueueWorker;
+import org.hibernate.search.backend.impl.BatchedQueueWorker;
+import org.hibernate.search.util.ContextHelper;
+import org.hibernate.search.SearchFactory;
+import org.hibernate.Session;
+import org.hibernate.engine.SessionImplementor;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class JMSHibernateSearchController implements MessageListener {
+ private static Log log = LogFactory.getLog( JMSHibernateSearchController.class );
+
+ protected abstract Session getSession();
+
+ public void onMessage(Message message) {
+ if (! (message instanceof ObjectMessage) ) {
+ log.error( "Incorrect message type: " + message.getClass() );
+ return;
+ }
+ ObjectMessage objectMessage = (ObjectMessage) message;
+ List<Work> queue;
+ try {
+ queue = (List<Work>) objectMessage.getObject();
+ }
+ catch (JMSException e) {
+ log.error( "Unable to retrieve object from message: " + message.getClass(), e );
+ return;
+ }
+ catch( ClassCastException e ) {
+ log.error( "Illegal object retrieved from message", e );
+ return;
+ }
+ QueueWorker worker = getWorker( queue );
+ worker.run();
+ }
+
+ private QueueWorker getWorker(List<Work> queue) {
+ //FIXME casting sucks becasue we do not control what get session from
+ SearchFactory factory = ContextHelper.getSearchFactory( (SessionImplementor) getSession() );
+ QueueWorker worker = new BatchedQueueWorker();
+ worker.initialize( new Properties(), factory );
+ worker.setQueue( queue );
+ return worker;
+ }
+
+ @PostConstruct
+ public void initialize() {
+ //init the source copy process
+
+ }
+ @PreDestroy
+ public void shutdown() {
+ //stop the source copy process
+ }
+}
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSQueueWorker.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSQueueWorker.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/backend/impl/jms/JMSQueueWorker.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -2,11 +2,9 @@
package org.hibernate.search.backend.impl.jms;
import java.util.List;
-import java.util.Map;
import java.util.Properties;
import java.util.HashSet;
import java.util.Iterator;
-import java.util.concurrent.locks.ReentrantLock;
import java.io.Serializable;
import javax.jms.QueueSender;
@@ -22,8 +20,7 @@
import org.hibernate.search.backend.QueueWorker;
import org.hibernate.search.backend.Work;
-import org.hibernate.search.engine.DocumentBuilder;
-import org.hibernate.search.store.DirectoryProvider;
+import org.hibernate.search.SearchFactory;
import org.hibernate.search.Environment;
import org.hibernate.HibernateException;
@@ -32,8 +29,6 @@
*/
public class JMSQueueWorker implements QueueWorker {
private List<Work> queue;
- private Map<DirectoryProvider, ReentrantLock> lockableDirectoryProviders;
- private Map<Class, DocumentBuilder<Object>> documentBuilders;
private String jmsQueueName;
private String jmsConnectionFactoryName;
private static final String JNDI_PREFIX = Environment.WORKER_PREFIX + "jndi.";
@@ -43,9 +38,9 @@
public void run() {
resetJMSTools();
- QueueConnection cnn = null;
- QueueSender sender = null;
- QueueSession session = null;
+ QueueConnection cnn;
+ QueueSender sender;
+ QueueSession session;
try {
cnn = factory.createQueueConnection();
//TODO make transacted parameterized
@@ -75,10 +70,7 @@
}
}
- public void initialize(Properties props, Map<Class, DocumentBuilder<Object>> documentBuilders,
- Map<DirectoryProvider, ReentrantLock> lockableDirectoryProviders) {
- this.documentBuilders = documentBuilders;
- this.lockableDirectoryProviders = lockableDirectoryProviders;
+ public void initialize(Properties props, SearchFactory searchFactory) {
this.properties = props;
this.jmsConnectionFactoryName = props.getProperty( Environment.WORKER_PREFIX + "jms.connection_factory" );
this.jmsQueueName = props.getProperty( Environment.WORKER_PREFIX + "jms.queue" );
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProvider.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProvider.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProvider.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -4,6 +4,7 @@
import java.util.Properties;
import org.apache.lucene.store.Directory;
+import org.hibernate.search.SearchFactory;
/**
@@ -21,7 +22,7 @@
/**
* get the information to initialize the directory and build its hashCode
*/
- void initialize(String directoryProviderName, Properties properties);
+ void initialize(String directoryProviderName, Properties properties, SearchFactory searchFactory);
/**
* Returns an initialized Lucene Directory. This method call <b>must</b> be threadsafe
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProviderFactory.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProviderFactory.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/DirectoryProviderFactory.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -10,6 +10,7 @@
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.search.annotations.Indexed;
+import org.hibernate.search.SearchFactory;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.reflection.ReflectionManager;
import org.hibernate.reflection.XClass;
@@ -40,9 +41,7 @@
private static String DEFAULT_DIRECTORY_PROVIDER = FSDirectoryProvider.class.getName();
//TODO for the public?
- //public DirectoryProvider<?> createDirectoryProvider(XClass entity, Configuration cfg) {
-
- public DirectoryProvider<?> createDirectoryProvider(XClass entity, Configuration cfg) {
+ public DirectoryProvider<?> createDirectoryProvider(XClass entity, Configuration cfg, SearchFactory searchFactory) {
//get properties
String directoryProviderName = getDirectoryProviderName( entity, cfg );
Properties indexProps = getDirectoryProperties( cfg, directoryProviderName );
@@ -63,7 +62,12 @@
catch (Exception e) {
throw new HibernateException( "Unable to instanciate directory provider: " + className, e );
}
- provider.initialize( directoryProviderName, indexProps );
+ try {
+ provider.initialize( directoryProviderName, indexProps, searchFactory );
+ }
+ catch (Exception e) {
+ throw new HibernateException( "Unable to initialize: " + directoryProviderName, e);
+ }
int index = providers.indexOf( provider );
if ( index != -1 ) {
//share the same Directory provider for the same underlying store
@@ -93,7 +97,7 @@
return indexProps;
}
- public static String getDirectoryProviderName(XClass clazz, Configuration cfg) {
+ private static String getDirectoryProviderName(XClass clazz, Configuration cfg) {
//yuk
ReflectionManager reflectionManager =
( (AnnotationConfiguration) cfg ).createExtendedMappings().getReflectionManager();
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSDirectoryProvider.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSDirectoryProvider.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSDirectoryProvider.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -3,7 +3,6 @@
import java.io.File;
import java.io.IOException;
-import java.text.MessageFormat;
import java.util.Properties;
import org.apache.commons.logging.Log;
@@ -12,6 +11,8 @@
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.hibernate.HibernateException;
+import org.hibernate.search.util.DirectoryProviderHelper;
+import org.hibernate.search.SearchFactory;
/**
* Use a Lucene FSDirectory
@@ -26,24 +27,11 @@
private static Log log = LogFactory.getLog( FSDirectoryProvider.class );
private String indexName;
- public void initialize(String directoryProviderName, Properties properties) {
- String indexBase = properties.getProperty( "indexBase", "." );
- File indexDir = new File( indexBase );
-
- if ( !( indexDir.exists() && indexDir.isDirectory() ) ) {
- //TODO create the directory?
- throw new HibernateException( MessageFormat.format( "Index directory does not exists: {0}", indexBase ) );
- }
- if ( !indexDir.canWrite() ) {
- throw new HibernateException( "Cannot write into index directory: " + indexBase );
- }
- log.info( "Setting index dir to " + indexDir );
-
- File file = new File( indexDir, directoryProviderName );
-
+ public void initialize(String directoryProviderName, Properties properties, SearchFactory searchFactory) {
+ File indexDir = DirectoryProviderHelper.determineIndexDir( directoryProviderName, properties );
try {
- boolean create = !file.exists();
- indexName = file.getCanonicalPath();
+ boolean create = !indexDir.exists();
+ indexName = indexDir.getCanonicalPath();
directory = FSDirectory.getDirectory( indexName, create );
if ( create ) {
IndexWriter iw = new IndexWriter( directory, new StandardAnalyzer(), create );
@@ -53,7 +41,6 @@
catch (IOException e) {
throw new HibernateException( "Unable to initialize index: " + directoryProviderName, e );
}
-
}
public FSDirectory getDirectory() {
Added: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSMasterDirectoryProvider.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSMasterDirectoryProvider.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSMasterDirectoryProvider.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -0,0 +1,193 @@
+//$Id: $
+package org.hibernate.search.store;
+
+import java.util.Timer;
+import java.util.Properties;
+import java.util.TimerTask;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.locks.Lock;
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.search.util.DirectoryProviderHelper;
+import org.hibernate.search.util.FileHelper;
+import org.hibernate.search.SearchFactory;
+import org.hibernate.HibernateException;
+
+/**
+ * Use a Lucene FSDirectory
+ * The base directory is represented by hibernate.search.<index>.indexBase
+ * The index is created in <base directory>/<index name>
+ *
+ * @author Emmanuel Bernard
+ */
+public class FSMasterDirectoryProvider implements DirectoryProvider<FSDirectory> {
+ private static Log log = LogFactory.getLog( FSMasterDirectoryProvider.class );
+ private FSDirectory directory;
+ private int current;
+ private String indexName;
+ private Timer timer;
+ private SearchFactory searchFactory;
+
+ public void initialize(String directoryProviderName, Properties properties, SearchFactory searchFactory) {
+ //source guessing
+ String source = DirectoryProviderHelper.getSourceDirectory( "sourceBase", "source", properties );
+ if (source == null)
+ throw new IllegalStateException("FSMasterDirectoryProvider requires a viable source directory");
+ File indexDir = DirectoryProviderHelper.determineIndexDir( directoryProviderName, properties );
+ String refreshPeriod = properties.getProperty( "refresh", "60" );
+ long period = Long.parseLong( refreshPeriod );
+
+ try {
+ boolean create = !indexDir.exists();
+ indexName = indexDir.getCanonicalPath();
+ if (create) {
+ log.debug( "Index directory '" + indexName + "' will be initialized");
+ indexDir.mkdir();
+ }
+ directory = FSDirectory.getDirectory( indexName, create );
+ if ( create ) {
+ IndexWriter iw = new IndexWriter( directory, new StandardAnalyzer(), create );
+ iw.close();
+ }
+
+ //copy to source
+ if ( new File(source, "current1").exists() ) {
+ current = 2;
+ }
+ else if ( new File(source, "current2").exists() ) {
+ current = 1;
+ }
+ else {
+ log.debug( "Source directory for '" + indexName + "' will be initialized");
+ current = 1;
+ }
+ String currentString = Integer.valueOf( current ).toString();
+ File subDir = new File(source, currentString );
+ FileHelper.synchronize( indexDir, subDir, true );
+ new File(source, "current1").delete();
+ new File(source, "current2").delete();
+ //TODO small hole, no file can be found here
+ new File(source, "current" + currentString).createNewFile();
+ log.debug( "Current directory: " + current);
+ }
+ catch (IOException e) {
+ throw new HibernateException( "Unable to initialize index: " + directoryProviderName, e );
+ }
+ timer = new Timer();
+ TimerTask task = new FSMasterDirectoryProvider.TriggerTask(indexName, source, this );
+ timer.scheduleAtFixedRate( task, period, period );
+ this.searchFactory = searchFactory;
+ }
+
+ public FSDirectory getDirectory() {
+ return directory;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ // this code is actually broken since the value change after initialize call
+ // but from a practical POV this is fine since we only call this method
+ // after initialize call
+ if ( obj == this ) return true;
+ if ( obj == null || !( obj instanceof FSMasterDirectoryProvider ) ) return false;
+ return indexName.equals( ( (FSMasterDirectoryProvider) obj ).indexName );
+ }
+
+ @Override
+ public int hashCode() {
+ // this code is actually broken since the value change after initialize call
+ // but from a practical POV this is fine since we only call this method
+ // after initialize call
+ int hash = 11;
+ return 37 * hash + indexName.hashCode();
+ }
+
+ class TriggerTask extends TimerTask {
+
+ private ExecutorService executor;
+ private FSMasterDirectoryProvider.CopyDirectory copyTask;
+
+ public TriggerTask(String source, String destination, DirectoryProvider directoryProvider) {
+ executor = Executors.newSingleThreadExecutor();
+ copyTask = new FSMasterDirectoryProvider.CopyDirectory( source, destination, directoryProvider );
+ }
+
+ public void run() {
+ if (!copyTask.inProgress) {
+ executor.execute( copyTask );
+ }
+ else {
+ log.info( "Skipping directory synchronization, previous work still in progress: " + indexName);
+ }
+ }
+ }
+
+ class CopyDirectory implements Runnable {
+ private String source;
+ private String destination;
+ private volatile boolean inProgress;
+ private Lock directoryProviderLock;
+ private DirectoryProvider directoryProvider;
+
+ public CopyDirectory(String source, String destination, DirectoryProvider directoryProvider) {
+ this.source = source;
+ this.destination = destination;
+ this.directoryProvider = directoryProvider;
+ }
+
+ public void run() {
+ //TODO get rid of current and use the marker file instead?
+ inProgress = true;
+ if (directoryProviderLock == null) {
+ directoryProviderLock = searchFactory.getLockableDirectoryProviders().get( directoryProvider );
+ directoryProvider = null;
+ searchFactory = null; //get rid of any useless link (help hot redeployment?)
+ }
+ try {
+ directoryProviderLock.lock();
+ int oldIndex = current;
+ int index = current == 1 ? 2 : 1;
+ File sourceFile = new File(source);
+
+ File destinationFile = new File(destination, Integer.valueOf(index).toString() );
+ //TODO make smart a parameter
+ try {
+ FileHelper.synchronize( sourceFile, destinationFile, true);
+ current = index;
+ }
+ catch (IOException e) {
+ //don't change current
+ log.error( "Unable to synchronize source of " + indexName, e);
+ inProgress = false;
+ return;
+ }
+ if ( ! new File(source, "current" + oldIndex).delete() ) {
+ log.warn( "Unable to remove previous marker file from source of " + indexName );
+ }
+ try {
+ new File(source, "current" + index).createNewFile();
+ }
+ catch( IOException e ) {
+ log.warn( "Unable to create current marker in source of " + indexName, e );
+ }
+ }
+ finally {
+ directoryProviderLock.unlock();
+ inProgress = false;
+ }
+ }
+ }
+
+ public void finalize() throws Throwable {
+ super.finalize();
+ timer.cancel();
+ //TODO find a better cycle from Hibernate core
+ }
+}
Added: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSSwitchableDirectoryProvider.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSSwitchableDirectoryProvider.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/FSSwitchableDirectoryProvider.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -0,0 +1,217 @@
+//$Id: $
+package org.hibernate.search.store;
+
+import java.util.Properties;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
+import org.hibernate.AssertionFailure;
+import org.hibernate.search.util.FileHelper;
+import org.hibernate.search.util.DirectoryProviderHelper;
+import org.hibernate.search.SearchFactory;
+
+/**
+ * Use a Lucene FSDirectory
+ * The base directory is represented by hibernate.search.<index>.indexBase
+ * The index is created in <base directory>/<index name>
+ *
+ * @author Emmanuel Bernard
+ */
+public class FSSwitchableDirectoryProvider implements DirectoryProvider<FSDirectory> {
+ private static Log log = LogFactory.getLog( FSSwitchableDirectoryProvider.class );
+ private FSDirectory directory1;
+ private FSDirectory directory2;
+ private int current;
+ private String indexName;
+ private Timer timer;
+
+ public void initialize(String directoryProviderName, Properties properties, SearchFactory searchFactory) {
+ //source guessing
+ String source = DirectoryProviderHelper.getSourceDirectory( "sourceBase", "source", properties );
+ if (source == null)
+ throw new IllegalStateException("FSSwitchableDirectoryProvider requires a viable source directory");
+ if ( ! new File(source, "current1").exists() && ! new File(source, "current2").exists() ) {
+ throw new IllegalStateException("No current marker in source directory");
+ }
+ File indexDir = DirectoryProviderHelper.determineIndexDir( directoryProviderName, properties );
+ String refreshPeriod = properties.getProperty( "refresh", "60" );
+ long period = Long.parseLong( refreshPeriod );
+
+ try {
+ boolean create = !indexDir.exists();
+ indexName = indexDir.getCanonicalPath();
+ if (create) indexDir.mkdir();
+
+ File subDir = new File( indexName, "1" );
+ create = ! subDir.exists();
+ directory1 = FSDirectory.getDirectory( subDir.getCanonicalPath(), create );
+ if ( create ) {
+ IndexWriter iw = new IndexWriter( directory1, new StandardAnalyzer(), create );
+ iw.close();
+ }
+
+ subDir = new File( indexName, "2" );
+ create = ! subDir.exists();
+ directory2 = FSDirectory.getDirectory( subDir.getCanonicalPath(), create );
+ if ( create ) {
+ IndexWriter iw = new IndexWriter( directory2, new StandardAnalyzer(), create );
+ iw.close();
+ }
+ File currentMarker = new File(indexName, "current1");
+ File current2Marker = new File(indexName, "current2");
+ if ( currentMarker.exists() ) {
+ current = 1;
+ }
+ else if ( current2Marker.exists() ) {
+ current = 2;
+ }
+ else {
+ //no default
+ log.debug( "Setting directory 1 as current");
+ current = 1;
+ File sourceFile = new File(source);
+ File destinationFile = new File(indexName, Integer.valueOf(current).toString() );
+ //TODO make smart a parameter
+ try {
+ FileHelper.synchronize( sourceFile, destinationFile, true);
+ }
+ catch (IOException e) {
+ throw new HibernateException("Umable to synchonize directory: " + indexName, e);
+ }
+ if (! currentMarker.createNewFile() ) {
+ throw new HibernateException("Unable to create the directory marker file: " + indexName);
+ }
+ }
+ log.debug( "Current directory: " + current);
+ }
+ catch (IOException e) {
+ throw new HibernateException( "Unable to initialize index: " + directoryProviderName, e );
+ }
+ timer = new Timer();
+ TimerTask task = new TriggerTask(source, indexName);
+ timer.scheduleAtFixedRate( task, period, period );
+ }
+
+ public FSDirectory getDirectory() {
+ if (current == 1) {
+ return directory1;
+ }
+ else if (current == 2) {
+ return directory2;
+ }
+ else {
+ throw new AssertionFailure("Illegal current directory: " + current);
+ }
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ // this code is actually broken since the value change after initialize call
+ // but from a practical POV this is fine since we only call this method
+ // after initialize call
+ if ( obj == this ) return true;
+ if ( obj == null || !( obj instanceof FSSwitchableDirectoryProvider ) ) return false;
+ return indexName.equals( ( (FSSwitchableDirectoryProvider) obj ).indexName );
+ }
+
+ @Override
+ public int hashCode() {
+ // this code is actually broken since the value change after initialize call
+ // but from a practical POV this is fine since we only call this method
+ // after initialize call
+ int hash = 11;
+ return 37 * hash + indexName.hashCode();
+ }
+
+ class TriggerTask extends TimerTask {
+
+ private ExecutorService executor;
+ private CopyDirectory copyTask;
+
+ public TriggerTask(String source, String destination) {
+ executor = Executors.newSingleThreadExecutor();
+ copyTask = new CopyDirectory( source, destination );
+ }
+
+ public void run() {
+ if (!copyTask.inProgress) {
+ executor.execute( copyTask );
+ }
+ else {
+ log.info( "Skipping directory synchronization, previous work still in progress: " + indexName);
+ }
+ }
+ }
+
+ class CopyDirectory implements Runnable {
+ private String source;
+ private String destination;
+ private volatile boolean inProgress;
+
+ public CopyDirectory(String source, String destination) {
+ this.source = source;
+ this.destination = destination;
+ }
+
+ public void run() {
+ try {
+ inProgress = true;
+ int oldIndex = current;
+ int index = current == 1 ? 2 : 1;
+ File sourceFile;
+ if ( new File( source, "current1" ).exists() ) {
+ sourceFile = new File(source, "1");
+ }
+ else if ( new File( source, "current2" ).exists() ) {
+ sourceFile = new File(source, "2");
+ }
+ else {
+ log.error("Unable to determine current in source directory");
+ inProgress = false;
+ return;
+ }
+
+ File destinationFile = new File(destination, Integer.valueOf(index).toString() );
+ //TODO make smart a parameter
+ try {
+ FileHelper.synchronize( sourceFile, destinationFile, true);
+ current = index;
+ }
+ catch (IOException e) {
+ //don't change current
+ log.error( "Unable to synchronize " + indexName, e);
+ inProgress = false;
+ return;
+ }
+ if ( ! new File(indexName, "current" + oldIndex).delete() ) {
+ log.warn( "Unable to remove previous marker file in " + indexName );
+ }
+ try {
+ new File(indexName, "current" + index).createNewFile();
+ }
+ catch( IOException e ) {
+ log.warn( "Unable to create current marker file in " + indexName, e );
+ }
+ }
+ finally {
+ inProgress = false;
+ }
+ }
+ }
+
+ public void finalize() throws Throwable {
+ super.finalize();
+ timer.cancel();
+ //TODO find a better cycle from Hibernate core
+ }
+}
Modified: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/RAMDirectoryProvider.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/RAMDirectoryProvider.java 2007-01-23 19:24:37 UTC (rev 11084)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/store/RAMDirectoryProvider.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -8,6 +8,7 @@
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.RAMDirectory;
import org.hibernate.HibernateException;
+import org.hibernate.search.SearchFactory;
/**
* Use a Lucene RAMDirectory
@@ -20,7 +21,7 @@
private RAMDirectory directory;
private String indexName;
- public void initialize(String directoryProviderName, Properties properties) {
+ public void initialize(String directoryProviderName, Properties properties, SearchFactory searchFactory) {
indexName = directoryProviderName;
directory = new RAMDirectory();
try {
Added: branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/FileHelper.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/FileHelper.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/java/org/hibernate/search/util/FileHelper.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -0,0 +1,86 @@
+//$Id: $
+package org.hibernate.search.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Arrays;
+import java.nio.channels.FileChannel;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public abstract class FileHelper {
+ private static final int FAT_PRECISION = 2000;
+
+ public static void synchronize(File source, File destination, boolean smart) throws IOException {
+ if ( source.isDirectory() ) {
+ if ( ! destination.exists() ) {
+ destination.mkdirs();
+ }
+ else if ( ! destination.isDirectory() ) {
+ throw new IOException("Source and Destination not of the same type:"
+ + source.getCanonicalPath() + " , " + destination.getCanonicalPath() );
+ }
+ String[] sources = source.list();
+ Set<String> srcNames = new HashSet<String>( Arrays.asList( sources ) );
+ String[] dests = destination.list();
+
+ //delete files not present in source
+ for (String fileName : dests) {
+ if ( ! srcNames.contains( fileName ) ) {
+ delete( new File(destination, fileName) );
+ }
+ }
+ //copy each file from source
+ for (String fileName : sources) {
+ File srcFile = new File(source, fileName);
+ File destFile = new File(destination, fileName);
+ synchronize( srcFile, destFile, smart );
+ }
+ }
+ else {
+ if ( destination.exists() && destination.isDirectory() ) {
+ delete( destination );
+ }
+ if ( destination.exists() ) {
+ long sts = source.lastModified() / FAT_PRECISION;
+ long dts = destination.lastModified() / FAT_PRECISION;
+ //do not copy if smart and same timestamp and same length
+ if ( !smart || sts == 0 || sts != dts || source.length() != destination.length() ) {
+ copyFile(source, destination);
+ }
+ }
+ else {
+ copyFile(source, destination);
+ }
+ }
+ }
+
+ private static void copyFile(File srcFile, File destFile) throws IOException {
+ FileInputStream is = null;
+ FileOutputStream os = null;
+ try {
+ is = new FileInputStream(srcFile);
+ FileChannel iChannel = is.getChannel();
+ os = new FileOutputStream( destFile, false );
+ FileChannel oChannel = os.getChannel();
+ oChannel.transferFrom( iChannel, 0, srcFile.length() );
+ }
+ finally {
+ if (is != null) is.close();
+ if (os != null) os.close();
+ }
+ destFile.setLastModified( srcFile.lastModified() );
+ }
+
+ public static void delete(File file) {
+ if ( file.isDirectory() ) {
+ for ( File subFile : file.listFiles() ) delete( subFile );
+ }
+ if ( file.exists() ) file.delete();
+ }
+}
Added: branches/Branch_3_2/HibernateExt/metadata/src/test/org/hibernate/search/test/util/FileHelperTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/test/org/hibernate/search/test/util/FileHelperTest.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/metadata/src/test/org/hibernate/search/test/util/FileHelperTest.java 2007-01-23 19:26:42 UTC (rev 11085)
@@ -0,0 +1,82 @@
+//$Id: $
+package org.hibernate.search.test.util;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import junit.framework.TestCase;
+import org.hibernate.search.util.FileHelper;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class FileHelperTest extends TestCase {
+ public void testTiti() throws Exception {
+ File titi = new File("file:/c:/titi", "file:/d:/toito");
+ assertFalse ( titi.exists() );
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ File dir = new File("./filehelpersrc");
+ dir.mkdir();
+ String name = "a";
+ createFile( dir, name );
+ name = "b";
+ createFile( dir, name );
+ dir = new File(dir, "subdir");
+ dir.mkdir();
+ name = "c";
+ createFile( dir, name );
+ }
+
+ private void createFile(File dir, String name) throws IOException {
+ File a = new File(dir, name);
+ a.createNewFile();
+ FileOutputStream os = new FileOutputStream( a, false );
+ os.write( 1 );
+ os.write( 2 );
+ os.write( 3 );
+ os.flush();
+ os.close();
+ }
+
+ protected void tearDown() throws Exception {
+ super.setUp();
+ File dir = new File("./filehelpersrc");
+ FileHelper.delete( dir );
+ dir = new File("./filehelperdest");
+ FileHelper.delete( dir );
+ }
+
+ public void testSynchronize() throws Exception {
+ File src = new File("./filehelpersrc");
+ File dest = new File("./filehelpertest");
+ FileHelper.synchronize( src, dest, true );
+ File test = new File(dest, "b");
+ assertTrue( test.exists() );
+ test = new File( new File(dest, "subdir"), "c");
+ assertTrue( test.exists() );
+
+ //change
+ Thread.sleep( 2*2000 );
+ test = new File( src, "c");
+ FileOutputStream os = new FileOutputStream( test, true );
+ os.write( 1 );
+ os.write( 2 );
+ os.write( 3 );
+ os.flush();
+ os.close();
+ File destTest = new File(dest, "c");
+ assertNotSame( test.lastModified(), destTest.lastModified() );
+ FileHelper.synchronize( src, dest, true );
+ assertEquals( test.lastModified(), destTest.lastModified() );
+ assertEquals( test.length(), destTest.length() );
+
+ //delete file
+ test.delete();
+ FileHelper.synchronize( src, dest, true );
+ assertTrue( ! destTest.exists() );
+ }
+}
18 years, 1 month
Hibernate SVN: r11084 - branches/Branch_3_2/HibernateExt/metadata/src/test.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-23 14:24:37 -0500 (Tue, 23 Jan 2007)
New Revision: 11084
Modified:
branches/Branch_3_2/HibernateExt/metadata/src/test/hibernate.properties
Log:
format sql
Modified: branches/Branch_3_2/HibernateExt/metadata/src/test/hibernate.properties
===================================================================
--- branches/Branch_3_2/HibernateExt/metadata/src/test/hibernate.properties 2007-01-23 19:23:13 UTC (rev 11083)
+++ branches/Branch_3_2/HibernateExt/metadata/src/test/hibernate.properties 2007-01-23 19:24:37 UTC (rev 11084)
@@ -11,8 +11,10 @@
#hibernate.query.factory_class org.hibernate.hql.classic.ClassicQueryTranslatorFactory
+hibernate.format_sql true
+
#################
### Platforms ###
#################
18 years, 1 month
Hibernate SVN: r11083 - branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2007-01-23 14:23:13 -0500 (Tue, 23 Jan 2007)
New Revision: 11083
Added:
branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Colony.java
branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Empire.java
Modified:
branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/MergeTest.java
Log:
test on merging a managed object
Added: branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Colony.java
===================================================================
--- branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Colony.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Colony.java 2007-01-23 19:23:13 UTC (rev 11083)
@@ -0,0 +1,25 @@
+//$Id: $
+package org.hibernate.ejb.test.emops;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Colony {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+}
Added: branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Empire.java
===================================================================
--- branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Empire.java (rev 0)
+++ branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/Empire.java 2007-01-23 19:23:13 UTC (rev 11083)
@@ -0,0 +1,39 @@
+//$Id: $
+package org.hibernate.ejb.test.emops;
+
+import java.util.HashSet;
+import java.util.Set;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.GeneratedValue;
+import javax.persistence.OneToMany;
+import javax.persistence.CascadeType;
+
+/**
+ * @author Emmanuel Bernard
+ */
+@Entity
+public class Empire {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ @OneToMany(cascade= CascadeType.ALL )
+ private Set<Colony> colonies = new HashSet<Colony>();
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Set<Colony> getColonies() {
+ return colonies;
+ }
+
+ public void setColonies(Set<Colony> colonies) {
+ this.colonies = colonies;
+ }
+}
Modified: branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/MergeTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/MergeTest.java 2007-01-23 17:12:25 UTC (rev 11082)
+++ branches/Branch_3_2/HibernateExt/ejb/src/test/org/hibernate/ejb/test/emops/MergeTest.java 2007-01-23 19:23:13 UTC (rev 11083)
@@ -140,11 +140,32 @@
em.close();
}
+ public void testMergeUnidirectionalOneToMany() throws Exception {
+ EntityManager em = factory.createEntityManager();
+ em.getTransaction().begin();
+ Empire roman = new Empire();
+ em.persist( roman );
+ em.flush();
+ em.clear();
+ roman = em.find( Empire.class, roman.getId() );
+ Colony gaule = new Colony();
+ roman.getColonies().add(gaule);
+ em.merge( roman );
+ em.flush();
+ em.clear();
+ roman = em.find(Empire.class, roman.getId() );
+ assertEquals( 1, roman.getColonies().size() );
+ em.getTransaction().rollback();
+ em.close();
+ }
+
public Class[] getAnnotatedClasses() {
return new Class[] {
Race.class,
Competitor.class,
- Competition.class
+ Competition.class,
+ Empire.class,
+ Colony.class
};
}
}
18 years, 1 month
Hibernate SVN: r11082 - in branches/Branch_3_2/HibernateExt/tools/src: test/org/hibernate/tool/hbm2x and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2007-01-23 12:12:25 -0500 (Tue, 23 Jan 2007)
New Revision: 11082
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2CfgTest.java
Log:
HBX-859 cfg.xml generation should ignore "magic" properties
Modified: branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java 2007-01-23 16:31:13 UTC (rev 11081)
+++ branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java 2007-01-23 17:12:25 UTC (rev 11082)
@@ -9,6 +9,7 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
@@ -89,13 +90,24 @@
String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME);
pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">");
+
+ Map ignoredProperties = new HashMap();
+ ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null);
+ ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" );
+ ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null );
Set set = props.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext() ) {
Map.Entry element = (Map.Entry) iterator.next();
String key = (String) element.getKey();
- if(!key.equals(Environment.SESSION_FACTORY_NAME) && key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml
+ if(ignoredProperties.containsKey( key )) {
+ Object ignoredValue = ignoredProperties.get( key );
+ if(ignoredValue == null || element.getValue().equals(ignoredValue)) {
+ continue;
+ }
+ }
+ if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml
pw.println(" <property name=\"" + key + "\">" + element.getValue() + "</property>");
}
}
Modified: branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2CfgTest.java
===================================================================
--- branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2CfgTest.java 2007-01-23 16:31:13 UTC (rev 11081)
+++ branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/Hbm2CfgTest.java 2007-01-23 17:12:25 UTC (rev 11082)
@@ -6,6 +6,8 @@
import java.io.File;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
import org.hibernate.tool.NonReflectiveTestCase;
/**
@@ -28,6 +30,32 @@
}
+ public void testMagicPropertyHandling() {
+ Configuration srcCfg = new Configuration();
+
+ srcCfg.setProperty( "hibernate.basic", "aValue" );
+ srcCfg.setProperty( Environment.SESSION_FACTORY_NAME, "shouldNotShowUp");
+ srcCfg.setProperty( Environment.HBM2DDL_AUTO, "false");
+ srcCfg.setProperty( "hibernate.temp.use_jdbc_metadata_defaults", "false");
+
+ new HibernateConfigurationExporter(srcCfg, getOutputDir()).start();
+
+ File file = new File(getOutputDir(), "hibernate.cfg.xml");
+ assertNull(findFirstString( Environment.SESSION_FACTORY_NAME, file ));
+ assertNotNull(findFirstString( "hibernate.basic\">aValue<", file ));
+ assertNull(findFirstString( Environment.HBM2DDL_AUTO, file ));
+ assertNull(findFirstString( "hibernate.temp.use_jdbc_metadata_defaults", file ));
+
+ srcCfg = new Configuration();
+
+ srcCfg.setProperty( Environment.HBM2DDL_AUTO, "validator");
+
+ new HibernateConfigurationExporter(srcCfg, getOutputDir()).start();
+
+ assertNotNull(findFirstString( Environment.HBM2DDL_AUTO, file ));
+
+ }
+
public void testFileExistence() {
assertFileAndExists(new File(getOutputDir(), "hibernate.cfg.xml") );
18 years, 1 month
Hibernate SVN: r11081 - in branches/Branch_3_2/Hibernate3: src/org/hibernate/hql/classic and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2007-01-23 11:31:13 -0500 (Tue, 23 Jan 2007)
New Revision: 11081
Added:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java
Removed:
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/cache/
Modified:
branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/Dialect.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java
branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java
branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java
Log:
HHH-1889 : LockModes + Sybase / SQL Server
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/Dialect.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/Dialect.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/Dialect.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -38,6 +38,7 @@
import org.hibernate.sql.ANSIJoinFragment;
import org.hibernate.sql.CaseFragment;
import org.hibernate.sql.JoinFragment;
+import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.type.Type;
import org.hibernate.util.ReflectHelper;
import org.hibernate.util.StringHelper;
@@ -901,7 +902,24 @@
return tableName;
}
+ /**
+ * Modifies the given SQL by applying the appropriate updates for the specified
+ * lock modes and key columns.
+ * <p/>
+ * The behavior here is that of an ANSI SQL <tt>SELECT FOR UPDATE</tt>. This
+ * method is really intended to allow dialects which do not support
+ * <tt>SELECT FOR UPDATE</tt> to achieve this in their own fashion.
+ *
+ * @param sql the SQL string to modify
+ * @param aliasedLockModes a map of lock modes indexed by aliased table names.
+ * @param keyColumnNames a map of key columns indexed by aliased table names.
+ * @return the modified SQL string.
+ */
+ public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
+ return sql + new ForUpdateFragment( this, aliasedLockModes, keyColumnNames ).toFragmentString();
+ }
+
// temporary table support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SQLServerDialect.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -86,7 +86,7 @@
}
public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan(LockMode.READ) ) {
+ if ( mode.greaterThan( LockMode.READ ) ) {
// does this need holdlock also? : return tableName + " with (updlock, rowlock, holdlock)";
return tableName + " with (updlock, rowlock)";
}
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/dialect/SybaseDialect.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -5,6 +5,8 @@
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
+import java.util.Map;
+import java.util.Iterator;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
@@ -133,7 +135,7 @@
}
public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan(LockMode.READ) ) {
+ if ( mode.greaterThan( LockMode.READ ) ) {
return tableName + " holdlock";
}
else {
@@ -141,6 +143,41 @@
}
}
+ public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
+ Iterator itr = aliasedLockModes.entrySet().iterator();
+ StringBuffer buffer = new StringBuffer( sql );
+ int correction = 0;
+ while ( itr.hasNext() ) {
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final LockMode lockMode = ( LockMode ) entry.getValue();
+ if ( lockMode.greaterThan( LockMode.READ ) ) {
+ final String alias = ( String ) entry.getKey();
+ int start = -1, end = -1;
+ if ( sql.endsWith( " " + alias ) ) {
+ start = ( sql.length() - alias.length() ) + correction;
+ end = start + alias.length();
+ }
+ else {
+ int position = sql.indexOf( " " + alias + " " );
+ if ( position <= -1 ) {
+ position = sql.indexOf( " " + alias + "," );
+ }
+ if ( position > -1 ) {
+ start = position + correction + 1;
+ end = start + alias.length();
+ }
+ }
+
+ if ( start > -1 ) {
+ final String lockHint = appendLockHint( lockMode, alias );
+ buffer.replace( start, end, lockHint );
+ correction += ( lockHint.length() - alias.length() );
+ }
+ }
+ }
+ return buffer.toString();
+ }
+
public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
return col; // sql server just returns automatically
}
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/hql/classic/QueryTranslatorImpl.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -17,12 +17,12 @@
import org.apache.commons.collections.SequencedHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.ScrollableResults;
-import org.hibernate.hql.ParameterTranslations;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.QueryParameters;
@@ -33,6 +33,7 @@
import org.hibernate.hql.FilterTranslator;
import org.hibernate.hql.HolderInstantiator;
import org.hibernate.hql.NameGenerator;
+import org.hibernate.hql.ParameterTranslations;
import org.hibernate.impl.IteratorImpl;
import org.hibernate.loader.BasicLoader;
import org.hibernate.persister.collection.CollectionPersister;
@@ -40,7 +41,6 @@
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.PropertyMapping;
import org.hibernate.persister.entity.Queryable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.QuerySelect;
import org.hibernate.transform.ResultTransformer;
@@ -56,8 +56,7 @@
* An instance of <tt>QueryTranslator</tt> translates a Hibernate
* query string to SQL.
*/
-public class QueryTranslatorImpl extends BasicLoader
- implements FilterTranslator {
+public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator {
private static final String[] NO_RETURN_ALIASES = new String[] {};
@@ -121,6 +120,13 @@
/**
* Construct a query translator
+ *
+ * @param queryIdentifier A unique identifier for the query of which this
+ * translation is part; typically this is the original, user-supplied query string.
+ * @param queryString The "preprocessed" query string; at the very least
+ * already processed by {@link org.hibernate.hql.QuerySplitter}.
+ * @param enabledFilters Any enabled filters.
+ * @param factory The session factory.
*/
public QueryTranslatorImpl(
String queryIdentifier,
@@ -134,7 +140,11 @@
}
/**
- * Construct a query translator
+ * Construct a query translator; this form used internally.
+ *
+ * @param queryString The query string to process.
+ * @param enabledFilters Any enabled filters.
+ * @param factory The session factory.
*/
public QueryTranslatorImpl(
String queryString,
@@ -144,10 +154,16 @@
}
/**
- * Compile a subquery
+ * Compile a subquery.
+ *
+ * @param superquery The containing query of the query to be compiled.
+ *
+ * @throws org.hibernate.MappingException Indicates problems resolving
+ * things referenced in the query.
+ * @throws org.hibernate.QueryException Generally some form of syntatic
+ * failure.
*/
- void compile(QueryTranslatorImpl superquery)
- throws QueryException, MappingException {
+ void compile(QueryTranslatorImpl superquery) throws QueryException, MappingException {
this.tokenReplacements = superquery.tokenReplacements;
this.superQuery = superquery;
this.shallowQuery = true;
@@ -160,8 +176,9 @@
* Compile a "normal" query. This method may be called multiple
* times. Subsequent invocations are no-ops.
*/
- public synchronized void compile(Map replacements, boolean scalar)
- throws QueryException, MappingException {
+ public synchronized void compile(
+ Map replacements,
+ boolean scalar) throws QueryException, MappingException {
if ( !compiled ) {
this.tokenReplacements = replacements;
this.shallowQuery = scalar;
@@ -173,8 +190,10 @@
* Compile a filter. This method may be called multiple
* times. Subsequent invocations are no-ops.
*/
- public synchronized void compile(String collectionRole, Map replacements, boolean scalar)
- throws QueryException, MappingException {
+ public synchronized void compile(
+ String collectionRole,
+ Map replacements,
+ boolean scalar) throws QueryException, MappingException {
if ( !isCompiled() ) {
addFromAssociation( "this", collectionRole );
@@ -184,6 +203,11 @@
/**
* Compile the query (generate the SQL).
+ *
+ * @throws org.hibernate.MappingException Indicates problems resolving
+ * things referenced in the query.
+ * @throws org.hibernate.QueryException Generally some form of syntatic
+ * failure.
*/
private void compile() throws QueryException, MappingException {
@@ -245,7 +269,7 @@
public Type[] getReturnTypes() {
return actualReturnTypes;
}
-
+
public String[] getReturnAliases() {
// return aliases not supported in classic translator!
return NO_RETURN_ALIASES;
@@ -917,11 +941,11 @@
}
catch ( SQLException sqle ) {
- throw JDBCExceptionHelper.convert(
+ throw JDBCExceptionHelper.convert(
getFactory().getSQLExceptionConverter(),
sqle,
"could not execute query using iterate",
- getSQLString()
+ getSQLString()
);
}
@@ -1031,7 +1055,7 @@
keyColumnNames.put( names[i], persisters[i].getIdentifierColumnNames() );
}
}
- result = sql + new ForUpdateFragment( dialect, aliasedLockModes, keyColumnNames ).toFragmentString();
+ result = dialect.applyLocksToSql( sql, aliasedLockModes, keyColumnNames );
}
logQuery( queryString, result );
return result;
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/AbstractEntityJoinWalker.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -20,14 +20,14 @@
/**
* Abstract walker for walkers which begin at an entity (criteria
* queries and entity loaders).
- *
+ *
* @author Gavin King
*/
public abstract class AbstractEntityJoinWalker extends JoinWalker {
private final OuterJoinLoadable persister;
private String alias;
-
+
public AbstractEntityJoinWalker(OuterJoinLoadable persister, SessionFactoryImplementor factory, Map enabledFilters) {
super( factory, enabledFilters );
this.persister = persister;
@@ -39,25 +39,25 @@
final String orderByString,
final LockMode lockMode)
throws MappingException {
-
+
walkEntityTree( persister, getAlias() );
-
+
List allAssociations = new ArrayList();
allAssociations.addAll(associations);
- allAssociations.add( new OuterJoinableAssociation(
+ allAssociations.add( new OuterJoinableAssociation(
persister.getEntityType(),
- null,
- null,
- alias,
- JoinFragment.LEFT_OUTER_JOIN,
+ null,
+ null,
+ alias,
+ JoinFragment.LEFT_OUTER_JOIN,
getFactory(),
CollectionHelper.EMPTY_MAP
) );
-
+
initPersisters(allAssociations, lockMode);
initStatementString( whereString, orderByString, lockMode);
}
-
+
protected final void initProjection(
final String projectionString,
final String whereString,
@@ -77,38 +77,37 @@
throws MappingException {
initStatementString(null, condition, orderBy, "", lockMode);
}
-
+
private void initStatementString(
final String projection,
final String condition,
final String orderBy,
final String groupBy,
- final LockMode lockMode)
- throws MappingException {
+ final LockMode lockMode) throws MappingException {
final int joins = countEntityPersisters( associations );
- suffixes = BasicLoader.generateSuffixes( joins+1 );
+ suffixes = BasicLoader.generateSuffixes( joins + 1 );
JoinFragment ojf = mergeOuterJoins( associations );
-
+
Select select = new Select( getDialect() )
- .setLockMode(lockMode)
- .setSelectClause(
- projection==null ?
- persister.selectFragment( alias, suffixes[joins] ) + selectString(associations) :
- projection
- )
- .setFromClause(
- persister.fromTableFragment(alias) +
- persister.fromJoinFragment(alias, true, true)
- )
- .setWhereClause(condition)
- .setOuterJoins(
- ojf.toFromFragmentString(),
- ojf.toWhereFragmentString() + getWhereFragment()
- )
- .setOrderByClause( orderBy( associations, orderBy ) )
- .setGroupByClause(groupBy);
+ .setLockMode( lockMode )
+ .setSelectClause(
+ projection == null ?
+ persister.selectFragment( alias, suffixes[joins] ) + selectString( associations ) :
+ projection
+ )
+ .setFromClause(
+ getDialect().appendLockHint( lockMode, persister.fromTableFragment( alias ) ) +
+ persister.fromJoinFragment( alias, true, true )
+ )
+ .setWhereClause( condition )
+ .setOuterJoins(
+ ojf.toFromFragmentString(),
+ ojf.toWhereFragmentString() + getWhereFragment()
+ )
+ .setOrderByClause( orderBy( associations, orderBy ) )
+ .setGroupByClause( groupBy );
if ( getFactory().getSettings().isCommentsEnabled() ) {
select.setComment( getComment() );
@@ -116,10 +115,8 @@
sql = select.toStatementString();
}
- /**
- * Don't bother with the discriminator, unless overridded by subclass
- */
protected String getWhereFragment() throws MappingException {
+ // here we do not bother with the discriminator.
return persister.whereJoinFragment(alias, true, true);
}
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/criteria/CriteriaLoader.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -21,7 +21,6 @@
import org.hibernate.loader.OuterJoinLoader;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.OuterJoinLoadable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.Type;
@@ -33,8 +32,8 @@
*/
public class CriteriaLoader extends OuterJoinLoader {
- //TODO: this class depends directly upon CriteriaImpl,
- // in the impl package ... add a CriteriaImplementor
+ //TODO: this class depends directly upon CriteriaImpl,
+ // in the impl package ... add a CriteriaImplementor
// interface
//NOTE: unlike all other Loaders, this one is NOT
@@ -48,49 +47,49 @@
private final String[] userAliases;
public CriteriaLoader(
- final OuterJoinLoadable persister,
- final SessionFactoryImplementor factory,
- final CriteriaImpl criteria,
+ final OuterJoinLoadable persister,
+ final SessionFactoryImplementor factory,
+ final CriteriaImpl criteria,
final String rootEntityName,
final Map enabledFilters)
throws HibernateException {
super(factory, enabledFilters);
translator = new CriteriaQueryTranslator(
- factory,
- criteria,
- rootEntityName,
+ factory,
+ criteria,
+ rootEntityName,
CriteriaQueryTranslator.ROOT_SQL_ALIAS
);
querySpaces = translator.getQuerySpaces();
-
+
CriteriaJoinWalker walker = new CriteriaJoinWalker(
- persister,
+ persister,
translator,
- factory,
- criteria,
- rootEntityName,
+ factory,
+ criteria,
+ rootEntityName,
enabledFilters
);
initFromWalker(walker);
-
+
userAliases = walker.getUserAliases();
resultTypes = walker.getResultTypes();
postInstantiate();
}
-
- public ScrollableResults scroll(SessionImplementor session, ScrollMode scrollMode)
+
+ public ScrollableResults scroll(SessionImplementor session, ScrollMode scrollMode)
throws HibernateException {
QueryParameters qp = translator.getQueryParameters();
qp.setScrollMode(scrollMode);
return scroll(qp, resultTypes, null, session);
}
- public List list(SessionImplementor session)
+ public List list(SessionImplementor session)
throws HibernateException {
return list( session, translator.getQueryParameters(), querySpaces, resultTypes );
@@ -121,33 +120,28 @@
return querySpaces;
}
- protected String applyLocks(String sqlSelectString, Map lockModes, Dialect dialect)
- throws QueryException {
-
- if ( lockModes==null || lockModes.size()==0 ) {
+ protected String applyLocks(String sqlSelectString, Map lockModes, Dialect dialect) throws QueryException {
+ if ( lockModes == null || lockModes.isEmpty() ) {
return sqlSelectString;
}
- else {
- Map keyColumnNames = null;
- Loadable[] persisters = getEntityPersisters();
- String[] entityAliases = getAliases();
- if ( dialect.forUpdateOfColumns() ) {
- keyColumnNames = new HashMap();
- for ( int i=0; i<entityAliases.length; i++ ) {
- keyColumnNames.put(
- entityAliases[i],
- persisters[i].getIdentifierColumnNames()
- );
- }
+
+ Map keyColumnNames = null;
+ Loadable[] persisters = getEntityPersisters();
+ String[] entityAliases = getAliases();
+ if ( dialect.forUpdateOfColumns() ) {
+ keyColumnNames = new HashMap();
+ for ( int i=0; i<entityAliases.length; i++ ) {
+ keyColumnNames.put( entityAliases[i], persisters[i].getIdentifierColumnNames() );
}
- return sqlSelectString +
- new ForUpdateFragment(dialect, lockModes, keyColumnNames).toFragmentString();
}
+ return dialect.applyLocksToSql( sqlSelectString, lockModes, keyColumnNames );
}
protected LockMode[] getLockModes(Map lockModes) {
final String[] entityAliases = getAliases();
- if (entityAliases==null) return null;
+ if ( entityAliases == null ) {
+ return null;
+ }
final int size = entityAliases.length;
LockMode[] lockModesArray = new LockMode[size];
for ( int i=0; i<size; i++ ) {
@@ -160,10 +154,9 @@
protected boolean isSubselectLoadingEnabled() {
return hasSubselectLoadableCollections();
}
-
+
protected List getResultList(List results, ResultTransformer resultTransformer) {
- return translator.getRootCriteria().getResultTransformer()
- .transformList(results);
+ return translator.getRootCriteria().getResultTransformer().transformList( results );
}
}
Modified: branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java
===================================================================
--- branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/src/org/hibernate/loader/hql/QueryLoader.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -9,9 +9,6 @@
import java.util.List;
import java.util.Map;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.QueryException;
@@ -33,7 +30,6 @@
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.entity.Queryable;
-import org.hibernate.sql.ForUpdateFragment;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
@@ -46,11 +42,11 @@
*/
public class QueryLoader extends BasicLoader {
- private static final Log log = LogFactory.getLog( QueryLoader.class );
+ /**
+ * The query translator that is delegating to this object.
+ */
+ private QueryTranslatorImpl queryTranslator;
- private final QueryTranslatorImpl queryTranslator;
- private final boolean isCollectionFilter;
-
private Queryable[] entityPersisters;
private String[] entityAliases;
private String[] sqlAliases;
@@ -61,6 +57,7 @@
private boolean hasScalars;
private String[][] scalarColumnNames;
+ //private Type[] sqlResultTypes;
private Type[] queryReturnTypes;
private final Map sqlAliasByEntityAlias = new HashMap(8);
@@ -93,13 +90,14 @@
final SelectClause selectClause) {
super( factory );
this.queryTranslator = queryTranslator;
- this.isCollectionFilter = selectClause.getWalker().isFilter();
initialize( selectClause );
postInstantiate();
}
private void initialize(SelectClause selectClause) {
+
List fromElementList = selectClause.getFromElementsForLoad();
+
hasScalars = selectClause.isScalarSelect();
scalarColumnNames = selectClause.getColumnNames();
//sqlResultTypes = selectClause.getSqlResultTypes();
@@ -172,7 +170,7 @@
}
}
- //NONE, because its the requested lock mode, not the actual!
+ //NONE, because its the requested lock mode, not the actual!
defaultLockModes = ArrayHelper.fillArray(LockMode.NONE, size);
}
@@ -269,7 +267,7 @@
for ( int i = 0; i < entityAliases.length; i++ ) {
LockMode lockMode = (LockMode) lockModes.get( entityAliases[i] );
if ( lockMode == null ) {
- //NONE, because its the requested lock mode, not the actual!
+ //NONE, because its the requested lock mode, not the actual!
lockMode = LockMode.NONE;
}
lockModeArray[i] = lockMode;
@@ -278,15 +276,12 @@
}
}
- protected String applyLocks(String sql, Map lockModes, Dialect dialect)
- throws QueryException {
-
+ protected String applyLocks(String sql, Map lockModes, Dialect dialect) throws QueryException {
if ( lockModes == null || lockModes.size() == 0 ) {
return sql;
}
else {
// can't cache this stuff either (per-invocation)
-
//we are given a map of user alias -> lock mode
//create a new map of sql alias -> lock mode
final Map aliasedLockModes = new HashMap();
@@ -311,8 +306,7 @@
}
}
- return sql + new ForUpdateFragment( dialect, aliasedLockModes, keyColumnNames ).toFragmentString();
-
+ return dialect.applyLocksToSql( sql, aliasedLockModes, keyColumnNames );
}
}
@@ -374,31 +368,22 @@
// --- Query translator methods ---
- /**
- * Delegats
- *
- * @param session
- * @param queryParameters
- * @return
- * @throws HibernateException
- */
- public List list(SessionImplementor session, QueryParameters queryParameters)
- throws HibernateException {
+ public List list(
+ SessionImplementor session,
+ QueryParameters queryParameters) throws HibernateException {
checkQuery( queryParameters );
return list( session, queryParameters, queryTranslator.getQuerySpaces(), queryReturnTypes );
}
private void checkQuery(QueryParameters queryParameters) {
- if(hasSelectNew() && queryParameters.getResultTransformer()!=null) {
- throw new QueryException("ResultTransformer is not allowed for 'select new' queries.");
+ if ( hasSelectNew() && queryParameters.getResultTransformer() != null ) {
+ throw new QueryException( "ResultTransformer is not allowed for 'select new' queries." );
}
}
- /**
- * Return the query results as an iterator
- */
- public Iterator iterate(QueryParameters queryParameters, EventSource session)
- throws HibernateException {
+ public Iterator iterate(
+ QueryParameters queryParameters,
+ EventSource session) throws HibernateException {
checkQuery( queryParameters );
final boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0;
Modified: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 16:29:18 UTC (rev 11080)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/AllTests.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -30,7 +30,8 @@
import org.hibernate.test.cuk.CompositePropertyRefTest;
import org.hibernate.test.cut.CompositeUserTypeTest;
import org.hibernate.test.deletetransient.DeleteTransientEntityTest;
-import org.hibernate.test.dialect.cache.SQLFunctionsInterSystemsTest;
+import org.hibernate.test.dialect.functional.DialectFunctionalTestsSuite;
+import org.hibernate.test.dialect.unit.DialectUnitTestsSuite;
import org.hibernate.test.discriminator.DiscriminatorTest;
import org.hibernate.test.dynamicentity.interceptor.InterceptorDynamicEntityTest;
import org.hibernate.test.dynamicentity.tuplizer.TuplizerDynamicEntityTest;
@@ -271,12 +272,13 @@
suite.addTest( AbstractCompositeIdTest.suite() );
suite.addTest( UtilSuite.suite() );
suite.addTest( AnyTypeTest.suite() );
- suite.addTest( SQLFunctionsInterSystemsTest.suite() );
suite.addTest( LobSuite.suite() );
suite.addTest( IdentifierPropertyReferencesTest.suite() );
suite.addTest( DeleteTransientEntityTest.suite() );
suite.addTest( UserCollectionTypeTest.suite() );
suite.addTest( KeyManyToOneSuite.suite() );
+ suite.addTest( DialectFunctionalTestsSuite.suite() );
+ suite.addTest( DialectUnitTestsSuite.suite() );
return filter( suite );
}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/DialectFunctionalTestsSuite.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,18 @@
+package org.hibernate.test.dialect.functional;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.test.dialect.functional.cache.SQLFunctionsInterSystemsTest;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class DialectFunctionalTestsSuite {
+ public static TestSuite suite() {
+ TestSuite suite = new TestSuite( "Dialect tests" );
+ suite.addTest( SQLFunctionsInterSystemsTest.suite() );
+ return suite;
+ }
+}
Copied: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java (from rev 10976, branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/cache/SQLFunctionsInterSystemsTest.java)
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/SQLFunctionsInterSystemsTest.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,740 @@
+package org.hibernate.test.dialect.functional.cache;
+
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.Test;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.hibernate.Hibernate;
+import org.hibernate.LockMode;
+import org.hibernate.Query;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.dialect.Cache71Dialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.InterbaseDialect;
+import org.hibernate.dialect.MckoiDialect;
+import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.dialect.Oracle9Dialect;
+import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.TimesTenDialect;
+import org.hibernate.dialect.function.SQLFunction;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.legacy.Blobber;
+import org.hibernate.test.legacy.Broken;
+import org.hibernate.test.legacy.Fixed;
+import org.hibernate.test.legacy.Simple;
+import org.hibernate.test.legacy.Single;
+
+/**
+ * Tests for function support on CacheSQL...
+ *
+ * @author Jonathan Levinson
+ */
+public class SQLFunctionsInterSystemsTest extends DatabaseSpecificFunctionalTestCase {
+
+ private static final Log log = LogFactory.getLog(SQLFunctionsInterSystemsTest.class);
+
+ public SQLFunctionsInterSystemsTest(String name) {
+ super(name);
+ }
+
+ public String[] getMappings() {
+ return new String[] {
+ "legacy/AltSimple.hbm.xml",
+ "legacy/Broken.hbm.xml",
+ "legacy/Blobber.hbm.xml",
+ "dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml"
+ };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SQLFunctionsInterSystemsTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ // all these test case apply only to testing InterSystems' CacheSQL dialect
+ return dialect instanceof Cache71Dialect;
+ }
+
+ public void testDialectSQLFunctions() throws Exception {
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Iterator iter = s.iterate("select max(s.count) from Simple s");
+
+ if ( getDialect() instanceof MySQLDialect ) assertTrue( iter.hasNext() && iter.next()==null );
+
+ Simple simple = new Simple();
+ simple.setName("Simple Dialect Function Test");
+ simple.setAddress("Simple Address");
+ simple.setPay(new Float(45.8));
+ simple.setCount(2);
+ s.save(simple, new Long(10) );
+
+ // Test to make sure allocating an specified object operates correctly.
+ assertTrue(
+ s.find("select new org.hibernate.test.legacy.S(s.count, s.address) from Simple s").size() == 1
+ );
+
+ // Quick check the base dialect functions operate correctly
+ assertTrue(
+ s.find("select max(s.count) from Simple s").size() == 1
+ );
+ assertTrue(
+ s.find("select count(*) from Simple s").size() == 1
+ );
+
+ if ( getDialect() instanceof Cache71Dialect) {
+ // Check Oracle Dialect mix of dialect functions - no args (no parenthesis and single arg functions
+ java.util.List rset = s.find("select s.name, sysdate, floor(s.pay), round(s.pay,0) from Simple s");
+ assertNotNull("Name string should have been returned",(((Object[])rset.get(0))[0]));
+ assertNotNull("Todays Date should have been returned",(((Object[])rset.get(0))[1]));
+ assertEquals("floor(45.8) result was incorrect ", new Integer(45), ( (Object[]) rset.get(0) )[2] );
+ assertEquals("round(45.8) result was incorrect ", new Float(46), ( (Object[]) rset.get(0) )[3] );
+
+ simple.setPay(new Float(-45.8));
+ s.update(simple);
+
+ // Test type conversions while using nested functions (Float to Int).
+ rset = s.find("select abs(round(s.pay,0)) from Simple s");
+ assertEquals("abs(round(-45.8)) result was incorrect ", new Float(46), rset.get(0));
+
+ // Test a larger depth 3 function example - Not a useful combo other than for testing
+ assertTrue(
+ s.find("select floor(round(sysdate,1)) from Simple s").size() == 1
+ );
+
+ // Test the oracle standard NVL funtion as a test of multi-param functions...
+ simple.setPay(null);
+ s.update(simple);
+ Double value = (Double) s.createQuery("select mod( nvl(s.pay, 5000), 2 ) from Simple as s where s.id = 10").list().get(0);
+ assertTrue( 0 == value.intValue() );
+ }
+
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ // Test the hsql standard MOD funtion as a test of multi-param functions...
+ Double value = (Double) s.find("select MOD(s.count, 2) from Simple as s where s.id = 10" ).get(0);
+ assertTrue( 0 == value.intValue() );
+ }
+
+ /*
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ // Test the hsql standard MOD funtion as a test of multi-param functions...
+ Date value = (Date) s.find("select sysdate from Simple as s where nvl(cast(null as date), sysdate)=sysdate" ).get(0);
+ assertTrue( value.equals(new java.sql.Date(System.currentTimeMillis())));
+ }
+ */
+
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testSetProperties() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save(simple, new Long(10) );
+ Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count");
+ q.setProperties(simple);
+ assertTrue( q.list().get(0)==simple );
+ //misuse of "Single" as a propertyobject, but it was the first testclass i found with a collection ;)
+ Single single = new Single() { // trivial hack to test properties with arrays.
+ String[] getStuff() { return (String[]) getSeveral().toArray(new String[getSeveral().size()]); }
+ };
+
+ List l = new ArrayList();
+ l.add("Simple 1");
+ l.add("Slimeball");
+ single.setSeveral(l);
+ q = s.createQuery("from Simple s where s.name in (:several)");
+ q.setProperties(single);
+ assertTrue( q.list().get(0)==simple );
+
+
+ q = s.createQuery("from Simple s where s.name in (:stuff)");
+ q.setProperties(single);
+ assertTrue( q.list().get(0)==simple );
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testBroken() throws Exception {
+ if (getDialect() instanceof Oracle9Dialect) return;
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Broken b = new Fixed();
+ b.setId( new Long(123));
+ b.setOtherId("foobar");
+ s.save(b);
+ s.flush();
+ b.setTimestamp( new Date() );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update(b);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ b = (Broken) s.load( Broken.class, b );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(b);
+ t.commit();
+ s.close();
+ }
+
+ public void testNothinToUpdate() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+ }
+
+ public void testCachedQuery() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setCacheable(true);
+ q.setString("name", "Simple 1");
+ assertTrue( q.list().size()==1 );
+ simple = (Simple) q.list().get(0);
+
+ q.setString("name", "Simple 2");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ simple.setName("Simple 2");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setString("name", "Simple 2");
+ q.setCacheable(true);
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ t.commit();
+ s.close();
+ }
+
+ public void testCachedQueryRegion() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name=:name");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString("name", "Simple 1");
+ assertTrue( q.list().size()==1 );
+ simple = (Simple) q.list().get(0);
+
+ q.setString("name", "Simple 2");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ simple.setName("Simple 2");
+ assertTrue( q.list().size()==1 );
+ assertTrue( q.list().size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.update( simple, new Long(10) );
+ s.delete(simple);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s where s.name=?");
+ q.setCacheRegion("foo");
+ q.setCacheable(true);
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==0 );
+ assertTrue( q.list().size()==0 );
+ t.commit();
+ s.close();
+ }
+
+ public void testSQLFunctions() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save(simple, new Long(10) );
+
+ if ( getDialect() instanceof Cache71Dialect) {
+ s.find("from Simple s where repeat('foo', 3) = 'foofoofoo'");
+ s.find("from Simple s where repeat(s.name, 3) = 'foofoofoo'");
+ s.find("from Simple s where repeat( lower(s.name), (3 + (1-1)) / 2) = 'foofoofoo'");
+ }
+
+ assertTrue(
+ s.find("from Simple s where upper( s.name ) ='SIMPLE 1'").size()==1
+ );
+ if ( !(getDialect() instanceof HSQLDialect) ) {
+ assertTrue(
+ s.find("from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )").size()==1
+ );
+ }
+ if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SybaseDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof InterbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { //My SQL has a funny concatenation operator
+ assertTrue(
+ s.find("from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'").size()==1
+ );
+ }
+ /* + is not concat in Cache
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ assertTrue(
+ s.find("from Simple s where lower( cons.name ' foo' ) ='simple 1 foo'").size()==1
+ );
+ }
+ */
+ if ( (getDialect() instanceof Cache71Dialect) ) {
+ assertTrue(
+ s.find("from Simple s where lower( concat(s.name, ' foo') ) ='simple 1 foo'").size()==1
+ );
+ }
+
+ Simple other = new Simple();
+ other.setName("Simple 2");
+ other.setCount(12);
+ simple.setOther(other);
+ s.save( other, new Long(20) );
+ //s.find("from Simple s where s.name ## 'cat|rat|bag'");
+ assertTrue(
+ s.find("from Simple s where upper( s.other.name ) ='SIMPLE 2'").size()==1
+ );
+ assertTrue(
+ s.find("from Simple s where not ( upper( s.other.name ) ='SIMPLE 2' )").size()==0
+ );
+ assertTrue(
+ s.find("select distinct s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2").size()==1
+ );
+ assertTrue(
+ s.find("select s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2 order by s.other.count").size()==1
+ );
+ Simple min = new Simple();
+ min.setCount(-1);
+ s.save(min, new Long(30) );
+ if ( ! (getDialect() instanceof MySQLDialect) && ! (getDialect() instanceof HSQLDialect) ) { //My SQL has no subqueries
+ assertTrue(
+ s.find("from Simple s where s.count > ( select min(sim.count) from Simple sim )").size()==2
+ );
+ t.commit();
+ t = s.beginTransaction();
+ assertTrue(
+ s.find("from Simple s where s = some( select sim from Simple sim where sim.count>=0 ) and s.count >= 0").size()==2
+ );
+ assertTrue(
+ s.find("from Simple s where s = some( select sim from Simple sim where sim.other.count=s.other.count ) and s.other.count > 0").size()==1
+ );
+ }
+
+ Iterator iter = s.iterate("select sum(s.count) from Simple s group by s.count having sum(s.count) > 10");
+ assertTrue( iter.hasNext() );
+ assertEquals( new Long(12), iter.next() );
+ assertTrue( !iter.hasNext() );
+ if ( ! (getDialect() instanceof MySQLDialect) ) {
+ iter = s.iterate("select s.count from Simple s group by s.count having s.count = 12");
+ assertTrue( iter.hasNext() );
+ }
+
+ s.iterate("select s.id, s.count, count(t), max(t.date) from Simple s, Simple t where s.count = t.count group by s.id, s.count order by s.count");
+
+ Query q = s.createQuery("from Simple s");
+ q.setMaxResults(10);
+ assertTrue( q.list().size()==3 );
+ q = s.createQuery("from Simple s");
+ q.setMaxResults(1);
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s");
+ assertTrue( q.list().size()==3 );
+ q = s.createQuery("from Simple s where s.name = ?");
+ q.setString(0, "Simple 1");
+ assertTrue( q.list().size()==1 );
+ q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?");
+ q.setString(1, "SIMPLE 1");
+ q.setString(0, "Simple 1");
+ q.setFirstResult(0);
+ assertTrue( q.iterate().hasNext() );
+ q = s.createQuery("from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1");
+ q.setParameter("bar", "SIMPLE 1");
+ q.setString("foo", "Simple 1");
+ q.setInteger("count", 69);
+ q.setFirstResult(0);
+ assertTrue( q.iterate().hasNext() );
+ q = s.createQuery("select s.id from Simple s");
+ q.setFirstResult(1);
+ q.setMaxResults(2);
+ iter = q.iterate();
+ int i=0;
+ while ( iter.hasNext() ) {
+ assertTrue( iter.next() instanceof Long );
+ i++;
+ }
+ assertTrue(i==2);
+ q = s.createQuery("select all s, s.other from Simple s where s = :s");
+ q.setParameter("s", simple);
+ assertTrue( q.list().size()==1 );
+
+
+ q = s.createQuery("from Simple s where s.name in (:name_list) and s.count > :count");
+ HashSet set = new HashSet();
+ set.add("Simple 1"); set.add("foo");
+ q.setParameterList( "name_list", set );
+ q.setParameter("count", new Integer(-1) );
+ assertTrue( q.list().size()==1 );
+
+ ScrollableResults sr = s.createQuery("from Simple s").scroll();
+ sr.next();
+ sr.get(0);
+ sr.close();
+
+ s.delete(other);
+ s.delete(simple);
+ s.delete(min);
+ t.commit();
+ s.close();
+
+ }
+
+ public void testBlobClob() throws Exception {
+
+ Session s = openSession();
+ Blobber b = new Blobber();
+ b.setBlob( Hibernate.createBlob( "foo/bar/baz".getBytes() ) );
+ b.setClob( Hibernate.createClob("foo/bar/baz") );
+ s.save(b);
+ //s.refresh(b);
+ //assertTrue( b.getClob() instanceof ClobImpl );
+ s.flush();
+ s.refresh(b);
+ //b.getBlob().setBytes( 2, "abc".getBytes() );
+ log.debug("levinson: just bfore b.getClob()");
+ b.getClob().getSubString(2, 3);
+ //b.getClob().setString(2, "abc");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ Blobber b2 = new Blobber();
+ s.save(b2);
+ b2.setBlob( b.getBlob() );
+ b.setBlob(null);
+ //assertTrue( b.getClob().getSubString(1, 3).equals("fab") );
+ b.getClob().getSubString(1, 6);
+ //b.getClob().setString(1, "qwerty");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ b.setClob( Hibernate.createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb") );
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+ s = openSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ assertTrue( b.getClob().getSubString(1, 7).equals("xcvfxvc") );
+ //b.getClob().setString(5, "1234567890");
+ s.flush();
+ s.connection().commit();
+ s.close();
+
+
+ /*InputStream is = getClass().getClassLoader().getResourceAsStream("jdbc20.pdf");
+ s = sessionsopenSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ System.out.println( is.available() );
+ int size = is.available();
+ b.setBlob( Hibernate.createBlob( is, is.available() ) );
+ s.flush();
+ s.connection().commit();
+ ResultSet rs = s.connection().createStatement().executeQuery("select datalength(blob_) from blobber where id=" + b.getId() );
+ rs.next();
+ assertTrue( size==rs.getInt(1) );
+ rs.close();
+ s.close();
+
+ s = sessionsopenSession();
+ b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
+ File f = new File("C:/foo.pdf");
+ f.createNewFile();
+ FileOutputStream fos = new FileOutputStream(f);
+ Blob blob = b.getBlob();
+ byte[] bytes = blob.getBytes( 1, (int) blob.length() );
+ System.out.println( bytes.length );
+ fos.write(bytes);
+ fos.flush();
+ fos.close();
+ s.close();*/
+
+ }
+
+ public void testSqlFunctionAsAlias() throws Exception {
+ String functionName = locateAppropriateDialectFunctionNameForAliasTest();
+ if (functionName == null) {
+ log.info("Dialect does not list any no-arg functions");
+ return;
+ }
+
+ log.info("Using function named [" + functionName + "] for 'function as alias' test");
+ String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10";
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List result = s.find(query);
+ assertTrue( result.size() == 1 );
+ assertTrue(result.get(0) instanceof Simple);
+ s.delete( result.get(0) );
+ t.commit();
+ s.close();
+ }
+
+ private String locateAppropriateDialectFunctionNameForAliasTest() {
+ for (Iterator itr = getDialect().getFunctions().entrySet().iterator(); itr.hasNext(); ) {
+ final Map.Entry entry = (Map.Entry) itr.next();
+ final SQLFunction function = (SQLFunction) entry.getValue();
+ if ( !function.hasArguments() && !function.hasParenthesesIfNoArguments() ) {
+ return (String) entry.getKey();
+ }
+ }
+ return null;
+ }
+
+ public void testCachedQueryOnInsert() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Simple simple = new Simple();
+ simple.setName("Simple 1");
+ s.save( simple, new Long(10) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query q = s.createQuery("from Simple s");
+ List list = q.setCacheable(true).list();
+ assertTrue( list.size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==1 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Simple simple2 = new Simple();
+ simple2.setCount(133);
+ s.save( simple2, new Long(12) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==2 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ q = s.createQuery("from Simple s");
+ list = q.setCacheable(true).list();
+ assertTrue( list.size()==2 );
+ Iterator i = list.iterator();
+ while ( i.hasNext() ) s.delete( i.next() );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testInterSystemsFunctions() throws Exception {
+ Calendar cal = new GregorianCalendar();
+ cal.set(1977,6,3,0,0,0);
+ java.sql.Timestamp testvalue = new java.sql.Timestamp(cal.getTimeInMillis());
+ testvalue.setNanos(0);
+ Calendar cal3 = new GregorianCalendar();
+ cal3.set(1976,2,3,0,0,0);
+ java.sql.Timestamp testvalue3 = new java.sql.Timestamp(cal3.getTimeInMillis());
+ testvalue3.setNanos(0);
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ try {
+ Statement stmt = s.connection().createStatement();
+ stmt.executeUpdate("DROP FUNCTION spLock FROM TestInterSystemsFunctionsClass");
+ t.commit();
+ }
+ catch (Exception ex) {
+ System.out.println("as we expected stored procedure sp does not exist when we drop it");
+
+ }
+ t = s.beginTransaction();
+ Statement stmt = s.connection().createStatement();
+ String create_function = "CREATE FUNCTION SQLUser.TestInterSystemsFunctionsClass_spLock\n" +
+ " ( INOUT pHandle %SQLProcContext, \n" +
+ " ROWID INTEGER \n" +
+ " )\n" +
+ " FOR User.TestInterSystemsFunctionsClass " +
+ " PROCEDURE\n" +
+ " RETURNS INTEGER\n" +
+ " LANGUAGE OBJECTSCRIPT\n" +
+ " {\n" +
+ " q 0\n" +
+ " }";
+ stmt.executeUpdate(create_function);
+ t.commit();
+ t = s.beginTransaction();
+
+ TestInterSystemsFunctionsClass object = new TestInterSystemsFunctionsClass();
+ object.setDateText("1977-07-03");
+ object.setDate1(testvalue);
+ object.setDate3(testvalue3);
+ s.save( object, new Long(10));
+ t.commit();
+ s.close();
+ s = openSession();
+ s.clear();
+ t = s.beginTransaction();
+ TestInterSystemsFunctionsClass test = (TestInterSystemsFunctionsClass) s.get(TestInterSystemsFunctionsClass.class, new Long(10));
+ assertTrue( test.getDate1().equals(testvalue));
+ test = (TestInterSystemsFunctionsClass) s.get(TestInterSystemsFunctionsClass.class, new Long(10), LockMode.UPGRADE);
+ assertTrue( test.getDate1().equals(testvalue));
+ Date value = (Date) s.find("select nvl(o.date,o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ Object nv = s.find("select nullif(o.dateText,o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( nv == null);
+ String dateText = (String) s.find("select nvl(o.dateText,o.date) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( dateText.equals("1977-07-03"));
+ value = (Date) s.find("select ifnull(o.date,o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ value = (Date) s.find("select ifnull(o.date3,o.date,o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( value.equals(testvalue));
+ Integer pos = (Integer) s.find("select position('07', o.dateText) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(pos.intValue() == 6);
+ String st = (String) s.find("select convert(o.date1, SQL_TIME) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( st.equals("00:00:00"));
+ java.sql.Time tm = (java.sql.Time) s.find("select cast(o.date1, time) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue( tm.toString().equals("00:00:00"));
+ Double diff = (Double)s.find("select timestampdiff(SQL_TSI_FRAC_SECOND, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() != 0.0);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_MONTH, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() == 16.0);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_WEEK, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() >= 16*4);
+ diff = (Double)s.find("select timestampdiff(SQL_TSI_YEAR, o.date3, o.date1) from TestInterSystemsFunctionsClass as o" ).get(0);
+ assertTrue(diff.doubleValue() == 1.0);
+
+ t.commit();
+ s.close();
+
+
+ }
+
+}
Copied: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml (from rev 10964, branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/cache/TestInterSystemsFunctionsClass.hbm.xml)
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.hbm.xml 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.hibernate.test.dialect.functional.cache" >
+
+ <class name="TestInterSystemsFunctionsClass" table="SQLUser.TestInterSystemsFunctionsClass">
+ <id type="long" column="id_">
+ <generator class="assigned"/>
+ </id>
+ <property name="date" column="date_"/>
+ <property name="date1" column="date1_"/>
+ <property name="date3" column="date3_"/>
+ <property name="dateText" column="dateText_"/>
+ </class>
+
+</hibernate-mapping>
Copied: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java (from rev 10964, branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/cache/TestInterSystemsFunctionsClass.java)
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/functional/cache/TestInterSystemsFunctionsClass.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,51 @@
+package org.hibernate.test.dialect.functional.cache;
+
+import java.util.Date;
+
+/**
+ * Entity for testing function support of InterSystems' CacheSQL...
+ *
+ * @author Jonathan Levinson
+ */
+public class TestInterSystemsFunctionsClass {
+ private java.util.Date date3;
+ private java.util.Date date1;
+ private java.util.Date date;
+ private String dateText;
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+
+ public String getDateText() {
+ return dateText;
+ }
+
+ public void setDateText(String dateText) {
+ this.dateText = dateText;
+ }
+
+
+ public Date getDate1() {
+ return date1;
+ }
+
+ public void setDate1(Date date1) {
+ this.date1 = date1;
+ }
+
+
+ public Date getDate3() {
+ return date3;
+ }
+
+ public void setDate3(Date date3) {
+ this.date3 = date3;
+ }
+
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/DialectUnitTestsSuite.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,20 @@
+package org.hibernate.test.dialect.unit;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.test.dialect.unit.lockhint.SybaseLockHintsTest;
+import org.hibernate.test.dialect.unit.lockhint.SQLServerLockHintsTest;
+
+/**
+ * Suite of all unit tests of the Dialect(s).
+ *
+ * @author Steve Ebersole
+ */
+public class DialectUnitTestsSuite {
+ public static TestSuite suite() {
+ TestSuite suite = new TestSuite( "Dialect unit-tests" );
+ suite.addTest( SybaseLockHintsTest.suite() );
+ suite.addTest( SQLServerLockHintsTest.suite() );
+ return suite;
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/AbstractLockHintTest.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,64 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import java.util.HashMap;
+import java.util.Collections;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.util.StringHelper;
+import org.hibernate.LockMode;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractLockHintTest extends UnitTestCase {
+ public AbstractLockHintTest(String string) {
+ super( string );
+ }
+
+ private Dialect dialect;
+
+ protected abstract String getLockHintUsed();
+ protected abstract Dialect getDialectUnderTest();
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ this.dialect = getDialectUnderTest();
+ }
+
+ protected void tearDown() throws Exception {
+ this.dialect = null;
+ super.tearDown();
+ }
+
+ public void testBasicLocking() {
+ new SyntaxChecker( "select xyz from ABC $HOLDER$", "a" ).verify();
+ new SyntaxChecker( "select xyz from ABC $HOLDER$ join DEF d", "a" ).verify();
+ new SyntaxChecker( "select xyz from ABC $HOLDER$, DEF d", "a" ).verify();
+ }
+
+ protected class SyntaxChecker {
+ private final String aliasToLock;
+ private final String rawSql;
+ private final String expectedProcessedSql;
+
+ public SyntaxChecker(String template) {
+ this( template, "" );
+ }
+
+ public SyntaxChecker(String template, String aliasToLock) {
+ this.aliasToLock = aliasToLock;
+ rawSql = StringHelper.replace( template, "$HOLDER$", aliasToLock );
+ expectedProcessedSql = StringHelper.replace( template, "$HOLDER$", aliasToLock + " " + getLockHintUsed() );
+ }
+
+ public void verify() {
+ HashMap lockModes = new HashMap();
+ lockModes.put( aliasToLock, LockMode.UPGRADE );
+ String actualProcessedSql = dialect.applyLocksToSql( rawSql, lockModes, Collections.EMPTY_MAP );
+ assertEquals( expectedProcessedSql, actualProcessedSql );
+ }
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SQLServerLockHintsTest.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,31 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SQLServerDialect;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class SQLServerLockHintsTest extends AbstractLockHintTest {
+ public static final Dialect DIALECT = new SQLServerDialect();
+
+ public SQLServerLockHintsTest(String string) {
+ super( string );
+ }
+
+ protected String getLockHintUsed() {
+ return "with (updlock, rowlock)";
+ }
+
+ protected Dialect getDialectUnderTest() {
+ return DIALECT;
+ }
+
+ public static TestSuite suite() {
+ return new TestSuite( SQLServerLockHintsTest.class );
+ }
+}
Added: branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java
===================================================================
--- branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java (rev 0)
+++ branches/Branch_3_2/Hibernate3/test/org/hibernate/test/dialect/unit/lockhint/SybaseLockHintsTest.java 2007-01-23 16:31:13 UTC (rev 11081)
@@ -0,0 +1,31 @@
+package org.hibernate.test.dialect.unit.lockhint;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SybaseDialect;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class SybaseLockHintsTest extends AbstractLockHintTest {
+ public static final Dialect DIALECT = new SybaseDialect();
+
+ public SybaseLockHintsTest(String string) {
+ super( string );
+ }
+
+ protected String getLockHintUsed() {
+ return "holdlock";
+ }
+
+ protected Dialect getDialectUnderTest() {
+ return DIALECT;
+ }
+
+ public static TestSuite suite() {
+ return new TestSuite( SybaseLockHintsTest.class );
+ }
+}
18 years, 1 month