diff options
author | Stefan Winkler | 2009-04-07 09:47:44 -0400 |
---|---|---|
committer | Stefan Winkler | 2009-04-07 09:47:44 -0400 |
commit | 9afef76b89dea834e9d4b81ade31e9f3646572e5 (patch) | |
tree | 6087cdbaf27cd7839d0e6ba755c76f3bd1b565ec | |
parent | a1796a62d7f66e705d3461d4c0d5e3b93c3e3280 (diff) | |
download | cdo-9afef76b89dea834e9d4b81ade31e9f3646572e5.zip cdo-9afef76b89dea834e9d4b81ade31e9f3646572e5.tar.gz cdo-9afef76b89dea834e9d4b81ade31e9f3646572e5.tar.xz |
Finished inlining JDBCDelegate stuff
Restructured meta stuff into MetaDataManager
13 files changed, 619 insertions, 3596 deletions
diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IDBStore.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IDBStore.java index d236155..9fd4f41 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IDBStore.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IDBStore.java @@ -19,8 +19,6 @@ import org.eclipse.net4j.db.IDBAdapter; import org.eclipse.net4j.db.IDBConnectionProvider; import org.eclipse.net4j.db.ddl.IDBSchema; -import org.eclipse.emf.ecore.EModelElement; - /** * @author Eike Stepper * @noimplement This interface is not intended to be implemented by clients. @@ -43,25 +41,16 @@ public interface IDBStore extends IStore /** * @since 2.0 - * @deprecated should be moved to metamanager - */ - @Deprecated - public long getMetaID(EModelElement modelElement); - - /** - * @since 2.0 - * @deprecated should be moved to metamanager */ - @Deprecated - public EModelElement getMetaInstance(long id); + public IDBStoreAccessor getReader(ISession session); /** * @since 2.0 */ - public IDBStoreAccessor getReader(ISession session); + public IDBStoreAccessor getWriter(ITransaction transaction); /** * @since 2.0 */ - public IDBStoreAccessor getWriter(ITransaction transaction); + public IMetaDataManager getMetaDataManager(); } diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IMetaDataManager.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IMetaDataManager.java new file mode 100644 index 0000000..ac76a09 --- /dev/null +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/IMetaDataManager.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + * Stefan Winkler - major refactoring + */ +package org.eclipse.emf.cdo.server.db; + +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; + +import org.eclipse.net4j.db.DBType; +import org.eclipse.net4j.util.om.monitor.OMMonitor; + +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EModelElement; +import org.eclipse.emf.ecore.EPackage; + +import java.sql.Connection; +import java.util.Collection; + +/** + * @author Eike Stepper + * @author Stefan Winkler + * @since 2.0 + */ +public interface IMetaDataManager +{ + /** + * @since 2.0 + */ + public long getMetaID(EModelElement modelElement); + + /** + * @since 2.0 + */ + public EModelElement getMetaInstance(long id); + + /** + * @since 2.0 + */ + public EPackage[] loadPackageUnit(Connection connection, InternalCDOPackageUnit packageUnit); + + /** + * @since 2.0 + */ + public Collection<InternalCDOPackageUnit> readPackageUnits(Connection connection); + + /** + * @since 2.0 + */ + public void writePackageUnits(Connection connection, InternalCDOPackageUnit[] packageUnits, OMMonitor monitor); + + /** + * @since 2.0 + */ + public DBType getDBType(EClassifier eType); + +} diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/mapping/IReferenceMapping.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/mapping/IReferenceMapping.java index deb57c4..80caca9 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/mapping/IReferenceMapping.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/db/mapping/IReferenceMapping.java @@ -29,8 +29,6 @@ public interface IReferenceMapping extends IFeatureMapping { public IDBTable getTable(); - public boolean isWithFeature(); - /** * Write a list of references completely */ @@ -70,7 +68,7 @@ public interface IReferenceMapping extends IFeatureMapping /** * Clears the list of references for the revision with ID <code>id</code>. */ - public void deleteReference(IDBStoreAccessor accessor, CDOID id); + public void clearReference(IDBStoreAccessor accessor, CDOID id); public void readReference(IDBStoreAccessor accessor, InternalCDORevision revision, int referenceChunk); diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStore.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStore.java index 834c28c..e89758e 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStore.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStore.java @@ -11,21 +11,17 @@ */ package org.eclipse.emf.cdo.server.internal.db; -import org.eclipse.emf.cdo.common.id.CDOID; -import org.eclipse.emf.cdo.common.id.CDOIDMeta; -import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.server.ISession; import org.eclipse.emf.cdo.server.ITransaction; import org.eclipse.emf.cdo.server.IView; import org.eclipse.emf.cdo.server.db.IDBStore; +import org.eclipse.emf.cdo.server.db.IMetaDataManager; import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy; import org.eclipse.emf.cdo.server.internal.db.bundle.OM; -import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry; import org.eclipse.emf.cdo.spi.server.LongIDStore; import org.eclipse.emf.cdo.spi.server.StoreAccessorPool; import org.eclipse.net4j.db.DBException; -import org.eclipse.net4j.db.DBType; import org.eclipse.net4j.db.DBUtil; import org.eclipse.net4j.db.IDBAdapter; import org.eclipse.net4j.db.IDBConnectionProvider; @@ -33,22 +29,14 @@ import org.eclipse.net4j.db.ddl.IDBSchema; import org.eclipse.net4j.db.ddl.IDBTable; import org.eclipse.net4j.spi.db.DBSchema; import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; +import org.eclipse.net4j.util.lifecycle.ILifecycle; import org.eclipse.net4j.util.lifecycle.LifecycleUtil; import org.eclipse.net4j.util.om.monitor.ProgressDistributor; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.EEnum; -import org.eclipse.emf.ecore.EModelElement; -import org.eclipse.emf.ecore.EcorePackage; -import org.eclipse.emf.ecore.InternalEObject; - import javax.sql.DataSource; import java.sql.Connection; import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; import java.util.Set; /** @@ -92,32 +80,7 @@ public class DBStore extends LongIDStore implements IDBStore @ExcludeFromDump private transient StoreAccessorPool writerPool = new StoreAccessorPool(this, null); - @Deprecated - private static Map<EClassifier, DBType> typeMap = new HashMap<EClassifier, DBType>(); - - static - { - typeMap.put(EcorePackage.eINSTANCE.getEDate(), DBType.TIMESTAMP); - typeMap.put(EcorePackage.eINSTANCE.getEString(), DBType.VARCHAR); - - typeMap.put(EcorePackage.eINSTANCE.getEBoolean(), DBType.BOOLEAN); - typeMap.put(EcorePackage.eINSTANCE.getEByte(), DBType.SMALLINT); - typeMap.put(EcorePackage.eINSTANCE.getEChar(), DBType.CHAR); - typeMap.put(EcorePackage.eINSTANCE.getEDouble(), DBType.DOUBLE); - typeMap.put(EcorePackage.eINSTANCE.getEFloat(), DBType.FLOAT); - typeMap.put(EcorePackage.eINSTANCE.getEInt(), DBType.INTEGER); - typeMap.put(EcorePackage.eINSTANCE.getELong(), DBType.BIGINT); - typeMap.put(EcorePackage.eINSTANCE.getEShort(), DBType.SMALLINT); - - typeMap.put(EcorePackage.eINSTANCE.getEBooleanObject(), DBType.BOOLEAN); - typeMap.put(EcorePackage.eINSTANCE.getEByteObject(), DBType.SMALLINT); - typeMap.put(EcorePackage.eINSTANCE.getECharacterObject(), DBType.CHAR); - typeMap.put(EcorePackage.eINSTANCE.getEDoubleObject(), DBType.DOUBLE); - typeMap.put(EcorePackage.eINSTANCE.getEFloatObject(), DBType.FLOAT); - typeMap.put(EcorePackage.eINSTANCE.getEIntegerObject(), DBType.INTEGER); - typeMap.put(EcorePackage.eINSTANCE.getELongObject(), DBType.BIGINT); - typeMap.put(EcorePackage.eINSTANCE.getEShortObject(), DBType.SMALLINT); - } + private MetaDataManager metaDataManager; public DBStore() { @@ -210,36 +173,7 @@ public class DBStore extends LongIDStore implements IDBStore return new DBStoreAccessor(this, transaction); } - /** @deprecated move to meta manager */ - @Deprecated - public long getMetaID(EModelElement modelElement) - { - InternalCDOPackageRegistry packageRegistry = (InternalCDOPackageRegistry)getRepository().getPackageRegistry(); - - try - { - CDOID cdoid = packageRegistry.getMetaInstanceMapper().lookupMetaInstanceID((InternalEObject)modelElement); - return ((CDOIDMeta)cdoid).getLongValue(); - } - catch (RuntimeException ex) - { - packageRegistry.getMetaInstanceMapper().lookupMetaInstanceID((InternalEObject)modelElement); - throw ex; - } - } - - /** @deprecated move to meta manager */ - @Deprecated - public EModelElement getMetaInstance(long id) - { - CDOIDMeta cdoid = CDOIDUtil.createMeta(id); - InternalCDOPackageRegistry packageRegistry = (InternalCDOPackageRegistry)getRepository().getPackageRegistry(); - InternalEObject metaInstance = packageRegistry.getMetaInstanceMapper().lookupMetaInstance(cdoid); - return (EModelElement)metaInstance; - } - - @Deprecated - public Connection getConnection() + protected Connection getConnection() { Connection connection = dbConnectionProvider.getConnection(); if (connection == null) @@ -273,9 +207,12 @@ public class DBStore extends LongIDStore implements IDBStore protected void doActivate() throws Exception { super.doActivate(); + + metaDataManager = new MetaDataManager(this); + ((ILifecycle)metaDataManager).activate(); + Connection connection = getConnection(); - // TODO move to meta manager? try { Set<IDBTable> createdTables = CDODBSchema.INSTANCE.create(dbAdapter, connection); @@ -290,6 +227,8 @@ public class DBStore extends LongIDStore implements IDBStore LifecycleUtil.activate(mappingStrategy); dbSchema = createSchema(); + + connection.commit(); } finally { @@ -302,7 +241,6 @@ public class DBStore extends LongIDStore implements IDBStore creationTime = getStartupTime(); firstTime = true; - // TODO: unify and standardize repository management DBUtil.insertRow(connection, dbAdapter, CDODBSchema.REPOSITORY, creationTime, 1, creationTime, 0, CRASHED, CRASHED); OM.LOG.info(MessageFormat.format("First start: {0,date} {0,time}", creationTime)); } @@ -361,6 +299,9 @@ public class DBStore extends LongIDStore implements IDBStore { Connection connection = null; + ((ILifecycle)metaDataManager).deactivate(); + metaDataManager = null; + try { connection = getConnection(); @@ -390,6 +331,8 @@ public class DBStore extends LongIDStore implements IDBStore { throw new DBException("No row updated in table " + CDODBSchema.REPOSITORY); } + + connection.commit(); } finally { @@ -417,28 +360,8 @@ public class DBStore extends LongIDStore implements IDBStore return System.currentTimeMillis(); } - /** - * @deprecated move to meta-manager - */ - @Deprecated - public static DBType getDBType(EClassifier type) + public IMetaDataManager getMetaDataManager() { - if (type instanceof EClass) - { - return DBType.BIGINT; - } - - if (type instanceof EEnum) - { - return DBType.INTEGER; - } - - DBType dbType = typeMap.get(type); - if (dbType != null) - { - return dbType; - } - - return DBType.VARCHAR; + return metaDataManager; } } diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStoreAccessor.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStoreAccessor.java index dcdeecd..808bd0b 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStoreAccessor.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/DBStoreAccessor.java @@ -13,14 +13,8 @@ package org.eclipse.emf.cdo.server.internal.db; import org.eclipse.emf.cdo.common.CDOQueryInfo; import org.eclipse.emf.cdo.common.id.CDOID; -import org.eclipse.emf.cdo.common.id.CDOIDMeta; -import org.eclipse.emf.cdo.common.id.CDOIDMetaRange; -import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.common.model.CDOClassifierRef; -import org.eclipse.emf.cdo.common.model.CDOModelUtil; import org.eclipse.emf.cdo.common.model.CDOPackageRegistry; -import org.eclipse.emf.cdo.common.model.CDOPackageUnit; -import org.eclipse.emf.cdo.common.model.EMFUtil; import org.eclipse.emf.cdo.common.revision.CDORevisionUtil; import org.eclipse.emf.cdo.server.IQueryContext; import org.eclipse.emf.cdo.server.IRepository; @@ -32,7 +26,6 @@ import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; import org.eclipse.emf.cdo.server.db.mapping.IClassMapping; import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy; import org.eclipse.emf.cdo.server.internal.db.bundle.OM; -import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo; import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevisionDelta; @@ -40,8 +33,6 @@ import org.eclipse.emf.cdo.spi.server.LongIDStoreAccessor; import org.eclipse.net4j.db.DBException; import org.eclipse.net4j.db.DBUtil; -import org.eclipse.net4j.db.IDBRowHandler; -import org.eclipse.net4j.db.ddl.IDBTable; import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; import org.eclipse.net4j.util.collection.CloseableIterator; import org.eclipse.net4j.util.om.monitor.OMMonitor; @@ -57,14 +48,7 @@ import org.eclipse.emf.ecore.EStructuralFeature; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; /** * @author Eike Stepper @@ -73,10 +57,6 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce { private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, DBStoreAccessor.class); - /** @deprecated move to meta manager */ - @Deprecated - private static final boolean ZIP_PACKAGE_BYTES = true; - private Connection connection = null; @ExcludeFromDump @@ -121,85 +101,6 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce } /** - * @deprecated move to meta manager - */ - @Deprecated - public final Collection<InternalCDOPackageUnit> readPackageUnits() - { - final Map<String, InternalCDOPackageUnit> packageUnits = new HashMap<String, InternalCDOPackageUnit>(); - IDBRowHandler unitRowHandler = new IDBRowHandler() - { - public boolean handle(int row, final Object... values) - { - InternalCDOPackageUnit packageUnit = createPackageUnit(); - packageUnit.setOriginalType(CDOPackageUnit.Type.values()[(Integer)values[1]]); - packageUnit.setTimeStamp((Long)values[2]); - packageUnits.put((String)values[0], packageUnit); - return true; - } - }; - - DBUtil.select(getConnection(), unitRowHandler, CDODBSchema.PACKAGE_UNITS_ID, - CDODBSchema.PACKAGE_UNITS_ORIGINAL_TYPE, CDODBSchema.PACKAGE_UNITS_TIME_STAMP); - - final Map<String, List<InternalCDOPackageInfo>> packageInfos = new HashMap<String, List<InternalCDOPackageInfo>>(); - IDBRowHandler infoRowHandler = new IDBRowHandler() - { - public boolean handle(int row, final Object... values) - { - long metaLB = (Long)values[3]; - long metaUB = (Long)values[4]; - CDOIDMetaRange metaIDRange = metaLB == 0 ? null : CDOIDUtil.createMetaRange(CDOIDUtil.createMeta(metaLB), - (int)(metaUB - metaLB) + 1); - - InternalCDOPackageInfo packageInfo = createPackageInfo(); - packageInfo.setPackageURI((String)values[1]); - packageInfo.setParentURI((String)values[2]); - packageInfo.setMetaIDRange(metaIDRange); - - String unit = (String)values[0]; - List<InternalCDOPackageInfo> list = packageInfos.get(unit); - if (list == null) - { - list = new ArrayList<InternalCDOPackageInfo>(); - packageInfos.put(unit, list); - } - - list.add(packageInfo); - return true; - } - }; - - DBUtil.select(getConnection(), infoRowHandler, CDODBSchema.PACKAGE_INFOS_UNIT, CDODBSchema.PACKAGE_INFOS_URI, - CDODBSchema.PACKAGE_INFOS_PARENT, CDODBSchema.PACKAGE_INFOS_META_LB, CDODBSchema.PACKAGE_INFOS_META_UB); - - for (Entry<String, InternalCDOPackageUnit> entry : packageUnits.entrySet()) - { - String id = entry.getKey(); - InternalCDOPackageUnit packageUnit = entry.getValue(); - - List<InternalCDOPackageInfo> list = packageInfos.get(id); - InternalCDOPackageInfo[] array = list.toArray(new InternalCDOPackageInfo[list.size()]); - packageUnit.setPackageInfos(array); - } - - return packageUnits.values(); - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - public final EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit) - { - String where = CDODBSchema.PACKAGE_UNITS_ID.getName() + "='" + packageUnit.getID() + "'"; - Object[] values = DBUtil.select(getConnection(), where, CDODBSchema.PACKAGE_UNITS_PACKAGE_DATA); - byte[] bytes = (byte[])values[0]; - EPackage ePackage = createEPackage(packageUnit, bytes); - return EMFUtil.getAllPackages(ePackage); - } - - /** * TODO caching? */ public CloseableIterator<CDOID> readObjectIDs() @@ -347,104 +248,6 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce } /** - * @deprecated move to meta manager - */ - @Deprecated - public final void writePackageUnits(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) - { - try - { - monitor.begin(2); - fillSystemTables(packageUnits, monitor.fork()); - createModelTables(packageUnits, monitor.fork()); - } - finally - { - monitor.done(); - } - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - private void fillSystemTables(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) - { - try - { - monitor.begin(packageUnits.length); - for (InternalCDOPackageUnit packageUnit : packageUnits) - { - fillSystemTables(packageUnit, monitor.fork()); - } - } - finally - { - monitor.done(); - } - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - private void fillSystemTables(InternalCDOPackageUnit packageUnit, OMMonitor monitor) - { - try - { - InternalCDOPackageInfo[] packageInfos = packageUnit.getPackageInfos(); - monitor.begin(1 + packageInfos.length); - - if (TRACER.isEnabled()) - { - TRACER.format("Writing package unit: {0}", packageUnit); - } - - String sql = "INSERT INTO " + CDODBSchema.PACKAGE_UNITS + " VALUES (?, ?, ?, ?)"; - DBUtil.trace(sql); - PreparedStatement pstmt = null; - Async async = monitor.forkAsync(); - - try - { - pstmt = getPreparedStatement(sql); - pstmt.setString(1, packageUnit.getID()); - pstmt.setInt(2, packageUnit.getOriginalType().ordinal()); - pstmt.setLong(3, packageUnit.getTimeStamp()); - pstmt.setBytes(4, getEPackageBytes(packageUnit)); - - if (pstmt.execute()) - { - throw new DBException("No result set expected"); - } - - if (pstmt.getUpdateCount() == 0) - { - throw new DBException("No row inserted into table " + CDODBSchema.PACKAGE_UNITS); - } - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - DBUtil.close(pstmt); - async.stop(); - } - - for (InternalCDOPackageInfo packageInfo : packageInfos) - { - fillSystemTables(packageInfo, monitor); // Don't fork monitor - } - } - finally - { - monitor.done(); - } - } - - /** * TODO - inline statement preparing to simplify handling */ private PreparedStatement getPreparedStatement(String sql) throws SQLException @@ -452,101 +255,6 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce return getConnection().prepareStatement(sql); } - /** - * @deprecated move to meta manager - */ - @Deprecated - private byte[] getEPackageBytes(InternalCDOPackageUnit packageUnit) - { - EPackage ePackage = packageUnit.getTopLevelPackageInfo().getEPackage(); - CDOPackageRegistry packageRegistry = getStore().getRepository().getPackageRegistry(); - return EMFUtil.getEPackageBytes(ePackage, ZIP_PACKAGE_BYTES, packageRegistry); - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - private EPackage createEPackage(InternalCDOPackageUnit packageUnit, byte[] bytes) - { - CDOPackageRegistry packageRegistry = getStore().getRepository().getPackageRegistry(); - return EMFUtil.createEPackage(packageUnit.getID(), bytes, ZIP_PACKAGE_BYTES, packageRegistry); - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - private void fillSystemTables(InternalCDOPackageInfo packageInfo, OMMonitor monitor) - { - if (TRACER.isEnabled()) - { - TRACER.format("Writing package info: {0}", packageInfo); - } - - String packageURI = packageInfo.getPackageURI(); - String parentURI = packageInfo.getParentURI(); - String unitID = packageInfo.getPackageUnit().getID(); - CDOIDMetaRange metaIDRange = packageInfo.getMetaIDRange(); - long metaLB = metaIDRange == null ? 0L : ((CDOIDMeta)metaIDRange.getLowerBound()).getLongValue(); - long metaUB = metaIDRange == null ? 0L : ((CDOIDMeta)metaIDRange.getUpperBound()).getLongValue(); - - String sql = "INSERT INTO " + CDODBSchema.PACKAGE_INFOS + " VALUES (?, ?, ?, ?, ?)"; - DBUtil.trace(sql); - PreparedStatement pstmt = null; - Async async = monitor.forkAsync(); - - try - { - pstmt = getPreparedStatement(sql); - pstmt.setString(1, packageURI); - pstmt.setString(2, parentURI); - pstmt.setString(3, unitID); - pstmt.setLong(4, metaLB); - pstmt.setLong(5, metaUB); - - if (pstmt.execute()) - { - throw new DBException("No result set expected"); - } - - if (pstmt.getUpdateCount() == 0) - { - throw new DBException("No row inserted into table " + CDODBSchema.PACKAGE_INFOS); - } - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - DBUtil.close(pstmt); - async.stop(); - } - } - - /** - * @deprecated move to meta manager - */ - @Deprecated - private void createModelTables(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) - { - monitor.begin(); - Async async = monitor.forkAsync(); - - try - { - Set<IDBTable> affectedTables = mapPackageUnits(packageUnits); - getStore().getDBAdapter().createTables(affectedTables, getConnection()); - } - finally - { - async.stop(); - monitor.done(); - } - } - @Override protected void writeRevisionDeltas(InternalCDORevisionDelta[] revisionDeltas, long created, OMMonitor monitor) { @@ -663,73 +371,6 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce throw new IllegalArgumentException("Not a boolean value: " + value); } - /** @deprecated move to meta manager */ - @Deprecated - protected Set<IDBTable> mapPackageUnits(InternalCDOPackageUnit[] packageUnits) - { - Set<IDBTable> affectedTables = new HashSet<IDBTable>(); - if (packageUnits != null && packageUnits.length != 0) - { - for (InternalCDOPackageUnit packageUnit : packageUnits) - { - mapPackageInfos(packageUnit.getPackageInfos(), affectedTables); - } - } - - return affectedTables; - } - - /** @deprecated move to meta manager */ - @Deprecated - protected void mapPackageInfos(InternalCDOPackageInfo[] packageInfos, Set<IDBTable> affectedTables) - { - for (InternalCDOPackageInfo packageInfo : packageInfos) - { - EPackage ePackage = packageInfo.getEPackage(); - if (!CDOModelUtil.isCorePackage(ePackage)) - { - EClass[] persistentClasses = EMFUtil.getPersistentClasses(ePackage); - Set<IDBTable> tables = mapClasses(persistentClasses); - affectedTables.addAll(tables); - } - } - } - - /** @deprecated move to meta manager */ - @Deprecated - protected Set<IDBTable> mapClasses(EClass... eClasses) - { - Set<IDBTable> affectedTables = new HashSet<IDBTable>(); - if (eClasses != null && eClasses.length != 0) - { - IMappingStrategy mappingStrategy = getStore().getMappingStrategy(); - for (EClass eClass : eClasses) - { - IClassMapping mapping = mappingStrategy.getClassMapping(eClass); - if (mapping != null) - { - affectedTables.addAll(mapping.getAffectedTables()); - } - } - } - - return affectedTables; - } - - /** @deprecated move to meta manager */ - @Deprecated - protected InternalCDOPackageUnit createPackageUnit() - { - return (InternalCDOPackageUnit)CDOModelUtil.createPackageUnit(); - } - - /** @deprecated move to meta manager */ - @Deprecated - protected InternalCDOPackageInfo createPackageInfo() - { - return (InternalCDOPackageInfo)CDOModelUtil.createPackageInfo(); - } - public Connection getConnection() { return connection; @@ -792,4 +433,19 @@ public class DBStoreAccessor extends LongIDStoreAccessor implements IDBStoreAcce { // TODO Check if connection is still valid. } + + public EPackage[] loadPackageUnit(InternalCDOPackageUnit packageUnit) + { + return getStore().getMetaDataManager().loadPackageUnit(getConnection(), packageUnit); + } + + public Collection<InternalCDOPackageUnit> readPackageUnits() + { + return getStore().getMetaDataManager().readPackageUnits(getConnection()); + } + + public void writePackageUnits(InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + getStore().getMetaDataManager().writePackageUnits(getConnection(), packageUnits, monitor); + } } diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/MetaDataManager.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/MetaDataManager.java new file mode 100644 index 0000000..015ae4b --- /dev/null +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/MetaDataManager.java @@ -0,0 +1,453 @@ +/** + * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + * Stefan Winkler - major refactoring + */ +package org.eclipse.emf.cdo.server.internal.db; + +import org.eclipse.emf.cdo.common.id.CDOID; +import org.eclipse.emf.cdo.common.id.CDOIDMeta; +import org.eclipse.emf.cdo.common.id.CDOIDMetaRange; +import org.eclipse.emf.cdo.common.id.CDOIDUtil; +import org.eclipse.emf.cdo.common.model.CDOModelUtil; +import org.eclipse.emf.cdo.common.model.CDOPackageRegistry; +import org.eclipse.emf.cdo.common.model.CDOPackageUnit; +import org.eclipse.emf.cdo.common.model.EMFUtil; +import org.eclipse.emf.cdo.server.db.IDBStore; +import org.eclipse.emf.cdo.server.db.IMetaDataManager; +import org.eclipse.emf.cdo.server.db.mapping.IClassMapping; +import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy; +import org.eclipse.emf.cdo.server.internal.db.bundle.OM; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageInfo; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageRegistry; +import org.eclipse.emf.cdo.spi.common.model.InternalCDOPackageUnit; + +import org.eclipse.net4j.db.DBException; +import org.eclipse.net4j.db.DBType; +import org.eclipse.net4j.db.DBUtil; +import org.eclipse.net4j.db.IDBRowHandler; +import org.eclipse.net4j.db.ddl.IDBTable; +import org.eclipse.net4j.util.lifecycle.Lifecycle; +import org.eclipse.net4j.util.om.monitor.OMMonitor; +import org.eclipse.net4j.util.om.monitor.OMMonitor.Async; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EModelElement; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EcorePackage; +import org.eclipse.emf.ecore.InternalEObject; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; + +/** + * @author Eike Stepper + * @author Stefan Winkler + */ +public class MetaDataManager extends Lifecycle implements IMetaDataManager +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, MetaDataManager.class); + + private static Map<EClassifier, DBType> typeMap = new HashMap<EClassifier, DBType>(); + + private static final boolean ZIP_PACKAGE_BYTES = true; + + public MetaDataManager(IDBStore store) + { + this.store = store; + } + + static + { + typeMap.put(EcorePackage.eINSTANCE.getEDate(), DBType.TIMESTAMP); + typeMap.put(EcorePackage.eINSTANCE.getEString(), DBType.VARCHAR); + + typeMap.put(EcorePackage.eINSTANCE.getEBoolean(), DBType.BOOLEAN); + typeMap.put(EcorePackage.eINSTANCE.getEByte(), DBType.SMALLINT); + typeMap.put(EcorePackage.eINSTANCE.getEChar(), DBType.CHAR); + typeMap.put(EcorePackage.eINSTANCE.getEDouble(), DBType.DOUBLE); + typeMap.put(EcorePackage.eINSTANCE.getEFloat(), DBType.FLOAT); + typeMap.put(EcorePackage.eINSTANCE.getEInt(), DBType.INTEGER); + typeMap.put(EcorePackage.eINSTANCE.getELong(), DBType.BIGINT); + typeMap.put(EcorePackage.eINSTANCE.getEShort(), DBType.SMALLINT); + + typeMap.put(EcorePackage.eINSTANCE.getEBooleanObject(), DBType.BOOLEAN); + typeMap.put(EcorePackage.eINSTANCE.getEByteObject(), DBType.SMALLINT); + typeMap.put(EcorePackage.eINSTANCE.getECharacterObject(), DBType.CHAR); + typeMap.put(EcorePackage.eINSTANCE.getEDoubleObject(), DBType.DOUBLE); + typeMap.put(EcorePackage.eINSTANCE.getEFloatObject(), DBType.FLOAT); + typeMap.put(EcorePackage.eINSTANCE.getEIntegerObject(), DBType.INTEGER); + typeMap.put(EcorePackage.eINSTANCE.getELongObject(), DBType.BIGINT); + typeMap.put(EcorePackage.eINSTANCE.getEShortObject(), DBType.SMALLINT); + } + + private IDBStore store; + + private InternalCDOPackageRegistry getPackageRegistry() + { + return (InternalCDOPackageRegistry)store.getRepository().getPackageRegistry(); + } + + public long getMetaID(EModelElement modelElement) + { + CDOID cdoid = getPackageRegistry().getMetaInstanceMapper().lookupMetaInstanceID((InternalEObject)modelElement); + return CDOIDUtil.getLong(cdoid); + } + + public EModelElement getMetaInstance(long id) + { + CDOIDMeta cdoid = CDOIDUtil.createMeta(id); + InternalEObject metaInstance = getPackageRegistry().getMetaInstanceMapper().lookupMetaInstance(cdoid); + return (EModelElement)metaInstance; + } + + private EPackage createEPackage(InternalCDOPackageUnit packageUnit, byte[] bytes) + { + return EMFUtil.createEPackage(packageUnit.getID(), bytes, ZIP_PACKAGE_BYTES, getPackageRegistry()); + } + + private void createModelTables(Connection connection, InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + monitor.begin(); + Async async = monitor.forkAsync(); + + try + { + Set<IDBTable> affectedTables = mapPackageUnits(packageUnits); + getStore().getDBAdapter().createTables(affectedTables, connection); + } + finally + { + async.stop(); + monitor.done(); + } + } + + protected InternalCDOPackageInfo createPackageInfo() + { + return (InternalCDOPackageInfo)CDOModelUtil.createPackageInfo(); + } + + protected InternalCDOPackageUnit createPackageUnit() + { + return (InternalCDOPackageUnit)CDOModelUtil.createPackageUnit(); + } + + private byte[] getEPackageBytes(InternalCDOPackageUnit packageUnit) + { + EPackage ePackage = packageUnit.getTopLevelPackageInfo().getEPackage(); + CDOPackageRegistry packageRegistry = getStore().getRepository().getPackageRegistry(); + return EMFUtil.getEPackageBytes(ePackage, ZIP_PACKAGE_BYTES, packageRegistry); + } + + public final EPackage[] loadPackageUnit(Connection connection, InternalCDOPackageUnit packageUnit) + { + String where = CDODBSchema.PACKAGE_UNITS_ID.getName() + "='" + packageUnit.getID() + "'"; + Object[] values = DBUtil.select(connection, where, CDODBSchema.PACKAGE_UNITS_PACKAGE_DATA); + byte[] bytes = (byte[])values[0]; + EPackage ePackage = createEPackage(packageUnit, bytes); + return EMFUtil.getAllPackages(ePackage); + } + + protected void mapPackageInfos(InternalCDOPackageInfo[] packageInfos, Set<IDBTable> affectedTables) + { + for (InternalCDOPackageInfo packageInfo : packageInfos) + { + EPackage ePackage = packageInfo.getEPackage(); + if (!CDOModelUtil.isCorePackage(ePackage)) + { + EClass[] persistentClasses = EMFUtil.getPersistentClasses(ePackage); + Set<IDBTable> tables = mapClasses(persistentClasses); + affectedTables.addAll(tables); + } + } + } + + protected Set<IDBTable> mapClasses(EClass... eClasses) + { + Set<IDBTable> affectedTables = new HashSet<IDBTable>(); + if (eClasses != null && eClasses.length != 0) + { + IMappingStrategy mappingStrategy = getStore().getMappingStrategy(); + for (EClass eClass : eClasses) + { + IClassMapping mapping = mappingStrategy.getClassMapping(eClass); + if (mapping != null) + { + affectedTables.addAll(mapping.getAffectedTables()); + } + } + } + + return affectedTables; + } + + protected Set<IDBTable> mapPackageUnits(InternalCDOPackageUnit[] packageUnits) + { + Set<IDBTable> affectedTables = new HashSet<IDBTable>(); + if (packageUnits != null && packageUnits.length != 0) + { + for (InternalCDOPackageUnit packageUnit : packageUnits) + { + mapPackageInfos(packageUnit.getPackageInfos(), affectedTables); + } + } + + return affectedTables; + } + + public Collection<InternalCDOPackageUnit> readPackageUnits(Connection connection) + { + final Map<String, InternalCDOPackageUnit> packageUnits = new HashMap<String, InternalCDOPackageUnit>(); + IDBRowHandler unitRowHandler = new IDBRowHandler() + { + public boolean handle(int row, final Object... values) + { + InternalCDOPackageUnit packageUnit = createPackageUnit(); + packageUnit.setOriginalType(CDOPackageUnit.Type.values()[(Integer)values[1]]); + packageUnit.setTimeStamp((Long)values[2]); + packageUnits.put((String)values[0], packageUnit); + return true; + } + }; + + DBUtil.select(connection, unitRowHandler, CDODBSchema.PACKAGE_UNITS_ID, CDODBSchema.PACKAGE_UNITS_ORIGINAL_TYPE, + CDODBSchema.PACKAGE_UNITS_TIME_STAMP); + + final Map<String, List<InternalCDOPackageInfo>> packageInfos = new HashMap<String, List<InternalCDOPackageInfo>>(); + IDBRowHandler infoRowHandler = new IDBRowHandler() + { + public boolean handle(int row, final Object... values) + { + long metaLB = (Long)values[3]; + long metaUB = (Long)values[4]; + CDOIDMetaRange metaIDRange = metaLB == 0 ? null : CDOIDUtil.createMetaRange(CDOIDUtil.createMeta(metaLB), + (int)(metaUB - metaLB) + 1); + + InternalCDOPackageInfo packageInfo = createPackageInfo(); + packageInfo.setPackageURI((String)values[1]); + packageInfo.setParentURI((String)values[2]); + packageInfo.setMetaIDRange(metaIDRange); + + String unit = (String)values[0]; + List<InternalCDOPackageInfo> list = packageInfos.get(unit); + if (list == null) + { + list = new ArrayList<InternalCDOPackageInfo>(); + packageInfos.put(unit, list); + } + + list.add(packageInfo); + return true; + } + }; + + DBUtil.select(connection, infoRowHandler, CDODBSchema.PACKAGE_INFOS_UNIT, CDODBSchema.PACKAGE_INFOS_URI, + CDODBSchema.PACKAGE_INFOS_PARENT, CDODBSchema.PACKAGE_INFOS_META_LB, CDODBSchema.PACKAGE_INFOS_META_UB); + + for (Entry<String, InternalCDOPackageUnit> entry : packageUnits.entrySet()) + { + String id = entry.getKey(); + InternalCDOPackageUnit packageUnit = entry.getValue(); + + List<InternalCDOPackageInfo> list = packageInfos.get(id); + InternalCDOPackageInfo[] array = list.toArray(new InternalCDOPackageInfo[list.size()]); + packageUnit.setPackageInfos(array); + } + + return packageUnits.values(); + } + + public final void writePackageUnits(Connection connection, InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + try + { + monitor.begin(2); + fillSystemTables(connection, packageUnits, monitor.fork()); + createModelTables(connection, packageUnits, monitor.fork()); + } + finally + { + monitor.done(); + } + } + + private void fillSystemTables(Connection connection, InternalCDOPackageUnit packageUnit, OMMonitor monitor) + { + try + { + InternalCDOPackageInfo[] packageInfos = packageUnit.getPackageInfos(); + monitor.begin(1 + packageInfos.length); + + if (TRACER.isEnabled()) + { + TRACER.format("Writing package unit: {0}", packageUnit); + } + + String sql = "INSERT INTO " + CDODBSchema.PACKAGE_UNITS + " VALUES (?, ?, ?, ?)"; + DBUtil.trace(sql); + PreparedStatement pstmt = null; + Async async = monitor.forkAsync(); + + try + { + pstmt = connection.prepareStatement(sql); + pstmt.setString(1, packageUnit.getID()); + pstmt.setInt(2, packageUnit.getOriginalType().ordinal()); + pstmt.setLong(3, packageUnit.getTimeStamp()); + pstmt.setBytes(4, getEPackageBytes(packageUnit)); + + if (pstmt.execute()) + { + throw new DBException("No result set expected"); + } + + if (pstmt.getUpdateCount() == 0) + { + throw new DBException("No row inserted into table " + CDODBSchema.PACKAGE_UNITS); + } + } + catch (SQLException ex) + { + throw new DBException(ex); + } + finally + { + DBUtil.close(pstmt); + async.stop(); + } + + for (InternalCDOPackageInfo packageInfo : packageInfos) + { + fillSystemTables(connection, packageInfo, monitor); // Don't fork monitor + } + } + finally + { + monitor.done(); + } + } + + /** + * @deprecated move to meta manager + */ + @Deprecated + private void fillSystemTables(Connection connection, InternalCDOPackageUnit[] packageUnits, OMMonitor monitor) + { + try + { + monitor.begin(packageUnits.length); + for (InternalCDOPackageUnit packageUnit : packageUnits) + { + fillSystemTables(connection, packageUnit, monitor.fork()); + } + } + finally + { + monitor.done(); + } + } + + /** + * @deprecated move to meta manager + */ + @Deprecated + private void fillSystemTables(Connection connection, InternalCDOPackageInfo packageInfo, OMMonitor monitor) + { + if (TRACER.isEnabled()) + { + TRACER.format("Writing package info: {0}", packageInfo); + } + + String packageURI = packageInfo.getPackageURI(); + String parentURI = packageInfo.getParentURI(); + String unitID = packageInfo.getPackageUnit().getID(); + CDOIDMetaRange metaIDRange = packageInfo.getMetaIDRange(); + long metaLB = metaIDRange == null ? 0L : ((CDOIDMeta)metaIDRange.getLowerBound()).getLongValue(); + long metaUB = metaIDRange == null ? 0L : ((CDOIDMeta)metaIDRange.getUpperBound()).getLongValue(); + + String sql = "INSERT INTO " + CDODBSchema.PACKAGE_INFOS + " VALUES (?, ?, ?, ?, ?)"; + DBUtil.trace(sql); + PreparedStatement pstmt = null; + Async async = monitor.forkAsync(); + + try + { + pstmt = connection.prepareStatement(sql); + pstmt.setString(1, packageURI); + pstmt.setString(2, parentURI); + pstmt.setString(3, unitID); + pstmt.setLong(4, metaLB); + pstmt.setLong(5, metaUB); + + if (pstmt.execute()) + { + throw new DBException("No result set expected"); + } + + if (pstmt.getUpdateCount() == 0) + { + throw new DBException("No row inserted into table " + CDODBSchema.PACKAGE_INFOS); + } + } + catch (SQLException ex) + { + throw new DBException(ex); + } + finally + { + DBUtil.close(pstmt); + async.stop(); + } + } + + public DBType getDBType(EClassifier type) + { + if (type instanceof EClass) + { + return DBType.BIGINT; + } + + if (type instanceof EEnum) + { + return DBType.INTEGER; + } + + DBType dbType = typeMap.get(type); + if (dbType != null) + { + return dbType; + } + + return DBType.VARCHAR; + } + + protected IDBStore getStore() + { + return store; + } + + @Override + protected void doBeforeActivate() throws Exception + { + checkState(store != null, "Store is not set"); + } +} diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/ObjectTypeCache.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/ObjectTypeCache.java index 8b6194e..dcb8d58 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/ObjectTypeCache.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/ObjectTypeCache.java @@ -16,6 +16,7 @@ import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.common.model.CDOClassifierRef; import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; +import org.eclipse.emf.cdo.server.db.IMetaDataManager; import org.eclipse.emf.cdo.server.db.IObjectTypeCache; import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy; @@ -58,6 +59,8 @@ public class ObjectTypeCache extends Lifecycle implements IObjectTypeCache private String sqlSelect; + private IMetaDataManager metaDataManager; + public ObjectTypeCache() { } @@ -93,7 +96,7 @@ public class ObjectTypeCache extends Lifecycle implements IObjectTypeCache } long classID = resultSet.getLong(1); - EClass eClass = (EClass)mappingStrategy.getStore().getMetaInstance(classID); + EClass eClass = (EClass)metaDataManager.getMetaInstance(classID); return new CDOClassifierRef(eClass); } catch (SQLException ex) @@ -118,7 +121,7 @@ public class ObjectTypeCache extends Lifecycle implements IObjectTypeCache { stmt = connection.prepareStatement(sqlInsert); stmt.setLong(1, CDOIDUtil.getLong(id)); - stmt.setLong(2, accessor.getStore().getMetaID(type)); + stmt.setLong(2, metaDataManager.getMetaID(type)); DBUtil.trace(stmt.toString()); int result = stmt.executeUpdate(); @@ -216,6 +219,12 @@ public class ObjectTypeCache extends Lifecycle implements IObjectTypeCache } @Override + protected void doActivate() throws Exception + { + metaDataManager = getMappingStrategy().getStore().getMetaDataManager(); + } + + @Override protected void doDeactivate() throws Exception { table = null; diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/AbstractJDBCDelegate.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/AbstractJDBCDelegate.java deleted file mode 100644 index 06a656a..0000000 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/AbstractJDBCDelegate.java +++ /dev/null @@ -1,551 +0,0 @@ -/** - * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Stefan Winkler - initial API and implementation - * Eike Stepper - maintenance - * Stefan Winkler - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259402 - */ -package org.eclipse.emf.cdo.server.internal.db.jdbc; - -import org.eclipse.emf.cdo.common.id.CDOID; -import org.eclipse.emf.cdo.common.id.CDOIDUtil; -import org.eclipse.emf.cdo.common.revision.CDORevision; -import org.eclipse.emf.cdo.server.IStoreChunkReader.Chunk; -import org.eclipse.emf.cdo.server.db.CDODBUtil; -import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; -import org.eclipse.emf.cdo.server.db.IDBStoreChunkReader; -import org.eclipse.emf.cdo.server.db.mapping.IAttributeMapping; -import org.eclipse.emf.cdo.server.db.mapping.IClassMapping; -import org.eclipse.emf.cdo.server.db.mapping.IReferenceMapping; -import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; - -import org.eclipse.net4j.db.DBException; -import org.eclipse.net4j.db.DBUtil; -import org.eclipse.net4j.db.IDBConnectionProvider; -import org.eclipse.net4j.util.collection.MoveableList; -import org.eclipse.net4j.util.collection.Pair; -import org.eclipse.net4j.util.lifecycle.Lifecycle; -import org.eclipse.net4j.util.om.monitor.OMMonitor; -import org.eclipse.net4j.util.om.monitor.OMMonitor.Async; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * This abstract implementation of the {@link IJDBCDelegate} interface is used to translate CDO-related objects to base - * types (e.g. CDOIDs to long) and then to delegate the database execution part to the doXYZ methods which should be - * implemented by extenders. The purpose of this is to provide several JDBC strategies (e.g. simple or prepared - * statement database access) depending on the requirements, but a single point of interpreting and transforming - * CDO-internal structures. The JDBCDelegate also keeps open one database connection and one statement which can be used - * to perform operations on the database. Extenders may, but don't have to, use the statement to perform operations. - * - * @author Stefan Winkler - * @since 2.0 - */ -public abstract class AbstractJDBCDelegate extends Lifecycle -{ - private IDBStoreAccessor storeAccessor; - - private Connection connection; - - private Statement statement; - - public AbstractJDBCDelegate() - { - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - connection = getConnectionProvider().getConnection(); - connection.setAutoCommit(isReadOnly()); - } - - @Override - protected void doDeactivate() throws Exception - { - DBUtil.close(statement); - statement = null; - - DBUtil.close(connection); - connection = null; - - super.doDeactivate(); - } - - public IDBStoreAccessor getStoreAccessor() - { - return storeAccessor; - } - - public void setStoreAccessor(IDBStoreAccessor storeAccessor) - { - checkInactive(); - this.storeAccessor = storeAccessor; - } - - public IDBConnectionProvider getConnectionProvider() - { - return storeAccessor.getStore().getDBConnectionProvider(); - } - - public boolean isReadOnly() - { - return storeAccessor.isReader(); - } - - public Connection getConnection() - { - return connection; - } - - public final Statement getStatement() - { - if (statement == null) - { - try - { - statement = getConnection().createStatement(); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - } - - return statement; - } - - public PreparedStatement getPreparedStatement(String sql) - { - try - { - return getConnection().prepareStatement(sql); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - } - - public final void commit(OMMonitor monitor) - { - monitor.begin(); - Async async = monitor.forkAsync(); - - try - { - getConnection().commit(); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - async.stop(); - monitor.done(); - } - } - - public final void rollback() - { - try - { - getConnection().rollback(); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - } - - public final void insertAttributes(InternalCDORevision revision, IClassMapping classMapping) - { - doInsertAttributes(classMapping.getTable().getName(), revision, classMapping.getAttributeMappings(), classMapping - .hasFullRevisionInfo()); - } - - public final void updateAttributes(InternalCDORevision cdoRevision, IClassMapping classMapping) - { - InternalCDORevision revision = cdoRevision; - - List<IAttributeMapping> attributeMappings = classMapping.getAttributeMappings(); - if (attributeMappings == null) - { - attributeMappings = Collections.emptyList(); - } - - List<Pair<IAttributeMapping, Object>> attributeChanges = new ArrayList<Pair<IAttributeMapping, Object>>( - attributeMappings.size()); - - for (IAttributeMapping am : classMapping.getAttributeMappings()) - { - attributeChanges.add(new Pair<IAttributeMapping, Object>(am, am.getRevisionValue(revision))); - } - - updateAttributes(revision.getID(), revision.getVersion(), revision.getCreated(), (CDOID)revision.getContainerID(), - revision.getContainingFeatureID(), revision.getResourceID(), attributeChanges, classMapping); - } - - public void updateAttributes(CDOID id, int newVersion, long created, CDOID newContainerId, - int newContainingFeatureId, CDOID newResourceId, List<Pair<IAttributeMapping, Object>> attributeChanges, - IClassMapping classMapping) - { - doUpdateAttributes(classMapping.getTable().getName(), CDOIDUtil.getLong(id), newVersion, created, CDOIDUtil - .getLong(newContainerId), newContainingFeatureId, CDOIDUtil.getLong(newResourceId), attributeChanges, - classMapping.hasFullRevisionInfo()); - } - - public final void updateAttributes(CDOID id, int newVersion, long created, - List<Pair<IAttributeMapping, Object>> attributeChanges, IClassMapping classMapping) - { - doUpdateAttributes(classMapping.getTable().getName(), CDOIDUtil.getLong(id), newVersion, created, attributeChanges, - classMapping.hasFullRevisionInfo()); - } - - public final void updateRevisedForReplace(InternalCDORevision revision, IClassMapping classMapping) - { - doUpdateRevisedForReplace(classMapping.getTable().getName(), revision.getCreated() - 1, CDOIDUtil.getLong(revision - .getID()), revision.getVersion() - 1); - } - - public final void updateRevisedForDetach(CDOID id, long revised, IClassMapping classMapping) - { - doUpdateRevisedForDetach(classMapping.getTable().getName(), revised, CDOIDUtil.getLong(id)); - } - - public final void deleteAttributes(CDOID id, IClassMapping classMapping) - { - doDeleteAttributes(classMapping.getTable().getName(), CDOIDUtil.getLong(id)); - } - - public final void insertReference(CDOID id, int version, int index, CDOID targetId, IReferenceMapping referenceMapping) - { - doInsertReference(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id), version, - index, CDODBUtil.getLong(targetId)); - } - - public void insertReferenceRow(CDOID id, int newVersion, int index, CDOID value, IReferenceMapping referenceMapping) - { - doInsertReferenceRow(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id), - newVersion, CDODBUtil.getLong(value), index); - } - - public void moveReferenceRow(CDOID id, int newVersion, int oldPosition, int newPosition, - IReferenceMapping referenceMapping) - { - doMoveReferenceRow(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id), - newVersion, oldPosition, newPosition); - } - - public void removeReferenceRow(CDOID id, int index, int newVersion, IReferenceMapping referenceMapping) - { - doRemoveReferenceRow(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id), - index, newVersion); - } - - public final void deleteReferences(CDOID id, IReferenceMapping referenceMapping) - { - doDeleteReferences(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id)); - } - - public void updateReference(CDOID id, int version, int index, CDOID targetId, IReferenceMapping referenceMapping) - { - doUpdateReference(referenceMapping.getTable().getName(), getDBID(referenceMapping), CDOIDUtil.getLong(id), version, - index, CDODBUtil.getLong(targetId)); - } - - public final void updateReferenceVersion(CDOID id, int newVersion, IReferenceMapping referenceMapping) - { - doUpdateReferenceVersion(referenceMapping.getTable().getName(), CDOIDUtil.getLong(id), newVersion); - } - - public final boolean selectRevisionAttributes(InternalCDORevision revision, IClassMapping classMapping, String where) - { - List<IAttributeMapping> attributeMappings = classMapping.getAttributeMappings(); - if (attributeMappings == null) - { - attributeMappings = Collections.emptyList(); - } - - boolean withFullRevisionInfo = classMapping.hasFullRevisionInfo(); - ResultSet resultSet = null; - try - { - resultSet = doSelectRevisionAttributes(classMapping.getTable().getName(), CDOIDUtil.getLong(revision.getID()), - attributeMappings, withFullRevisionInfo, where); - - if (!resultSet.next()) - { - return false; - } - - int i = 0; - if (withFullRevisionInfo) - { - InternalCDORevision rev = revision; - rev.setVersion(resultSet.getInt(++i)); - rev.setCreated(resultSet.getLong(++i)); - rev.setRevised(resultSet.getLong(++i)); - rev.setResourceID(CDOIDUtil.createLong(resultSet.getLong(++i))); - rev.setContainerID(CDOIDUtil.createLong(resultSet.getLong(++i))); - rev.setContainingFeatureID(resultSet.getInt(++i)); - } - - if (attributeMappings != null) - { - for (IAttributeMapping attributeMapping : attributeMappings) - { - attributeMapping.extractValue(resultSet, ++i, revision); - } - } - - return true; - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - close(resultSet); - } - } - - public void selectRevisionReferences(InternalCDORevision revision, IReferenceMapping referenceMapping, - int referenceChunk) - { - MoveableList<Object> list = revision.getList(referenceMapping.getFeature()); - - CDOID source = revision.getID(); - long sourceId = CDOIDUtil.getLong(source); - int version = revision.getVersion(); - - ResultSet resultSet = null; - try - { - resultSet = doSelectRevisionReferences(referenceMapping.getTable().getName(), sourceId, version, - getDBID(referenceMapping), ""); - - while (resultSet.next() && (referenceChunk == CDORevision.UNCHUNKED || --referenceChunk >= 0)) - { - long target = resultSet.getLong(1); - list.add(CDOIDUtil.createLong(target)); - } - - // TODO Optimize this? - while (resultSet.next()) - { - list.add(InternalCDORevision.UNINITIALIZED); - } - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - close(resultSet); - } - } - - public void selectRevisionReferenceChunks(IDBStoreChunkReader chunkReader, List<Chunk> chunks, - IReferenceMapping referenceMapping, String where) - { - CDOID source = chunkReader.getRevision().getID(); - long sourceId = CDOIDUtil.getLong(source); - int version = chunkReader.getRevision().getVersion(); - - ResultSet resultSet = null; - - try - { - resultSet = doSelectRevisionReferences(referenceMapping.getTable().getName(), sourceId, version, - getDBID(referenceMapping), where); - - Chunk chunk = null; - int chunkSize = 0; - int chunkIndex = 0; - int indexInChunk = 0; - - while (resultSet.next()) - { - long target = resultSet.getLong(1); - if (chunk == null) - { - chunk = chunks.get(chunkIndex++); - chunkSize = chunk.size(); - } - - chunk.add(indexInChunk++, CDOIDUtil.createLong(target)); - if (indexInChunk == chunkSize) - { - chunk = null; - indexInChunk = 0; - } - } - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - close(resultSet); - } - } - - private long getDBID(IReferenceMapping referenceMapping) - { - if (referenceMapping.isWithFeature()) - { - return storeAccessor.getStore().getMetaID(referenceMapping.getFeature()); - } - - return 0; - } - - /** - * Close the given result set and the statement, if this is needed (which is the case, iff the resultSet's statement - * is not the one which is kept open by this instance). - */ - private void close(ResultSet resultSet) - { - Statement stmt = null; - - try - { - stmt = resultSet.getStatement(); - } - catch (Exception ex) - { - // Ignore - } - finally - { - DBUtil.close(resultSet); - } - - // if the statement is one that has been created for the operation only - // release it. - if (stmt != statement) - { - releaseStatement(stmt); - } - } - - /** - * Release a statement which has been used by the doSelectXxx implementations to create the respective ResultSet. This - * must only be called with statements created by subclasses. Subclasses should override to handle special cases like - * cached statements which are kept open. - * - * @param stmt - * the statement to close - */ - protected void releaseStatement(Statement stmt) - { - DBUtil.close(stmt); - } - - /** - * Insert an attribute row. - */ - protected abstract void doInsertAttributes(String tableName, CDORevision revision, - List<IAttributeMapping> attributeMappings, boolean withFullRevisionInfo); - - /** - * Update an attribute row. - */ - protected abstract void doUpdateAttributes(String name, long long1, int newVersion, long created, - List<Pair<IAttributeMapping, Object>> attributeChanges, boolean hasFullRevisionInfo); - - /** - * Update an attribute row including containment and resource attributes. - */ - protected abstract void doUpdateAttributes(String name, long long1, int newVersion, long created, - long newContainerId, int newContainingFeatureId, long newResourceId, - List<Pair<IAttributeMapping, Object>> attributeChanges, boolean hasFullRevisionInfo); - - /** - * Set the revised date of a cdoid (the cdoid is to be detached) - */ - protected abstract void doUpdateRevisedForDetach(String tableName, long revised, long cdoid); - - /** - * Set the revised date of a specific revision's previous version (the previous version is to be replaced). - */ - protected abstract void doUpdateRevisedForReplace(String tableName, long revisedStamp, long cdoid, int version); - - /** - * Delete an attribute row. - */ - protected abstract void doDeleteAttributes(String name, long cdoid1); - - /** - * Insert one reference of a particular CDOID and adjusts indexes. - */ - protected abstract void doInsertReferenceRow(String tableName, long metaID, long cdoid, int newVersion, long l, - int index); - - /** - * Insert a reference row. Note: this is likely to be replaced by an implementation that supports storing multiple - * references in one batch. - */ - protected abstract void doInsertReference(String tableName, long metaID, long source, int version, int i, long target); - - /** - * Update the target ID of one reference of a particular CDOID. - */ - protected abstract void doUpdateReference(String name, long metaID, long sourceId, int newVersion, int index, - long targetId); - - /** - * Moves one reference of a particular CDOID and adjusts indexes. - */ - protected abstract void doMoveReferenceRow(String tableName, long metaID, long cdoid, int newVersion, - int oldPosition, int newPosition); - - /** - * Delete all references of a particular CDOID. - */ - protected abstract void doDeleteReferences(String tableName, long metaID, long cdoid); - - /** - * Deletes one reference of a particular CDOID and adjusts indexes. - * - * @param newVersion - */ - protected abstract void doRemoveReferenceRow(String tableName, long metaID, long cdoid, int index, int newVersion); - - /** - * Update all references of cdoid to newVersion - */ - protected abstract void doUpdateReferenceVersion(String tableName, long cdoid, int newVersion); - - /** - * Select a revision's attributes. The caller is resposible for closing resultSet and associated statement, if - * appropriate. - */ - protected abstract ResultSet doSelectRevisionAttributes(String tableName, long revisionId, - List<IAttributeMapping> attributeMappings, boolean hasFullRevisionInfo, String where) throws SQLException; - - /** - * Select a revision's references (or a part thereof) The caller is resposible for closing resultSet and associated - * statement, if appropriate. - */ - abstract ResultSet doSelectRevisionReferences(String tableName, long sourceId, int version, long metaID, String where) - throws SQLException; -} diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/PreparedStatementJDBCDelegate.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/PreparedStatementJDBCDelegate.java deleted file mode 100644 index 72893bf..0000000 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/PreparedStatementJDBCDelegate.java +++ /dev/null @@ -1,1673 +0,0 @@ -/** - * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - * Stefan Winkler - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259402 - */ -package org.eclipse.emf.cdo.server.internal.db.jdbc; - -import org.eclipse.emf.cdo.common.id.CDOID; -import org.eclipse.emf.cdo.common.id.CDOIDUtil; -import org.eclipse.emf.cdo.common.revision.CDORevision; -import org.eclipse.emf.cdo.server.db.CDODBUtil; -import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; -import org.eclipse.emf.cdo.server.db.mapping.IAttributeMapping; -import org.eclipse.emf.cdo.server.internal.db.CDODBSchema; -import org.eclipse.emf.cdo.server.internal.db.bundle.OM; -import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; - -import org.eclipse.net4j.db.DBException; -import org.eclipse.net4j.db.DBUtil; -import org.eclipse.net4j.util.collection.Pair; -import org.eclipse.net4j.util.om.monitor.OMMonitor; -import org.eclipse.net4j.util.om.monitor.OMMonitor.Async; -import org.eclipse.net4j.util.om.trace.ContextTracer; -import org.eclipse.net4j.util.ref.ReferenceValueMap; - -import org.eclipse.emf.ecore.EEnumLiteral; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * @author Stefan Winkler - * @since 2.0 - */ -public class PreparedStatementJDBCDelegate extends AbstractJDBCDelegate -{ - @Override - public Connection getConnection() - { - return null; - } - - @Override - public IDBStoreAccessor getStoreAccessor() - { - return null; - } - - /** - * Value for {@link #cachingFlag}: Guess if caching is needed - */ - public static final String CACHE_STMTS_GUESS = "guess"; - - /** - * Value for {@link #cachingFlag}: Turn caching on - */ - public static final String CACHE_STMTS_TRUE = "true"; - - /** - * Value for {@link #cachingFlag}: Turn caching off - */ - public static final String CACHE_STMTS_FALSE = "false"; - - public static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, PreparedStatementJDBCDelegate.class); - - public static final String SQL_UPDATE_REVISE_VERSION = " SET " + CDODBSchema.ATTRIBUTES_REVISED + " = ? WHERE " - + CDODBSchema.ATTRIBUTES_ID + " = ? AND " + CDODBSchema.ATTRIBUTES_VERSION + " = ?"; - - public static final String SQL_UPDATE_REVISE_UNREVISED = " SET " + CDODBSchema.ATTRIBUTES_REVISED + " = ? WHERE " - + CDODBSchema.ATTRIBUTES_ID + " = ? AND " + CDODBSchema.ATTRIBUTES_REVISED + " = 0"; - - public static final String SQL_INSERT_REFERENCE_WITH_DBID = " VALUES (?, ?, ?, ?, ?)"; - - public static final String SQL_INSERT_REFERENCE = " VALUES (?, ?, ?, ?)"; - - /** - * Cache for preparedStatements used in diverse methods - */ - private Map<CacheKey, WrappedPreparedStatement> statementCache = null; - - /** - * Container for dirty statements. A statement is considered 'dirty', if addBatch was called, but not executeBatch. - */ - private Map<CacheKey, PreparedStatement> dirtyStatements = null; - - /** - * This flag determines, if prepared statements should be cached within this delegate. Its value is guessed in - * {@link #postInitConnection()} based on the fact if the JDBC driver supports pooled statements. If it does, caching - * in the delegate is unnecessary. - */ - private boolean cacheStatements; - - private CachingEnablement cachingEnablement; - - /** - * This statement is used for unprepared batched statements like in - * {@link #doUpdateAttributes(String, long, int, long, List, boolean)} - */ - private Statement miscStatement = null; - - public PreparedStatementJDBCDelegate() - { - } - - @Override - protected void doActivate() throws Exception - { - // super.doActivate(); - dirtyStatements = new ReferenceValueMap.Strong<CacheKey, PreparedStatement>(); - - switch (cachingEnablement) - { - case ENABLED: - cacheStatements = true; - break; - - case DISABLED: - cacheStatements = false; - break; - - case GUESS: - try - { - cacheStatements = !getConnection().getMetaData().supportsStatementPooling(); - } - catch (SQLException ex) - { - OM.LOG.warn("Failed to guess JDBC statement pooling. Activating cache, just to be sure ...", ex); - cacheStatements = true; - } - } - - if (TRACER.isEnabled()) - { - TRACER.trace("JDBC PreparedStatement caching is " + (cacheStatements ? "enabled." : "NOT enabled.")); - } - - if (cacheStatements) - { - // initialize cache ... - statementCache = new ReferenceValueMap.Soft<CacheKey, WrappedPreparedStatement>(); - } - } - - @Override - protected void doBeforeDeactivate() throws Exception - { - for (PreparedStatement ps : dirtyStatements.values()) - { - DBUtil.close(ps); - } - - dirtyStatements.clear(); - if (cacheStatements) - { - for (WrappedPreparedStatement ps : statementCache.values()) - { - DBUtil.close(ps.getWrappedStatement()); - } - - statementCache.clear(); - } - - // super.doBeforeDeactivate(); - } - - public CachingEnablement getCachingEnablement() - { - return cachingEnablement; - } - - public void setCachingEnablement(CachingEnablement cachingEnablement) - { - // checkInactive(); - this.cachingEnablement = cachingEnablement; - } - - public void flush(OMMonitor monitor) - { - try - { - monitor.begin(dirtyStatements.size() + 1); - - if (miscStatement != null) - { - Async async = monitor.forkAsync(); - try - { - int[] results = miscStatement.executeBatch(); - for (int result : results) - { - checkState(result == 1, "Batch of misc statements did not return '1'"); - } - } - catch (SQLException ex) - { - throw new DBException("Batch execution failed for misc statement.", ex); - } - finally - { - try - { - miscStatement.close(); - } - catch (SQLException ex) - { - // eat up ... - } - miscStatement = null; - async.stop(); - } - } - - for (Entry<CacheKey, PreparedStatement> entry : dirtyStatements.entrySet()) - { - try - { - int[] results; - Async async = monitor.forkAsync(); - - try - { - results = entry.getValue().executeBatch(); - } - finally - { - async.stop(); - } - - if (TRACER.isEnabled()) - { - TRACER.format("Executing batch for {0} [{1}]", entry.getKey().toString(), entry.getValue()); - } - - for (int result : results) - { - checkState(result != Statement.EXECUTE_FAILED, "Batch execution returned EXECUTE_FAILED!"); - } - } - catch (SQLException ex) - { - throw new DBException("Batch execution failed for " + entry.getKey().toString() + " [" + entry.getValue() - + "]", ex); - } - } - } - finally - { - if (!cacheStatements) - { - if (TRACER.isEnabled()) - { - TRACER.format("Closing prepared statements."); - } - - for (PreparedStatement ps : dirtyStatements.values()) - { - DBUtil.close(ps); - } - } - else - { - if (TRACER.isEnabled()) - { - TRACER.format("Re-caching prepared statements."); - } - - for (Entry<CacheKey, PreparedStatement> entry : dirtyStatements.entrySet()) - { - cacheStatement(entry.getKey(), entry.getValue()); - } - } - - dirtyStatements.clear(); - - monitor.done(); - } - } - - @Override - public void doInsertAttributes(String tableName, CDORevision rev, List<IAttributeMapping> attributeMappings, - boolean withFullRevisionInfo) - { - boolean firstBatch = false; - InternalCDORevision revision = (InternalCDORevision)rev; - - if (attributeMappings == null) - { - attributeMappings = Collections.emptyList(); - } - - PreparedStatement stmt = getDirtyStatement(StmtType.INSERT_ATTRIBUTES, tableName); - if (stmt == null && cacheStatements) - { - firstBatch = true; - stmt = getAndRemoveCachedStatement(StmtType.INSERT_ATTRIBUTES, tableName); - } - - try - { - firstBatch = true; - if (stmt == null) - { - StringBuilder sql = new StringBuilder(); - - sql.append("INSERT INTO "); - sql.append(tableName); - sql.append(" VALUES (?, ?, "); - if (withFullRevisionInfo) - { - sql.append("?, ?, ?, ?, ?, ?"); - } - - for (int i = 0; i < attributeMappings.size(); i++) - { - sql.append(", ?"); - } - - sql.append(")"); - stmt = getConnection().prepareStatement(sql.toString()); - } - - int col = 1; - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.setLong(col++, CDOIDUtil.getLong(revision.getID())); - stmt.setInt(col++, revision.getVersion()); - if (withFullRevisionInfo) - { - stmt.setLong(col++, getStoreAccessor().getStore().getMetaID(revision.getEClass())); - stmt.setLong(col++, revision.getCreated()); - stmt.setLong(col++, revision.getRevised()); - stmt.setLong(col++, CDOIDUtil.getLong(revision.getResourceID())); - stmt.setLong(col++, CDODBUtil.getLong((CDOID)revision.getContainerID())); - stmt.setInt(col++, revision.getContainingFeatureID()); - } - - for (IAttributeMapping attributeMapping : attributeMappings) - { - Object value = attributeMapping.getRevisionValue(revision); - - if (value == null) - { - stmt.setNull(col++, attributeMapping.getField().getType().getCode()); - } - else if (value instanceof java.util.Date) - { - // BUG 217255 - stmt.setTimestamp(col++, new Timestamp(((Date)value).getTime())); - } - else if (value instanceof EEnumLiteral) - { - stmt.setInt(col++, ((EEnumLiteral)value).getValue()); - } - else - { - stmt.setObject(col++, value); - } - } - - if (firstBatch) - { - addDirtyStatement(StmtType.INSERT_ATTRIBUTES, tableName, stmt); - } - - stmt.addBatch(); - } - catch (SQLException e) - { - throw new DBException(e); - } - } - - @Override - public void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created, - List<Pair<IAttributeMapping, Object>> attributeChanges, boolean hasFullRevisionInfo) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - builder.append(" = "); - builder.append(created); - - for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges) - { - IAttributeMapping attributeMapping = attributeChange.getElement1(); - builder.append(", "); - builder.append(attributeMapping.getField()); - builder.append(" = "); - attributeMapping.appendValue(builder, attributeChange.getElement2()); - } - - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = "); - builder.append(cdoid); - - String sql = builder.toString(); - - if (TRACER.isEnabled()) - { - TRACER.trace("Batching misc statement:" + sql); - } - - try - { - if (miscStatement == null) - { - miscStatement = getConnection().createStatement(); - } - miscStatement.addBatch(sql); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - } - - @Override - public void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created, long newContainerId, - int newContainingFeatureId, long newResourceId, List<Pair<IAttributeMapping, Object>> attributeChanges, - boolean hasFullRevisionInfo) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - builder.append(" = "); - builder.append(created); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CONTAINER); - builder.append(" = "); - builder.append(newContainerId); - - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_FEATURE); - builder.append(" = "); - builder.append(newContainingFeatureId); - - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_RESOURCE); - builder.append(" = "); - builder.append(newResourceId); - - for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges) - { - IAttributeMapping attributeMapping = attributeChange.getElement1(); - builder.append(", "); - builder.append(attributeMapping.getField()); - builder.append(" = "); - attributeMapping.appendValue(builder, attributeChange.getElement2()); - } - - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = "); - builder.append(cdoid); - - String sql = builder.toString(); - - if (TRACER.isEnabled()) - { - TRACER.trace(sql); - } - - try - { - if (miscStatement == null) - { - miscStatement = getConnection().createStatement(); - } - miscStatement.addBatch(sql); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - } - - @Override - public void doUpdateRevisedForReplace(String tableName, long revisedStamp, long cdoid, int version) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.REVISE_VERSION, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("UPDATE "); - sql.append(tableName); - sql.append(SQL_UPDATE_REVISE_VERSION); - stmt = getConnection().prepareStatement(sql.toString()); - - if (cacheStatements) - { - cacheStatement(StmtType.REVISE_VERSION, tableName, stmt); - } - } - - stmt.setLong(1, revisedStamp); - stmt.setLong(2, cdoid); - stmt.setInt(3, version); - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - @Override - public void doUpdateRevisedForDetach(String tableName, long revisedStamp, long cdoid) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.REVISE_UNREVISED, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("UPDATE "); - sql.append(tableName); - sql.append(SQL_UPDATE_REVISE_UNREVISED); - stmt = getConnection().prepareStatement(sql.toString()); - - if (cacheStatements) - { - cacheStatement(StmtType.REVISE_UNREVISED, tableName, stmt); - } - } - - stmt.setLong(1, revisedStamp); - stmt.setLong(2, cdoid); - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - /* - * This has been the preparedStatement version of updateAttributes. Does not make sense now, as amount of attributes - * is variable. Preparing for any number of attributes is not very intelligent ... protected void - * doUpdateAllAttributes(String tableName, long cdoid, int version, long created, List<Pair<IAttributeMapping, - * Object>> attributeChanges, boolean withFullRevisionInfo) { boolean firstBatch = false; PreparedStatement stmt = - * getDirtyStatement(StmtType.UPDATE_ATTRIBUTES, tableName); if (stmt == null && cacheStatements) { firstBatch = true; - * stmt = getAndRemoveCachedStatement(StmtType.UPDATE_ATTRIBUTES, tableName); } try { firstBatch = true; if (stmt == - * null) { StringBuilder sql = new StringBuilder(); sql.append("UPDATE "); sql.append(tableName); sql.append(" SET "); - * sql.append(CDODBSchema.ATTRIBUTES_VERSION); sql.append(" = ? "); if (withFullRevisionInfo) { sql.append(", "); - * sql.append(CDODBSchema.ATTRIBUTES_RESOURCE); sql.append(" = ?,"); sql.append(CDODBSchema.ATTRIBUTES_CONTAINER); - * sql.append(" = ?,"); sql.append(CDODBSchema.ATTRIBUTES_FEATURE); sql.append(" = ?"); } for (IAttributeMapping - * attributeMapping : attributeMappings) { sql.append(", "); sql.append(attributeMapping.getField()); - * sql.append(" = ?"); } sql.append(" WHERE "); sql.append(CDODBSchema.ATTRIBUTES_ID); sql.append(" = ? "); stmt = - * getConnection().prepareStatement(sql.toString()); } int col = 1; if (TRACER.isEnabled()) { - * TRACER.trace(stmt.toString()); } stmt.setInt(col++, revision.getVersion()); if (withFullRevisionInfo) { - * stmt.setLong(col++, CDOIDUtil.getLong(revision.getResourceID())); stmt.setLong(col++, - * CDOIDUtil.getLong((CDOID)revision.getContainerID())); stmt.setInt(col++, revision.getContainingFeatureID()); } for - * (IAttributeMapping attributeMapping : attributeMappings) { Object value = - * attributeMapping.getRevisionValue(revision); if (value == null) { stmt.setNull(col++, - * attributeMapping.getField().getType().getCode()); } else { stmt.setObject(col++, value); } } stmt.setLong(col++, - * CDOIDUtil.getLong(revision.getID())); if (firstBatch) { addDirtyStatement(StmtType.UPDATE_ATTRIBUTES, tableName, - * stmt); } stmt.addBatch(); } catch (SQLException e) { throw new DBException(e); } } - */ - - @Override - public void doDeleteAttributes(String tableName, long cdoid) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.DELETE_ATTRIBUTES, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("DELETE FROM "); - sql.append(tableName); - sql.append(" WHERE "); - sql.append(CDODBSchema.ATTRIBUTES_ID); - sql.append(" = ? "); - - stmt = getConnection().prepareStatement(sql.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.DELETE_ATTRIBUTES, tableName, stmt); - } - } - - stmt.setLong(1, cdoid); - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - @Override - public void doInsertReference(String tableName, long dbID, long source, int version, int index, long target) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.INSERT_REFERENCES, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("INSERT INTO "); - sql.append(tableName); - sql.append(dbID != 0 ? SQL_INSERT_REFERENCE_WITH_DBID : SQL_INSERT_REFERENCE); - stmt = getConnection().prepareStatement(sql.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.INSERT_REFERENCES, tableName, stmt); - } - } - - int idx = 1; - if (dbID != 0) - { - stmt.setLong(idx++, dbID); - } - - stmt.setLong(idx++, source); - stmt.setInt(idx++, version); - stmt.setInt(idx++, index); - stmt.setLong(idx++, target); - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - @Override - public void doInsertReferenceRow(String tableName, long metaID, long cdoid, int newVersion, long target, int index) - { - move1up(tableName, metaID, cdoid, newVersion, index); - doInsertReference(tableName, metaID, cdoid, newVersion, index, target); - } - - @Override - public void doMoveReferenceRow(String tableName, long metaID, long cdoid, int newVersion, int oldPosition, - int newPosition) - { - if (oldPosition == newPosition) - { - return; - } - - // move element away temporarily - updateOneIndex(tableName, metaID, cdoid, newVersion, oldPosition, -1); - - // move elements in between - if (oldPosition < newPosition) - { - move1down(tableName, metaID, cdoid, newVersion, oldPosition, newPosition); - } - else - { - // oldPosition > newPosition -- equal case is handled above - move1up(tableName, metaID, cdoid, newVersion, newPosition, oldPosition); - } - - // move temporary element to new position - updateOneIndex(tableName, metaID, cdoid, newVersion, -1, newPosition); - - } - - @Override - public void doRemoveReferenceRow(String tableName, long metaID, long cdoid, int index, int newVersion) - { - deleteReferenceRow(tableName, metaID, cdoid, index); - move1down(tableName, metaID, cdoid, newVersion, index); - } - - @Override - public void doUpdateReference(String tableName, long metaID, long sourceId, int newVersion, int index, long targetId) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.UPDATE_REFERENCE, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_TARGET); - builder.append(" = ?, "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.UPDATE_REFERENCE, tableName, stmt); - } - } - - int idx = 1; - stmt.setLong(idx++, targetId); - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, sourceId); - stmt.setLong(idx++, index); - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - @Override - public void doUpdateReferenceVersion(String tableName, long cdoid, int newVersion) - { - boolean firstBatch = false; - - PreparedStatement stmt = getDirtyStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName); - if (stmt == null && cacheStatements) - { - firstBatch = true; - stmt = getAndRemoveCachedStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName); - } - - try - { - if (stmt == null) - { - firstBatch = true; - - StringBuilder sql = new StringBuilder(); - sql.append("UPDATE "); - sql.append(tableName); - sql.append(" SET "); - sql.append(CDODBSchema.REFERENCES_VERSION); - sql.append(" = ? "); - sql.append(" WHERE "); - sql.append(CDODBSchema.REFERENCES_SOURCE); - sql.append(" = ?"); - - stmt = getConnection().prepareStatement(sql.toString()); - } - - stmt.setInt(1, newVersion); - stmt.setLong(2, cdoid); - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - if (firstBatch) - { - addDirtyStatement(StmtType.UPDATE_REFERENCE_VERSION, tableName, stmt); - } - - stmt.addBatch(); - } - catch (SQLException e) - { - throw new DBException(e); - } - } - - @Override - public void doDeleteReferences(String tableName, long metaID, long cdoid) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.DELETE_REFERENCES, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("DELETE FROM "); - sql.append(tableName); - sql.append(" WHERE "); - sql.append(CDODBSchema.REFERENCES_SOURCE); - sql.append(" = ? "); - - if (metaID != 0) - { - sql.append("AND"); - sql.append(CDODBSchema.REFERENCES_FEATURE); - sql.append(" = ? "); - } - - stmt = getConnection().prepareStatement(sql.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.DELETE_REFERENCES, tableName, stmt); - } - } - - stmt.setLong(1, cdoid); - if (metaID != 0) - { - stmt.setLong(2, metaID); - } - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - @Override - public ResultSet doSelectRevisionAttributes(String tableName, long revisionId, - List<IAttributeMapping> attributeMappings, boolean hasFullRevisionInfo, String where) throws SQLException - { - // Because of the variable where clause, statement caching can not be - // based on table names. Instead, we build the sql in any case and - // use this as key (similar to what JDBC3 does ...). - - StringBuilder builder = new StringBuilder(); - builder.append("SELECT "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - - if (hasFullRevisionInfo) - { - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_RESOURCE); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CONTAINER); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_FEATURE); - } - - for (IAttributeMapping attributeMapping : attributeMappings) - { - builder.append(", "); - builder.append(attributeMapping.getField()); - } - - builder.append(" FROM "); - builder.append(tableName); - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append("= ? AND ("); - builder.append(where); - builder.append(")"); - String sql = builder.toString(); - if (TRACER.isEnabled()) - { - TRACER.format("{0} ({1})", sql, revisionId); - } - - PreparedStatement pstmt = null; - if (cacheStatements) - { - pstmt = getCachedStatement(StmtType.GENERAL, sql); - if (pstmt == null) - { - pstmt = getConnection().prepareStatement(sql); - cacheStatement(StmtType.GENERAL, sql, pstmt); - } - } - else - { - /* no caching */ - pstmt = getConnection().prepareStatement(sql); - } - - pstmt.setLong(1, revisionId); - return pstmt.executeQuery(); - } - - @Override - public ResultSet doSelectRevisionReferences(String tableName, long sourceId, int version, long metaID, String where) - throws SQLException - { - StringBuilder builder = new StringBuilder(); - builder.append("SELECT "); - builder.append(CDODBSchema.REFERENCES_TARGET); - builder.append(" FROM "); - builder.append(tableName); - builder.append(" WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append("= ? "); - if (where != null) - { - builder.append(where); - } - - builder.append(" ORDER BY "); - builder.append(CDODBSchema.REFERENCES_IDX); - - String sql = builder.toString(); - if (TRACER.isEnabled()) - { - TRACER.trace(sql); - } - - PreparedStatement pstmt = null; - if (cacheStatements) - { - pstmt = getCachedStatement(StmtType.GENERAL, sql); - if (pstmt == null) - { - pstmt = getConnection().prepareStatement(sql); - cacheStatement(StmtType.GENERAL, sql, pstmt); - } - } - else - { - /* no caching */ - pstmt = getConnection().prepareStatement(sql); - } - - int idx = 1; - if (metaID != 0) - { - pstmt.setLong(idx++, metaID); - } - - pstmt.setLong(idx++, sourceId); - pstmt.setInt(idx++, version); - return pstmt.executeQuery(); - } - - /** - * Implementation of the hook which is called after selects. - */ - @Override - protected void releaseStatement(Statement stmt) - { - // leave open cached statements - if (!cacheStatements || !(stmt instanceof PreparedStatement)) - { - // super.releaseStatement(stmt); - } - - // /* This code would guarantee that releaseStatement is only called - // for cached statements. However this looks through the whole hashmap - // and is thus too expensive to do in non-debugging mode. */ - // - // else { - // if(!selectStatementsCache.containsValue(stmt)) { - // super.releaseStatement(stmt); - // } - // } - } - - // ---------------------------------------------------------- - // List management helpers - // ---------------------------------------------------------- - - public void updateOneIndex(String tableName, long metaID, long cdoid, int newVersion, int oldIndex, int newIndex) - { - if (TRACER.isEnabled()) - { - TRACER.format("updateOneIndex ({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, oldIndex, newIndex); - } - - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.MOVE_ONE_INDEX, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = ?, "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.MOVE_ONE_INDEX, tableName, stmt); - } - } - - int idx = 1; - stmt.setInt(idx++, newIndex); - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, cdoid); - stmt.setLong(idx++, oldIndex); - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - /** - * Move references downwards to close a gap at position <code>index</code>. Only indexes starting with - * <code>index + 1</code> and ending with <code>upperIndex</code> are moved down. - */ - public void move1down(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex) - { - if (TRACER.isEnabled()) - { - TRACER.format("move1down({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, index, upperIndex); - } - - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.MOVE_RANGE_1_DOWN, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("-1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" > ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" <= ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.MOVE_RANGE_1_DOWN, tableName, stmt); - } - } - - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, cdoid); - stmt.setInt(idx++, index); - stmt.setInt(idx++, upperIndex); - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - /** - * Move references downwards to close a gap at position <code>index</code>. All indexes starting with - * <code>index + 1</code> are moved down. - */ - public void move1down(String tableName, long metaID, long cdoid, int newVersion, int index) - { - if (TRACER.isEnabled()) - { - TRACER.format("move1down({0},{1},{2},{3})", tableName, cdoid, newVersion, index); - } - - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.MOVE_1_DOWN, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("-1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" > ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.MOVE_1_DOWN, tableName, stmt); - } - } - - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, cdoid); - stmt.setInt(idx++, index); - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - - } - } - - /** - * Move references upwards to make room at position <code>index</code>. Only indexes starting with <code>index</code> - * and ending with <code>upperIndex - 1</code> are moved up. - */ - public void move1up(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex) - { - if (TRACER.isEnabled()) - { - TRACER.format("move1up({0},{1},{2},{3},{4})", tableName, cdoid, newVersion, index, upperIndex); - } - - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.MOVE_RANGE_1_UP, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("+1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" => ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" < ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.MOVE_RANGE_1_UP, tableName, stmt); - } - } - - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, cdoid); - stmt.setInt(idx++, index); - stmt.setInt(idx++, upperIndex); - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - - } - } - - /** - * Move references upwards to make room at position <code>index</code>. Only indexes starting with <code>index</code>. - */ - public void move1up(String tableName, long metaID, long cdoid, int newVersion, int index) - { - if (TRACER.isEnabled()) - { - TRACER.format("move1up({0},{1},{2},{3})", tableName, cdoid, newVersion, index); - } - - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.MOVE_1_UP, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("+1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = ? WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("= ? AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" >= ?"); - - stmt = getConnection().prepareStatement(builder.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.MOVE_1_UP, tableName, stmt); - } - } - - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (metaID != 0) - { - stmt.setLong(idx++, metaID); - } - - stmt.setLong(idx++, cdoid); - stmt.setInt(idx++, index); - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - - } - } - - public void deleteReferenceRow(String tableName, long metaID, long cdoid, int index) - { - PreparedStatement stmt = null; - if (cacheStatements) - { - stmt = getCachedStatement(StmtType.DELETE_ONE_REFERENCE, tableName); - } - - try - { - if (stmt == null) - { - StringBuilder sql = new StringBuilder("DELETE FROM "); - sql.append(tableName); - sql.append(" WHERE "); - sql.append(CDODBSchema.REFERENCES_SOURCE); - sql.append(" = ? AND "); - sql.append(CDODBSchema.REFERENCES_IDX); - sql.append(" = ? "); - - if (metaID != 0) - { - sql.append("AND"); - sql.append(CDODBSchema.REFERENCES_FEATURE); - sql.append(" = ? "); - } - - stmt = getConnection().prepareStatement(sql.toString()); - if (cacheStatements) - { - cacheStatement(StmtType.DELETE_ONE_REFERENCE, tableName, stmt); - } - } - - stmt.setLong(1, cdoid); - stmt.setInt(2, index); - if (metaID != 0) - { - stmt.setLong(3, metaID); - } - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - stmt.execute(); - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - if (!cacheStatements) - { - DBUtil.close(stmt); - } - } - } - - // ---------------------------------------------------------- - // Statement caching - // ---------------------------------------------------------- - - /** - * Add a dirty statement to the dirty statements container. - */ - private void addDirtyStatement(StmtType type, String subKey, PreparedStatement stmt) - { - if (TRACER.isEnabled()) - { - TRACER.format("Adding dirty statement: ({0},{1}) -> {2}", type, subKey, stmt); - } - - dirtyStatements.put(new CacheKey(type, subKey), stmt); - } - - /** - * Query the dirty statements container. - * - * @return - */ - private PreparedStatement getDirtyStatement(StmtType type, String subKey) - { - return dirtyStatements.get(CacheKey.useOnce(type, subKey)); - } - - /** - * Cache a prepared statement. - */ - private void cacheStatement(StmtType type, String subKey, PreparedStatement stmt) - { - cacheStatement(new CacheKey(type, subKey), stmt); - } - - /** - * Cache a prepared statement with given key. - */ - private void cacheStatement(CacheKey key, PreparedStatement stmt) - { - if (TRACER.isEnabled()) - { - TRACER.format("Adding cached statement: {0} -> {1}", key, stmt); - } - - statementCache.put(key, new WrappedPreparedStatement(stmt)); - } - - /** - * Query the cache of prepared statements. - */ - private PreparedStatement getCachedStatement(StmtType type, String subKey) - { - WrappedPreparedStatement wrapped = statementCache.get(CacheKey.useOnce(type, subKey)); - if (wrapped == null) - { - return null; - } - - PreparedStatement stmt = wrapped.getWrappedStatement(); - if (TRACER.isEnabled()) - { - TRACER.format("Using cached statement: ({0},{1}) -> {2}", type, subKey, stmt); - } - - return stmt; - } - - private PreparedStatement getAndRemoveCachedStatement(StmtType type, String subKey) - { - WrappedPreparedStatement wrapped = statementCache.remove(CacheKey.useOnce(type, subKey)); - if (wrapped == null) - { - return null; - } - - PreparedStatement stmt = wrapped.unwrapStatement(); - if (TRACER.isEnabled()) - { - TRACER.format("Removing cached statement: ({0},{1}) -> {2}", type, subKey, stmt); - } - - return stmt; - } - - /** - * @author Stefan Winkler - */ - public static enum CachingEnablement - { - ENABLED, DISABLED, GUESS - } - - /** - * Statement type as first part of the statement cache key. - * - * @author Stefan Winkler - */ - private static enum StmtType - { - INSERT_ATTRIBUTES, DELETE_ATTRIBUTES, INSERT_REFERENCES, DELETE_REFERENCES, DELETE_ONE_REFERENCE, REVISE_VERSION, REVISE_UNREVISED, GENERAL, UPDATE_REFERENCE_VERSION, MOVE_1_UP, MOVE_RANGE_1_UP, MOVE_1_DOWN, MOVE_RANGE_1_DOWN, MOVE_ONE_INDEX, UPDATE_REFERENCE - } - - /** - * Convenience definition for Pair<StmtType, String> - * - * @author Stefan Winkler - */ - private static class CacheKey extends Pair<StmtType, String> - { - public CacheKey(StmtType type, String subKey) - { - super(type, subKey); - } - - private static CacheKey useOnceKey = new CacheKey(StmtType.GENERAL, ""); - - /** - * Memory-resource-friendly method which uses a single static field, modifies it and returns it to be used at once, - * e.g., to use it in a cache lookup. Do not store a reference to the result!!! - */ - public static CacheKey useOnce(StmtType type, String subKey) - { - useOnceKey.setElement1(type); - useOnceKey.setElement2(subKey); - return useOnceKey; - } - } -} diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/StatementJDBCDelegate.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/StatementJDBCDelegate.java deleted file mode 100644 index 11d0e0b..0000000 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/jdbc/StatementJDBCDelegate.java +++ /dev/null @@ -1,648 +0,0 @@ -/** - * Copyright (c) 2004 - 2009 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - * Stefan Winkler - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259402 - */ -package org.eclipse.emf.cdo.server.internal.db.jdbc; - -import org.eclipse.emf.cdo.common.id.CDOID; -import org.eclipse.emf.cdo.common.id.CDOIDUtil; -import org.eclipse.emf.cdo.common.revision.CDORevision; -import org.eclipse.emf.cdo.common.revision.CDORevisionData; -import org.eclipse.emf.cdo.server.db.CDODBUtil; -import org.eclipse.emf.cdo.server.db.mapping.IAttributeMapping; -import org.eclipse.emf.cdo.server.internal.db.CDODBSchema; -import org.eclipse.emf.cdo.server.internal.db.bundle.OM; -import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; - -import org.eclipse.net4j.db.DBException; -import org.eclipse.net4j.util.collection.Pair; -import org.eclipse.net4j.util.om.monitor.OMMonitor; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -/** - * @author Stefan Winkler - * @since 2.0 - */ -public class StatementJDBCDelegate extends AbstractJDBCDelegate -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, StatementJDBCDelegate.class); - - public StatementJDBCDelegate() - { - } - - public void flush(OMMonitor monitor) - { - // Do nothing - } - - @Override - protected void doInsertAttributes(String table, CDORevision revision, List<IAttributeMapping> attributeMappings, - boolean withFullRevisionInfo) - { - StringBuilder builder = new StringBuilder(); - builder.append("INSERT INTO "); - builder.append(table); - builder.append(" VALUES ("); - - builder.append(CDOIDUtil.getLong(revision.getID())); - builder.append(", "); - builder.append(revision.getVersion()); - - if (withFullRevisionInfo) - { - CDORevisionData data = revision.data(); - builder.append(", "); - builder.append(getStoreAccessor().getStore().getMetaID(revision.getEClass())); - builder.append(", "); - builder.append(revision.getCreated()); - builder.append(", "); - builder.append(revision.getRevised()); - builder.append(", "); - builder.append(CDOIDUtil.getLong(data.getResourceID())); - builder.append(", "); - builder.append(CDODBUtil.getLong((CDOID)data.getContainerID())); - builder.append(", "); - builder.append(data.getContainingFeatureID()); - } - - if (attributeMappings != null) - { - for (IAttributeMapping attributeMapping : attributeMappings) - { - builder.append(", "); - attributeMapping.appendValue(builder, (InternalCDORevision)revision); - } - } - - builder.append(")"); - sqlUpdate(builder.toString()); - } - - @Override - protected void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created, - List<Pair<IAttributeMapping, Object>> attributeChanges, boolean hasFullRevisionInfo) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - builder.append(" = "); - builder.append(created); - - for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges) - { - IAttributeMapping attributeMapping = attributeChange.getElement1(); - builder.append(", "); - builder.append(attributeMapping.getField()); - builder.append(" = "); - attributeMapping.appendValue(builder, attributeChange.getElement2()); - } - - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = "); - builder.append(cdoid); - - sqlUpdate(builder.toString()); - } - - @Override - protected void doUpdateAttributes(String tableName, long cdoid, int newVersion, long created, long newContainerId, - int newContainingFeatureId, long newResourceId, List<Pair<IAttributeMapping, Object>> attributeChanges, - boolean hasFullRevisionInfo) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - builder.append(" = "); - builder.append(created); - - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CONTAINER); - builder.append(" = "); - builder.append(newContainerId); - - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_FEATURE); - builder.append(" = "); - builder.append(newContainingFeatureId); - - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_RESOURCE); - builder.append(" = "); - builder.append(newResourceId); - - for (Pair<IAttributeMapping, Object> attributeChange : attributeChanges) - { - IAttributeMapping attributeMapping = attributeChange.getElement1(); - builder.append(", "); - builder.append(attributeMapping.getField()); - builder.append(" = "); - attributeMapping.appendValue(builder, attributeChange.getElement2()); - } - - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = "); - builder.append(cdoid); - - sqlUpdate(builder.toString()); - } - - @Override - protected void doDeleteAttributes(String name, long cdoid) - { - StringBuilder builder = new StringBuilder(); - builder.append("DELETE FROM "); - builder.append(name); - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = "); - builder.append(cdoid); - sqlUpdate(builder.toString()); - } - - @Override - protected void doUpdateRevisedForReplace(String table, long revisedStamp, long cdoid, int version) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(table); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append("="); - builder.append(revisedStamp); - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append("="); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append("="); - builder.append(version); - sqlUpdate(builder.toString()); - } - - @Override - protected void doUpdateRevisedForDetach(String table, long revisedStamp, long cdoid) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(table); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append("="); - builder.append(revisedStamp); - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append("="); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append("=0"); - sqlUpdate(builder.toString()); - } - - @Override - protected void doInsertReferenceRow(String tableName, long metaID, long cdoid, int newVersion, long target, int index) - { - move1up(tableName, metaID, cdoid, newVersion, index, -1); - doInsertReference(tableName, metaID, cdoid, newVersion, index, target); - } - - @Override - protected void doInsertReference(String table, long metaID, long source, int version, int i, long target) - { - StringBuilder builder = new StringBuilder(); - builder.append("INSERT INTO "); - builder.append(table); - builder.append(" VALUES ("); - if (metaID != 0) - { - builder.append(metaID); - builder.append(", "); - } - builder.append(source); - builder.append(", "); - builder.append(version); - builder.append(", "); - builder.append(i); - builder.append(", "); - builder.append(target); - builder.append(")"); - sqlUpdate(builder.toString()); - } - - @Override - protected void doMoveReferenceRow(String tableName, long metaID, long cdoid, int newVersion, int oldPosition, - int newPosition) - { - if (oldPosition == newPosition) - { - return; - } - - // move element away temporarily - updateOneIndex(tableName, metaID, cdoid, newVersion, oldPosition, -1); - - // move elements in between - if (oldPosition < newPosition) - { - move1down(tableName, metaID, cdoid, newVersion, oldPosition, newPosition); - } - else - { - // oldPosition > newPosition -- equal case is handled above - move1up(tableName, metaID, cdoid, newVersion, newPosition, oldPosition); - } - - // move temporary element to new position - updateOneIndex(tableName, metaID, cdoid, newVersion, -1, newPosition); - } - - @Override - protected void doDeleteReferences(String name, long metaID, long cdoid) - { - StringBuilder builder = new StringBuilder(); - builder.append("DELETE FROM "); - builder.append(name); - builder.append(" WHERE "); - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append(" = "); - builder.append(cdoid); - if (metaID != 0) - { - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append(" = "); - builder.append(metaID); - } - sqlUpdate(builder.toString()); - } - - @Override - protected void doRemoveReferenceRow(String tableName, long metaID, long cdoid, int index, int newVersion) - { - deleteReferenceRow(tableName, metaID, cdoid, index); - move1down(tableName, metaID, cdoid, newVersion, index, -1); - } - - @Override - protected void doUpdateReferenceVersion(String tableName, long cdoid, int newVersion) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(" WHERE "); - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append(" = "); - builder.append(cdoid); - sqlUpdate(builder.toString()); - } - - @Override - protected void doUpdateReference(String tableName, long metaID, long sourceId, int newVersion, int index, - long targetId) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_TARGET); - builder.append(" = "); - builder.append(targetId); - builder.append(", "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(" WHERE "); - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append(" = "); - builder.append(sourceId); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(index); - - if (metaID != 0) - { - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append(" = "); - builder.append(metaID); - } - - sqlUpdate(builder.toString()); - } - - @Override - protected ResultSet doSelectRevisionAttributes(String tableName, long revisionId, - List<IAttributeMapping> attributeMappings, boolean hasFullRevisionInfo, String where) throws SQLException - { - StringBuilder builder = new StringBuilder(); - builder.append("SELECT "); - if (hasFullRevisionInfo) - { - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CREATED); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_RESOURCE); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_CONTAINER); - builder.append(", "); - builder.append(CDODBSchema.ATTRIBUTES_FEATURE); - } - else - { - if (attributeMappings == null) - { - // Only references return - return null; - } - } - - if (attributeMappings != null) - { - for (IAttributeMapping attributeMapping : attributeMappings) - { - builder.append(", "); - builder.append(attributeMapping.getField()); - } - } - - builder.append(" FROM "); - builder.append(tableName); - builder.append(" WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append("="); - builder.append(revisionId); - builder.append(" AND ("); - builder.append(where); - builder.append(")"); - String sql = builder.toString(); - if (TRACER.isEnabled()) - { - TRACER.trace(sql); - } - - return getStatement().executeQuery(sql); - } - - @Override - protected ResultSet doSelectRevisionReferences(String tableName, long sourceId, int version, long metaID, String where) - throws SQLException - { - - StringBuilder builder = new StringBuilder(); - builder.append("SELECT "); - builder.append(CDODBSchema.REFERENCES_TARGET); - builder.append(" FROM "); - builder.append(tableName); - builder.append(" WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("="); - builder.append(metaID); - builder.append(" AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("="); - builder.append(sourceId); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append("="); - builder.append(version); - - if (where != null) - { - builder.append(where); - } - - builder.append(" ORDER BY "); - builder.append(CDODBSchema.REFERENCES_IDX); - - String sql = builder.toString(); - - if (TRACER.isEnabled()) - { - TRACER.trace(sql); - } - - return getStatement().executeQuery(sql); - } - - private int sqlUpdate(String sql) throws DBException - { - if (TRACER.isEnabled()) - { - TRACER.trace(sql); - } - - Statement statement = null; - try - { - statement = getConnection().createStatement(); - return statement.executeUpdate(sql); - } - catch (SQLException ex) - { - throw new DBException(ex); - } - finally - { - try - { - statement.close(); - } - catch (SQLException e) - { - if (TRACER.isEnabled()) - { - TRACER.trace(e); - } - } - } - } - - private void deleteReferenceRow(String name, long metaID, long cdoid, int index) - { - StringBuilder builder = new StringBuilder(); - builder.append("DELETE FROM "); - builder.append(name); - builder.append(" WHERE "); - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append(" = "); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(index); - if (metaID != 0) - { - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append(" = "); - builder.append(metaID); - } - sqlUpdate(builder.toString()); - } - - /** - * Move references upwards to make room at position <code>index</code>. If <code>upperIndex</code> is <code>-1</code>, - * then all indices beginning with <code>index</code> are moved. Else, only indexes starting with <code>index</code> - * and ending with <code>upperIndex - 1</code> are moved up. - */ - private void move1up(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("+1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(" WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("="); - builder.append(metaID); - builder.append(" AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("="); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" >= "); - builder.append(index); - - if (upperIndex != -1) - { - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" < "); - builder.append(upperIndex); - } - - sqlUpdate(builder.toString()); - } - - /** - * Move references downwards to close a gap at position <code>index</code>. If <code>upperIndex</code> is - * <code>-1</code>, then all indices beginning with <code>index + 1</code> are moved. Else, only indexes starting with - * <code>index + 1</code> and ending with <code>upperIndex</code> are moved down. - */ - private void move1down(String tableName, long metaID, long cdoid, int newVersion, int index, int upperIndex) - { - StringBuilder builder = new StringBuilder(); - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append("-1 ,"); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(" WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("="); - builder.append(metaID); - builder.append(" AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("="); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" > "); - builder.append(index); - - if (upperIndex != -1) - { - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" <= "); - builder.append(upperIndex); - } - - sqlUpdate(builder.toString()); - } - - private void updateOneIndex(String tableName, long metaID, long cdoid, int newVersion, int oldIndex, int newIndex) - { - StringBuilder builder = new StringBuilder(); - - builder.append("UPDATE "); - builder.append(tableName); - builder.append(" SET "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(newIndex); - builder.append(", "); - builder.append(CDODBSchema.REFERENCES_VERSION); - builder.append(" = "); - builder.append(newVersion); - builder.append(" WHERE "); - if (metaID != 0) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("="); - builder.append(metaID); - builder.append(" AND "); - } - - builder.append(CDODBSchema.REFERENCES_SOURCE); - builder.append("="); - builder.append(cdoid); - builder.append(" AND "); - builder.append(CDODBSchema.REFERENCES_IDX); - builder.append(" = "); - builder.append(oldIndex); - - sqlUpdate(builder.toString()); - } -} diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ClassMapping.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ClassMapping.java index 96a0a5d..542accb 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ClassMapping.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ClassMapping.java @@ -20,12 +20,12 @@ import org.eclipse.emf.cdo.server.IStore; import org.eclipse.emf.cdo.server.db.CDODBUtil; import org.eclipse.emf.cdo.server.db.IDBStore; import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; +import org.eclipse.emf.cdo.server.db.IMetaDataManager; import org.eclipse.emf.cdo.server.db.mapping.IAttributeMapping; import org.eclipse.emf.cdo.server.db.mapping.IClassMapping; import org.eclipse.emf.cdo.server.db.mapping.IFeatureMapping; import org.eclipse.emf.cdo.server.db.mapping.IReferenceMapping; import org.eclipse.emf.cdo.server.internal.db.CDODBSchema; -import org.eclipse.emf.cdo.server.internal.db.DBStore; import org.eclipse.emf.cdo.server.internal.db.ToMany; import org.eclipse.emf.cdo.server.internal.db.bundle.OM; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; @@ -85,8 +85,6 @@ public abstract class ClassMapping implements IClassMapping private String sqlReviseAttributes; - private String sqlReviseAttributesByID; - private String sqlInsertAttributes; private String sqlUpdateAttributesAffix; @@ -200,12 +198,12 @@ public abstract class ClassMapping implements IClassMapping protected DBType getDBType(EStructuralFeature feature) { - return DBStore.getDBType(feature.getEType()); + return getMetaDataManager().getDBType(feature.getEType()); } protected int getDBLength(EStructuralFeature feature) { - // TODO make length DB dependent (Oracle only supports 30 chars) + // TODO delegate to DBAdapter! // Derby: The maximum length for a VARCHAR string is 32,672 characters. CDOType type = CDOModelUtil.getType(feature.getEType()); return type == CDOType.STRING || type == CDOType.CUSTOM ? 32672 : IDBField.DEFAULT; @@ -383,7 +381,7 @@ public abstract class ClassMapping implements IClassMapping if (revision.getVersion() > 1 && hasFullRevisionInfo() && isAuditing()) { - writeRevisedRow(accessor, revision); + writeRevisedRow(accessor, revision.getID(), revision.getCreated() - 1); } monitor.worked(); @@ -464,47 +462,13 @@ public abstract class ClassMapping implements IClassMapping } } - protected final void writeRevisedRow(IDBStoreAccessor accessor, InternalCDORevision revision) - { - PreparedStatement stmt = null; - - try - { - stmt = accessor.getConnection().prepareStatement(sqlReviseAttributes); - - stmt.setLong(1, (revision.getCreated() - 1)); - stmt.setLong(2, CDOIDUtil.getLong(revision.getID())); - stmt.setInt(3, (revision.getVersion() - 1)); - - if (TRACER.isEnabled()) - { - TRACER.trace(stmt.toString()); - } - - int result = stmt.executeUpdate(); - // only one unrevised row may exist - update count must be 1 - if (result != 1) - { - throw new IllegalStateException(stmt.toString() + " returned Update count " + result + " (expected: 1)"); - } - } - catch (SQLException e) - { - throw new DBException(e); - } - finally - { - DBUtil.close(stmt); - } - } - protected final void writeRevisedRow(IDBStoreAccessor accessor, CDOID id, long revised) { PreparedStatement stmt = null; try { - stmt = accessor.getConnection().prepareStatement(sqlReviseAttributesByID); + stmt = accessor.getConnection().prepareStatement(sqlReviseAttributes); stmt.setLong(1, revised); stmt.setLong(2, CDOIDUtil.getLong(id)); @@ -558,7 +522,7 @@ public abstract class ClassMapping implements IClassMapping stmt.setInt(col++, revision.getVersion()); if (hasFullRevisionInfo()) { - stmt.setLong(col++, accessor.getStore().getMetaID(revision.getEClass())); + stmt.setLong(col++, accessor.getStore().getMetaDataManager().getMetaID(revision.getEClass())); stmt.setLong(col++, revision.getCreated()); stmt.setLong(col++, revision.getRevised()); stmt.setLong(col++, CDOIDUtil.getLong(revision.getResourceID())); @@ -717,7 +681,7 @@ public abstract class ClassMapping implements IClassMapping { for (IReferenceMapping referenceMapping : referenceMappings) { - referenceMapping.deleteReference(accessor, id); + referenceMapping.clearReference(accessor, id); } } } @@ -824,20 +788,7 @@ public abstract class ClassMapping implements IClassMapping sqlDeleteAttributes = builder.toString(); - // ----------- Update to set revised --------------------- - builder = new StringBuilder("UPDATE "); - builder.append(table.getName()); - builder.append(" SET "); - builder.append(CDODBSchema.ATTRIBUTES_REVISED); - builder.append(" = ? WHERE "); - builder.append(CDODBSchema.ATTRIBUTES_ID); - builder.append(" = ? AND "); - builder.append(CDODBSchema.ATTRIBUTES_VERSION); - builder.append(" = ?"); - sqlReviseAttributes = builder.toString(); - - // TODO unify both ways to revise revisions! - // ----------- Update to set revised by ID ---------------- + // ----------- Update to set revised ---------------- builder = new StringBuilder("UPDATE "); builder.append(getTable().getName()); builder.append(" SET "); @@ -847,7 +798,7 @@ public abstract class ClassMapping implements IClassMapping builder.append(" = ? AND "); builder.append(CDODBSchema.ATTRIBUTES_REVISED); builder.append(" = 0"); - sqlReviseAttributesByID = builder.toString(); + sqlReviseAttributes = builder.toString(); // ----------- Insert Attributes ------------------------- builder = new StringBuilder(); @@ -987,4 +938,9 @@ public abstract class ClassMapping implements IClassMapping { throw new UnsupportedOperationException(); } + + protected IMetaDataManager getMetaDataManager() + { + return getMappingStrategy().getStore().getMetaDataManager(); + } } diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/MappingStrategy.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/MappingStrategy.java index 8e1abf6..4095bc5 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/MappingStrategy.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/MappingStrategy.java @@ -18,6 +18,7 @@ import org.eclipse.emf.cdo.common.revision.CDORevision; import org.eclipse.emf.cdo.server.IStoreAccessor.QueryResourcesContext; import org.eclipse.emf.cdo.server.db.IDBStore; import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; +import org.eclipse.emf.cdo.server.db.IMetaDataManager; import org.eclipse.emf.cdo.server.db.mapping.IClassMapping; import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy; import org.eclipse.emf.cdo.server.internal.db.CDODBSchema; @@ -106,6 +107,11 @@ public abstract class MappingStrategy extends Lifecycle implements IMappingStrat return value == null ? store.getDBAdapter().getMaxFieldNameLength() : Integer.valueOf(value); } + protected IMetaDataManager getMetaDataManager() + { + return getStore().getMetaDataManager(); + } + public String getTableNamePrefix() { String value = getProperties().get(PROP_TABLE_NAME_PREFIX); @@ -164,13 +170,13 @@ public abstract class MappingStrategy extends Lifecycle implements IMappingStrat public String getTableName(EPackage ePackage) { String name = isQualifiedNames() ? EMFUtil.getQualifiedName(ePackage, NAME_SEPARATOR) : ePackage.getName(); - return getTableName(name, "P" + getStore().getMetaID(ePackage)); + return getTableName(name, "P" + getMetaDataManager().getMetaID(ePackage)); } public String getTableName(EClass eClass) { String name = isQualifiedNames() ? EMFUtil.getQualifiedName(eClass, NAME_SEPARATOR) : eClass.getName(); - return getTableName(name, "C" + getStore().getMetaID(eClass)); + return getTableName(name, "C" + getMetaDataManager().getMetaID(eClass)); } public String getReferenceTableName(EClass eClass, EStructuralFeature feature) @@ -179,26 +185,26 @@ public abstract class MappingStrategy extends Lifecycle implements IMappingStrat name += NAME_SEPARATOR; name += feature.getName(); name += "_refs"; - return getTableName(name, "F" + getStore().getMetaID(feature)); + return getTableName(name, "F" + getMetaDataManager().getMetaID(feature)); } public String getReferenceTableName(EClass eClass) { String name = isQualifiedNames() ? EMFUtil.getQualifiedName(eClass, NAME_SEPARATOR) : eClass.getName(); name += "_refs"; - return getTableName(name, "F" + getStore().getMetaID(eClass)); + return getTableName(name, "F" + getMetaDataManager().getMetaID(eClass)); } public String getReferenceTableName(EPackage ePackage) { String name = isQualifiedNames() ? EMFUtil.getQualifiedName(ePackage, NAME_SEPARATOR) : ePackage.getName(); name += "_refs"; - return getTableName(name, "F" + getStore().getMetaID(ePackage)); + return getTableName(name, "F" + getMetaDataManager().getMetaID(ePackage)); } public String getFieldName(EStructuralFeature feature) { - return getName(feature.getName(), "F" + getStore().getMetaID(feature), getMaxFieldNameLength()); + return getName(feature.getName(), "F" + getMetaDataManager().getMetaID(feature), getMaxFieldNameLength()); } private String getTableName(String name, String suffix) diff --git a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ReferenceMapping.java b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ReferenceMapping.java index 2c7e2b1..10ea246 100644 --- a/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ReferenceMapping.java +++ b/plugins/org.eclipse.emf.cdo.server.db/src/org/eclipse/emf/cdo/server/internal/db/mapping/ReferenceMapping.java @@ -14,7 +14,6 @@ package org.eclipse.emf.cdo.server.internal.db.mapping; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.id.CDOIDUtil; import org.eclipse.emf.cdo.common.revision.CDORevision; -import org.eclipse.emf.cdo.server.IRepository; import org.eclipse.emf.cdo.server.IStoreChunkReader.Chunk; import org.eclipse.emf.cdo.server.db.CDODBUtil; import org.eclipse.emf.cdo.server.db.IDBStoreAccessor; @@ -23,7 +22,6 @@ import org.eclipse.emf.cdo.server.db.mapping.IReferenceMapping; import org.eclipse.emf.cdo.server.internal.db.CDODBSchema; import org.eclipse.emf.cdo.server.internal.db.ToMany; import org.eclipse.emf.cdo.server.internal.db.bundle.OM; -import org.eclipse.emf.cdo.server.internal.db.jdbc.PreparedStatementJDBCDelegate; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; import org.eclipse.net4j.db.DBException; @@ -36,7 +34,6 @@ import org.eclipse.net4j.util.collection.MoveableList; import org.eclipse.net4j.util.om.trace.ContextTracer; import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EStructuralFeature; import java.sql.PreparedStatement; @@ -58,15 +55,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin private IDBTable table; - // TODO - refactor into subclass - private ToMany toMany; - - // TODO - refactor into subclass - private boolean withFeature; - - // TODO - remove - PreparedStatementJDBCDelegate TEMP = null; - private String sqlSelectChunksPrefix; private String sqlOrderByIndex; @@ -94,7 +82,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin public ReferenceMapping(ClassMapping classMapping, EStructuralFeature feature, ToMany toMany) { super(classMapping, feature); - this.toMany = toMany; mapReference(classMapping.getEClass(), feature); initSqlStrings(); @@ -105,45 +92,13 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin return table; } - public boolean isWithFeature() - { - return withFeature; - } - protected void mapReference(EClass eClass, EStructuralFeature feature) { MappingStrategy mappingStrategy = getClassMapping().getMappingStrategy(); - switch (toMany) - { - case PER_REFERENCE: - { - withFeature = false; - String tableName = mappingStrategy.getReferenceTableName(eClass, feature); - Object referenceMappingKey = getReferenceMappingKey(feature); - table = mapReferenceTable(referenceMappingKey, tableName); - break; - } - - case PER_CLASS: - withFeature = true; - table = mapReferenceTable(eClass, mappingStrategy.getReferenceTableName(eClass)); - break; - case PER_PACKAGE: - withFeature = true; - EPackage ePackage = eClass.getEPackage(); - table = mapReferenceTable(ePackage, mappingStrategy.getReferenceTableName(ePackage)); - break; - - case PER_REPOSITORY: - withFeature = true; - IRepository repository = mappingStrategy.getStore().getRepository(); - table = mapReferenceTable(repository, repository.getName() + "_refs"); - break; - - default: - throw new IllegalArgumentException("Invalid mapping: " + toMany); - } + String tableName = mappingStrategy.getReferenceTableName(eClass, feature); + Object referenceMappingKey = getReferenceMappingKey(feature); + table = mapReferenceTable(referenceMappingKey, tableName); } protected Object getReferenceMappingKey(EStructuralFeature feature) @@ -151,11 +106,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin return getClassMapping().createReferenceMappingKey(feature); } - protected final long getMetaID() - { - return getClassMapping().getMappingStrategy().getStore().getMetaID(getFeature()); - } - protected IDBTable mapReferenceTable(Object key, String tableName) { Map<Object, IDBTable> referenceTables = getClassMapping().getMappingStrategy().getReferenceTables(); @@ -172,11 +122,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin protected IDBTable addReferenceTable(String tableName) { IDBTable table = getClassMapping().addTable(tableName); - if (withFeature) - { - table.addField(CDODBSchema.REFERENCES_FEATURE, DBType.BIGINT); - } - IDBField sourceField = table.addField(CDODBSchema.REFERENCES_SOURCE, DBType.BIGINT); IDBField versionField = table.addField(CDODBSchema.REFERENCES_VERSION, DBType.INTEGER); IDBField idxField = table.addField(CDODBSchema.REFERENCES_IDX, DBType.INTEGER); @@ -204,16 +149,10 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin { stmt = accessor.getConnection().prepareStatement(sqlInsertEntry); - int idx1 = 1; - if (withFeature) - { - stmt.setLong(idx1++, getMetaID()); - } - - stmt.setLong(idx1++, CDOIDUtil.getLong(id)); - stmt.setInt(idx1++, version); - stmt.setInt(idx1++, idx++); - stmt.setLong(idx1++, CDODBUtil.getLong(targetId)); + stmt.setLong(1, CDOIDUtil.getLong(id)); + stmt.setInt(2, version); + stmt.setInt(3, idx++); + stmt.setLong(4, CDODBUtil.getLong(targetId)); if (TRACER.isEnabled()) { TRACER.trace(stmt.toString()); @@ -245,10 +184,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin stmt.setLong(1, CDOIDUtil.getLong(id)); stmt.setInt(2, index); - if (withFeature) - { - stmt.setLong(3, getMetaID()); - } if (TRACER.isEnabled()) { @@ -322,16 +257,10 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin stmt = accessor.getConnection().prepareStatement(sqlUpdateIndex); int idx = 1; - stmt.setInt(idx++, newIndex); - stmt.setInt(idx++, newVersion); - - if (withFeature) - { - stmt.setLong(idx++, getMetaID()); - } - - stmt.setLong(idx++, CDOIDUtil.getLong(cdoid)); - stmt.setLong(idx++, oldIndex); + stmt.setInt(1, newIndex); + stmt.setInt(2, newVersion); + stmt.setLong(3, CDOIDUtil.getLong(cdoid)); + stmt.setLong(4, oldIndex); if (TRACER.isEnabled()) { @@ -374,19 +303,12 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin stmt = accessor.getConnection().prepareStatement(sqlMoveDownWithLimit); } - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (withFeature) - { - stmt.setLong(idx++, getMetaID()); - } - - stmt.setLong(idx++, CDOIDUtil.getLong(cdoid)); - stmt.setInt(idx++, index); + stmt.setInt(1, newVersion); + stmt.setLong(2, CDOIDUtil.getLong(cdoid)); + stmt.setInt(3, index); if (upperIndex != MOVE_UNBOUNDED) { - stmt.setInt(idx++, upperIndex); + stmt.setInt(4, upperIndex); } int result = stmt.executeUpdate(); @@ -425,19 +347,12 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin stmt = accessor.getConnection().prepareStatement(sqlMoveUpWithLimit); } - int idx = 1; - stmt.setInt(idx++, newVersion); - - if (withFeature) - { - stmt.setLong(idx++, getMetaID()); - } - - stmt.setLong(idx++, CDOIDUtil.getLong(cdoid)); - stmt.setInt(idx++, index); + stmt.setInt(1, newVersion); + stmt.setLong(2, CDOIDUtil.getLong(cdoid)); + stmt.setInt(3, index); if (upperIndex != MOVE_UNBOUNDED) { - stmt.setInt(idx++, upperIndex); + stmt.setInt(4, upperIndex); } int result = stmt.executeUpdate(); @@ -462,19 +377,12 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin try { - stmt = TEMP.getConnection().prepareStatement(sqlUpdateTarget); - - int idx = 1; - stmt.setLong(idx++, CDODBUtil.getLong(value)); - stmt.setInt(idx++, newVersion); - - if (withFeature) - { - stmt.setLong(idx++, getMetaID()); - } + stmt = accessor.getConnection().prepareStatement(sqlUpdateTarget); - stmt.setLong(idx++, CDOIDUtil.getLong(id)); - stmt.setLong(idx++, index); + stmt.setLong(1, CDODBUtil.getLong(value)); + stmt.setInt(2, newVersion); + stmt.setLong(3, CDOIDUtil.getLong(id)); + stmt.setLong(4, index); if (TRACER.isEnabled()) { @@ -528,7 +436,7 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin } } - public void deleteReference(IDBStoreAccessor accessor, CDOID id) + public void clearReference(IDBStoreAccessor accessor, CDOID id) { PreparedStatement stmt = null; @@ -537,10 +445,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin stmt = accessor.getConnection().prepareStatement(sqlClearReference); stmt.setLong(1, CDOIDUtil.getLong(id)); - if (withFeature) - { - stmt.setLong(2, getMetaID()); - } int result = stmt.executeUpdate(); if (result == Statement.EXECUTE_FAILED) @@ -579,16 +483,9 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin } pstmt = accessor.getConnection().prepareStatement(sql); - int idx = 1; - - // TODO- refactor - if (withFeature) - { - pstmt.setLong(idx++, getMetaID()); - } - pstmt.setLong(idx++, sourceId); - pstmt.setInt(idx++, version); + pstmt.setLong(1, sourceId); + pstmt.setInt(2, version); resultSet = pstmt.executeQuery(); while (resultSet.next() && (referenceChunk == CDORevision.UNCHUNKED || --referenceChunk >= 0)) @@ -640,16 +537,8 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin pstmt = chunkReader.getAccessor().getConnection().prepareStatement(sql); - int idx = 1; - - // TODO - refactor into subclass - if (withFeature) - { - pstmt.setLong(idx++, getMetaID()); - } - - pstmt.setLong(idx++, sourceId); - pstmt.setInt(idx++, version); + pstmt.setLong(1, sourceId); + pstmt.setInt(2, version); resultSet = pstmt.executeQuery(); Chunk chunk = null; @@ -702,14 +591,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append(" FROM "); builder.append(tableName); builder.append(" WHERE "); - - // TODO - remove condition - if (withFeature) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append("= ? AND "); builder.append(CDODBSchema.REFERENCES_VERSION); @@ -725,14 +606,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append(" WHERE "); builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append(" = ? "); - - if (withFeature) - { - builder.append("AND"); - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append(" = ? "); - } - sqlClearReference = builder.toString(); // ----------------- UPDATE - reference version ------------------ @@ -757,12 +630,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append(" = ?, "); builder.append(CDODBSchema.REFERENCES_VERSION); builder.append(" = ? WHERE "); - if (withFeature) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append("= ? AND "); builder.append(CDODBSchema.REFERENCES_IDX); @@ -778,12 +645,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append(" = ?, "); builder.append(CDODBSchema.REFERENCES_VERSION); builder.append(" = ? WHERE "); - if (withFeature) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append("= ? AND "); builder.append(CDODBSchema.REFERENCES_IDX); @@ -801,12 +662,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append("+1 ,"); builder.append(CDODBSchema.REFERENCES_VERSION); builder.append(" = ? WHERE "); - if (withFeature) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append("= ? AND "); builder.append(CDODBSchema.REFERENCES_IDX); @@ -828,12 +683,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append("-1 ,"); builder.append(CDODBSchema.REFERENCES_VERSION); builder.append(" = ? WHERE "); - if (withFeature) - { - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append("= ? AND "); - } - builder.append(CDODBSchema.REFERENCES_SOURCE); builder.append("= ? AND "); builder.append(CDODBSchema.REFERENCES_IDX); @@ -848,7 +697,7 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin // ----------------- INSERT - reference entry ----------------- builder = new StringBuilder("INSERT INTO "); builder.append(tableName); - builder.append(withFeature ? " VALUES (?, ?, ?, ?, ?)" : " VALUES (?, ?, ?, ?)"); + builder.append(" VALUES (?, ?, ?, ?)"); sqlInsertEntry = builder.toString(); // ----------------- DELETE - reference entry ----------------- @@ -860,13 +709,6 @@ public class ReferenceMapping extends FeatureMapping implements IReferenceMappin builder.append(CDODBSchema.REFERENCES_IDX); builder.append(" = ? "); - if (withFeature) - { - builder.append("AND"); - builder.append(CDODBSchema.REFERENCES_FEATURE); - builder.append(" = ? "); - } - sqlDeleteEntry = builder.toString(); } } |