Author: tfischer
Date: Mon Apr 10 13:59:16 2006
New Revision: 393063
URL: http://svn.apache.org/viewcvs?rev=393063&view=rev
Log:
- centralized the information about the database kept in the Torque runtime in
a central place, the Database class.
- deprecated the non-centralized methods to acces the database information
- modified the initialisation procedure to use the new database information
structure.
- added a new convenience method, Transaction.begin(), which is the same as
Transaction.begin(Torque.getDefaultDb())
- idBroker is only started if the IdBroker is used in the database.
Added:
db/torque/runtime/trunk/src/java/org/apache/torque/Database.java
Modified:
db/torque/runtime/trunk/src/java/org/apache/torque/Torque.java
db/torque/runtime/trunk/src/java/org/apache/torque/TorqueInstance.java
db/torque/runtime/trunk/src/java/org/apache/torque/adapter/DB.java
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/AbstractDataSourceFactory.java
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/DataSourceFactory.java
db/torque/runtime/trunk/src/java/org/apache/torque/map/ColumnMap.java
db/torque/runtime/trunk/src/java/org/apache/torque/map/DatabaseMap.java
db/torque/runtime/trunk/src/java/org/apache/torque/map/TableMap.java
db/torque/runtime/trunk/src/java/org/apache/torque/oid/IDBroker.java
db/torque/runtime/trunk/src/java/org/apache/torque/util/BasePeer.java
db/torque/runtime/trunk/src/java/org/apache/torque/util/Transaction.java
Added: db/torque/runtime/trunk/src/java/org/apache/torque/Database.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/Database.java?rev=393063&view=auto
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/Database.java (added)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/Database.java Mon Apr 10
13:59:16 2006
@@ -0,0 +1,220 @@
+package org.apache.torque;
+
+/*
+ * Copyright 2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import org.apache.torque.adapter.DB;
+import org.apache.torque.dsfactory.DataSourceFactory;
+import org.apache.torque.map.DatabaseMap;
+import org.apache.torque.oid.IDBroker;
+import org.apache.torque.oid.IdGenerator;
+
+/**
+ * Bundles all information about a database. This includes the database
adapter,
+ * the database Map and the Data Source Factory.
+ */
+public class Database
+{
+ /**
+ * The name of the database. Must be the same as the key in Torque's
+ * databaseMap.
+ */
+ private String name;
+
+ /**
+ * The Database adapter which encapsulates database-specific
peculiarities.
+ */
+ private DB adapter;
+
+ /**
+ * the Map of this database.
+ */
+ private DatabaseMap databaseMap;
+
+ /**
+ * The DataSourceFactory to optain connections to this database.
+ */
+ private DataSourceFactory dataSourceFactory;
+
+ /**
+ * Creates a new Database with the given name.
+ *
+ * @param name the name of the database, not null.
+ */
+ Database(String name)
+ {
+ this.name = name;
+ }
+
+ /**
+ * returns the name of the database.
+ *
+ * @return the name of the database. May be null.
+ */
+ public String getName()
+ {
+ return name;
+ }
+
+ /**
+ * Returns the adapther to this database.
+ *
+ * @return the adapter to this database, or null if no adapter is set.
+ */
+ public DB getAdapter()
+ {
+ return adapter;
+ }
+
+ /**
+ * Sets the adapter for this database.
+ *
+ * @param adapter The adapter for this database, or null to remove the
+ * current adapter from this database.
+ */
+ public void setAdapter(DB adapter)
+ {
+ this.adapter = adapter;
+ }
+
+ /**
+ * Returns the database map for this database.
+ * If the database map does not exist yet, it is created by this method.
+ *
+ * @param adapter The database map for this database, never null.
+ */
+ public synchronized DatabaseMap getDatabaseMap()
+ {
+ if (databaseMap == null)
+ {
+ databaseMap = new DatabaseMap(name);
+ }
+ return databaseMap;
+ }
+
+ /**
+ * Returns the DataSourceFactory for this database.
+ * The DataSourceFactory is responsible to create connections
+ * to this database.
+ *
+ * @return the DataSourceFactory for this database, or null if no
+ * DataSourceFactory exists for this database.
+ */
+ public DataSourceFactory getDataSourceFactory()
+ {
+ return dataSourceFactory;
+ }
+
+ /**
+ * Sets the DataSourceFactory for this database.
+ * The DataSourceFactory is responsible to create connections
+ * to this database.
+ *
+ * @param dataSourceFactory The new DataSorceFactory for this database,
+ * or null to remove the current DataSourceFactory.
+ */
+ public void setDataSourceFactory(DataSourceFactory dataSourceFactory)
+ {
+ this.dataSourceFactory = dataSourceFactory;
+ }
+
+ /**
+ * Get the IDBroker for this database.
+ *
+ * @return The IDBroker for this database, or null if no IdBroker has
+ * been started for this database.
+ */
+ public IDBroker getIDBroker()
+ {
+ if (databaseMap == null)
+ {
+ return null;
+ }
+ return databaseMap.getIDBroker();
+ }
+
+ /**
+ * Creates the IDBroker for this DatabaseMap and starts it for the
+ * given database.
+ * The information about the IdTable is stored in the databaseMap.
+ * If an IDBroker already exists for the DatabaseMap, the method
+ * does nothing.
+ *
+ * @return true if a new IDBroker was created, false otherwise.
+ */
+ public synchronized boolean startIDBroker()
+ {
+ DatabaseMap databaseMap = getDatabaseMap();
+ if (databaseMap.getIDBroker() != null)
+ {
+ return false;
+ }
+ return databaseMap.startIdBroker();
+ }
+
+ /**
+ * Returns the IdGenerator of the given type for this Database.
+ * @param type The type (i.e.name) of the IdGenerator
+ * @return The IdGenerator of the requested type, or null if no IdGenerator
+ * exists for the requested type.
+ */
+ public IdGenerator getIdGenerator(String type)
+ {
+ if (databaseMap == null)
+ {
+ return null;
+ }
+ return databaseMap.getIdGenerator(type);
+ }
+
+ /**
+ * Adds an IdGenerator to the database.
+ * @param type The type of the IdGenerator
+ * @param idGen The new IdGenerator for the type, or null
+ * to remove the IdGenerator of the given type.
+ */
+ public void addIdGenerator(String type, IdGenerator idGen)
+ {
+ getDatabaseMap().addIdGenerator(type, idGen);
+ }
+
+ /**
+ * Returns the database schema for this Database.
+ * @return the database schema for this database, or null if no schema
+ * has been set.
+ */
+ public String getSchema()
+ {
+ DataSourceFactory dsf = getDataSourceFactory();
+ if (dsf == null)
+ {
+ return null;
+ }
+ return dsf.getSchema();
+ }
+
+ /**
+ * Sets the schema for this database.
+ * @param schema the name of the database schema to set, or null to remove
+ * the current schema.
+ * @throws NullPointerException if no DatasourceFactory exists for this
+ * database.
+ */
+ public void setSchema(String schema)
+ {
+ getDataSourceFactory().setSchema(schema);
+ }
+}
\ No newline at end of file
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/Torque.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/Torque.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/Torque.java (original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/Torque.java Mon Apr 10
13:59:16 2006
@@ -17,9 +17,9 @@
*/
import java.sql.Connection;
+import java.util.Map;
import org.apache.commons.configuration.Configuration;
-
import org.apache.torque.adapter.DB;
import org.apache.torque.manager.AbstractBaseManager;
import org.apache.torque.map.DatabaseMap;
@@ -41,17 +41,18 @@
public abstract class Torque
{
/**
- * The prefix for all configuration keys used by Torque
+ * The prefix for all configuration keys used by Torque.
*/
public static final String TORQUE_KEY = "torque";
/**
- * the prefix for configuring the database adapters and the default
database
+ * The prefix for configuring the database adapters
+ * and the default database.
*/
public static final String DATABASE_KEY = "database";
/**
- * The key used to configure the name of the default database
+ * The key used to configure the name of the default database.
*/
public static final String DEFAULT_KEY = "default";
@@ -350,4 +351,36 @@
{
return getInstance().getSchema(name);
}
-}
+
+ /**
+ * Returns the database for the given key.
+ *
+ * @param name The database name.
+ * @return the Database for the given name, or null if no database exists
+ * for the given name.
+ * @throws TorqueException if Torque is not yet initialized.
+ */
+ public static Database getDatabase(String name) throws TorqueException
+ {
+ return getInstance().getDatabase(name);
+ }
+
+ /**
+ * Returns a Map containing all Databases registered to Torque.
+ * The key of the Map is the name of the database, and the value is the
+ * database instance. <br/>
+ * Note that in the very special case where a new database which
+ * is not configured in Torque's configuration gets known to Torque
+ * at a later time, the returned map may change, and there is no way to
+ * protect you against this. However, Databases should be initialized
+ * in the init() method, so this will not happen if Torque is used
+ * properly.
+ *
+ * @return a Map containing all Databases known to Torque, never null.
+ * @throws TorqueException if Torque is not yet initialized.
+ */
+ public static Map getDatabases() throws TorqueException
+ {
+ return getInstance().getDatabases();
+ }
+}
\ No newline at end of file
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/TorqueInstance.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/TorqueInstance.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/TorqueInstance.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/TorqueInstance.java Mon
Apr 10 13:59:16 2006
@@ -1,7 +1,7 @@
package org.apache.torque;
/*
- * Copyright 2001-2005 The Apache Software Foundation.
+ * Copyright 2001-2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
-import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.torque.adapter.DB;
@@ -36,7 +35,6 @@
import org.apache.torque.dsfactory.DataSourceFactory;
import org.apache.torque.manager.AbstractBaseManager;
import org.apache.torque.map.DatabaseMap;
-import org.apache.torque.map.TableMap;
import org.apache.torque.oid.IDBroker;
import org.apache.torque.oid.IDGeneratorFactory;
import org.apache.torque.util.BasePeer;
@@ -67,15 +65,13 @@
/** The db name that is specified as the default in the property file */
private String defaultDBName = null;
-
- /** The global cache of database maps */
- private Map dbMaps;
-
- /** The cache of DataSourceFactory's */
- private Map dsFactoryMap;
-
- /** The cache of DB adapter keys */
- private Map adapterMap;
+
+ /**
+ * The Map which contains all known databases. All iterations over the map
+ * and other operations where the databaase map needs to stay
+ * in a defined state must be synchronized to this map.
+ */
+ private Map databases = Collections.synchronizedMap(new HashMap());
/** A repository of Manager instances. */
private Map managers;
@@ -87,12 +83,12 @@
private boolean isInit = false;
/**
- * a flag which indicates whether the DataSourceFactory with the key
- * <code>DEFAULT</code> is a reference to another
+ * a flag which indicates whether the DataSourceFactory in the database
+ * named <code>DEFAULT</code> is a reference to another
* DataSourceFactory. This is important to know when closing the
* DataSourceFactories on shutdown();
*/
- private boolean defaultDSFIsReference = false;
+ private boolean defaultDsfIsReference = false;
/**
* Store mapbuilder classnames for peers that have been referenced prior
@@ -157,7 +153,6 @@
initAdapters(conf);
initDataSourceFactories(conf);
- dbMaps = new HashMap();
for (Iterator i = mapBuilders.iterator(); i.hasNext();)
{
//this will add any maps in this builder to the proper database map
@@ -174,10 +169,13 @@
/**
- * initializes the name of the default database
- * @param conf the configuration representing the torque section
- * of the properties file
- * @throws TorqueException if the appropriate key is not set
+ * Initializes the name of the default database and
+ * associates the database with the name <code>DEFAULT_NAME</code>
+ * to the default database.
+ *
+ * @param conf the configuration representing the torque section.
+ * of the properties file.
+ * @throws TorqueException if the appropriate key is not set.
*/
private final void initDefaultDbName(Configuration conf)
throws TorqueException
@@ -203,6 +201,9 @@
}
/**
+ * Reads the adapter settings from the configuration and
+ * assigns the appropriate database adapters and Id Generators
+ * to the databases.
*
* @param conf the Configuration representing the torque section of the
* properties file
@@ -213,7 +214,6 @@
throws TorqueException
{
log.debug("initAdapters(" + conf + ")");
- adapterMap = new HashMap();
Configuration c = conf.subset(Torque.DATABASE_KEY);
if (c == null || c.isEmpty())
@@ -233,14 +233,34 @@
for (Iterator it = c.getKeys(); it.hasNext(); )
{
String key = (String) it.next();
- if (key.endsWith(DB.ADAPTER_KEY))
+ if (key.endsWith(DB.ADAPTER_KEY)
+ || key.endsWith(DB.DRIVER_KEY))
{
String adapter = c.getString(key);
String handle = key.substring(0, key.indexOf('.'));
DB db = DBFactory.create(adapter);
+ Database database = getOrCreateDatabase(handle);
+
// register the adapter for this name
- adapterMap.put(handle, db);
- log.debug("Adding " + adapter + " -> " + handle + " as
Adapter");
+ database.setAdapter(db);
+ log.debug("Adding " + adapter + " -> "
+ + handle + " as Adapter");
+
+ // add Id generators
+
+ // first make sure that the dtabaseMap exists for the name
+ // as the idGenerators are still stored in the database map
+ // TODO: change when the idGenerators are stored in the
+ // database
+ getDatabaseMap(handle);
+ for (int i = 0;
+ i < IDGeneratorFactory.ID_GENERATOR_METHODS.length;
+ i++)
+ {
+ database.addIdGenerator(
+ IDGeneratorFactory.ID_GENERATOR_METHODS[i],
+ IDGeneratorFactory.create(db, handle));
+ }
}
}
}
@@ -251,7 +271,11 @@
throw new TorqueException(e);
}
- if (adapterMap.get(Torque.getDefaultDB()) == null)
+ // check that at least the default database has got an adapter.
+ Database defaultDatabase
+ = (Database) databases.get(Torque.getDefaultDB());
+ if (defaultDatabase == null
+ || defaultDatabase.getAdapter() == null)
{
String error = "Invalid configuration : "
+ "No adapter definition found for default DB "
@@ -269,7 +293,13 @@
}
/**
- *
+ * Reads the settings for the DataSourceFactories from the configuration
+ * and creates and/or cinfigures the DataSourceFactories for the databases.
+ * If no DataSorceFactory is assigned to the database with the name
+ * <code>DEFAULT_NAME</code>, a reference to the DataSourceFactory
+ * of the default daztabase is made from the database with the name
+ * <code>DEFAULT_NAME</code>.
+ *
* @param conf the Configuration representing the properties file
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
@@ -278,7 +308,6 @@
throws TorqueException
{
log.debug("initDataSourceFactories(" + conf + ")");
- dsFactoryMap = new HashMap();
Configuration c = conf.subset(DataSourceFactory.DSFACTORY_KEY);
if (c == null || c.isEmpty())
@@ -308,7 +337,9 @@
DataSourceFactory dsf =
(DataSourceFactory) dsfClass.newInstance();
dsf.initialize(c.subset(handle));
- dsFactoryMap.put(handle, dsf);
+
+ Database database = getOrCreateDatabase(handle);
+ database.setDataSourceFactory(dsf);
}
}
}
@@ -318,7 +349,10 @@
throw new TorqueException(e);
}
- if (dsFactoryMap.get(Torque.getDefaultDB()) == null)
+ Database defaultDatabase
+ = (Database) databases.get(defaultDBName);
+ if (defaultDatabase == null
+ || defaultDatabase.getDataSourceFactory() == null)
{
String error = "Invalid configuration : "
+ "No DataSourceFactory definition for default DB found. "
@@ -327,13 +361,13 @@
+ "."
+ DataSourceFactory.DSFACTORY_KEY
+ "."
- + Torque.getDefaultDB()
+ + defaultDBName
+ "."
+ DataSourceFactory.FACTORY_KEY;
log.error(error);
throw new TorqueException(error);
}
-
+
// As there might be a default database configured
// to map "default" onto an existing datasource, we
// must check, whether there _is_ really an entry for
@@ -347,16 +381,22 @@
//
// in your Torque.properties
//
- String defaultDB = getDefaultDB();
- if (dsFactoryMap.get(DEFAULT_NAME) == null
- && !defaultDB.equals(DEFAULT_NAME))
{
- log.debug("Adding a dummy entry for "
- + DEFAULT_NAME + ", mapped onto " + defaultDB);
- dsFactoryMap.put(DEFAULT_NAME, dsFactoryMap.get(defaultDB));
- this.defaultDSFIsReference = true;
+ Database databaseInfoForKeyDefault
+ = getOrCreateDatabase(DEFAULT_NAME);
+ if ((!defaultDBName.equals(DEFAULT_NAME))
+ && databaseInfoForKeyDefault.getDataSourceFactory() == null)
+ {
+ log.debug("Adding the DatasourceFactory from database "
+ + defaultDBName
+ + " onto database " + DEFAULT_NAME);
+ databaseInfoForKeyDefault.setDataSourceFactory(
+ defaultDatabase.getDataSourceFactory());
+ this.defaultDsfIsReference = true;
+ }
}
+
}
/**
@@ -384,13 +424,13 @@
}
/**
- * Initialization of Torque with a properties file.
+ * Initialization of Torque with a Configuration object.
*
* @param conf The Torque configuration.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
- public void init(Configuration conf)
+ public synchronized void init(Configuration conf)
throws TorqueException
{
log.debug("init(" + conf + ")");
@@ -504,8 +544,10 @@
/**
* Sets the configuration for Torque and all dependencies.
+ * The prefix <code>TORQUE_KEY</code> needs to be removed from the
+ * configuration keys for the provided configuration.
*
- * @param conf the Configuration
+ * @param conf the Configuration.
*/
public void setConfiguration(Configuration conf)
{
@@ -586,47 +628,59 @@
public synchronized void shutdown()
throws TorqueException
{
- if (dbMaps != null)
+ // stop the idbrokers
+ synchronized (databases)
{
- for (Iterator it = dbMaps.values().iterator(); it.hasNext();)
+ for (Iterator it = databases.values().iterator(); it.hasNext();)
{
- DatabaseMap map = (DatabaseMap) it.next();
- IDBroker idBroker = map.getIDBroker();
+ Database database = (Database) it.next();
+ IDBroker idBroker = database.getIDBroker();
if (idBroker != null)
{
idBroker.stop();
}
}
}
+
+ // shut down the data source factories
TorqueException exception = null;
- for (Iterator it = dsFactoryMap.keySet().iterator(); it.hasNext();)
+ synchronized (databases)
{
- Object dsfKey = it.next();
-
- if (DEFAULT_NAME.equals(dsfKey) && defaultDSFIsReference)
- {
- // the entry with the key DEFAULT_NAME
- // is just a reference to aynother entry. Do not close because
- // this leads to closing the same DataSourceFactory twice.
- it.remove();
- break;
- }
-
- DataSourceFactory dsf
- = (DataSourceFactory) dsFactoryMap.get(dsfKey);
- try
+ for (Iterator it = databases.keySet().iterator(); it.hasNext();)
{
- dsf.close();
- it.remove();
- }
- catch (TorqueException e)
- {
- log.error("Error while closing the DataSourceFactory "
- + dsfKey,
- e);
- if (exception == null)
+ Object databaseKey = it.next();
+
+ Database database
+ = (Database) databases.get(databaseKey);
+ if (DEFAULT_NAME.equals(databaseKey) && defaultDsfIsReference)
{
- exception = e;
+ // the DataSourceFactory of the database with the name
+ // DEFAULT_NAME is just a reference to aynother entry.
+ // Do not close because this leads to closing
+ // the same DataSourceFactory twice.
+ database.setDataSourceFactory(null);
+ break;
+ }
+
+ try
+ {
+ DataSourceFactory dataSourceFactory
+ = database.getDataSourceFactory();
+ if (dataSourceFactory != null)
+ {
+ dataSourceFactory.close();
+ database.setDataSourceFactory(null);
+ }
+ }
+ catch (TorqueException e)
+ {
+ log.error("Error while closing the DataSourceFactory "
+ + databaseKey,
+ e);
+ if (exception == null)
+ {
+ exception = e;
+ }
}
}
}
@@ -679,68 +733,8 @@
throw new TorqueException ("DatabaseMap name was null!");
}
- if (dbMaps == null)
- {
- throw new TorqueException("Torque was not initialized properly.");
- }
-
- synchronized (dbMaps)
- {
- DatabaseMap map = (DatabaseMap) dbMaps.get(name);
- if (map == null)
- {
- // Still not there. Create and add.
- map = initDatabaseMap(name);
- }
- return map;
- }
- }
-
- /**
- * Creates and initializes the mape for the named database.
- * Assumes that <code>dbMaps</code> member is sync'd.
- *
- * @param name The name of the database to map.
- * @return The desired map.
- * @throws TorqueException Any exceptions caught during processing will be
- * rethrown wrapped into a TorqueException.
- */
- private final DatabaseMap initDatabaseMap(String name)
- throws TorqueException
- {
- DatabaseMap map = new DatabaseMap(name);
-
- // Add info about IDBroker's table.
- setupIdTable(map);
-
- // Setup other ID generators for this map.
- try
- {
- String key = getDatabaseProperty(name, "adapter");
- if (StringUtils.isEmpty(key))
- {
- key = getDatabaseProperty(name, "driver");
- }
- DB db = DBFactory.create(key);
- for (int i = 0; i < IDGeneratorFactory.ID_GENERATOR_METHODS.length;
- i++)
- {
- map.addIdGenerator(IDGeneratorFactory.ID_GENERATOR_METHODS[i],
- IDGeneratorFactory.create(db, name));
- }
- }
- catch (java.lang.InstantiationException e)
- {
- throw new TorqueException(e);
- }
-
- // Avoid possible ConcurrentModificationException by
- // constructing a copy of dbMaps.
- Map newMaps = new HashMap(dbMaps);
- newMaps.put(name, map);
- dbMaps = newMaps;
-
- return map;
+ Database database = getOrCreateDatabase(name);
+ return database.getDatabaseMap();
}
/**
@@ -754,45 +748,9 @@
}
/**
- * Returns the specified property of the given database, or the empty
- * string if no value is set for the property.
- *
- * @param db The name of the database whose property to get.
- * @param prop The name of the property to get.
- * @return The property's value.
- */
- private String getDatabaseProperty(String db, String prop)
- {
- return conf.getString(new StringBuffer("database.")
- .append(db)
- .append('.')
- .append(prop)
- .toString(), "");
- }
-
- /**
- * Setup IDBroker's table information within given database map.
- *
- * This method should be called on all new database map to ensure that
- * IDBroker functionality is available in all databases used by the
- * application.
- *
- * @param map the DataBaseMap to setup.
- */
- private final void setupIdTable(DatabaseMap map)
- {
- map.setIdTable("ID_TABLE");
- TableMap tMap = map.getIdTable();
- tMap.addPrimaryKey("ID_TABLE_ID", new Integer(0));
- tMap.addColumn("TABLE_NAME", "");
- tMap.addColumn("NEXT_ID", new Integer(0));
- tMap.addColumn("QUANTITY", new Integer(0));
- }
-
- /**
* This method returns a Connection from the default pool.
*
- * @return The requested connection.
+ * @return The requested connection, never null.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
@@ -803,18 +761,23 @@
}
/**
- *
+ * Returns a database connection to the database with the key
+ * <code>name</code>.
* @param name The database name.
- * @return a database connection
- * @throws TorqueException Any exceptions caught during processing will be
- * rethrown wrapped into a TorqueException.
+ * @return a database connection, never null.
+ * @throws TorqueException If no DataSourceFactory is configured for the
+ * named database, the connection information is wrong, or the
+ * connection cannot be returned for any other reason.
*/
public Connection getConnection(String name)
throws TorqueException
{
try
{
- return getDataSourceFactory(name).getDataSource().getConnection();
+ return getDatabase(name)
+ .getDataSourceFactory()
+ .getDataSource()
+ .getConnection();
}
catch(SQLException se)
{
@@ -823,33 +786,28 @@
}
/**
- * Returns a DataSourceFactory
+ * Returns the DataSourceFactory for the database with the name
+ * <code>name</code>.
*
- * @param name Name of the DSF to get
- * @return A DataSourceFactory object
+ * @param name The name of the database to get the DSF for.
+ * @return A DataSourceFactory object, never null.
+ * @throws TorqueException if Torque is not initiliaized, or
+ * no DatasourceFactory is configured for the given name.
*/
- protected DataSourceFactory getDataSourceFactory(String name)
+ public DataSourceFactory getDataSourceFactory(String name)
throws TorqueException
{
- if (!isInit())
- {
- throw new TorqueException("Torque is not initialized.");
- }
+ Database database = getDatabase(name);
DataSourceFactory dsf = null;
-
- try
+ if (database != null)
{
- dsf = (DataSourceFactory) dsFactoryMap.get(name);
- }
- catch (Exception e)
- {
- throw new TorqueException(e);
+ dsf = database.getDataSourceFactory();
}
if (dsf == null)
{
- throw new NullPointerException(
+ throw new TorqueException(
"There was no DataSourceFactory "
+ "configured for the connection " + name);
}
@@ -858,7 +816,7 @@
}
/**
- * This method returns a Connecton using the given parameters.
+ * This method returns a Connection using the given parameters.
* You should only use this method if you need user based access to the
* database!
*
@@ -875,7 +833,8 @@
{
try
{
- return
getDataSourceFactory(name).getDataSource().getConnection(username, password);
+ return getDataSourceFactory(name)
+ .getDataSource().getConnection(username, password);
}
catch(SQLException se)
{
@@ -884,16 +843,22 @@
}
/**
- * Returns database adapter for a specific connection pool.
+ * Returns the database adapter for a specific database.
*
- * @param name A pool name.
- * @return The corresponding database adapter.
+ * @param name the name of the database to get the adapter for.
+ * @return The corresponding database adapter, or null if no database
+ * adapter is defined for the given database.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public DB getDB(String name) throws TorqueException
{
- return (DB) adapterMap.get(name);
+ Database database = getDatabase(name);
+ if (database == null)
+ {
+ return null;
+ }
+ return database.getAdapter();
}
///////////////////////////////////////////////////////////////////////////
@@ -932,14 +897,14 @@
* Sets the current schema for a database connection
*
* @param name The database name.
- * @param schema The current schema name
+ * @param schema The current schema name.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
*/
public void setSchema(String name, String schema)
throws TorqueException
{
- getDataSourceFactory(name).setSchema(schema);
+ getOrCreateDatabase(name).setSchema(schema);
}
/**
@@ -953,7 +918,72 @@
public String getSchema(String name)
throws TorqueException
{
- return getDataSourceFactory(name).getSchema();
+ Database database = getDatabase(name);
+ if (database == null)
+ {
+ return null;
+ }
+ return database.getSchema();
}
+ /**
+ * Returns the database for the key <code>databaseName</code>.
+ *
+ * @param databaseName the key to get the database for.
+ * @return the database for the specified key, or null if the database
+ * does not exist.
+ * @throws TorqueException if Torque is not yet initialized.
+ */
+ public Database getDatabase(String databaseName) throws TorqueException
+ {
+ if (!isInit())
+ {
+ throw new TorqueException("Torque is not initialized.");
+ }
+ return (Database) databases.get(databaseName);
+ }
+
+ /**
+ * Returns a Map containing all Databases registered to Torque.
+ * The key of the Map is the name of the database, and the value is the
+ * database instance. <br/>
+ * Note that in the very special case where a new database which
+ * is not configured in Torque's configuration gets known to Torque
+ * at a later time, the returned map may change, and there is no way to
+ * protect you against this.
+ *
+ * @return a Map containing all Databases known to Torque, never null.
+ * @throws TorqueException if Torque is not yet initialized.
+ */
+ public Map getDatabases() throws TorqueException
+ {
+ if (!isInit())
+ {
+ throw new TorqueException("Torque is not initialized.");
+ }
+ return Collections.unmodifiableMap(databases);
+ }
+
+ /**
+ * Returns the database for the key <code>databaseName</code>.
+ * If no database is associated to the specified key,
+ * a new database is created, mapped to the specified key, and returned.
+ *
+ * @param databaseName the key to get the database for.
+ * @return the database associated with specified key, or the newly created
+ * database, never null.
+ */
+ public Database getOrCreateDatabase(String databaseName)
+ {
+ synchronized (databases)
+ {
+ Database result = (Database) databases.get(databaseName);
+ if (result == null)
+ {
+ result = new Database(databaseName);
+ databases.put(databaseName, result);
+ }
+ return result;
+ }
+ }
}
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/adapter/DB.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/adapter/DB.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/adapter/DB.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/adapter/DB.java Mon Apr
10 13:59:16 2006
@@ -74,11 +74,16 @@
public static final int LIMIT_STYLE_DB2 = 5;
/**
- * Key for the configuration which contains database adapters
+ * Key for the configuration which contains database adapters.
*/
public static final String ADAPTER_KEY = "adapter";
/**
+ * Key for the configuration which contains database drivers.
+ */
+ public static final String DRIVER_KEY = "driver";
+
+ /**
* Empty constructor.
*/
protected DB()
@@ -247,4 +252,4 @@
{
return (Boolean.TRUE.equals(b) ? "1" : "0");
}
-}
+}
\ No newline at end of file
Modified:
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/AbstractDataSourceFactory.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/AbstractDataSourceFactory.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
---
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/AbstractDataSourceFactory.java
(original)
+++
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/AbstractDataSourceFactory.java
Mon Apr 10 13:59:16 2006
@@ -258,6 +258,8 @@
* @return The current schema name. Null means, no schema has been set.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
+ * @deprecated use DatabaseInfo.setSchema() instead. Will be removed
+ * in a future version of Torque.
*/
public String getSchema()
{
Modified:
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/DataSourceFactory.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/DataSourceFactory.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
---
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/DataSourceFactory.java
(original)
+++
db/torque/runtime/trunk/src/java/org/apache/torque/dsfactory/DataSourceFactory.java
Mon Apr 10 13:59:16 2006
@@ -60,6 +60,8 @@
* Sets the current schema for the database connection
*
* @param schema The current schema name
+ * @deprecated use DatabaseInfo.setSchema() instead. Will be removed
+ * in a future version of Torque.
*/
void setSchema(String schema);
@@ -69,6 +71,8 @@
* @return The current schema name. Null means, no schema has been set.
* @throws TorqueException Any exceptions caught during processing will be
* rethrown wrapped into a TorqueException.
+ * @deprecated use DatabaseInfo.getSchema() instead. Will be removed
+ * in a future version of Torque.
*/
String getSchema();
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/map/ColumnMap.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/map/ColumnMap.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/map/ColumnMap.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/map/ColumnMap.java Mon
Apr 10 13:59:16 2006
@@ -24,6 +24,9 @@
*/
public class ColumnMap implements java.io.Serializable
{
+ /** The serialVersionUID for this class. */
+ private static final long serialVersionUID = -5971184507395399165L;
+
/** Type of the column. */
private Object type = null;
Modified:
db/torque/runtime/trunk/src/java/org/apache/torque/map/DatabaseMap.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/map/DatabaseMap.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/map/DatabaseMap.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/map/DatabaseMap.java Mon
Apr 10 13:59:16 2006
@@ -16,9 +16,11 @@
* limitations under the License.
*/
-import java.util.Iterator;
import java.util.HashMap;
import java.util.Hashtable;
+import java.util.Iterator;
+
+import org.apache.torque.Database;
import org.apache.torque.adapter.IDMethod;
import org.apache.torque.oid.IDBroker;
import org.apache.torque.oid.IdGenerator;
@@ -32,6 +34,9 @@
*/
public class DatabaseMap implements java.io.Serializable
{
+ /** The serialVersionUID for this class. */
+ private static final long serialVersionUID = 955251837095032274L;
+
/** Name of the database. */
private String name;
@@ -51,10 +56,12 @@
private HashMap idGenerators;
/**
- * Required by proxy. Not used.
+ * Constructs a new DatabaseMap.
*/
public DatabaseMap()
{
+ tables = new Hashtable();
+ idGenerators = new HashMap(6);
}
/**
@@ -62,6 +69,8 @@
*
* @param name Name of the database.
* @param numberOfTables Number of tables in the database.
+ * @deprecated use DatabaseMap() instead. Will be removed
+ * in a future version of Torque.
*/
public DatabaseMap(String name, int numberOfTables)
{
@@ -74,6 +83,8 @@
* Constructor.
*
* @param name Name of the database.
+ * @deprecated use DatabaseMap() instead. Will be removed
+ * in a future version of Torque.
*/
public DatabaseMap(String name)
{
@@ -122,6 +133,9 @@
* Get the IDBroker for this database.
*
* @return An IDBroker.
+ * @deprecated Will be removed in a future version of Torque.
+ * Use DatabaseInfo#getIdBroker() instead
+ * to access the IDBroker.
*/
public IDBroker getIDBroker()
{
@@ -132,6 +146,8 @@
* Get the name of this database.
*
* @return A String.
+ * @deprecated Will be removed in a future version of Torque.
+ * Use the name of the corresponding database instead.
*/
public String getName()
{
@@ -210,8 +226,6 @@
{
this.idTable = idTable;
addTable(idTable);
- idBroker = new IDBroker(idTable);
- addIdGenerator(IDMethod.ID_BROKER, idBroker);
}
/**
@@ -230,6 +244,8 @@
*
* @param type a <code>String</code> value
* @param idGen an <code>IdGenerator</code> value
+ * @deprecated use DatabaseInfo.addGenerator() instead.
+ * Will be removed in a future version of Torque.
*/
public void addIdGenerator(String type, IdGenerator idGen)
{
@@ -242,9 +258,36 @@
*
* @param type a <code>String</code> value
* @return an <code>IdGenerator</code> value
+ * @deprecated use DatabaseInfo.getIdGenerator() instead.
+ * Will be removed in a future version of Torque.
*/
- IdGenerator getIdGenerator(String type)
+ public IdGenerator getIdGenerator(String type)
{
return (IdGenerator) idGenerators.get(type);
+ }
+
+ /**
+ * Creates the Idbroker for this DatabaseMap.
+ * If an IDBroker already exists for the DatabaseMap, the method
+ * does nothing.
+ * @return true if a new IdBroker was created, false otherwise.
+ * @deprecated Will be removed in a future version of Torque.
+ * Use DatabaseInfo.startIdBroker() instead.
+ */
+ public synchronized boolean startIdBroker()
+ {
+ if (idBroker == null)
+ {
+ setIdTable("ID_TABLE");
+ TableMap tMap = getIdTable();
+ tMap.addPrimaryKey("ID_TABLE_ID", new Integer(0));
+ tMap.addColumn("TABLE_NAME", "");
+ tMap.addColumn("NEXT_ID", new Integer(0));
+ tMap.addColumn("QUANTITY", new Integer(0));
+ idBroker = new IDBroker(idTable);
+ addIdGenerator(IDMethod.ID_BROKER, idBroker);
+ return true;
+ }
+ return false;
}
}
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/map/TableMap.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/map/TableMap.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/map/TableMap.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/map/TableMap.java Mon
Apr 10 13:59:16 2006
@@ -34,6 +34,9 @@
*/
public class TableMap implements IDMethod, java.io.Serializable
{
+ /** The serialVersionUID for this class. */
+ private static final long serialVersionUID = -9053174532511492818L;
+
/** The list of valid ID generation methods. */
protected static final String[] VALID_ID_METHODS =
{
@@ -217,6 +220,8 @@
/**
* Get the value of idGenerator.
* @return value of idGenerator.
+ * @deprecated use DatabaseInfo.getIdGenerator(getPrimaryKeyMethod())
+ * instead. Will be removed in a future version of Torque.
*/
public IdGenerator getIdGenerator()
{
@@ -488,6 +493,10 @@
primaryKeyMethod = method;
break;
}
+ }
+ if (ID_BROKER.equalsIgnoreCase(method))
+ {
+ getDatabaseMap().startIdBroker();
}
}
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/oid/IDBroker.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/oid/IDBroker.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/oid/IDBroker.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/oid/IDBroker.java Mon
Apr 10 13:59:16 2006
@@ -26,10 +26,9 @@
import java.util.List;
import org.apache.commons.configuration.Configuration;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
+import org.apache.torque.Database;
import org.apache.torque.Torque;
import org.apache.torque.TorqueException;
import org.apache.torque.map.DatabaseMap;
@@ -105,8 +104,8 @@
/** Fully qualified Quantity column name */
public static final String QUANTITY = ID_TABLE + "." + COL_QUANTITY;
- /** The TableMap referencing the ID_TABLE for this IDBroker. */
- private TableMap tableMap;
+ /** the name of the database in which this IdBroker is running. */
+ private String databaseName;
/**
* The default size of the per-table meta data <code>Hashtable</code>
@@ -182,13 +181,36 @@
private Log log = LogFactory.getLog(IDBroker.class);
/**
+ * constructs an IdBroker for the given Database.
+ * @param database the database where this IdBroker is running in.
+ */
+ public IDBroker(Database database)
+ {
+ this(database.getName());
+ }
+
+ /**
* Creates an IDBroker for the ID table.
*
* @param tMap A TableMap.
+ * @deprecated Use IDBroker(DatabaseInfo) instead. Will be removed
+ * in a future version of Torque.
*/
public IDBroker(TableMap tMap)
{
- this.tableMap = tMap;
+ this(tMap.getDatabaseMap().getName());
+ }
+
+ /**
+ * Constructor.
+ * Provided as long as both Constructors, IDBroker(DatabaseInfo) and
+ * IDBroker(TableMap), are around.
+ * @param databaseName the name of the database for which this IdBroker
+ * provides Ids.
+ */
+ private IDBroker(String databaseName)
+ {
+ this.databaseName = databaseName;
configuration = Torque.getConfiguration();
// Start the housekeeper thread only if prefetch has not been disabled
@@ -207,15 +229,28 @@
// Check for Transaction support. Give warning message if
// IDBroker is being used with a database that does not
// support transactions.
- String dbName = tMap.getDatabaseMap().getName();
Connection dbCon = null;
try
{
- dbCon = Torque.getConnection(dbName);
+ dbCon = Torque.getConnection(databaseName);
+ }
+ catch (Throwable t)
+ {
+ log.error("Could not open a connection to the database "
+ + databaseName,
+ t);
+ transactionsSupported = false;
+ }
+ try
+ {
transactionsSupported = dbCon.getMetaData().supportsTransactions();
}
catch (Exception e)
{
+ log.warn("Could not read from connection Metadata"
+ + " whether transactions are supported for the database "
+ + databaseName,
+ e);
transactionsSupported = false;
}
finally
@@ -231,7 +266,7 @@
}
if (!transactionsSupported)
{
- log.warn("IDBroker is being used with db '" + dbName
+ log.warn("IDBroker is being used with db '" + databaseName
+ "', which does not support transactions. IDBroker "
+ "attempts to use transactions to limit the possibility "
+ "of duplicate key generation. Without transactions, "
@@ -463,8 +498,6 @@
Connection dbCon = null;
try
{
- String databaseName = tableMap.getDatabaseMap().getName();
-
dbCon = Torque.getConnection(databaseName);
Statement statement = dbCon.createStatement();
ResultSet rs = statement.executeQuery(query);
@@ -618,7 +651,6 @@
{
BigDecimal nextId = null;
BigDecimal quantity = null;
- DatabaseMap dbMap = tableMap.getDatabaseMap();
// Block on the table. Multiple tables are allowed to ask for
// ids simultaneously.
@@ -636,7 +668,7 @@
{
if (useNewConnection)
{
- connection = Transaction.beginOptional(dbMap.getName(),
+ connection = Transaction.beginOptional(databaseName,
transactionsSupported);
}
@@ -724,7 +756,6 @@
if (connection == null || configuration
.getBoolean(DB_IDBROKER_USENEWCONNECTION, true))
{
- String databaseName = tableMap.getDatabaseMap().getName();
// Get a connection to the db
dbCon = Torque.getConnection(databaseName);
}
Modified: db/torque/runtime/trunk/src/java/org/apache/torque/util/BasePeer.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/util/BasePeer.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/util/BasePeer.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/util/BasePeer.java Mon
Apr 10 13:59:16 2006
@@ -32,6 +32,7 @@
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.torque.Database;
import org.apache.torque.Torque;
import org.apache.torque.TorqueException;
import org.apache.torque.adapter.DB;
@@ -480,10 +481,12 @@
}
String dbName = criteria.getDbName();
- DatabaseMap dbMap = Torque.getDatabaseMap(dbName);
+ Database database = Torque.getDatabase(dbName);
+ DatabaseMap dbMap = database.getDatabaseMap();
TableMap tableMap = dbMap.getTable(table);
Object keyInfo = tableMap.getPrimaryKeyMethodInfo();
- IdGenerator keyGen = tableMap.getIdGenerator();
+ IdGenerator keyGen
+ = database.getIdGenerator(tableMap.getPrimaryKeyMethod());
ColumnMap pk = getPrimaryKey(criteria);
Modified:
db/torque/runtime/trunk/src/java/org/apache/torque/util/Transaction.java
URL:
http://svn.apache.org/viewcvs/db/torque/runtime/trunk/src/java/org/apache/torque/util/Transaction.java?rev=393063&r1=393062&r2=393063&view=diff
==============================================================================
--- db/torque/runtime/trunk/src/java/org/apache/torque/util/Transaction.java
(original)
+++ db/torque/runtime/trunk/src/java/org/apache/torque/util/Transaction.java
Mon Apr 10 13:59:16 2006
@@ -48,6 +48,21 @@
private static Log log = LogFactory.getLog(Transaction.class);
/**
+ * Begin a transaction for the default database.
+ * This method will fallback gracefully to
+ * return a normal connection, if the database being accessed does
+ * not support transactions.
+ *
+ * @return The Connection for the transaction.
+ * @throws TorqueException Any exceptions caught during processing will be
+ * rethrown wrapped into a TorqueException.
+ */
+ public static Connection begin() throws TorqueException
+ {
+ return Transaction.begin(Torque.getDefaultDB());
+ }
+
+ /**
* Begin a transaction. This method will fallback gracefully to
* return a normal connection, if the database being accessed does
* not support transactions.
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]